text:
Cannot save a client mac address for the life of me, thus no whitelist

I apologize, this is more a bawling cry for help than a bug. I've been working on getting two esp32-c3s talking to each other. This is my first BLE project, so I went for it in Arduino for simplicity, and I've come a long way in the last few months. I've got a working server and client exchanging data through 4 characteristics. The server is essentially activating "relays" based on the characteristic settings set by the client. I'm worried about security so that random people don't walk up and start flipping switches, so I successfully got encryption working between the two, but since that encryption is based on a weak passkey that could probably be hacked out far too easily anyway, I'd like to set up a whitelist. The devices won't be moving, so random addresses to prevent tracking are unnecessary, I think. Of course mac spoofing is a concern, but bluetooth is not the most secure standard. I'm just trying to make sure it isn't easy to interfere with. So, I should be able to accomplish this goal with my current IDE and libraries (barely an IDE but still).
First let me say that the dearth of information on doing ANYTHING with BLE is insane. I finally switched from Bluedroid to NimBLE, and my progress has sped up tremendously. Thank you very much for actually documenting your library. Unfortunately, the documentation around whitelists with NimBLE is lacking, in my opinion.
I have very basic questions that I cannot find answers to. Stack Overflow ignores all esp32 based BLE questions, Arduino forums ignore all BLE questions in general, and Espressif forums ignore all BLE questions period. It's as if BLE is a steamy pile of crap that no one wants to touch. I wonder why...
Let me stop venting and get to some questions. I've made zero progress in about 48 hours of coding, so I can't keep going like this.
I'll post the pertinent parts of my code with lots of comments describing my thought process, goals, and results. If that's not enough, please ask and I'll explain anything in excruciating detail.
Start off prototyping the NimBLEAddress variable that will hold the client mac address.. starting with 1 hardcoded address till it works
NimBLEAddress WLaddress1 = NimBLEAddress("00:00:00:00:00:00"); // or is it better to use("")? Neither way works.

Later we setup server callbacks, and within that class is this callback:
void onAuthenticationComplete (NimBLEServer *pServer, ble_gap_conn_desc *desc)
   {
    //WLaddress1 = new (WLaddress1) NimBLEAddress(desc->peer_ota_addr);
	// I couldn't get this method to work at all

    WLaddress1 = NimBLEAddress(desc->peer_ota_addr);
	// This compiles but doesn't seem to work.

    NimBLEDevice::whiteListAdd(WLaddress1);
	//This is an evolution of NimBLEDevice::whiteListAdd(NimBLEAddress(desc->peer_ota_addr);
	//which works for whitelisting till the esp is reset, then useless.

    preferences.putBytes("wladdress1", &WLaddress1, sizeof(NimBLEAddress));
	//This never seems to actually work. I've tried half a dozen ways. OR it does work, and retrieving doesn't work? Or neither works.
	//preferences.putBytes("wladdress1", &WLaddress1, sizeof(WLaddress1));
	//I tried this way too, it doesn't work either. replacing the length with a 6, 7, 17, nothing works. I would like to just see the data once then maybe I can hack something together. I have no idea what a BLEAddress actually looks like. So far, in my experience, it looks like "0"

	Serial.println("#######onauthcallback address: "); // These 2 prints never send anything to the serial monitor, why? I know the callback is firing and doing something cause the whitelist works till reset.. maybe blocking calls are not allowed? Cannot find information specific to this callback anywhere. Other callbacks do allow prints, so who knows.

	Serial.println(WLaddress1);  // always returns 0 in other places, in this callback, never returns anything.
    }

Later in setup() I start the serial monitor (only while trying to debug this stuff otherwise it gets in the way of BLE in my experience, then load my preferences NVS saved data:
	preferences.begin("savedstuff", false);
	//[...]
	WLaddress1 = preferences.getBytes("wladdress1", &WLaddress1, sizeof(NimBLEAddress)); // I only added this "WLaddress1 = " recently. I don't think it's needed with getBytes. Didn't work either way.
	Serial.println("#######setupload address: "); // this one works
	Serial.println(WLaddress1); // this only ever returns 0

Then a little further down after all my server setup and security settings while still in setup() :
if (digitalRead(pin1) == LOW && digitalRead(pin2) == LOW && digitalRead(pin3) == LOW) // if these 3 pins are low, anyone can connect
          {
            pAdvertising->setScanFilter(false,false); //scanning is not filtered, connecting is not filtered
            pAdvertising->start();
          }
    else
          {
            NimBLEDevice::whiteListAdd(NimBLEAddress(WLaddress1)); // this never works, but of course not, the loaded address is == 0.
            Serial.println("#######loadaddbeforescanfilt address: "); // this one works
            Serial.println(WLaddress1); // this one says 0

            pAdvertising->setScanFilter(true,true); //scanning is filtered, connecting is filtered
            pAdvertising->start();

          }

(I have a similar conditional setup for the onDisconnect callback which seems to work as far as changing the filtering settings)
This is pretty much the end of it. The rest is my loop() code which checks for button presses and some stuff dealing with my "relays".
This is basically where I find myself stuck. I'm more of a hardware person than software, so please forgive stupid mistakes I may be making. I'm 100% self taught, so I have gaps.
Oh, here's another snippet I tried when getByte-ing things back from preferences, but it never worked right either:
  size_t schLen = preferences.getBytes("wladdress1", NULL, NULL);

  NimBLEAddress buffer[schLen]; // prepare a buffer for the data... didn't like being char, doesn't like being NimBLEAddress

  preferences.getBytes("wladdress1", buffer, schLen);
  memcpy(WLaddress1, buffer, schLen);

I get an infuriating error from memcpy at times. I don't even understand how a variable can be void... It's supposed to just be copying bytes of memory.. how can it screw that up? This is one of my gaps.
So in summary, I want to use a whitelist that persists across resets, so I THINK I need to save my whitelist to NVS, but I can't get my whitelist or any mac address to save into NVS. I cannot find sufficient information on how to do this. I've come across half a dozen code snippets strewn across various forums and chat rooms (ugh what a hassle that was), but they never seem to work together. I would like a bit more detail on how to go about this, maybe a few example code snippets of saving a mac address (the currently connected device would be perfect) and especially loading that back into a whitelist from NVS upon reset. Best places to place these methods would be helpful as well.

I thought inline comments to my code would make it easier to read... then it made a scroll bar. I tried to clean some of it up, but it's hard to refer to lines of code with comments that are far away from the line of code they're referring to... apologies.

Hello, just a quick comment. This: Serial.println(WLaddress1);  will not work as you may expect. Instead you will want to use Serial.println(WLaddress1.toString().c_str());.
As for storing the address I think you may need to use desc->peer_id_addr instead of desc->peer_ota_addr but you'll need to check in the callback by printing each of them as described above.

Thank you very much. I have been grasping at straws for the last couple of my programming days, so I tried a large variety of methods as getting anything output. Even if it was garbage, I wanted to see something just to get a little progress and find a direction to start moving forward again. The tip about peer_id_addr should indeed come in handy.
I'll give it a try and get back to you.

Well, after a few hours attempting to get it to work with varying combinations of peer_ota_addr and peer_id_addr, the only real progress I've made is being able to store NimBLEAddress-like strings in Preferences. I couldn't get the actual address of the connected device, but I could store and retrieve a static address declared in code. I'll eventually come back to this I imagine, but for now I'm moving it to the bottom of my todo list. There's just too little documentation for me and my skill level to understand where I'm going wrong. Thanks for your help. I might be back one day.


text:
Refactoring 2.0 Typescript version

I have been working on refactoring the Typescript version of the piexifjs library as I experienced the 2.0 branch in its current stage is not very usable for Typescript projects. Assuming that you do not have some uncommited work on this branch, I hope that you can consider merging this or at least parts of this so that we can use the piexif library for Typescript too.
I have also added some automated publishing/linting/formatting scripts that might be of interest. I think this library could benefit from being developed in Typescript and hope that you would consider making the Typescript branch the main branch for development some time in the future, has having two separate branches does not seem like the way to go. The alternative is to make a typings file for based on the master branch so that we could then import the latest updates into our Typescript project :)

Thank you!

source: gharchive/pull-request

authors: hMatoba holwech

repo: hMatoba/piexifjs

license: mit

license_type: permissive

license_source: bigquery


text:
Interest in project

Dear @Haacked ,
as I do often run in a similar situation, I was thinking that I should have something out of the box, as your Rothko project, that will supply to my need of abstracting system resources.
I would like to contribute and I do think that I have a couple of good ideas.
Is this project still active and do you still have interest in following it?
Thanks
Mario

I agree. HttpClient is what is sorely missed.

source: gharchive/issue

authors: mmajcica nawfalhasan

repo: haacked/Rothko

license: MIT

license_source: github-api


text:
feat: reimplement callbacks and fix gmx and gamemode reloading

[X] reimplementation of callbacks
[ ] document "pyreload" rcon command
[ ] document usage with docker
[ ] do some more testing

@habecker good to go?

@habecker good to go?

@dennorske Honestly, I don't know  .. it's been 3 months 😄. I'm testing it now

@dennorske Honestly, I don't know  .. it's been 3 months 😄. I'm testing it now

@dennorske It's almost done now, we only need documentation and more testing

@dennorske It's almost done now, we only need documentation and more testing

I'll have some time this weekend, and then I can work on the docker documentation.

I'll have some time this weekend, and then I can work on the docker documentation.

authors: dennorske habecker

repo: habecker/PySAMP


text:
PCB update

Larger heat dissipation planes
Silkscreen layers

@Hugoyhu pls remember to get leo to review your designs (and post in the main haxidraw channel )

authors: karamassie leomcelroy

repo: hackclub/haxidraw


text:
Chain Remove

Your checklist for this pull request
Author name
imcute
About your game
A simple game about eliminating squares.If you remove one,every square that's connected to it and have the same color would get removed too.If one of them includes a bomb,then a 3x3 area around the bomb would be removed.(directly removing a bomb wouldn't do anything)
Press WASD to move your cursor.Press K to remove the square under the cursor.There is no points/goals in  this game.
Code
Check off the items that are true.

[x] The game was made using the Sprig editor.
[x] The game is placed in the in the /games directory.
[x] The code is significantly different from all other games in the Sprig gallery (except for games labeled "demo").(I'm not reallly sure,but I did not intentionally copy any of them.(I can make another game if this one is same as some other game/it is not good enough))
[x] The game runs without errors.
[x] The name of the file/game contains only alphanumeric characters, -s, or _s.
[x] The game name is not the same as the others from gallery

Image (If an image is used)
no an image is not used

[ ] The image is in the /games/img directory.
[ ] The name of the image matches the name of your file.

Thanks for your PR!

Yes,I di not set a goal for it.

repo: hackclub/sprig


text:
Add Hack Craft

About Hack Craft
What is your game about?
Hack Craft is a voxel game in which you can build and mine structures
How to play your game?
See controls
Try Hack Craft
Try Hack Craft (with editor)
Code
Check off the items that are true.

[x] The game was made using the Sprig editor.
[x] The game is placed in the in the /games directory.
[x] The code is significantly different from all other games in the Sprig gallery (except for games labeled "demo").
[x] The game runs without errors.
[x] The name of the file/game contains only alphanumeric characters, -s, or _s.
[x] The game name is not the same as the others from gallery

Image (If an image is used)

[x] The image is in the /games/img directory.
[x] The name of the image matches the name of your file.

Try Hack Craft
Try Hack Craft (with editor)

(I'm not sure why CI is broken, the game seems to work fine)

Great game! maybe a pre made structure, background and bigger map can make it even better:)

@LucasHT22 I've made the following changes:

Added a tree, a house and some stone as dirt as ground
Added a control: Hold s to clear the map (including prebuilt structures, so you can get a fresh slate)
The map is now larger and has nearly the same aspect ratio as the sprig

Test changes

Great changes! for me a background would make it even better:)

I don't really like the idea of a background, since it's just a Sprite tiled over and over.
I've tried implementing one, and it didn't really look good, so I decided to leave it out.

oh, ok!

@LucasHT22 btw the author seems wrong, I think you mixed PRs up

Sorry! Fixed.


text:
Link to Code of Conduct on Website

From @jonleung on December 17, 2015 21:46
This is part of the broader issue hackclub/meta#117 for adopting a code of conduct.
Copied from original issue: hackclub/meta#425

Closed by #196

authors: MaxWofford zachlatta

repo: hackclub/website


text:
F*: generics on methods

f TRAIT_GENERICS_CONST not_trait_const should be f #TRAIT_GENERICS_CONST not_trait_const

That's #719

repo: hacspec/hax


text:
Corrections and additions to powerfit tutorial

Please check whether all the points raised were added properly. If not let me know.

Nice work!

I notice that their still remain some small errors. I'll send another last fix soon, to properly address those.

From: Alexandre Bonvin [notifications@github.com]
Sent: Monday, March 07, 2016 3:15 PM
To: haddocking/haddocking.github.io
Cc: Zundert, G.C.P. van (Gydo)
Subject: Re: [haddocking.github.io] Corrections and additions to powerfit tutorial (#40)
Nice work!
—
Reply to this email directly or view it on GitHubhttps://github.com/haddocking/haddocking.github.io/pull/40#issuecomment-193264165.

Do update first - I had a new commit

On 07 Mar 2016, at 16:15, Gydo van Zundert notifications@github.com wrote:
I notice that their still remain some small errors. I'll send another last fix soon, to properly address those.

From: Alexandre Bonvin [notifications@github.com]
Sent: Monday, March 07, 2016 3:15 PM
To: haddocking/haddocking.github.io
Cc: Zundert, G.C.P. van (Gydo)
Subject: Re: [haddocking.github.io] Corrections and additions to powerfit tutorial (#40)
Nice work!
—
Reply to this email directly or view it on GitHubhttps://github.com/haddocking/haddocking.github.io/pull/40#issuecomment-193264165.
—
Reply to this email directly or view it on GitHub.

==================================
Alexandre Bonvin
Talingweide 91, 3403 AC IJsseltstein, NL
Tel: +31-30-7525883
Email: alexandre.bonvin@gmail.com

Will do!

From: Alexandre Bonvin [notifications@github.com]
Sent: Monday, March 07, 2016 4:35 PM
To: haddocking/haddocking.github.io
Cc: Zundert, G.C.P. van (Gydo)
Subject: Re: [haddocking.github.io] Corrections and additions to powerfit tutorial (#40)
Do update first - I had a new commit

On 07 Mar 2016, at 16:15, Gydo van Zundert notifications@github.com wrote:
I notice that their still remain some small errors. I'll send another last fix soon, to properly address those.

From: Alexandre Bonvin [notifications@github.com]
Sent: Monday, March 07, 2016 3:15 PM
To: haddocking/haddocking.github.io
Cc: Zundert, G.C.P. van (Gydo)
Subject: Re: [haddocking.github.io] Corrections and additions to powerfit tutorial (#40)
Nice work!
—
Reply to this email directly or view it on GitHubhttps://github.com/haddocking/haddocking.github.io/pull/40#issuecomment-193264165.
—
Reply to this email directly or view it on GitHub.

==================================
Alexandre Bonvin
Talingweide 91, 3403 AC IJsseltstein, NL
Tel: +31-30-7525883
Email: alexandre.bonvin@gmail.com
—
Reply to this email directly or view it on GitHubhttps://github.com/haddocking/haddocking.github.io/pull/40#issuecomment-193302598.

authors: amjjbonvin latrocinia


text:
Invalid method name

Assembly parser captured invalid method

Possibly caused by nested methods

Total: 33m


text:
internal/gamepaddb: enable to use the database for Android

This is forked from #2309

The current problem is, after I fixed a gamepad's GUID, the GUID is now correct but the button/axis assignments don't match with SDL's and the database's. This means that we cannot use the current database so far. Now Ebitengine prioritize the original mapping for Android so far, but I'd like to change the order of them later.

On Android, button IDs and axis IDs are SDL's rather than raw OS's. This seems weried, but the database says so...

https://github.com/libsdl-org/SDL/blob/47f2373dc13b66c48bf4024fcdab53cd0bdd59bb/src/joystick/android/SDL_sysjoystick.c
So SDL doesn't treat raw buttons and converts them to SDL buttons

Notable:
On Linux, SDL uses a remapping that skips indices, so the buttons are always indices from 0 to n-1: https://github.com/libsdl-org/SDL/blob/f398d8a42422c049d77c744658f1cd2bb011ed4a/src/joystick/linux/SDL_sysjoystick.c#L1423
On Android, however, the same function is called with a direct SDL controller button enum (or an integer that is larger), meaning on Android the indices can have holes. This then also goes through this mapping function, which seems to generate a 1:1 mapping but in gamecontrollerdb style: https://github.com/libsdl-org/SDL/blob/42cf6d6c56faaa0a4f8876f92b7254176030833e/src/joystick/SDL_gamecontroller.c#L456 - very odd.

For axis, SDL doesn't use Android's AXIS_* constants but enumerates available axes:
https://github.com/libsdl-org/SDL/blob/2df2da11f627299c6e05b7e0aff407c915043372/android-project/app/src/main/java/org/libsdl/app/SDLControllerManager.java#L182-L216
Yeah this is odd, but actually this is what they are doing.

authors: divVerent hajimehoshi

repo: hajimehoshi/ebiten


text:
Browser mouse capture not capturing on first load

Ebitengine Version
2.5
Operating System

[ ] Windows
[ ] macOS
[ ] Linux
[ ] FreeBSD
[ ] OpenBSD
[ ] Android
[ ] iOS
[ ] Nintendo Switch
[ ] Xbox
[X] Web Browsers

Go Version (go version)
1.19.6
What steps will reproduce the problem?
This is noticed only from browser wasm version. Visit the mouse capture example (#2636): https://harbdog.github.io/ebiten/
Note that it captures the mouse on first load, yet the OS mouse cursor is still showing which is not expected. Toggling the mouse capture off and back on again then hides the OS mouse cursor as expected.
What is the expected result?
The OS cursor should be hidden when captured on first load.
What happens instead?
The OS cursor still shows even while captured only on first load.
Anything else you feel useful to add?
No response

Did the developer console show anything?

@hajimehoshi here's what's in the console:
wasm_exec.js:349 pointerlockerror event is fired. 'sandbox="allow-pointer-lock"' might be required at an iframe. This function on browsers must be called as a result of a gestural interaction or orientation change.
syscall/js.valueCall @ wasm_exec.js:349
$syscall_js.valueCall @ 0271b102:0x17e37c
$syscall_js.Value.Call @ 0271b102:0x17b857
$wasm_pc_f_loop @ 0271b102:0xeb9f5
$wasm_export_resume @ 0271b102:0xeb9d6
_resume @ wasm_exec.js:538
(anonymous) @ wasm_exec.js:549
harbdog.github.io/:1 Uncaught (in promise) DOMException: A user gesture is required to request Pointer Lock.

I understand if it's a limitation, probably just needs to be documented and worked around by instructing the user to first press something to initiate capture.
I'm also wondering if it's just a timing issue, maybe just delaying the automatic capture until after the first update/draw is performed?

After playing around with various options it seems most likely a browser security limitation that expects direct user interaction to engage the mouse capture, so a key/button must be pressed.
I'll update the example to not attempt to capture on startup.

authors: hajimehoshi harbdog


text:
internal/glfw: check the difference from GLFW v3.3.10

Operating System

[x] Windows
[x] macOS
[x] Linux
[x] FreeBSD
[x] OpenBSD
[ ] Android
[ ] iOS
[ ] Nintendo Switch
[ ] PlayStation 5
[ ] Xbox
[ ] Web Browsers

What feature would you like to be added?
https://github.com/go-gl/glfw/commits/master/v3.3/glfw
internal/glfw's GLFW version is 3.3.8 (as far as I remember) [1], so there should be some differences.
Note that version 3.4 is already out.
[1] https://github.com/hajimehoshi/ebiten/commit/3dd2f15b649355a705a86d2a3f47680b48efa002
Why is this needed?
To reduce known bugs in GLFW.

What I have to apply are:
https://github.com/go-gl/glfw/commit/4149d755ea87d881ba258dd39d38d6b1edf5341b (3.3.8 -> 3.3.9)
https://github.com/go-gl/glfw/commit/916dd3ed2238527d279bb1a24c39762719ba33b2 (3.3.9 -> 3.3.10)


text:
Add Context.SetReadBufferSize.

This is useful for cases where you may need to sync visuals with audio.
The use case I have is with mGBA, where the buffer size needs to be consistent between the emulator and the system sound driver. The automatic sizing from Oto is too large and causes audio delays :(

Thanks, but this kind of change requires discussions before the implementation...

For a real-time streaming, I think it is possible by

Writing not-full data when Read is called
Adjusting the writing pace by seeing UnplayedBufferSize

and actually Tinne (in Ebiten Discord) created a proof of concept.
What do you think?

I don't think it's possible to adjust the writing pace in this case, because the received audio has to play immediately and the buffer size is fixed.

The io.Reader as an audio source doesn't have always to fill the given buffer 100%. So you can pass the data that is generated in real-time pace. You can adjust the pace with UnplayedBufferSize.
So, it works, but I admit this is not an elegant solution. It is in theory possible to adjust the amount of writing with UnplayedBufferSize, but this would not be a long-term solution.
I'm OK to give a way to adjust the buffer size. My thoughts are:

Adjusting the buffer size for each player would be ideal rather than the global context buffer size. Do you think this works?
I don't want Oto to guarantee the behavior when the buffer size is adjusted. So even if glitches happen, this is the user's responsibility.
Does a small amount of buffers work on browsers well?

Thanks,

I think that works for me -- do you have a code example for adjusting the pace wth UnplayedBufferSize actually, in case I'm missing something here?
Adjusting the buffer size at the per-player level works for me. I'm not sure what the behavior on browsers is, unfortunately.

I'll try to implement SetBufferSize for each player tomorrow.
@bigfarts Thank you for suggesting the prototype and explaining the situation, and @tinne26 thank you for the discussion in Discord!

Thank you so much! I'll close this PR.

@bigfarts Could you try 585752ada4316d230840ee3e20e415547b9fec07? Unfortunately we cannot modify Player interface, but you can use type-assersion like
p := context.NewPlayer(src)
p.(oto.BufferSizeSetter).SetBufferSize(4096)

Thanks,

Thanks, it works!

authors: bigfarts hajimehoshi

repo: hajimehoshi/oto


text:
Support the try ... except ImportError pattern

unimport doesn't seem to recognize this common pattern:
try:
    from django.core.handlers.wsgi import get_script_name
except ImportError:
    # django.VERSION < (1, 7)
    from django.core.handlers.base import get_script_name

If the initial import fails with ImportError, the second will be used. In this case, unimport flags the first import attempt as unused.

I think we should skip such imports. Because if it is controlled with ImportError, we do not know what purpose it is written for.


text:
macOS iterm2 won't display proper color codes in zsh / bash

Any help is greatly appreciated!

Hi there @tallinn-code,
You'll need to upgrade bash on your Mac OS system. Apple, due to licensing problems ships an outdated version of bash on Mac OS. You can very easily upgrade bash on Mac OS. Here is a nice tutorial that will help you upgrade bash,
Upgrade to bash 4 in Mac OS
Cheers!!!

Thank you for support! Now it's working, brew installation of bash v.4 went just fine.

Great!!!
Cheers!!!

authors: hakerdefo tallinn-code

repo: hakerdefo/pmrp


text:
Add spin.js as dependency in package.json

Something like this:
"dependencies": {
  "spin": "~1.3.0"
},
"volo": {
  "url": "https://raw.github.com/hakimel/Ladda/{version}/js/ladda.js",
  "dependencies": {
    "spin": "fgnass/spin.js/~1.3"
  }
},

spin.js is listed as a dependency in package.json, so I don't think this issue is relevant anymore.

authors: rafi theodorejb

repo: hakimel/Ladda


text:
fix: correct null-termination at the end of string values

Fix to null-termination at the end of created string values. Fixes #21

Codecov Report
All modified and coverable lines are covered by tests :white_check_mark:

Project coverage is 85.98%. Comparing base (612c8a4) to head (d45e141).

Additional details and impacted files
@@           Coverage Diff           @@
##             main      #22   +/-   ##
=======================================
  Coverage   85.98%   85.98%
=======================================
  Files           7        7
  Lines         214      214
=======================================
  Hits          184      184
  Misses         30       30

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

Nice catch! I plan to publish a new version with this fix tomorrow. Thank you for contributing!


text:
Continually calling Api.Text in a loop - eventually crashes.

My algorithm does this:

Initialises the API
Begins an endless loop with the body:

                           _Api.SetImage(filePath)
                            .ContinueWith((t) =>
                            {
                                RunOnUiThread(() =>
                                    {
                                        _OcrText.Text = _Api.Text;
                                    });
                            });

After a few seconds of execution, there is an exception tfrom within the  _Api.Text method. Do you have any existing test coverage for this scenario - i.e one that calls _API.Text many times on the same API instance?

No, I haven't implemented any tests for the lib yet. Shame on me. So all my testing is pure manual. Could you please give more extended sample of your code as at the moment it work's fine for me.

Sure - here is the complete android activity I am running!
https://gist.github.com/dazinator/e0ee587676a6ff454e9b

and I also just added the corresponding axml layout to that gist.

I created sample for camera preview recognition https://github.com/halkar/Tesseract.Xamarin/tree/android-camera-preview-sample
I managed to work directly with byte array received from the camera without saving data to file.
The only problem is that I don't know how to work with camera preview. I'm a little bit lazy, so I decided not to use queue but just to skip images received while recognitions is working.
So I found one problem - calling SetImage during recognition crashes the application - so for now avoid that, I'll try to fix it the next update.

Brilliant stuff! I'll take a look at that now! Thank you for looking into this so quickly!

I've updated framework and the sample project. BTW, it's better to use TesseractApi.Results (PageIteratorLevel.Block) method instead of TesseractApi.Text to get more information about results.

authors: dazinator halkar


text:
Vcf format shuffle

Fix bug where FORMAT field definition could change ordering while genotypes were cached.

Coverage increased (+0.01%) to 82.836% when pulling 649cc160f562d0d3cbf2a689be9c1a665f1ad7e5 on vcf_format_shuffle into 7f6b610f2463fd0dd65cc82299d1317a65b66cb3 on develop.

authors: coveralls ernfrid

repo: hall-lab/svtools


text:
🛑 DBA1 is down

In c279c3b, DBA1 (https://dba1.jenshamann.solutions) was down:

HTTP code: 0
Response time: 0 ms

Resolved: DBA1 is back up in 9e9e9a1 after 14 minutes.

repo: hamannjens/upptime


text:
⚠ ClamAV has degraded performance

In 5fedb50, ClamAV (https://spamassassin.apache.org/) experienced degraded performance:

HTTP code: 200
Response time: 207 ms

Resolved: ClamAV performance has improved in 6b7a9a6 after 12 minutes.

repo: hamboneZA/caffeine


text:
⚠ ClamAV has degraded performance

In 8573aee, ClamAV (https://spamassassin.apache.org/) experienced degraded performance:

HTTP code: 200
Response time: 102 ms

Resolved: ClamAV performance has improved in f60eb39 after 5 minutes.


text:
⚠ ClamAV has degraded performance

In dcede0a, ClamAV (https://spamassassin.apache.org/) experienced degraded performance:

HTTP code: 200
Response time: 245 ms

Resolved: ClamAV performance has improved in 0a44265 after 5 minutes.


text:
⚠ ClamAV has degraded performance

In 619f097, ClamAV (https://spamassassin.apache.org/) experienced degraded performance:

HTTP code: 200
Response time: 75 ms

Resolved: ClamAV performance has improved in 55dc531 after 5 minutes.


text:
⚠ ClamAV has degraded performance

In 26a037b, ClamAV (https://spamassassin.apache.org/) experienced degraded performance:

HTTP code: 200
Response time: 77 ms

Resolved: ClamAV performance has improved in 54d0570.


text:
⚠ ClamAV has degraded performance

In f622f3b, ClamAV (https://spamassassin.apache.org/) experienced degraded performance:

HTTP code: 200
Response time: 606 ms

Resolved: ClamAV performance has improved in cd766aa.


text:
⚠ ClamAV has degraded performance

In 5930345, ClamAV (https://spamassassin.apache.org/) experienced degraded performance:

HTTP code: 200
Response time: 87 ms

Resolved: ClamAV performance has improved in 84ab9cd.


text:
⚠ ClamAV has degraded performance

In 5f235f6, ClamAV (https://spamassassin.apache.org/) experienced degraded performance:

HTTP code: 200
Response time: 122 ms

Resolved: ClamAV performance has improved in 0df3377.


text:
⚠ ClamAV has degraded performance

In 5c9c052, ClamAV (https://spamassassin.apache.org/) experienced degraded performance:

HTTP code: 200
Response time: 51 ms

Resolved: ClamAV performance has improved in 18c1728.


text:
⚠ ClamAV has degraded performance

In 5b1039d, ClamAV (https://spamassassin.apache.org/) experienced degraded performance:

HTTP code: 200
Response time: 72 ms

Resolved: ClamAV performance has improved in 375e2fa.


text:
is rethinkdb-elixir production ready?

can we use rethinkdb-elixir in production? when can we expect rethinkdb-elixir 1.0 release?

@ashwinreddymekala FWIW i've been using it in production in two apps with great results 👍

@AdamBrodzinski It's good to hear that you are using in production with great results.
as README says The goal for 1.0.0 is to be stable. is version 0.4.0 unstable?

@ashwinreddymekala it is stable, its waiting for its last API change from its current response structure to :ok and :error tuple

Thanks for all your responses guys I don't see any reason to still open this issue.

repo: hamiltop/rethinkdb-elixir


text:
zig knucleotide - single threaded

followed the 8.rs solution pretty closely.
uses a custom HashMap context although i'm not sure it does much.
my big bottleneck for this was reading.  i was seeing really slow
readInput() time before switching to a io.bufferedReader.
reuses the same map instance calling clearRetainingCapacity() to
save on allocations.

Looks like counts are just slightly off
--- bench/algorithm/knucleotide/25000_out	2022-07-13 19:32:57.430884840 -0700
+++ act.txt	2022-07-16 00:25:34.423572205 -0700
@@ -9,7 +9,7 @@
 TT 9.060
 CA 6.014
 GA 5.996
-AG 5.993
+AG 5.994
 AC 5.988
 TG 5.987
 GT 5.967

Not sure why though. Looks like an extra AG:
AG 5.994 - count / total 7492/125000
But it should be:
AG 5.994 - count / total 7491/125000
:thinking:


text:
speed up javascript generator

Await is not necessary in generator.

This is coroutine benchmark, usage of generator aka simi-coroutine is not allowed

This is coroutine benchmark, usage of generator aka simi-coroutine is not allowed

But originally coroutine exection should not return the end of body. So usage of yield value  is the feature of generator.
AsyncGenerator without await in the body doesn't have any difference from basic generator.

authors: hanabi1224 lohaswinner tocque


text:
Create Hanami::DB::Repo

[x] Use Hanami::SliceConfigurable to find the "db.rom" registration for the given slice's container and inject it as a dependency.
[x] Configure the struct_namespace to be app_or_slice::Structs (dynamically define the module if needed)
[x] If a matching relation can be found, configure it as the repo's root relation

Fixed by https://github.com/hanami/db/pull/6, https://github.com/hanami/db/pull/8, https://github.com/hanami/hanami/pull/1410, https://github.com/hanami/hanami/pull/1412

repo: hanami/db


text:
Subfinder如何添加Source key

rt

很抱歉，目前还不支持直接添加自定义的source key，可以参照github.com/projectdiscovery/subfinder直接修改代码添加。
如果有功能需求，后面可以将该功能增加进来。

建议在后台可以自定义添加Source key，不带key和带key获取的域名数量明显对比

没问题，近期将该功能代码增加到系统里。

v2.4.18已更新添加provider-config.yml文件增加自定义的source key，使用方法参见https://github.com/projectdiscovery/subfinder#post-installation-instructions。


text:
while trying to run training on custom dataset [Rolodex] for detection, it is failing with signal 6 abort , please help me resolve this.

To report a bug, please provide the following:

the output of the darknet version command

Darknet v2.0-226-g39868921
CUDA runtime version 12020 (v12.2), driver version 12020 (v12.2)
cuDNN version 12020 (v8.9.6), use of half-size floats is ENABLED
=> 0: Tesla T4 [#7.5], 14.7 GiB
OpenCV v4.5.4

the exact command you ran

!darknet detector train  Rolodex.data rolo.cfg yolov4-tiny.weights Rolodex.names

the operating system you are using

Google colab/kaggle notebook with GPU enabled Linux
If relevant, please attach a screenshot showing the problem.
please find the below screen shot of same error .

Note the command you ran is invalid.  The proper training command is documented in the FAQ and in the README.  See:  https://www.ccoderun.ca/programming/yolo_faq/#training_command

Thanks for your quick response @stephanecharette , it was because -dont_show argument missing in train command .
Thanks again !! 😄

Thanks for your quick response @stephanecharette , it was because -dont_show argument missing in train command . Thanks again !! 😄

No, that is not the problem.  Please see the training command as documented in the readme or in the FAQ.

I already told you -- twice! -- that you are running an invalid command.  I cannot help you if you refuse to read.
Please read the FAQ and/or read the README which tells you the command you should be running.

Thanks again @stephanecharette  ,training is successful ..second issue was because of corrupt dataset .Request you to add a feature to export  it to onnx format .💐

repo: hank-ai/darknet


text:
HanLP2.1分词时大量文本会报错：RuntimeError: expected scalar type Float but found Long

Describe the bug
我在用HanLP2.1分词时会遇到大量文本报错：RuntimeError: expected scalar type Float but found Long
很多长文本分词时会报这个错。。
谷歌搜了半天，都说是pytorch里的代码问题，不确定是不是源码的问题，还是我这边的原因导致。。
Code to reproduce the issue
完整代码如下
import hanlp

HanLP = hanlp.load(hanlp.pretrained.mtl.CLOSE_TOK_POS_NER_SRL_DEP_SDP_CON_ELECTRA_SMALL_ZH) # 世界最大中文语料库
tok = HanLP[‘tok/coarse’]

# 读取自定义词表
beauty_vocab = set()
with open(’…/data/userdict.txt’, ‘r’, encoding=‘utf-8’) as fin:
    for line in fin:
        beauty_vocab.add(line.strip())
tok.dict_combine = beauty_vocab

text = ‘我最心水的那些 红：对口红这种东西真的是毫无抵抗力啊 每次入了新色就在蓝朋友手臂上试 他总会说 女生到底需要有多少口红啊 身为一个直男可能真的不懂 红有一百种 哈哈哈哈 言归正传 阿玛尼红管501 503 504 阿玛尼红管真的是我最爱的唇釉了 入的第一支是504 第一次用就被惊艳到了 竟然有这么丝滑的唇釉 完全是奶油慕斯质地 还呈现很高级的哑光感 真的是超爱 爱不释手 后来又相继收了501和503 以后一定还会继续收 喜爱程度 ysl方管17 13 17是我春夏用的最多次的一支 几乎每天都在用 不知道今天擦什么的时候就用它 准没错 一个夏天过去就下去了一大截 喜爱程度 13是后期入的 相比17利用率就没有那么高 怎么说呢 13还是有些挑皮的 素颜涂肯定是土爆了 喜爱程度 mac子弹头 see sheer也是我的心头爱 刚买的时候每天都放包里 随时补 超级滋润 颜色炒鸡日常 上班涂完全不会显得突兀 超爱 喜爱程度 chill小辣椒 也是超爱的一支 怎么涂都好看 毫不夸张 秋冬不知道涂啥时 擦它总不会出错 喜爱程度 雅诗兰黛love系列 300橘红色 310梅子色 都是我爱的颜色 很显白 喜爱程度 阿玛尼小胖丁504 大名鼎鼎的奶油橘 各种被夸 扛不住风种草的 但是！真的没有那么好 好吗 无论后涂薄涂感觉都不是很满意 我通常是叠加哑光其他口红上面用 喜爱程度 tf16 风老大的番茄色 忍不住入的 但是使用率很低 不知道为啥 可能不够日常 也可能是不舍得用 偷笑R 喜爱程度 香奈儿58 也是跟风入的 据说各种适合秋冬 适合黄皮 毫不犹豫拿下 but有点斯望 并不是很好驾驭啊 而且感觉不显白！ 喜爱程度 ysl黑管402 这只是盲选的 适合春夏 感觉一般 中规中矩 喜爱程度 ysl镜面唇釉09 水红色 颜色不错 但是但是 这个唇釉的质地我真的是爱不起来 不能抿嘴 粘粘的 很不好上均匀 喜爱程度 3ce 南瓜色116 干！巨干！炒鸡干！根本不能用 买之前被颜色吸引 很多人都说它很干 我心想 再干能干成啥样 前一天晚上做唇膜 早晨先用唇部打底再涂 上班不到两小时 嘴就干到起皮 南瓜色口红很多 千万别买这一支 喜爱程度 最后说一句 本人黄皮 唇色浅 干起皮唇纹重 借蓝票的胳膊试色 仅供参考 第一次写这么长的笔记 手指断了 好了就酱 叹气R’

cut_res = HanLP([text])[‘tok/coarse’][0]
print(cut_res)

Describe the current behavior
代码如上，碰到非常多如上的text文本，分词就会报错
Expected behavior
还请教原作者，如何解决这个问题。。万分感谢！
System information

OS Platform and Distribution (e.g., Linux Ubuntu 16.04):
mac OS 10.15.7

Python version:
python 3.9.2

HanLP version:
hanlp==2.1.0a20
hanlp-common==0.0.6
hanlp-trie==0.0.2
torch==1.7.1

Other info / logs
完整的报错信息如下：
Traceback (most recent call last):
File “/Users/river/Desktop/1-tag-recall/note-tag/optimization/src/preprocess.py”, line 27, in
cut_res = HanLP([text])
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/components/mtl/multi_task_learning.py”, line 768, in call
return super().call(data, batch_size, **kwargs)
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/torch/autograd/grad_mode.py”, line 26, in decorate_context
return func(*args, **kwargs)
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/common/torch_component.py”, line 629, in call
return super().call(data, **merge_dict(self.config, overwrite=True,
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/common/component.py”, line 36, in call
return self.predict(data, **kwargs)
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/components/mtl/multi_task_learning.py”, line 512, in predict
output_dict = self.predict_task(self.tasks[task_name], task_name, batch, results, output_dict,
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/components/mtl/multi_task_learning.py”, line 590, in predict_task
output_dict, batch = self.feed_batch(batch, output_key, output_dict, run_transform, cls_is_bos, sep_is_eos,
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/components/mtl/multi_task_learning.py”, line 682, in feed_batch
‘output’: task.feed_batch(h,
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/components/mtl/tasks/init.py”, line 182, in feed_batch
return decoder(h, batch=batch, mask=mask)
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/torch/nn/modules/module.py”, line 727, in _call_impl
result = self.forward(*input, **kwargs)
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/components/mtl/tasks/ner/tag_ner.py”, line 35, in forward
contextualized_embeddings = self.secondary_encoder(contextualized_embeddings, mask=mask)
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/torch/nn/modules/module.py”, line 727, in _call_impl
result = self.forward(*input, **kwargs)
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/layers/transformers/relative_transformer.py”, line 310, in forward
x = layer(x, mask)
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/torch/nn/modules/module.py”, line 727, in _call_impl
result = self.forward(*input, **kwargs)
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/layers/transformers/relative_transformer.py”, line 264, in forward
x = self.self_attn(x, mask)
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/torch/nn/modules/module.py”, line 727, in call_impl
result = self.forward(*input, **kwargs)
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/layers/transformers/relative_transformer.py”, line 150, in forward
D = torch.einsum(‘nd,ld->nl’, self.r_w_bias, pos_embed)[None, :, None] # head x 2max_len, 每个head对位置的bias
File “/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/torch/functional.py”, line 344, in einsum
return _VF.einsum(equation, operands) # type: ignore
RuntimeError: expected scalar type Float but found Long

[x] I've completed this form and searched the web for solutions.

感谢反馈，已经修复，请参考上面的commit。
如果还有问题，欢迎重开issue。
顺便有个建议，如果你只需要分词，可以用
HanLP('商品和服务', tasks='tok/coarse')

这样速度更快。另外，如果你只有一个句子，可以直接传入：
HanLP(text)

感谢反馈，已经修复，请参考上面的commit。
如果还有问题，欢迎重开issue。
顺便有个建议，如果你只需要分词，可以用
HanLP('商品和服务', tasks='tok/coarse')

这样速度更快。另外，如果你只有一个句子，可以直接传入：
HanLP(text)

您好，感谢及时的回复！谢谢作者！
但我刚刚重新pip install hanlp -U 之后，再运行同样的代码，会报如下新的错误，说是无法load模型，但我之前已经下载过这个模型到我本地了：
(base) river@riverdeMacBook-Pro mtl % ll
total 0
drwxr-xr-x   3 river  staff   96  2 23 01:21 ./
drwxr-xr-x   4 river  staff  128  2 22 21:36 ../
drwxr-xr-x  13 river  staff  416  2 22 22:10 close_tok_pos_ner_srl_dep_sdp_con_electra_small_20210111_124159/
完整报错信息如下：
Failed to load https://file.hankcs.com/hanlp/mtl/close_tok_pos_ner_srl_dep_sdp_con_electra_small_20210111_124159.zip. See traceback below:
================================ERROR LOG BEGINS================================
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/utils/component_util.py", line 81, in load_from_meta_file
obj.load(save_dir, verbose=verbose, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/common/torch_component.py", line 183, in load
self.to(devices)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/common/torch_component.py", line 519, in to
devices = cuda_devices(devices)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/utils/torch_util.py", line 73, in cuda_devices
query = gpus_available()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/hanlp/utils/torch_util.py", line 46, in gpus_available
nvmlShutdown()
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pynvml/nvml.py", line 772, in nvmlShutdown
fn = get_func_pointer("nvmlShutdown")
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/pynvml/nvml.py", line 387, in get_func_pointer
raise NVMLError(NVML_ERROR_UNINITIALIZED)
pynvml.nvml.NVMLError_Uninitialized: Uninitialized
=================================ERROR LOG ENDS=================================
Please upgrade hanlp with:
pip install --upgrade hanlp
If the problem still persists, please submit an issue to https://github.com/hankcs/HanLP/issues
When reporting an issue, make sure to paste the FULL ERROR LOG above.

感谢反馈，已经修复，请参考上面的commit。
如果还有问题，欢迎重开issue。
是另一个补丁引发了这个问题。

repo: hankcs/HanLP


text:
Crf分词结合ngram词典不能取得理想结果

@hanks, 你好。
关于下列输入
CRFSegment segment = new CRFSegment().;
segment.enableCustomDictionary(true);
List seg = segment.seg("哪些药产自上海");
一直出现不理想的分词结果
[哪些/r, 药产/nz, 自/p, 上海/ns]
理想的结果是 [哪些/r, 药/n,产自/v, 上海/ns]
已经按照您在其他issue里面说的修改了核心词典CoreNatureDictionary.mini.txt
其中包含（产自	v	999）新增，（药	n	41	v	1）药这个词是原来就有的
也修改了CoreNatureDictionary.ngram.mini.txt
（药@产自 10000）新增，
并且在自定义词典CustomDictionary.txt中新增（产自 v 999）
删除所有缓存，并且运行，还是出现[哪些/r, 药产/nz, 自/p, 上海/ns]结果
不知道我哪里做的不对，或者缺少了哪些步骤，还请务必告知
非常感谢！
@TylunasLi

版本号是1.3.2，差点忘了

我刚才仔细看了貌似源代码中没有对于crf分词修正的内容。

BiGram模型只作用于基于词图的分词方法，在HanLP里面是 Viterbi最短路分词、Dijkstra最短路分词、N-最短路分词三种。
CRF分词采用“由字构词”的策略，本身并没有涉及到Bigram模型，也不能如BiGram类算法一般简单地调整参数，只能重新训练。
请了解相关算法大致原理再来看如何调整。

谢谢你的解答

authors: TylunasLi kelciej


text:
Adding Jan and Feb radar charts

Per #1 I have added radar charts for the current two months. This is a manual process for now but I hope to make it automatic in the future!

Updated main to include GH actions. This will automatically update the radar charts each time a new commit is made.
In addition to adding new post files (i.e. january.md) - contributors must also add an entry in docs/_data/playlists.yml that follows the current convention. This was done to help parameterize the blog and the insertion of the radar plots.

This is great, thanks so much!!! (Note that it is now live. :) )
As discussed irl (!), pulled this PR's script in via #4 and decided to run it manually when adding a new month (rather than using github actions).


text:
关于 bind 你可能需要了解的知识点以及使用场景

不看不知道，一看吓一跳，已经整整一个月没有更新 underscore 源码解读系列文章了。前面我们已经完成了  Object ，Array，Collection 上的扩展方法的源码剖析，本文开始来解读 Function 上的扩展方法。
完整的 underscore 源码解读系列文章请移步 https://github.com/hanzichi/underscore-analysis，觉得还阔以的话，给个 star 鼓励下楼主呗 ^_^
bind 简介
Ok，今天要讲的正是 bind。关于 bind，可以先移步楼主以前写的文章 ECMAScript 5(ES5) 中 bind 方法简介备忘，有个基本的概念。
bind() 方法会创建一个新函数，当这个新函数被调用时，它的 this 值是传递给 bind() 的第一个参数, 它的参数是 bind() 的其他参数和其原本的参数。
语法是这样样子的：
fun.bind(thisArg[, arg1[, arg2[, ...]]])

thisArg 当绑定函数被调用时，该参数会作为原函数运行时的 this 指向。当使用 new 操作符调用绑定函数时，该参数无效。
arg1, arg2, ... （可选）当绑定函数被调用时，这些参数加上绑定函数本身的参数会按照顺序作为原函数运行时的参数。

参数
bind 的第一个参数会作为原函数运行时的 this 指向，不多说；而第二个开始的参数是可选的，当绑定函数被调用时，这些参数加上绑定函数本身的参数会按照顺序作为原函数运行时的参数。怎么理解？
function fn(a, b, c) {
  return a + b + c;
}

var _fn = fn.bind(null, 10);
var ans = _fn(20, 30); // 60

fn 函数需要三个参数，_fn 函数将 10 作为默认的第一个参数，所以只需要传入两个参数即可，如果你不小心传入了三个参数，放心，也只会取前两个。
function fn(a, b, c) {
  return a + b + c;
}

var _fn = fn.bind(null, 10);
var ans = _fn(20, 30, 40); // 60

这有啥用呢？如果某些函数，前几个参数已经 “内定” 了，我们便可以用 bind 返回一个新的函数。也就是说，bind() 能使一个函数拥有预设的初始参数。这些参数（如果有的话）作为 bind() 的第二个参数跟在 this 后面，之后它们会被插入到目标函数的参数列表的开始位置，传递给绑定函数的参数会跟在它们的后面。
function list() {
  return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]

// Create a function with a preset leading argument
var leadingThirtysevenList = list.bind(undefined, 37);

var list2 = leadingThirtysevenList(); // [37]
var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3]

new
使用 bind 返回的结果还是个 function，是个 function 就可以被 new 运算符调用，那么结果呢？规范中说的很清楚了，当使用 new 操作符调用绑定函数时，bind 的第一个参数无效。
function Person(name, age) {
  this.name = name;
  this.age = age;
}

var _Person = Person.bind({});
var p = new _Person('hanzichi', 30); // Person {name: "hanzichi", age: 30}

一般我们不会去这么用，但是如果要写个 bind 的 polyfill（http://caniuse.com/#search=bind），还是需要考虑用 new 调用的情况。
我们也可以设置默认值（参考上一小节），原先提供的那些参数仍然会被前置到构造函数调用的前面。
function Person(name, age) {
  this.name = name;
  this.age = age;
}

var _Person = Person.bind(null, 'hanzichi');
var p = new _Person(30); // Person {name: "hanzichi", age: 30}

配合 setTimeout
什么时候容易丢失 this 指向？恩，setTimeout 是一个场景，很容易把 this 指向 window，当然，setInterval 也是一样。当使用对象的方法时，需要 this 引用对象，你可能需要显式地把 this 绑定到回调函数以便继续使用对象。
var canvas = {
  render: function() {
    this.update();
    this.draw();
  },

  update: function() {
    // ...
  },

  draw: function() {
    // ...
  }
};

window.setInterval(canvas.render, 1000 / 60);

用 canvas 写特效或者做游戏时经常会碰到类似的问题。上面的代码是有问题的，render 方法中的 this 其实被指向了 window！我们可以用 bind，显式地把 this 绑定到回调函数以便继续使用该对象。
window.setInterval(canvas.render.bind(canvas), 1000);

类似的情况还有 dom 的事件监听，一不小心可能 this 就被指向了 dom 元素。可以参考下以前做 bigrender 时写的这部分代码 https://github.com/hanzichi/hanzichi.github.io/blob/master/2016/bigrender/js/bigrender.js#L179-L184。
tip
bind 还能做一些有意思的事情。
通常来说，将一个类数组转为数组，我们会用 slice（ie9- 不支持）。参考 https://github.com/hanzichi/underscore-analysis/issues/14
var slice = Array.prototype.slice;

// slice.apply(arguments);
// slice.call(arguments, 1);

bind 能让调用变的更加简单。
// same as "slice" in the previous example
var unboundSlice = Array.prototype.slice;
var slice = Function.prototype.call.bind(unboundSlice);

// ...

slice(arguments);
// slice(arguments, 1);

再举个类似的例子，比如说我们要添加事件到多个节点，for 循环当然没有任何问题，我们还可以 “剽窃” forEach 方法：
Array.prototype.forEach.call(document.querySelectorAll('input[type="button"]'), function(el){
  el.addEventListener('click', fn);
});

更进一步，我们可以用 bind 将函数封装的更好：
var unboundForEach = Array.prototype.forEach
  , forEach = Function.prototype.call.bind(unboundForEach);

forEach(document.querySelectorAll('input[type="button"]'), function (el) {
  el.addEventListener('click', fn);
});

同样类似的，我们可以将  x.y(z) 变成 y(x,z) 的形式：
var obj = {
  num: 10,
  getCount: function() {
    return this.num;
  }
};

var unboundBind = Function.prototype.bind
  , bind = Function.prototype.call.bind(unboundBind);

var getCount = bind(obj.getCount, obj);
console.log(getCount());  // 10

再举个栗子。每隔一秒在控制台打印 1-5，看起来是道考察闭包的经典题目。
for(var i = 1; i <= 5; i++) {
  !function(i) {
    setTimeout(function() {
      console.log(i);
    }, i * 1000);
  }(i);
}

ES6 下能用 let：
for(let i = 1; i <= 5; i++) {
  setTimeout(function() {
    console.log(i);
  }, i * 1000);
}

也可以用 bind，瞬间逼格提升：
for(var i = 1; i <= 5; i++) {
  setTimeout(console.log.bind(console, i), i * 1000);
}

2016-08-30 add：好吧，setTimeout 还能传入第三个参数，又涨姿势了 ...
for (var i = 1; i <= 5; i++) {
  setTimeout(function(num) {
    console.log(num)
  }, i * 1000, i);
}

Read more
关于 bind 的介绍就到这里，下一篇文章将结合 underscore 来讲讲如何实现一个 bind 的 polyfill。

Function.prototype.bind()
ECMAScript 5(ES5) 中 bind 方法简介备忘
Javascript 中的 Bind ，Call 以及 Apply
Javascript 中 bind() 方法的使用与实现
在 JavaScript 中借用方法

var unboundBind = Function.prototype.bind
  , bind = Function.prototype.call.bind(unboundBind);

请问为什么可以这样使用，这样使用有什么好处呢？
function bind3(func,context){
    return func.bind(context);
}

bind 和  bind3  是等效的吗？

Function.prototype.bind = Function.prototype.bind || function(context) {
var that = this;
return function() {
// console.log(arguments); // console [3,4] if ie<6-8>
return that.apply(context, arguments);
}
}`
这个在你es5 bind 那篇文章里的code 很confusing，其实真正的实现方法是
Function.prototype.bind = Function.prototype.bind || function(context){ 	var that = this; 	var args = Array.prototype.slice.call(arguments) 	return function(){ 		return that.apply(context, args.concat(Array.prototype.slice.call(arguments)); // that is function 	} }

authors: Arvinzhu hanzichi seaskymonster

repo: hanzichi/underscore-analysis


text:
Tags not being set with list.UpdateUser

I'm trying to update a users tags, I don't get an error but the tags are not being updated:
	req := &gochimp3.MemberRequest{
		EmailAddress: "montana@mathpix.com",
		Tags:         []string{"verified"},
	}

	m, err := list.UpdateMember("a36670ebcefcd9800c286cfbb101888f", req)
	if err != nil {
		fmt.Printf("Failed to update members %q\n", listID)
		os.Exit(1)
	}

	fmt.Printf("%+v\n", m)

Related: https://github.com/hanzoai/gochimp3/pull/31 cc @zeekay

I'm getting the same issue here.

Looks like the mailchimp api doesn't support tags for updates :( https://mailchimp.com/developer/reference/lists/list-members/#create-post_lists_list_id_members

@royalgiant I see tags at the bottom of the Request Body Parameters section.

@royalgiant I see tags at the bottom of the Request Body Parameters section.

Check under the "EDIT" instead of the "CREATE" section

This is very odd, tags is clearly on the Member request object with the correct parameter name.
https://github.com/hanzoai/gochimp3/blob/1023e7b1d6cf04f637b531a237e9b2a4bbe51459/members.go#L26

This is very odd, tags is clearly on the Member request object with the correct parameter name.
https://github.com/hanzoai/gochimp3/blob/1023e7b1d6cf04f637b531a237e9b2a4bbe51459/members.go#L26

@davidtai problem is I don't think Mailchimp accepts tags for edit members

@royalgiant thanks, I was looking at CREATE and not EDIT.
I found this which could possibly be used:
https://mailchimp.com/developer/reference/lists/list-members/list-member-tags/

@montanaflynn @davidtai You're going to kiss me for this.
// struct for Mailchimp's member tags
type MailChimpTags struct {
	Name   string `json:"name"`
	Status  string `json:"status"` // 2 options: 'active' and 'inactive' to add and remove tags respectively
}

var member_tags []MailChimpTags

member_tags = append(member_tags, MailChimpTags{Name: fill_in_name, Status: "active"})

endpoint := fmt.Sprintf("/lists/%s/members/%s/tags", fill_in_list, fill_in_email_address)

// errorz variable because i'm a gangster. :)
if errorz := client.Request("POST", endpoint, nil, map[string]interface{}{"tags": member_tags}, nil); errorz != nil {
			log.Println("the err %v", errorz)
		}

That's what worked for me. Let me know if it helps.

@royalgiant 😚
client := gochimp3.New(apiKey)

type MailChimpTags struct {
    Name   string `json:"name"`
    Status string `json:"status"` // 2 options: 'active' and 'inactive' to add and remove tags respectively
}

var memberTags []MailChimpTags

for _, tag := range tags {
    memberTags = append(memberTags, MailChimpTags{Name: tag, Status: "active"})
}

loweredEmail := strings.ToLower(email)
md5Sum := fmt.Sprintf("%x", md5.Sum([]byte(loweredEmail)))

endpoint := fmt.Sprintf("/lists/%s/members/%s/tags", listID, md5Sum)

err := client.Request("POST", endpoint, nil, map[string]interface{}{"tags": memberTags}, nil)
if err != nil {
    return err
}

authors: davidtai montanaflynn royalgiant


text:
Great project， but the memory usage is too big.

Describe the bug
hen I do inference with tensorrt(torch2trt), the memory need 3.5G(not calibration), it's too big for me, could you tell me how to reduce the memory usage? Thank you!
To Reproduce
Just run acoording to README;
Expected behavior
Reduce the
Full logs
If applicable, add full logs to help explain your problem.
Environment:

OS: [Ubuntu 18.04]
GPU: [Jetson Xavier NX]
CUDA Version [10.2]

Additional context
Add any other context about the problem here.

My mistakes

Loking for your reply! Thank you!

@haotian-liu

Hi, you could try reducing the calibration image dataset, reduce the image size, or use the FP16 only (which does not require calibration).

Hi, you could try reducing the calibration image dataset, reduce the image size, or use the FP16 only (which does not require calibration).

Thanks for your reply! I have reduced the calibration image dataset is not work,  the FP16 only mode also need 3.5G, if reduce the image size, it will reduce the performence;

Maybe you can try to convert each module to TensorRT separately, load the converted module later and run. This might require some extra code modification on your side. Thanks!

I am closing this issue for now due to inactivity. If there are any further questions that I could help with, please feel free to reopen, thanks.

authors: Byronnar haotian-liu


text:
Possible to get rid off regression head?

Bear with me for opening the issue for suggestions, I didn't see a discussion tab in the repository.
For my task, I only need per-frame classification labels, but in your method calculation of class/label for each frame is tightly coupled with the ranges. For example, label_points_single_video() takes in the gt_class (N) and gives us back cls_targets (T * C) classification labels for each FPN level point where N is a number of events/actions, T is the total number of points at all FPN levels and C is a total number of classes.
Given ground truth without ranges, I was thinking of adding arbitrary range e.g. convert gt class label at time t [c] -> [c, t-delta, t+delta]. I would get rid of the regression head and the regression loss. I thought this would be reasonable to do, but I am not very certain if it would correct with all the handling of FPN levels in ground truth for supervision and later in inference too. Would this be reasonable to do, what do you think?

The task you have described (labeling every frame) is referred to as action segmentation. This is distinct from action localization (as addressed in this repo). If we take 2D images as an analogue, action segmentation is akin to semantic segmentation, where action localization is like object detection. The key difference between the two lies in the identification of individual instances.
These two tasks are indeed related, yet they employ different sets of methods. While it is possible to re-purpose this repo for action segmentation, I'd recommend those methods designed for the task.

Thanks for the inputs.

This is not true. Let us construct the following example. Say the input video contains two actors, A and B. Actor A is performing action 1 from time step 1-4, actor B is performing the same action 1 from time step 2-5.

Action segmentation seek to label time step 1-5 as action 1.
Action localization aims at identifying two instances of action 1, one from time step 1-4 and other from 2-5.

Got it. Thanks.

authors: bhosalems happyharrycn


text:
All I/O must happen through recvmsg, with room for a cmsg

I think that explains the mysterious ERRNO=5 Input/Output errors we've all been seeing intermittently.
It's that little load-bearing sentence from the Linux kTLS docs:

If no cmsg buffer is provided, an error is returned if a control message is received.

I'm going to test my theory but for now I believe if a control message is received (such as a TLS 1.3 session ticket) then we get this error:
--- STDERR:              ktls::integration_test ktls_client_rustls_server_tls_1_3_aes_256_gcm ---
thread 'ktls_client_rustls_server_tls_1_3_aes_256_gcm' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 5, kind: Uncategorized, message: "Input/output error" }', tests/integration_test.rs:346:39
stack backtrace:

However if we configure the server not to send session tickets, like so:
    server_config.send_tls13_tickets = 0;

Then the same test passes. The logs show that four tickets are sent by default:

And Wireshark confirms that:

This was closed by #28

repo: hapsoc/ktls


text:
Update aws-connector-settings-reference.md

https://harness.slack.com/archives/CT069SRNJ/p1680874726817199?thread_ts=1680824154.385139&cid=CT069SRNJ
Clarification
Harness Developer Pull Request
Thanks for helping us make the Developer Hub better. The PR will be looked at
by the maintainers.
What Type of PR is This?

[ ] Issue
[ ] Feature
[ x] Maintenance/Chore

If tied to an Issue, list the Issue(s) here:

no Jira. Just a request for one sentence via Slack

House Keeping
Some items to keep track of. Screen shots of changes are optional but would help the maintainers review quicker.

[ ] Tested Locally
[ ] Optional Screen Shoot.

Please check the Execution Link of the Pipeline for the Website Draft URL. This is located in the Preview Step and also is available in #hdh_alerts. E.g Website Draft URL: https://unique-id--harness-developer.netlify.app

authors: bot-gitexp-user michaelcretzman

repo: harness/developer-hub


text:
Update templates-best-practices.md

Harness Developer Pull Request
Thanks for helping us make the Developer Hub better. The PR will be looked at
by the maintainers.
What Type of PR is This?

[ ] Issue
[ ] Feature
[ ] Maintenance/Chore

If tied to an Issue, list the Issue(s) here:

Issue(s)

House Keeping
Some items to keep track of. Screen shots of changes are optional but would help the maintainers review quicker.

[ ] Tested Locally
[ ] Optional Screen Shoot.

Please check the Execution Link of the Pipeline for the Website Draft URL. This is located in the Preview Step and also is available in #hdh_alerts. E.g Website Draft URL: https://unique-id--harness-developer.netlify.app

Please check the Execution Link of the Pipeline for the Website Draft URL. This is located in the Preview Step and also is available in #hdh_alerts. E.g Website Draft URL: https://unique-id--harness-developer.netlify.app

authors: bot-gitexp-user utkarshchoubey-harness


text:
Update shell-script-step.md

Harness Developer Pull Request
Thanks for helping us make the Developer Hub better. The PR will be looked at
by the CODEOWNERS.
What Type of PR is This?

[x] Issue
[ ] Feature
[ ] Maintenance/Chore

If tied to an Issue, list the Issue(s) here:

Issue(s)

House Keeping
Some items to keep track of. Screen shots of changes are optional but would help the maintainers review quicker.

[ ] Tested Locally
[ ] Optional Screen Shoot.

Please check the Execution Link of the Pipeline for the Website Draft URL. This is located in the Preview Step behind the Harness VPN and also is available in #hdh_alerts. E.g Website Draft URL: https://unique-id--harness-developer.netlify.app. Current Draft URL is: https://65707f2b0f894d08bba1c010--harness-developer.netlify.app

authors: bot-gitexp-user sourabh-awashti


text:
Update platform.md

Harness Developer Pull Request
Thanks for helping us make the Developer Hub better. The PR will be looked at
by the CODEOWNERS.
What Type of PR is This?

[ ] Issue
[ ] Feature
[ ] Maintenance/Chore

If tied to an Issue, list the Issue(s) here:

Issue(s)

House Keeping
Some items to keep track of. Screen shots of changes are optional but would help the maintainers review quicker.

[ ] Tested Locally
[ ] Optional Screen Shoot.

Please check the Execution Link of the Pipeline for the Website Draft URL. This is located in the Preview Step behind the Harness VPN and also is available in #hdh_alerts. E.g Website Draft URL: https://unique-id--harness-developer.netlify.app. Current Draft URL is: https://65b2f3b8f3f6e94ddf1b9703--harness-developer.netlify.app

Please check the Execution Link of the Pipeline for the Website Draft URL. This is located in the Preview Step behind the Harness VPN and also is available in #hdh_alerts. E.g Website Draft URL: https://unique-id--harness-developer.netlify.app. Current Draft URL is: https://65b3b8b9fdec1d0e6ccf02e9--harness-developer.netlify.app

Please check the Execution Link of the Pipeline for the Website Draft URL. This is located in the Preview Step behind the Harness VPN and also is available in #hdh_alerts. E.g Website Draft URL: https://unique-id--harness-developer.netlify.app. Current Draft URL is: https://65b3eb8481c5093a03029c60--harness-developer.netlify.app

authors: bot-gitexp-user brian-f-harness


text:
Docker-in-Docker sample don't works

pipeline:
kind: pipeline
spec:
  stages:
  - type: ci
    spec:
      volumes:
      - name: dockersock
        spec: {}
        type: temp
      steps:
      - name: dind
        type: background
        spec:
          container:
            image: docker:dind
            privileged: true
          mount:
          - name: dockersock
            path: /var/run

      - name: test
        type: run
        spec:
          container: docker:dind
          mount:
          - name: dockersock
            path: /var/run
          script: |-
            sleep 5
            docker ps -a

compose.yml
version: '3.3'
services:
    gitness:
        volumes:
            - '/var/run/docker.sock:/var/run/docker.sock'
        cap_add:
            - SYS_ADMIN
            - NET_ADMIN
        privileged: true
        image: harness/gitness

dind logs:
Certificate request self-signature ok
subject=CN = docker:dind server
/certs/server/cert.pem: OK
Certificate request self-signature ok
subject=CN = docker:dind client
/certs/client/cert.pem: OK
ip: can't find device 'ip_tables'
ip_tables 32768 11 iptable_mangle,iptable_nat,iptable_filter
x_tables 40960 26 xt_state,xt_REDIRECT,xt_ipvs,xt_policy,xt_bpf,iptable_mangle,xt_u32,xt_multiport,xt_nat,xt_MASQUERADE,xt_mark,ip6t_REJECT,xt_hl,ip6t_rt,ipt_REJECT,xt_LOG,xt_comment,xt_limit,xt_addrtype,xt_tcpudp,ip6table_filter,ip6_tables,xt_recent,xt_conntrack,iptable_filter,ip_tables
modprobe: can't change directory to '/lib/modules': No such file or directory
mount: permission denied (are you root?)
Could not mount /sys/kernel/security.
AppArmor detection and --privileged mode might break.
mount: permission denied (are you root?)

Unfortunately, I didn't get to solve the issue with Docker in Docker, so I switched to pipeline with caprover cli

repo: harness/gitness


text:
Implement string interpolation.

Now it is possible to use print a numeric variable in the middle of a text line by using ${expression}.

This fixes #21


text:
compilation error where cf-protection=return isn't available

i suspect it has to do with my CPU (AMD Ryzen 5 5600X).
error: option 'cf-protection=return' cannot be specified on this target
error: option 'cf-protection=branch' cannot be specified on this target

my knowledge of llvm is very little ~so i don't know how much of a deal-breaker removing this is, but it compiles nevertheless~ disregard, i tried it, it seems to work fine.
bonus: not worth including this in a separate ticket, but on arch linux you need to add vim to the dependencies since apparently xxd is included there – my excuse for not having vim installed is that i use neovim which apparently doesn't ship xxd.

Oh thanks for pointing out the xxd issue. It is annoying how Arch packages that but oh well. I will update the package list in the README, and also the PKGBUILD for the AUR.
As to your primary problem: I'm not sure what the context is of your error. Is this during the compilation of the eBPF or during the compilation of the main application? Are you adding a flag somewhere to resolve this? Except for enabling compilation warnings I don't really have any build flags in the CMake file.

sorry i should elaborate more as i did some work to fix the PKGBUILD to sort this out. so, i'm not sure where this happen because you don't seem to specify any weird CFLAGS, but for some reason cf-protection=return gets added, and it breaks the build. i edited PKGBUILD to sort it out, but it's a hack and i would not recommend it.
build() {
    cd "$srcdir/ebpfsnitch-$pkgver"
    mkdir build && cd build
    cmake -D CMAKE_INSTALL_PREFIX="/usr/bin" ..
    # the following two lines are the CFLAGS in the cmake cache, minus cf-protection=return
    cmake -D CMAKE_C_FLAGS:STRING="-march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions         -Wp,-D_FORTIFY_SOURCE=2,-D_GLIBCXX_ASSERTIONS         -Wformat -Werror=format-security         -fstack-clash-protection" ..
    cmake -D CMAKE_CXX_FLAGS:STRING="-march=x86-64 -mtune=generic -O2 -pipe -fno-plt -fexceptions         -Wp,-D_FORTIFY_SOURCE=2,-D_GLIBCXX_ASSERTIONS         -Wformat -Werror=format-security         -fstack-clash-protection" ..
   make
}

Hey @myyc I have a follow up.
I had a friend reproduce this on a couple machines I would of expected it to work on so this does not seem to be a weird one off issue. I'll try and get a fix up in the near future.

authors: harporoeder myyc

repo: harporoeder/ebpfsnitch


text:
Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same error when I tried to modify the code to gpu version?

I created this lane_detection file and wrote this:
import argparse
import sys
from time import time, clock
from os.path import splitext, basename, exists

from model import SCNN
from utils.check_extension import is_video, is_image
from utils.transforms import *

# ------------------------------------------------  SCNN parameters
time1 = time()
net = SCNN(input_size=(800, 288), pretrained=False)
mean = (0.3598, 0.3653, 0.3662)  # CULane mean, std
std = (0.2573, 0.2663, 0.2756)
transform_img = Resize((800, 288))
transform_to_net = Compose(ToTensor(), Normalize(mean=mean, std=std))

# ------------------------------------------------  Arguments

def parse_args():
    parser = argparse.ArgumentParser()

    parser.add_argument('--weights', type=str,
                        default='models/vgg_SCNN_DULR_w9.pth',
                        help='path to vgg models')

    parser.add_argument('--input', type=str, default='demo/line_3.mp4',
                        help='path to image file')

    parser.add_argument('--output', type=str, default='public/',
                        help='path to the output directory')
    args = parser.parse_args()

    return args

def main():
    args = parse_args()
    filename, extension = splitext(basename(args.input))

    print("Loading file [{}] ....".format(filename))
    if not exists(args.input):
        print("file [{}] is not recognized".format(args.input))
        sys.exit()

    if is_video(extension):
        video_capture = cv2.VideoCapture()
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        output = args.output + filename + '.avi'

        if video_capture.open(args.input):
            property_id = int(cv2.CAP_PROP_FRAME_COUNT)
            total_frames = int(cv2.VideoCapture.get(video_capture, property_id))
            frame_no = 1
            width, height = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH)), \
                            int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
            fps = video_capture.get(cv2.CAP_PROP_FPS)
            device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
            save_dict = torch.load(args.weights, map_location=device)
            net.load_state_dict(save_dict['net'])
            net.eval()
            net.to(device)

            # can't write out mp4, so try to write into an AVI file
            video_writer = cv2.VideoWriter(output, fourcc, fps, (width, height))
            while video_capture.isOpened():
                start = time()
                ret, frame = video_capture.read()
                if not ret:
                    break
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                frame = transform_img({'img': frame})['img']
                x = transform_to_net({'img': frame})['img']
                x.unsqueeze_(0)

                stop1 = time()
                print('stop1: ', stop1 - start)

                seg_pred, exist_pred = net(x)[:2]
                seg_pred = seg_pred.detach().cpu().numpy()
                exist_pred = exist_pred.detach().cpu().numpy()
                seg_pred = seg_pred[0]

                stop2 = time()
                print('stop2: ', stop2 - stop1)

                frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
                lane_img = np.zeros_like(frame)
                color = np.array([[255, 125, 0], [0, 255, 0], [0, 0, 255], [0, 255, 255]], dtype='uint8')
                coord_mask = np.argmax(seg_pred, axis=0)
                for i in range(0, 4):
                    if exist_pred[0, i] > 0.5:
                        lane_img[coord_mask == (i + 1)] = color[i]
                img = cv2.addWeighted(src1=lane_img, alpha=0.8, src2=frame, beta=1., gamma=0.)
                img = cv2.resize(img, (width, height))

                stop3 = time()
                print('stop3: ', stop3 - stop2)

                # if frame_no % 20 == 0:
                #     print('# {}/{} frames processed!'.format(frame_no, total_frames))
                frame_no += 1
                video_writer.write(img)
                end = time()
                print('Whole loop: {} seconds'.format(end - start))
                print('------------')
                print('------------')

            print('# All frames processed ')

            video_capture.release()
            video_writer.release()

    elif is_image(extension):
        img = cv2.imread(args.input)
        height, width, _ = img.shape
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        img = transform_img({'img': img})['img']
        x = transform_to_net({'img': img})['img']
        x.unsqueeze_(0)

        save_dict = torch.load(args.weights, map_location='cpu')
        net.load_state_dict(save_dict['net'])
        net.eval()

        seg_pred, exist_pred = net(x)[:2]
        seg_pred = seg_pred.detach().cpu().numpy()
        exist_pred = exist_pred.detach().cpu().numpy()
        seg_pred = seg_pred[0]

        img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
        lane_img = np.zeros_like(img)
        color = np.array([[255, 125, 0], [0, 255, 0], [0, 0, 255], [0, 255, 255]], dtype='uint8')
        coord_mask = np.argmax(seg_pred, axis=0)
        for i in range(0, 4):
            if exist_pred[0, i] > 0.5:
                lane_img[coord_mask == (i + 1)] = color[i]
        img = cv2.addWeighted(src1=lane_img, alpha=0.8, src2=img, beta=1., gamma=0.)
        img = cv2.resize(img, (width, height))
        output = args.output + filename + '.jpg'

        cv2.imwrite(output, img)

    else:
        print("file format [{}] is not supported".format(args.input))
        sys.exit()

if __name__ == '__main__':
    main()

And I got this error:
Traceback (most recent call last):
  File "/home/gpu/codes/MSD/scnn_pytorch/lane_detection_server.py", line 157, in <module>
    main()
  File "/home/gpu/codes/MSD/scnn_pytorch/lane_detection_server.py", line 83, in main
    seg_pred, exist_pred = net(x)[:2]
  File "/home/gpu/anaconda3/envs/slow_fast/lib/python3.6/site-packages/torch/nn/modules/module.py", line 541, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/gpu/codes/MSD/scnn_pytorch/model.py", line 32, in forward
    x = self.backbone(img)
  File "/home/gpu/anaconda3/envs/slow_fast/lib/python3.6/site-packages/torch/nn/modules/module.py", line 541, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/gpu/anaconda3/envs/slow_fast/lib/python3.6/site-packages/torch/nn/modules/container.py", line 92, in forward
    input = module(input)
  File "/home/gpu/anaconda3/envs/slow_fast/lib/python3.6/site-packages/torch/nn/modules/module.py", line 541, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/gpu/anaconda3/envs/slow_fast/lib/python3.6/site-packages/torch/nn/modules/conv.py", line 345, in forward
    return self.conv2d_forward(input, self.weight)
  File "/home/gpu/anaconda3/envs/slow_fast/lib/python3.6/site-packages/torch/nn/modules/conv.py", line 342, in conv2d_forward
    self.padding, self.dilation, self.groups)
RuntimeError: Input type (torch.FloatTensor) and weight type (torch.cuda.FloatTensor) should be the same

So how can I modify the code to be able to run the code on gpu machine? And if I be able to do so, Can I still use the weights vgg_SCNN_DULR_w9.pth for prediction or I have to train from scratch?

I think you forget to move data to gpu device.
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame = transform_img({'img': frame})['img']
x = transform_to_net({'img': frame})['img']
x.unsqueeze_(0)

Here, you should an additional line to move x to gpu. Be patience and double check you code.  :-)


text:
Bio field added in profile

Related Issuse or bug

Bio field added in profile section

Fixes: #127
Proposed Changes

In model bio field added
In UserProfileUpdateForm bio field added and init function added
-In view editprofile updated

Additional Info

One default image addded in media/admin/default.jpg for image handling.

Screenshots

Original
Updated

Checkout PR @harsh-9in @Kajol-Kumari @SKAUL05

@SKAUL05  plz review pr.

Checkout PR Removed conflicts and some line of codes in profile view for login user post(Additional- some code already written in profile.html for posts). @harsh-9in @Kajol-Kumari

@nooras plz remove conflicts.

@nooras plz remove conflicts.

Removed @harsh-9in


text:
UI Enhancement of simple interest calculator

As a GSSOC'22 contributor, I enhanced the UI of the Simple Interest Calculator Chrome Extension.
Before:

After:

@AkankshaGawade nice work!!
thanks for contributing!!💛💛🚀

authors: AkankshaGawade whiteHatpro


text:
Created Night Mode extension #18

ScreenShots of the extension
when Night Mode is ON

when Night Mode is OFF

Great work @RajulPE 👏  , Thanks for Contributing 🎊

Thank You


text: Gif to Readme

repo: harunakawakami/lost-and-found


text:
sort/gather step fails with high interval count

Testing on a dataset with ~12k intervals: the sort/gather step at the end (to collect each genotyped interval into the final vcf) fails. It is not clear if this is a temp file issue, a memory issue, or just a problem with the way we handle very large inputs to bcf concat.
Probably the solution is multiple rounds of merging, which we can investigate. For now, posting this issue in case other people have problems with datasets with >10k intervals to merge.

Possible solution:

refactor concat step to create a temp vcf file, using the -a and -d options and a file of files, but not doing the sort
sort in a second step with high memory

repo: harvardinformatics/snpArcher


text:
Take image virtual size into account when creating Volumes

This is a followup to https://github.com/harvester/dashboard/pull/1104
When creating new volumes on the Volume screen in Harvester, the default size is empty, i.e. it's not pre-filled with anything at all.  If the source is set to "VM image" we can now take the image virtual size and use that as the default size for the volume. Unlike when creating VMs (which always set the volume to a minimum of 10GiB regardless of virtual size, for consistency with earlier harvester versions), on this screen we just use the virtual size as-is.  If the user wants to make it bigger, they can.
Related issue: https://github.com/harvester/harvester/issues/4905

Wait, I've just discovered this isn't quite right -- it's now effectively impossible to manually edit the size once an image is chosen (I think because everything calls update()). I'll have to rework this somehow :-/

OK, that seems to have done the trick... If there's a better way to structure anything here, please LMK.

Sorry, not sure if I misunderstand this PR purpose,  we want to pre-fill the Size based on user selected image virtual size.
Do we need specific backend change or master-head is enough ?
It's not work as expected when I test locally.
https://github.com/user-attachments/assets/5d654b55-40cf-4697-bec3-b0b71b4ec09b

Sorry, not sure if I misunderstand this PR purpose, we want to pre-fill the Size based on user selected image virtual size or actual size.

Yep, it's meant to pre-fill the Size based on whichever is greater of the image virtual size or actual size.

Does this PR need specific backend change or master-head is enough ?

It should work fine provided your backend harvester cluster is v1.4 or master -- looking at the version in the video, it seems you're on v1.3.1, which doesn't support virtual size... But even in that case I would have expected it to at least fill the field with the physical size of the image -- const imageSize = Math.max(imageResource?.status?.size, imageResource?.status?.virtualSize) should pick up whichever is available, right? -- so I'm not sure what's going on here :-/

This change contains some more code changes, but you can make use of the already fetched images. Don't know why they are fetched because the current code does not make use of it. Maybe @torchiaf should have a final look on it if you want to apply this patch.
diff --git a/pkg/harvester/edit/harvesterhci.io.volume.vue b/pkg/harvester/edit/harvesterhci.io.volume.vue
--- a/pkg/harvester/edit/harvesterhci.io.volume.vue	(revision 3ee5fbdbd0b0d589ebbf7002ceab1ff488846b55)
+++ b/pkg/harvester/edit/harvesterhci.io.volume.vue	(date 1724838170157)
@@ -56,6 +56,7 @@
     const hash = await allHash(_hash);

     this.snapshots = hash.snapshots;
+    this.images = hash.images;

     const defaultStorage = this.$store.getters[`harvester/all`](STORAGE_CLASS).find( O => O.isDefault);

@@ -77,6 +78,7 @@
       storage,
       imageId,
       snapshots: [],
+      images: [],
     };
   },

@@ -108,10 +110,8 @@
     },

     imageOption() {
-      const choices = this.$store.getters['harvester/all'](HCI.IMAGE);
-
       return sortBy(
-        choices
+        this.images
           .filter(obj => obj.isReady)
           .map((obj) => {
             return {
@@ -251,8 +251,7 @@
     },
     updateImage() {
       if (this.isVMImage && this.imageId) {
-        const images = this.$store.getters['harvester/all'](HCI.IMAGE);
-        const imageResource = images?.find(image => this.imageId === image.id);
+        const imageResource = this.images?.find(image => this.imageId === image.id);
         const imageSize = Math.max(imageResource?.status?.size, imageResource?.status?.virtualSize);

         if (imageSize) {

Sorry, not sure if I misunderstand this PR purpose, we want to pre-fill the Size based on user selected image virtual size

Test with master-head deployment. It's good. 👍
Just notice the size only accepted integer.... I turn to use formatSi to get more precise size number to decimal.
  this.storage = formatSi(imageSize, {
            increment: 1024, addSuffix: true, maxExponent: 3, minExponent: 3, suffix: 'i'
          });

But got webhook error 😓

It might be best to just stay with and integer value - I could be wrong, but I don't think we allow decimals anywhere in any size fields, it's all just whole GiB.

Thanks @votdev, I've applied that patch and it seems to work fine. I'm happy to wait for @torchiaf to review as well.

@mergifyio backport release-harvester-v1.4

authors: a110605 tserong votdev

repo: harvester/dashboard


text:
[BUG] Static VIP address (spec.loadBalancerIP field) does not work

Describe the bug
Kube-VIP supports allocating a static VIP address to a service by setting the spec.loadBalancerIP field in the service manifest.
Ref: https://kube-vip.io/usage/on-prem/#the-kube-vip-cloud-provider-configmap
When creating such service manifest in a Harvester guest cluster, then instead of assigning the address in spec.loadBalancerIP field, a random IP address from the pool is assigned.
To Reproduce
Steps to reproduce the behavior:
In a guest cluster, create a service resource with a static loadBalancerIP address:
apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  ports:
  - name: http
    port: 80
    protocol: TCP
  selector:
    app: nginx
  type: LoadBalancer
  loadBalancerIP: "10.65.100.10"

It works well with the kube-vip of the 0.4 version. We have to upgrade the kube-vip to the latest version.

For testing

Set up a harvester
Create a deployment and related load balancer type service
Specify the field spec.loadBalancerIP with a static IP
Request the svc through the load balancer IP

Tested in Harvester master-1a861fc1-head and Rancher da382a8. with the test steps

For testing

Set up a harvester
Create a deployment and related load balancer type service
Specify the field spec.loadBalancerIP with a static IP
Request the svc through the load balancer IP

I creted a deployment in Rancher with nginx, then created a load balancer service and specified the load balancer IP. It isn't routing it's still going to the endpoint that's in the YAML. The load balancer IP doesn't appear to be routing. Also the static IP I was trying to assign was in the same subnet as the one it randomly assigned.

Verified fixed on master-b09e3233-head(02/14). Close this issue.
Result
In Harvester cluster, we can create nginx service with static IP set on spec.loadBalancerIP.
And can reach the services through the static IP
harvester-one-220214:/home/rancher # kubectl describe service nginx
Name:                     nginx
Namespace:                default
Labels:                   <none>
Annotations:              <none>
Selector:                 app=nginx
Type:                     LoadBalancer
IP Family Policy:         SingleStack
IP Families:              IPv4
IP:                       10.53.137.109
IPs:                      10.53.137.109
IP:                       192.168.122.35
Port:                     http  80/TCP
TargetPort:               80/TCP
NodePort:                 http  31251/TCP
Endpoints:                <none>
Session Affinity:         None
External Traffic Policy:  Cluster

curl http://192.168.122.35/
Found

Test Information

Test Environment: 1 node harvester on local kvm machine
Harvester version: master-b09e3233-head (02/14)

Verify Steps

ssh to harvester node VIP
Prepare the service manifest yaml with content, set the static IP to spec.loadBalancerIP

apiVersion: v1
kind: Service
metadata:
  name: nginx
spec:
  ports:
  - name: http
    port: 80
    protocol: TCP
  selector:
    app: nginx
  type: LoadBalancer
  loadBalancerIP: "10.65.100.10"

Run to kubectl create -f ./service.yaml to create service
Run kubectl describe service nginx to check status
Run curl http://192.168.122.35/ to request service through static IP

authors: TachunLin janeczku noahgildersleeve yaocw2020

repo: harvester/harvester


text:
[BUG] Can't delete a "Cordoned" host from the list of hosts

Describe the bug
Can't delete a "Cordoned" host from the list of hosts
To Reproduce

Set-up HA Harvester cluster with three nodes and add the Rancher integration
Wipe/destroy/lose a host
Remove the host from the list of hosts in Harvester (and don't remove it in Rancher)
Replace the host (reinstall the host using the same hostname and IP) and make it join the existing Harvester cluster
The host will be Cordoned as something prevents the node from successfully joining the Harvester cluster (something about the node already existing in an etcd)
In the Harvester UI, you can't delete that host. Regardless of whether you decide to reinstall the host using different hostname & IP, the host reference created from Step 4 will be impossible to remove from the UI.

Expected behavior
Being able to fully and properly remove a host from the list of hosts. Maybe "force" remove.
Support bundle
I'll provide the bundle securely upon request.
Environment

Harvester ISO version:
3 x baremetal with Dell PowerEdge R820

Additional context
I lost the raid array configuration following a pretty bad storm. I decided it was a good opportunity to re-configure the array (something I meant to do anyway) since https://github.com/harvester/harvester/issues/2665 seemed to suggest that it was possible to reinstall the first node/host of a cluster

After having the physical host shut down overnight, the host finally disappeared from the UI. I can't say why it took 3+ hours, but it finally worked.

As an added thought on this, it'd be really nice to have a "force delete" on host and virtual machine resources. It's not the first time I struggle to delete something.


text:
Parameterized markers filter testing

This patch removes all the hard-coded cases for markers filtering and replace them with a
parameterized testing.
Pytest expands test_markers into multiple tests, containing a test for the entire Cartesian product of the filtering flags.
Each test checks that results that were supposed to be filtered out got in, and at the end of all tests the marker_counter fixtures makes sure that we got the expected amount of result in total by comparing it against a hard-coded number. This number should be updated if we ever add more parameters to the test, or import additional marker data into the testing environment.

You can read more about parametrization here

repo: hasadna/anyway


text:
CLI rewrite

Hascal CLI
Reasons for the change

The main function in the hascal.py file is cluttered with so many if..else statements messing up the code.
In this situation, it will be difficult for a new contributor to understand the file

Solutions

The whole CLI can be rewritten in click(or any other CLI library)
OR
Create  a separate ArgumentParser for parsing the CLI commands

OK,i will change it and .I will use argparse.

Ok, Thank you

authors: hasan-kashi pranavbaburaj

repo: hascal/hascal


text:
Token transfer impossible - gives insufficient token balans

Hi there,
never used github before, so not sure if Im doing it right!
I tried to transfer tokens, but somehow I got the error 'insufficient token balance'. It worked with two tokens, and some others didnt work (at least hbarbarian and basil). It didnt make any sense because there was sufficient balance.
I tried with hex, which gave me the same error 'you don't have enough tokens'. So I thought maybe it was a hedera issue. However, I now succeeded in transferring all tokens with Dode Cane wallet. So, therefore I guess it must be an issue with Myhbarwallet and hex.
Do say if you need more info.

Hi,
We are currently working on the HTS functionality of MHW, and you should expect a better experience when version 0.6.0 releases sometime in the next week.

The issue is likely in looking up token information, fyi

Hello Chris! Thank you for your answer :)

try next.myhbarwallet.com!
Report any issues you experience here

authors: MilesNHH cacampbell

repo: hashgraph/MyHbarWallet


text:
Unable to use the signer to execute transactions in a create react dapp

Describe the bug A clear and concise description of what the bug is.
I am upgrading the CRA hedera template to use the hedera wallet connect signer, and whenever I try to complete a transaction, I get an error message. It occurs in the file walletConnectClient.tsx on line 71:  const txResult = await transferHBARTransaction.executeWithSigner(this.signer);
ERROR:
Uncaught runtime errors:
×
ERROR
Error executing transaction or query:
{
  "txError": {},
  "queryError": {
    "name": "Error",
    "message": "(BUG) Query.fromBytes() not implemented for type getByKey",
    "stack": "Error: (BUG) Query.fromBytes() not implemented for type getByKey\n    at vr.fromBytes (http://localhost:3000/static/js/bundle.js:68098:28)\n    at SA._tryExecuteQueryRequest (http://localhost:3000/static/js/bundle.js:96271:20)\n    at SA.call (http://localhost:3000/static/js/bundle.js:96292:26)\n    at async WalletConnectWallet.transferHBAR (http://localhost:3000/static/js/bundle.js:2111:22)\n    at async onClick (http://localhost:3000/static/js/bundle.js:1440:26)"
  }
}
Error: Error executing transaction or query:
{
  "txError": {},
  "queryError": {
    "name": "Error",
    "message": "(BUG) Query.fromBytes() not implemented for type getByKey",
    "stack": "Error: (BUG) Query.fromBytes() not implemented for type getByKey\n    at vr.fromBytes (http://localhost:3000/static/js/bundle.js:68098:28)\n    at SA._tryExecuteQueryRequest (http://localhost:3000/static/js/bundle.js:96271:20)\n    at SA.call (http://localhost:3000/static/js/bundle.js:96292:26)\n    at async WalletConnectWallet.transferHBAR (http://localhost:3000/static/js/bundle.js:2111:22)\n    at async onClick (http://localhost:3000/static/js/bundle.js:1440:26)"
  }
}
    at SA.call (http://localhost:3000/static/js/bundle.js:96294:13)
    at async WalletConnectWallet.transferHBAR (http://localhost:3000/static/js/bundle.js:2111:22)
    at async onClick (http://localhost:3000/static/js/bundle.js:1440:26)

I followed the documentation to use the signer, but to no avail. Hoping more can get uncovered 🙏
To Reproduce Steps to reproduce the behavior:

Open the following project in vscode
usewalletconnectsigner.zip
npm i
npm run start
Click on the connect button in the upper right
Copy the connection string
Paste it to any hedera wallet
pase an account id in the to address
click the button with the arrow to start a transfer transaction of 1 test HBAR.
Observe the following error

Expected behavior A clear and concise description of what you expected to happen.
I expect to be able to use the wallet connects signer to freeze and execute the transfer transaction to transfer 1 test HBAR.
Screenshots If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

OS: [e.g. iOS] MAC
Browser [e.g. chrome, safari] CHROME
Version [e.g. 22] Sonoma 14.1.2

Additional context Add any other context about the problem here.

This issue is no longer reproducible or occurring. Therefore I will close it.

repo: hashgraph/hedera-wallet-connect


text:
Getting Well Data back when setting the dTimLastChange element to dTimLastChange Equal or + 1 second of the well

Pre-Condition: Get Well dTimLastChange information
Reproduction Steps:

Modify Get from Store Well Query and input Well UID
Change the dTimLastChange info to 'Equal' or '1 second' ahead of the current TimeStamp
Send in Soap Request

Expected Results:  Well information is not returned.
Observed Results:  Well information is returned.
**Please note: When repeating steps above, no well is returned if no UID is inputted. This functionality should work with or without UID information.

The problem was identified and will be addressed as part of #377

repo: hashmapinc/Drillflow


text:
Error on Login Page

Login to tempus
Wait for first session to time out.
Open another Tab and Login
You should see following error

Go back to first Tab and click on any menu item.
You should see this message

7. You would this message in other situations also where current session has expired.
Therefore, this message should be reworded to 'Your session has expired,  please log in again".

Fixed as part of #705

authors: SPParnerkar anuj-akt

repo: hashmapinc/Tempus


text:
Implement Pagination and Value Truncation for Improved Performance

Hi hashrock,
Great project you have here, filling a notable gap with a Deno KV GUI editor.
I observed two areas for improvement:

Pagination is missing for listed entries. Currently, there's a hardcoded limit of 100 in the server/kv source code. Adding pagination controls would enhance usability.

Performance concerns arise when using large KV instances. I noticed the webview displays the entire value for each entry, which can be problematic for large data sets.

Possible fixes for performance:

Show truncated previews, like the first 50 characters from Deno.inspect(value).
Omit values in the list view and display them only during entry editing.

I'm open to submitting a PR to address these issues, if you're accepting contributions.
Thanks for your work on this!
Nick

Thanks!
I'm planning to work on serializing and deserializing things like BigInt for a while, so issues related to performance might be postponed. I would appreciate it if you could create a PR!

When you say serializing bigint, are those plain bigint values or Deno.KvU64 instances? I think a binary serialization could prove useful in either case... what I mean is something along the lines of the Deno.core.serialize function, which preserves data-types and returns a Uint8Array.
Actually, I believe it could be used to serialize / deserialize all of the data types (for simplicity).
Check this code out from the gokv project by ije for an example of what I'm talking about: https://github.com/ije/gokv/blob/main/src/common/structured.ts

That's right. Both Key and Value have various types, so they can't be handled by JSON.serialize. gokv seems like a good reference! Thanks.

I added two preferences to solve this issue:

kivi.listFetchSize
kivi.previewValue

it also added basic pagenation feature.
https://github.com/hashrock/kivi/assets/3132889/0c6775be-55ec-42d4-bbc5-11b94338664d
I don't think these are perfect solution for performance issue, but I think it will work on most cases.

authors: hashrock nberlette

repo: hashrock/deno-kv-admin


text:
Schedule page report notifier every Monday at 9AM

WHAT IT DOES:
Schedules the page views report notifier to be run every Monday at 9AM for whatever timezone you have set (or falls back to Chicago).

Thanks @tmock12 tremendous work! ❤ 🐦 ⛷ 🐗 🥇

repo: hashrocket/tilex


text:
[Fix] draggable elements can drag out of canvas

Now you can't drag out the elements out of canvas :)

Thanks a lot, sire :)

You welcome :)

authors: codexpert hasinhayder

repo: hasinhayder/banner-designer


text:
ghcide stuck on a failed hie.yaml with no feedback

I have this faulty hie.yaml  (as in .OUT/generated.flags didn't exist)
cradle:
  bios:
    shell: cat ".OUT/generated.flags" > $HIE_BIOS_OUTPUT

and I had ghcide 0.4.0 stuck on
Step 1/4: Finding files to test in /home/teto/nova/project

Hopefully hie-bios debug showed the error.
at some point I also had symlink cycles in my folders and IIRC I had ghcide endlessly looking for files without much to guess why (even with --verbose).

I think, the former is a hie-bios bug (although can be handled in ghcide if the interface is insufficient), while the latter is a ghcide bug.
If the bios program is faulty, it should not crash the whole application without feedback.

I wanted to iterate on the point 2 of this message https://github.com/mpickering/hie-bios/issues/250#issuecomment-696223578 .
The matter is not that its a symlink in this case but that ghcide is scanning the whole file hierarchy in ./. even though my multicradle config (the same as in that message), just mentions subfolders of project/ while setting ./. to the none cradle. I leave ghcide (in fact the haskell-language-server) scans those big bazel folders but in the end it crashes or is killed by the system, I am not sure which.
One workaround I found is to call haskell-language-server --cwd project but I wonder if it can find the hie.yaml in a parent folder of project ?
EDIT  one answer from @fendor on IRC

hls and ghcide do not honour the hie.yaml when finding haskell source files for testing

authors: fendor teto

repo: haskell/ghcide