问:
Suppressing scientific notation in pandas?
I have a DataFrame in pandas where some of the numbers are expressed in scientific notation (or exponent notation) like this:

```<code>                  id        value
id              1.00    -4.22e-01
value          -0.42     1.00e+00
percent        -0.72     1.00e-01
played          0.03    -4.35e-02
money          -0.22     3.37e-01
other            NaN          NaN
sy             -0.03     2.19e-04
sz             -0.33     3.83e-01
</code>```

And the scientific notation makes what should be an easy comparison, needlessly difficult. I assume it's the 21900 value that's screwing it up for the others. I mean 1.0 is encoded. ONE!

This doesn't work:

```<code>np.set_printoptions(supress=True)
</code>```

And pandas.set_printoptions doesn't implement suppress either, and I've looked all at pd.describe_options() in despair, and pd.core.format.set_eng_float_format() only seems to turn it on for all the other float values, with no ability to turn it off.

答:
I tried all the options like

pd.options.display.float_format = '{:.4f}'.format

pd.set_option('display.float_format', str)

pd.set_option('display.float_format', lambda x: f'%.{len(str(x%1))-2}f' % x)

pd.set_option('display.float_format', lambda x: '%.3f' % x)

but nothing worked for me.

so while assigning the variable / value (var1) to a variable (say num1) I used round(val,5).

```<code>num1 = round(var1,5)
</code>```

This is a crude method as you have to use this round function in each assignment.  But this ensures you control on how it happens and get what you want.

Body:
I have a DataFrame in pandas where some of the numbers are expressed in scientific notation (or exponent notation) like this:

                  id        value
id              1.00    -4.22e-01
value          -0.42     1.00e+00
percent        -0.72     1.00e-01
played          0.03    -4.35e-02
money          -0.22     3.37e-01
other            NaN          NaN
sy             -0.03     2.19e-04
sz             -0.33     3.83e-01

And the scientific notation makes what should be an easy comparison, needlessly difficult. I assume it's the 21900 value that's screwing it up for the others. I mean 1.0 is encoded. ONE!

This doesn't work:

np.set_printoptions(supress=True)

And pandas.set_printoptions doesn't implement suppress either, and I've looked all at pd.describe_options() in despair, and pd.core.format.set_eng_float_format() only seems to turn it on for all the other float values, with no ability to turn it off.

Body:
I tried all the options like

pd.options.display.float_format = '{:.4f}'.format

pd.set_option('display.float_format', str)

pd.set_option('display.float_format', lambda x: f'%.{len(str(x%1))-2}f' % x)

pd.set_option('display.float_format', lambda x: '%.3f' % x)

but nothing worked for me.

so while assigning the variable / value (var1) to a variable (say num1) I used round(val,5).

num1 = round(var1,5)

This is a crude method as you have to use this round function in each assignment.  But this ensures you control on how it happens and get what you want.


来源: stackexchange

问:
Dialogflow webhook not working with django
My Dialogflow webhook was working completely fine till yesterday but it is suddenly not connecting to the webhook today. Although I've made no changes in the code. I'm getting the following fulfillment status:

```<code>Webhook call failed. Error: NOT_FOUND, State: URL_ERROR, Reason: ERROR_NOT_FOUND, HTTP status code: 404.
</code>```

Please note the following points:

Fulfillment URL is written in the correct format (with HTTPS protocol).

My Django server is running fine and it is also receiving requests when instigated from the browser. (Just not receiving requests from Dialogflow)

Suddenly, none of my Dialogflow agents (previously built and working fine) are sending requests to Django/Flask server.

I've checked multiple things like trying from different Dialogflow accounts and different browsers but I can conclude that the issue is with the Dialogflow webhook/Fulfillment.

Please, help me with the solution. Thank you in advance.

答:
I'm glad that you were able to solve your issue somehow. I will leave this complementary recommendations as a community wiki answer to help community with this kind of issues and for visibility. Please feel free to edit this answer to fit your scope.

Recommendations when dealing with webhook errors:

Check your webhook links, status of the deployment services.

Check your dialog errors details on your logs, you can see the documentation to activate logging for dialogflow by visiting this page.

Check the status of google cloud service.

Check webhook documention about errors.

You can write code to directly interact with dialogflow API and detect the intent and check the status of the API.

You can also rise your issue or check similar issues on the main dialogflow for nodejs github project page.

For information about libraries, rest API, RPC API you can check this link to the official documentation.

If you keep getting the error you might be dealing with a bug, in those cases you can create bug request. For more details about dialogflow issue tracker check this link.

ContentLicense: CC BY-SA 4.0

Body:
My Dialogflow webhook was working completely fine till yesterday but it is suddenly not connecting to the webhook today. Although I've made no changes in the code. I'm getting the following fulfillment status:

Webhook call failed. Error: NOT_FOUND, State: URL_ERROR, Reason: ERROR_NOT_FOUND, HTTP status code: 404.

Please note the following points:

Fulfillment URL is written in the correct format (with HTTPS protocol).

My Django server is running fine and it is also receiving requests when instigated from the browser. (Just not receiving requests from Dialogflow)

Suddenly, none of my Dialogflow agents (previously built and working fine) are sending requests to Django/Flask server.

I've checked multiple things like trying from different Dialogflow accounts and different browsers but I can conclude that the issue is with the Dialogflow webhook/Fulfillment.

Please, help me with the solution. Thank you in advance.


问:
How to make flutter web size like app size
I am developing a flutter app and try to run it on web too. How do you make the size of a web app like a phone app? I saw some web app has the fixed size of phone app like following;https://i.stack.imgur.com/2J36E.jpg</p>

答:
Adaptive and responsive can be viewed as separate dimensions of a flutter app: you can have an adaptive app that is not responsive or vice versa. And, of course, an app can be both or neither.
You can follow the official docs: https://docs.flutter.dev/development/ui/layout/adaptive-responsive</p>


问:
String / label issue
I've got an issue with a label showing a String.

So, basically, I've got a function - (void) didFinishUpdatesSuccessfully. If this function is being called it means that an action has been completed successfully. It creates a time stamp and stores it to NSUserDefaults. All this works like a charme..
Here's the function:

```<code>    - (void) didFinishUpdatesSuccessfully {

        // Create formatted date string
        NSDate *currDate = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"dd/MM/YYYY - hh:mm:ss a"];
        NSString *dateString = [dateFormatter stringFromDate:currDate];

        NSMutableString* lastUpdated;
        lastUpdated = [[NSMutableString stringWithFormat:@"%@",dateString] retain];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:lastUpdated forKey:@"lastUpdated"];
        [defaults synchronize];

        //--- Alert dialog
        NSString *title;
        title = @"All the latest hotspots have now been saved!";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: title
                                                    message: lastUpdated
                                                   delegate: nil
                                          cancelButtonTitle: [FileUtils appResourceForKey:@"HOTSPOT_GENERAL_BUTTON_TITLE_OK"]
                                          otherButtonTitles: nil];

// ------------------------
//Create label
    UILabel *UpDLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 205, 250, 100)];
    UpDLabel.backgroundColor = [UIColor clearColor]; // [UIColor brownColor];
    UpDLabel.font = [UIFont fontWithName:@"Helvetica" size: 11.0];
    UpDLabel.shadowColor = [UIColor whiteColor];
    UpDLabel.shadowOffset = CGSizeMake(1,1);
    UpDLabel.textColor = [UIColor blackColor];
    UpDLabel.textAlignment = UITextAlignmentRight; // UITextAlignmentCenter, UITextAlignmentLeft
    UpDLabel.lineBreakMode = UILineBreakModeWordWrap;
    NSString *lupdate   = [NSString stringWithFormat: @"Last Update: %@", lastUpdated];

    UpDLabel.text = lupdate;

    [self.view addSubview:UpDLabel];

    [UpDLabel release];
// ------------------------

        [dateFormatter release];
        [lastUpdated release];
        [alert show];
        [alert release];

        //--- remove indicator view
        [self indicatorViewShow:NO];

    }
</code>```

The label with the date string is being displayed. It overrides itself but seems to keep the previous string so it actualy looks like it just adds another layer on top of the previous one. Or in other words, if I perform the - (void) didFinishUpdatesSuccessfully 3 times it will show 3 date strings on top of each other which looks screwed...

What am I doing wrong?

Cheers
Jan

答:
It's because you keep adding subviews to your view, instead of just putting new text into the UILabel.  Set up the UILabel once, and then just change the text with UpDLabel.text = lupdate.

joe

ContentLicense: CC BY-SA 3.0

Title: String / label issue

Body:
I've got an issue with a label showing a String.

So, basically, I've got a function - (void) didFinishUpdatesSuccessfully. If this function is being called it means that an action has been completed successfully. It creates a time stamp and stores it to NSUserDefaults. All this works like a charme..
Here's the function:

    - (void) didFinishUpdatesSuccessfully {

        // Create formatted date string
        NSDate *currDate = [NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setDateFormat:@"dd/MM/YYYY - hh:mm:ss a"];
        NSString *dateString = [dateFormatter stringFromDate:currDate];

        NSMutableString* lastUpdated;
        lastUpdated = [[NSMutableString stringWithFormat:@"%@",dateString] retain];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:lastUpdated forKey:@"lastUpdated"];
        [defaults synchronize];

        //--- Alert dialog
        NSString *title;
        title = @"All the latest hotspots have now been saved!";
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: title
                                                    message: lastUpdated
                                                   delegate: nil
                                          cancelButtonTitle: [FileUtils appResourceForKey:@"HOTSPOT_GENERAL_BUTTON_TITLE_OK"]
                                          otherButtonTitles: nil];

// ------------------------
//Create label
    UILabel *UpDLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 205, 250, 100)];
    UpDLabel.backgroundColor = [UIColor clearColor]; // [UIColor brownColor];
    UpDLabel.font = [UIFont fontWithName:@"Helvetica" size: 11.0];
    UpDLabel.shadowColor = [UIColor whiteColor];
    UpDLabel.shadowOffset = CGSizeMake(1,1);
    UpDLabel.textColor = [UIColor blackColor];
    UpDLabel.textAlignment = UITextAlignmentRight; // UITextAlignmentCenter, UITextAlignmentLeft
    UpDLabel.lineBreakMode = UILineBreakModeWordWrap;
    NSString *lupdate   = [NSString stringWithFormat: @"Last Update: %@", lastUpdated];

    UpDLabel.text = lupdate;

    [self.view addSubview:UpDLabel];

    [UpDLabel release];
// ------------------------

        [dateFormatter release];
        [lastUpdated release];
        [alert show];
        [alert release];

        //--- remove indicator view
        [self indicatorViewShow:NO];

    }

The label with the date string is being displayed. It overrides itself but seems to keep the previous string so it actualy looks like it just adds another layer on top of the previous one. Or in other words, if I perform the - (void) didFinishUpdatesSuccessfully 3 times it will show 3 date strings on top of each other which looks screwed...

What am I doing wrong?

Cheers
Jan


问:
How to trim leading spaces in Sublime Text 3
I have list of strings which all have leading whitespace

How do I remove it

答:
so I found a way to do this by using a sublime package Trimmer

trimmer screenshot


问:
I was unable to download node module through terminal
Command to download node modules module npm i
Error: npm ERR! code 1
npm ERR! path D:\Projects\fieldforce\node_modules\bcrypt
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c node-pre-gyp install --fallback-to-build
npm ERR! Failed to execute 'C:\Program Files\nodejs\node.exe C:\Users\nas\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js configure --fallback-to-build --module=D:\Projects\fieldforce\node_modules\bcrypt\lib\binding\bcrypt_lib.node --module_name=bcrypt_lib --module_path=D:\Projects\fieldforce\node_modules\bcrypt\lib\binding --napi_version=8 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v83' (1)
npm ERR! node-pre-gyp info it worked if it ends with ok
npm ERR! node-pre-gyp info using node-pre-gyp@0.14.0
npm ERR! node-pre-gyp info using node@14.18.1 | win32 | x64
npm ERR! node-pre-gyp WARN Using request for node-pre-gyp https download
npm ERR! node-pre-gyp info check checked for "D:\Projects\fieldforce\node_modules\bcrypt\lib\binding\bcrypt_lib.node" (not found)
npm ERR! node-pre-gyp http GET https://github.com/kelektiv/node.bcrypt.js/releases/download/v3.0.8/bcrypt_lib-v3.0.8-node-v83-win32-x64-unknown.tar.gz
npm ERR! node-pre-gyp http 404 https://github.com/kelektiv/node.bcrypt.js/releases/download/v3.0.8/bcrypt_lib-v3.0.8-node-v83-win32-x64-unknown.tar.gz
npm ERR! node-pre-gyp WARN Tried to download(404): https://github.com/kelektiv/node.bcrypt.js/releases/download/v3.0.8/bcrypt_lib-v3.0.8-node-v83-win32-x64-unknown.tar.gz
npm ERR! node-pre-gyp WARN Pre-built binaries not found for bcrypt@3.0.8 and node@14.18.1 (node-v83 ABI, unknown) (falling back to source compile with node-gyp)
npm ERR! node-pre-gyp http 404 status code downloading tarball https://github.com/kelektiv/node.bcrypt.js/releases/download/v3.0.8/bcrypt_lib-v3.0.8-node-v83-win32-x64-unknown.tar.gz
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@8.4.1
npm ERR! gyp info using node@14.18.1 | win32 | x64
npm ERR! gyp info ok
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp info using node-gyp@8.4.1
npm ERR! gyp info using node@14.18.1 | win32 | x64
npm ERR! gyp ERR! find Python
npm ERR! gyp ERR! find Python Python is not set from command line or npm configuration
npm ERR! gyp ERR! find Python Python is not set from environment variable PYTHON
npm ERR! gyp ERR! find Python checking if "python3" can be used
npm ERR! gyp ERR! find Python - "python3" is not in PATH or produced an error
npm ERR! gyp ERR! find Python checking if "python" can be used
npm ERR! gyp ERR! find Python - "python" is not in PATH or produced an error
npm ERR! gyp ERR! find Python checking if Python is C:\Users\nas\AppData\Local\Programs\Python\Python39\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\nas\AppData\Local\Programs\Python\Python39\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python39\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python39\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\nas\AppData\Local\Programs\Python\Python39-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\nas\AppData\Local\Programs\Python\Python39-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python39-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python39-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python39-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python39-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\nas\AppData\Local\Programs\Python\Python38\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\nas\AppData\Local\Programs\Python\Python38\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python38\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python38\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\nas\AppData\Local\Programs\Python\Python38-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\nas\AppData\Local\Programs\Python\Python38-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python38-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python38-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python38-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python38-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\nas\AppData\Local\Programs\Python\Python37\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\nas\AppData\Local\Programs\Python\Python37\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python37\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python37\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\nas\AppData\Local\Programs\Python\Python37-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\nas\AppData\Local\Programs\Python\Python37-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python37-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python37-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python37-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python37-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\nas\AppData\Local\Programs\Python\Python36\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\nas\AppData\Local\Programs\Python\Python36\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python36\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python36\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Users\nas\AppData\Local\Programs\Python\Python36-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Users\nas\AppData\Local\Programs\Python\Python36-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files\Python36-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files\Python36-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if Python is C:\Program Files (x86)\Python36-32\python.exe
npm ERR! gyp ERR! find Python - "C:\Program Files (x86)\Python36-32\python.exe" could not be run
npm ERR! gyp ERR! find Python checking if the py launcher can be used to find Python 3
npm ERR! gyp ERR! find Python - "py.exe" is not in PATH or produced an error
npm ERR! gyp ERR! find Python
npm ERR! gyp ERR! find Python **********************************************************
npm ERR! gyp ERR! find Python You need to install the latest version of Python.
npm ERR! gyp ERR! find Python Node-gyp should be able to find and use Python. If not,
npm ERR! gyp ERR! find Python you can try one of the following options:
npm ERR! gyp ERR! find Python - Use the switch --python="C:\Path\To\python.exe"
npm ERR! gyp ERR! find Python   (accepted by both node-gyp and npm)
npm ERR! gyp ERR! find Python - Set the environment variable PYTHON
npm ERR! gyp ERR! find Python - Set the npm configuration variable python:
npm ERR! gyp ERR! find Python   npm config set python "C:\Path\To\python.exe"
npm ERR! gyp ERR! find Python For more information consult the documentation at:
npm ERR! gyp ERR! find Python https://github.com/nodejs/node-gyp#installation
npm ERR! gyp ERR! find Python **********************************************************
npm ERR! gyp ERR! find Python
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: Could not find any Python installation to use
npm ERR! gyp ERR! stack     at PythonFinder.fail (C:\Users\nas\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-python.js:330:47)
npm ERR! gyp ERR! stack     at PythonFinder.runChecks (C:\Users\nas\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-python.js:159:21)
npm ERR! gyp ERR! stack     at PythonFinder. (C:\Users\nas\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-python.js:228:18)
npm ERR! gyp ERR! stack     at PythonFinder.execFileCallback (C:\Users\nas\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib\find-python.js:294:16)
npm ERR! gyp ERR! stack     at exithandler (child_process.js:390:5)
npm ERR! gyp ERR! stack     at ChildProcess.errorhandler (child_process.js:402:5)
npm ERR! gyp ERR! stack     at ChildProcess.emit (events.js:400:28)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:280:12)
npm ERR! gyp ERR! stack     at onErrorNT (internal/child_process.js:469:16)
npm ERR! gyp ERR! stack     at processTicksAndRejections (internal/process/task_queues.js:82:21)
npm ERR! gyp ERR! System Windows_NT 10.0.19042
npm ERR! gyp ERR! command "C:\Program Files\nodejs\node.exe" "C:\Users\nas\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" "configure" "--fallback-to-build" "--module=D:\Projects\fieldforce\node_modules\bcrypt\lib\binding\bcrypt_lib.node" "--module_name=bcrypt_lib" "--module_path=D:\Projects\fieldforce\node_modules\bcrypt\lib\binding" "--napi_version=8" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=node-v83"
npm ERR! gyp ERR! cwd D:\Projects\fieldforce\node_modules\bcrypt
npm ERR! gyp ERR! node -v v14.18.1
npm ERR! gyp ERR! node-gyp -v v8.4.1
npm ERR! gyp ERR! not ok
npm ERR! node-pre-gyp ERR! build error
npm ERR! node-pre-gyp ERR! stack Error: Failed to execute 'C:\Program Files\nodejs\node.exe C:\Users\nas\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js configure --fallback-to-build --module=D:\Projects\fieldforce\node_modules\bcrypt\lib\binding\bcrypt_lib.node --module_name=bcrypt_lib --module_path=D:\Projects\fieldforce\node_modules\bcrypt\lib\binding --napi_version=8 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v83' (1)
npm ERR! node-pre-gyp ERR! stack     at ChildProcess. (D:\Projects\fieldforce\node_modules\node-pre-gyp\lib\util\compile.js:83:29)
npm ERR! node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:400:28)
npm ERR! node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:1058:16)
npm ERR! node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:293:5)
npm ERR! node-pre-gyp ERR! System Windows_NT 10.0.19042
npm ERR! node-pre-gyp ERR! command "C:\Program Files\nodejs\node.exe" "D:\Projects\fieldforce\node_modules\node-pre-gyp\bin\node-pre-gyp" "install" "--fallback-to-build"
npm ERR! node-pre-gyp ERR! cwd D:\Projects\fieldforce\node_modules\bcrypt
npm ERR! node-pre-gyp ERR! node -v v14.18.1
npm ERR! node-pre-gyp ERR! node-pre-gyp -v v0.14.0
npm ERR! node-pre-gyp ERR! not ok

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\nas\AppData\Local\npm-cache_logs\2022-02-01T07_39_35_752Z-debug-0.log

答: Remove the bcryptjs from package. Then give "npm i" command after this install bcrypt separately</p>


问:
Problem to test and mock uuid with angular and jasmine
I cannot figure out to mock uuid4 within my test.

I have a object to test, which looks something like that:

```<code>
import { v4 as uuidv4 } from 'uuid';

...

{
    id: uuidv4(),
    testnumer: 'S1EQ20024808SSUS1',
    productid: 'S1P10186044S005',
    starttime: new Date(Date.now()),
  };
</code>```

with jest it seems to be easy with

```<code>jest.mock('uuid', () => ({ v4: () => '00000000-0000-0000-0000-000000000000' }));
</code>```

but I cant figure it out to write a test within the objewct is created with angular and jasmine.

The date is easy with:

```<code>jasmine.clock().mockDate();
</code>```

I tried simon.

```<code>sinon.stub(uuid, 'v4').returns('cd589508-dcd6-44d8-99f8-ea99a54c15ed');
</code>```

but this doesn't work.

Any suggestions?

Thanks and regards

答:
The way to make this work is to wrap uuid in a service that you can then easily mock in your tests:

uuid.service.ts:

```<code>import { Injectable } from '@angular/core';
import { v4 } from 'uuid';

@Injectable({
  providedIn: 'root'
})
export class UuidService {
  v4(): string {
    return v4();
  }
}
</code>```

In your testfile:

```<code>describe('SomeComponent', () => {
  let uuidServiceMock: jasmine.SpyObj<UuidService>;

  beforeEach(() => {
    uuidServiceMock = jasmine.createSpyObj('UuidService', ['v4']);
  });

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ SomeComponent ],
      providers: [
        { provide: UuidService, useValue: uuidServiceMock }
      ]
    })
    .compileComponents();
  });

  ...

  it('is a test using uuid', () => {
    const newUuid = 'some-randomly-generated-uuid';
    uuidServiceMock.v4.and.returnValue(newUuid);

    component.methodUsingUuid();

    ...
  });
});
</code>```

Body:
I cannot figure out to mock uuid4 within my test.

I have a object to test, which looks something like that:

import { v4 as uuidv4 } from 'uuid';

...

{
    id: uuidv4(),
    testnumer: 'S1EQ20024808SSUS1',
    productid: 'S1P10186044S005',
    starttime: new Date(Date.now()),
  };

with jest it seems to be easy with

jest.mock('uuid', () => ({ v4: () => '00000000-0000-0000-0000-000000000000' }));

but I cant figure it out to write a test within the objewct is created with angular and jasmine.

The date is easy with:

jasmine.clock().mockDate();

I tried simon.

sinon.stub(uuid, 'v4').returns('cd589508-dcd6-44d8-99f8-ea99a54c15ed');

but this doesn't work.

Any suggestions?

Thanks and regards

Body:
The way to make this work is to wrap uuid in a service that you can then easily mock in your tests:

uuid.service.ts:

import { Injectable } from '@angular/core';
import { v4 } from 'uuid';

@Injectable({
  providedIn: 'root'
})
export class UuidService {
  v4(): string {
    return v4();
  }
}

In your testfile:

describe('SomeComponent', () => {
  let uuidServiceMock: jasmine.SpyObj<UuidService>;

  beforeEach(() => {
    uuidServiceMock = jasmine.createSpyObj('UuidService', ['v4']);
  });

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ SomeComponent ],
      providers: [
        { provide: UuidService, useValue: uuidServiceMock }
      ]
    })
    .compileComponents();
  });

  ...

  it('is a test using uuid', () => {
    const newUuid = 'some-randomly-generated-uuid';
    uuidServiceMock.v4.and.returnValue(newUuid);

    component.methodUsingUuid();

    ...
  });
});


问:
Dowload Media in Download directory in android app
Am trying to download media file from server to android default Downloads directory,but on storing the media in downloads i got exception java.io.FileNotFoundException: Download/01-21-2022 04:15.jpeg (No such file or directory)

here is my code

```<code>val fileName = message.attributes.jsonObject!!.get("fileName")
val contentLength = response.body()!!.contentLength()
val file = File(Environment.DIRECTORY_DOWNLOADS, fileName as String)
responseBody.byteStream().apply {
    file.outputStream().use { fileOut ->
    var bytesCopied = 0
    val buffer = ByteArray(8*1024)
    var bytes = read(buffer)
    while (bytes >= 0) {
     fileOut.write(buffer, 0, bytes)
     bytesCopied += bytes
     bytes = read(buffer)
     reportStatus(((bytesCopied * 100) / contentLength).toInt())
    }
   }
  }
</code>```

答:
val file = File(Environment.DIRECTORY_DOWNLOADS, fileName as String)

You mean:

```<code>val file = File(Environment.getExternalStoragePyblicDirectory(Environment.DIRECTORY_DOWNLOADS),  fileName as String)
</code>```

Body:
Am trying to download media file from server to android default Downloads directory,but on storing the media in downloads i got exception java.io.FileNotFoundException: Download/01-21-2022 04:15.jpeg (No such file or directory)

here is my code

val fileName = message.attributes.jsonObject!!.get("fileName")
val contentLength = response.body()!!.contentLength()
val file = File(Environment.DIRECTORY_DOWNLOADS, fileName as String)
responseBody.byteStream().apply {
    file.outputStream().use { fileOut ->
    var bytesCopied = 0
    val buffer = ByteArray(8*1024)
    var bytes = read(buffer)
    while (bytes >= 0) {
     fileOut.write(buffer, 0, bytes)
     bytesCopied += bytes
     bytes = read(buffer)
     reportStatus(((bytesCopied * 100) / contentLength).toInt())
    }
   }
  }

Body:
val file = File(Environment.DIRECTORY_DOWNLOADS, fileName as String)

You mean:

val file = File(Environment.getExternalStoragePyblicDirectory(Environment.DIRECTORY_DOWNLOADS),  fileName as String)


问:
SQL request for filter change produtc price. Rails app with PostgreSQL
Please tell me how you can make a query using SQL or ActiveRecord. I have table price_history: id, product_id, price, date . I need to sort those products whose price has changed more than 2 times. I am new to SQL. My application uses Ruby-on-Rails and PostgreSQL . I will be glad for any help. Thank you.

I probably didn't formulate my question clearly. I need to get something like the following:

```<code>table: prices_history
id  | product | price | date
--------------------------------
1     milk      2.0     01/01/2022
2     milk      2.5     10/01/2022
3     milk      6.0     20/02/2022
4     bread     2.0     01/01/2022
5     bread     2.1     10/01/2022
6     bread     3.0     20/02/2022

SQL request =>
milk: min_price = 2.0, max_price = 6.0, max_price/min_price = 3 > 2? it`s true
bread: min_price = 2.0, max_price = 3.0, max_price/min_price = 1,5 > 2? it`s false

result SQL request = > milk
</code>```

答:
Thanks to those who answered. Based on your answers, I formed my request and it works.</p>
```<code>SELECT
  product,
  MIN(price) as first_price,
  MAX(price) as last_price
FROM
  prices_history
GROUP BY
  product
HAVING
  MAX(price)/MIN(price) > 2;
</code>```

Body:
Please tell me how you can make a query using SQL or ActiveRecord. I have table price_history: id, product_id, price, date . I need to sort those products whose price has changed more than 2 times. I am new to SQL. My application uses Ruby-on-Rails and PostgreSQL . I will be glad for any help. Thank you.

I probably didn't formulate my question clearly. I need to get something like the following:

table: prices_history
id  | product | price | date
--------------------------------
1     milk      2.0     01/01/2022
2     milk      2.5     10/01/2022
3     milk      6.0     20/02/2022
4     bread     2.0     01/01/2022
5     bread     2.1     10/01/2022
6     bread     3.0     20/02/2022

SQL request =>
milk: min_price = 2.0, max_price = 6.0, max_price/min_price = 3 > 2? it`s true
bread: min_price = 2.0, max_price = 3.0, max_price/min_price = 1,5 > 2? it`s false

result SQL request = > milk

Body:
Thanks to those who answered. Based on your answers, I formed my request and it works.

SELECT
  product,
  MIN(price) as first_price,
  MAX(price) as last_price
FROM
  prices_history
GROUP BY
  product
HAVING
  MAX(price)/MIN(price) > 2;


问:
How to add keyboard shortcut for custom nemo action?
I have an custom nemo action as explained here:
https://wiki.archlinux.org/index.php/Nemo#Nemo_Actions

How can I add an shortcut for this action?

(If it can be done adding a line in ~/.gnome2/accels/nemo, then I have the additional problem that on my system this file is auto generated on every reboot, so editing something here will not help. I have Cinnamon 3.2.7 and nemo 3.2.2.)

Any suggestions? Thanks in advance! :)

答:
Am trying to respond to Duncan Marshall but the post ended up in the mainthread. Yes, it's possible. Your file ~/.gnome2/accels/nemo can contain a line such as the following, which would execute a scrip file named edit.sh when F4 is pressed. The scripfile must be located in this special path (~/.local/share/nemo/scripts) and it must be enabled via a checkbox in User Interface>Edit>Preferences>Plugins>Scripts. Also i was unable to specify a script path such as ~/... instead of /home/username... When the syntax in the accels/nemo file is incorrect, nemo will prepend the incorrect line with ; and it will also delete the keycode at the end of the line and it also likes to resort lines in the accels file. I will also dismiss a line when the keycode was already used in another line. So it couldn't be more tricky to get this right.

```<code>(gtk_accel_path "<Actions>/ScriptsGroup/script_file:\\s\\s\\shome\\sUSERNAME\\s.local\\sshare\\snemo\\sscripts\\sedit.sh" "F4")
</code>```

the script file might look like this

```<code>#!/bin/bash
export FILETOEDIT="$1"
FILEOWNER=$(stat -c %U "$1")
if [ "$FILEOWNER" = "$USER" ]; then
  subl "$1"
else
  sudo xed -w "$FILETOEDIT"
fi
</code>```

Body:
Am trying to respond to Duncan Marshall but the post ended up in the mainthread. Yes, it's possible. Your file ~/.gnome2/accels/nemo can contain a line such as the following, which would execute a scrip file named edit.sh when F4 is pressed. The scripfile must be located in this special path (~/.local/share/nemo/scripts) and it must be enabled via a checkbox in User Interface>Edit>Preferences>Plugins>Scripts. Also i was unable to specify a script path such as ~/... instead of /home/username... When the syntax in the accels/nemo file is incorrect, nemo will prepend the incorrect line with ; and it will also delete the keycode at the end of the line and it also likes to resort lines in the accels file. I will also dismiss a line when the keycode was already used in another line. So it couldn't be more tricky to get this right.

(gtk_accel_path "<Actions>/ScriptsGroup/script_file:\\s\\s\\shome\\sUSERNAME\\s.local\\sshare\\snemo\\sscripts\\sedit.sh" "F4")

the script file might look like this

#!/bin/bash
export FILETOEDIT="$1"
FILEOWNER=$(stat -c %U "$1")
if [ "$FILEOWNER" = "$USER" ]; then
  subl "$1"
else
  sudo xed -w "$FILETOEDIT"
fi


问:
How to connect firebase if I have multiple modules in my android native app
I am working on my Final year project, which is an android native app, using Kotlin. my question is how to connect firebase with all modules do I need to copy the JSON file in every module as well as add all the required dependencies in every module i.e. auth module, resources module, etc. I am confused about this I think this would be really hard to maintain.

Please give me some best suggestions on how to handle multi-module project effectively

答:
As you are already having a multi module Android app, so you definitely must be having a base/core module on which all the other modules must be depending on.

There are 2 things you can do

Add a common wrapper class where are firebase related code is present into your base module and then access the same across different modules.

Use api instead of implementation in your build.gradle file while adding firebase dependancy. This way you will get access to Firebase across all the modules which depend on your base/common module.


问:
How is XOR helping find the unique value?
I have a problem to writhe a function that finds the unique value from an array, i could not solve the problem but i asked someone to help, he provided the solution by using XOR(^), but could not explain for me to understand it. I know that XOR has the following table:

```<code>1 ^ 0 = 1
1 ^ 1 = 0
0 ^ 0 = 0
0 ^ 1 = 1
</code>```

So, if the values are different XOR returns 1 or a non negative value in case of other numbers but I still don't get how this is helping me to solve this.
Can someone please explain how the code below is working and how is it finding the unique value?

int xor = 0;
int index = 0;

while(index < arr.length) {
    xor = arr[index] ^ xor;
    index++;
}

return xor;
```

答:
If all the elements of the array can be grouped as pairs of equal numbers, XORing each pair of numbers will result in 0.
The order in which the elements are XORed doesn't matter.

For example, if the array is 4,5,4,5

```<code>xor = arr[0] ^ xor; // 0..0100 ^ 0..0000 = 0..0100
xor = arr[1] ^ xor; // 0..0101 ^ 0..0100 = 0..0001
xor = arr[2] ^ xor; // 0..0100 ^ 0..0001 = 0..0101
xor = arr[3] ^ xor; // 0..0101 ^ 0..0101 = 0..0000 = 0
</code>```

If, on the other hand, all the elements of the array but one can be paired, after XORing all of them, only that one un-paired element will remain.

For example, if the array is 4,5,6,4,5

```<code>xor = arr[0] ^ xor; // 0..0100 ^ 0..0000 = 0..0100
xor = arr[1] ^ xor; // 0..0101 ^ 0..0100 = 0..0001
xor = arr[2] ^ xor; // 0..0110 ^ 0..0001 = 0..0111
xor = arr[3] ^ xor; // 0..0100 ^ 0..0111 = 0..0011
xor = arr[4] ^ xor; // 0..0101 ^ 0..0011 = 0..0110 = 6
</code>```

Body:
I have a problem to writhe a function that finds the unique value from an array, i could not solve the problem but i asked someone to help, he provided the solution by using XOR(^), but could not explain for me to understand it. I know that XOR has the following table:

1 ^ 0 = 1
1 ^ 1 = 0
0 ^ 0 = 0
0 ^ 1 = 1

So, if the values are different XOR returns 1 or a non negative value in case of other numbers but I still don't get how this is helping me to solve this.
Can someone please explain how the code below is working and how is it finding the unique value?

int xor = 0;
int index = 0;

while(index < arr.length) {
    xor = arr[index] ^ xor;
    index++;
}

return xor;

Body:
If all the elements of the array can be grouped as pairs of equal numbers, XORing each pair of numbers will result in 0.
The order in which the elements are XORed doesn't matter.

For example, if the array is 4,5,4,5

xor = arr[0] ^ xor; // 0..0100 ^ 0..0000 = 0..0100
xor = arr[1] ^ xor; // 0..0101 ^ 0..0100 = 0..0001
xor = arr[2] ^ xor; // 0..0100 ^ 0..0001 = 0..0101
xor = arr[3] ^ xor; // 0..0101 ^ 0..0101 = 0..0000 = 0

If, on the other hand, all the elements of the array but one can be paired, after XORing all of them, only that one un-paired element will remain.

For example, if the array is 4,5,6,4,5

xor = arr[0] ^ xor; // 0..0100 ^ 0..0000 = 0..0100
xor = arr[1] ^ xor; // 0..0101 ^ 0..0100 = 0..0001
xor = arr[2] ^ xor; // 0..0110 ^ 0..0001 = 0..0111
xor = arr[3] ^ xor; // 0..0100 ^ 0..0111 = 0..0011
xor = arr[4] ^ xor; // 0..0101 ^ 0..0011 = 0..0110 = 6


问:
How can I declare a variable ($output) with the output within an IF -Statement?
My goal is to fill the variable $output with the, you guessed it, output of the PSService.exe. Unfortunately this does not work. At all.
As you can see in the code, I'm looking for a specific line, which is needed to tell if the command was a success or not.

```<code>Get-Content .\Computer.txt | ForEach-Object {
            $var = $_.Split(“+”)
}

foreach ($pc in $var) {
            .\PSService.exe \\$pc start WinRM
            $output = <command>
            If ($output –like “START_PENDING”){
                        Write-Host “Success $pc”
            } else {
                        Write-Host “Error $pc”
            }
}
</code>```

How can I declare a variable ($output) with the output within an IF -Statement?

答:
```<code>$output = .\PSService.exe \\$pc start WinRM
</code>```

This one does the job.

Body:
My goal is to fill the variable $output with the, you guessed it, output of the PSService.exe. Unfortunately this does not work. At all.
As you can see in the code, I'm looking for a specific line, which is needed to tell if the command was a success or not.

Get-Content .\Computer.txt | ForEach-Object {
            $var = $_.Split(“+”)
}

foreach ($pc in $var) {
            .\PSService.exe \\$pc start WinRM
            $output = <command>
            If ($output –like “START_PENDING”){
                        Write-Host “Success $pc”
            } else {
                        Write-Host “Error $pc”
            }
}

How can I declare a variable ($output) with the output within an IF -Statement?

Body:
$output = .\PSService.exe \\$pc start WinRM

This one does the job.


问:
Formatting character in deltalake
columnName (FORMAT'99999999.999') (CHAR(12))

How can I format this in deltalake , I searched for to_char method but there is no such method .

Can anyone help me please !

答:
I think can use

cast(format_string(columnName,'99999999.999') as CHAR(12))

Title: Formatting character in deltalake


问:
Can not launch Google authenticator app by deeplink on iOS 15
On iOS 14 or lower, I'm able to launch Google Authenticator app by deep link as the code below:

UIApplication.sharedApplication().openURL(NSURL(string: "otpauth://")!)

However, it does not work on iOS 15 anymore. It seems iOS 15 does not allow to trigger Google Authenticator app by deep link. I also tried on my phone browser with "otpauth://". It's only able to open the app with iOS 14. Can anyone help me about this issue? Thank you.

答: you can use this schema : googleauthenticator://


问:
AppStore Connect - What is ready for review state?
I made a new app and filled all info (description, build, keywords ..)

I submitted it to review and the state of my app was changed from " Prepare for Submission" to " Ready for Review"

Should I do something from my end ?
I don't have any "submit for review" button enabled .. I don't know what to do , I am stuck

答:
You have to submit it manually.
In the Left side, in section 'General', there should be a section 'App Review':

Click on App Review, in the following screen select view located on the right side of your version, Here you can submit your app.


问:
nuxt-leaflet problem with server side rendering (window is not defined)
i've been working on a ssr nuxt project n wanted to add nuxt-leaflet but apparently there's a window reference in nuxt-leaflet module that causes an (window not defined) error while server side rendering</p>

答:
this is because nuxt-leaflet use window object, you should render your component on client-side

<client-side>
   <Component/>
</client-side>
```


问:
How to pass data from nodejs to inside html script tags
I'm using expressjs as a server on 8000 port. I want to send a string value from expressjs file to html script tags and use this string value in script tags.
name variable is coming as a empty string now.
How can i console.log name variable's value?

static-pages-server.js:

```<code> app.get('/index', function(req, res) {
        var name = "hello";
        res.render(__dirname + "/static-pages/journey-analize-report/index.html", {name:name});
    });
</code>```

index.html:

```<code> <script type="text/javascript">
        console.log(name);
 </script>
</code>```

Edit : I used ejs and now problem is how should i describe name attribute in script tags? Below code is giving syntax error.

```<code><script type="text/javascript">
        console.log(<%=name%>);
 </script>
</code>```

答:
Express.js itself is a backend server. If you would like to have dynamic HTML files you need to use templates engines.

Please follow this document -> https://expressjs.com/en/guide/using-template-engines.html

Eventually, you will realize you will need a frontend framework to write your code faster with good quality. So also recommend you to take a look at some of the frameworks like React, Vue.js. If you need Single Page Applications you only use express.js to provide data not to render HTML. If you need Server-side rendering it is good to investigate Next.js, Nuxt.js.

Body:
I'm using expressjs as a server on 8000 port. I want to send a string value from expressjs file to html script tags and use this string value in script tags.
name variable is coming as a empty string now.
How can i console.log name variable's value?

static-pages-server.js:

 app.get('/index', function(req, res) {
        var name = "hello";
        res.render(__dirname + "/static-pages/journey-analize-report/index.html", {name:name});
    });

index.html:

Edit : I used ejs and now problem is how should i describe name attribute in script tags? Below code is giving syntax error.


问:
Truncation error SQL server 2005 Delete/Insert
So I am trying to do a bulk insert with SSIS and continually get:

"Microsoft SQL Native Client"  Hresult: 0x80004005  Description: "String or binary data would be truncated."

Even though I already have a data conversion for every column into the exact same type as the table that the rows are getting inserted into. I used a view and the data looks like it supposed to just before the DB insert step. Still get the error.

Next I went into sql server management studio and setup an insert query into that damned table and still get the same truncation error. I then did a set ANSI_WARNINGS  OFF and the insert works data looks good in the table. Now when I try to delete this row I get the Truncation error.

My question besides any basic input to the situation is how can I turn off the ANSI_WARNINGS within SSIS so that the bulk load can go though?

答:
It sounds like you have a column that is too narrow to accept the data you are submitting.

Can you verify if this is or isn't the case?

I had a very similar issue arise frequently while we were nailing down a schema with a third party.

Can you select a LEN of all of the columns in the view?  That could help find the issue.

Other than that, the only way I have found is to print out a report of the actual lengths of the source data columns.

OwnerDisplayName: Andrew Jahn

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: John Gietzen


问:
Check if springboot model list contains a certain value
I'm trying to find all entries in a MySQL database, with springboot, that have a certain id, certain status (public, private) which works fine by its self but when I try and check if it supports a certain software (I made a new table to store it. An id and the value so I can get the data) it gives an error

If that didnt make sense

I am trying to get all the entries that contain a certain string in a list. The list is a different table with an id column and the value. The id is the id for the resource, resource has updates and each update has a list of supported software

```<code>Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Feb 07 20:57:56 AEDT 2022
There was an unexpected error (type=Internal Server Error, status=500).
Ordinal parameter not bound : 3; nested exception is org.hibernate.QueryException: Ordinal parameter not bound : 3
org.springframework.dao.InvalidDataAccessResourceUsageException: Ordinal parameter not bound : 3; nested exception is org.hibernate.QueryException: Ordinal parameter not bound : 3
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:285)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:230)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:145)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
    at jdk.proxy4/jdk.proxy4.$Proxy108.findAllByResourceIdAndStatusEqualsAndSoftware(Unknown Source)
    at com.imjustdoom.pluginsite.controller.ResourcesController.resource(ResourcesController.java:156)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:121)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:218)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: org.hibernate.QueryException: Ordinal parameter not bound : 3
    at org.hibernate.query.internal.QueryParameterBindingsImpl.verifyParametersBound(QueryParameterBindingsImpl.java:214)
    at org.hibernate.query.internal.AbstractProducedQuery.beforeQuery(AbstractProducedQuery.java:1496)
    at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1602)
    at org.hibernate.query.Query.getResultList(Query.java:165)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:126)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:88)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:155)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:143)
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137)
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:159)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:138)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
    ... 96 more

</code>```

I am using models to store this stuff and this is the code that I am using. I know the IN is probably wrong but not sure what else would work

    @Query("SELECT updates FROM Update updates WHERE ?3 in(updates.software)")
    List<Update> findAllByResourceIdAndStatusEqualsAndSoftware(int resourceId, String status, String software, Sort sort);
```
<p>Update model</p>
<pre class="lang-java prettyprint-override"><code>@Getter
@Setter
@Entity
@Table(name = "update_table")
public class Update {

    public Update(String description, String filename, String version, String download, String name,
                  List<String> versions, List<String> software, Resource resource, String external) {
        this.downloads = 0;
        this.description = description;
        this.filename = filename;
        this.version = version;
        this.download = download;
        this.name = name;
        this.uploaded = LocalDateTime.now();
        this.versions = versions;
        this.software = software;
        this.resource = resource;
        this.external = external;
        this.status = "public";
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(nullable = false)
    private String description;

    @Column(nullable = false)
    private String filename;

    @ElementCollection
    private List<String> versions;

    @ElementCollection
    private List<String> software;

    @Column(nullable = false)
    private String download;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private LocalDateTime uploaded;

    @Column(nullable = false)
    private String version;

    @Column(nullable = false)
    private int downloads;

    @Column(nullable = false)
    private String external;

    @ManyToOne(fetch = FetchType.LAZY)
    private Resource resource;

    @Column(nullable = false)
    private String status;

    public Update() {

    }
}
</code>```

答:
You should exchange the order in in clause and transform your software parameter in List<String> .

```<code> @Query("SELECT updates FROM Update updates WHERE software in ?3")
    List<Update> findAllByResourceIdAndStatusEqualsAndSoftware(int resourceId, String status, List<String> software, Sort sort);
</code>```

also you should use @Param annotation instead of position.

Example:

```<code> @Query("SELECT updates FROM Update updates WHERE software in :software")
    List<Update> findAllByResourceIdAndStatusEqualsAndSoftware(int resourceId, String status, @Param("software") List<String software>, Sort sort);
</code>```

Body:
I'm trying to find all entries in a MySQL database, with springboot, that have a certain id, certain status (public, private) which works fine by its self but when I try and check if it supports a certain software (I made a new table to store it. An id and the value so I can get the data) it gives an error

If that didnt make sense

I am trying to get all the entries that contain a certain string in a list. The list is a different table with an id column and the value. The id is the id for the resource, resource has updates and each update has a list of supported software

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Feb 07 20:57:56 AEDT 2022
There was an unexpected error (type=Internal Server Error, status=500).
Ordinal parameter not bound : 3; nested exception is org.hibernate.QueryException: Ordinal parameter not bound : 3
org.springframework.dao.InvalidDataAccessResourceUsageException: Ordinal parameter not bound : 3; nested exception is org.hibernate.QueryException: Ordinal parameter not bound : 3
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:285)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:230)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:145)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215)
    at jdk.proxy4/jdk.proxy4.$Proxy108.findAllByResourceIdAndStatusEqualsAndSoftware(Unknown Source)
    at com.imjustdoom.pluginsite.controller.ResourcesController.resource(ResourcesController.java:156)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:327)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:81)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:121)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:126)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:81)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:149)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:218)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:103)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:89)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:110)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:55)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:336)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:211)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:183)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: org.hibernate.QueryException: Ordinal parameter not bound : 3
    at org.hibernate.query.internal.QueryParameterBindingsImpl.verifyParametersBound(QueryParameterBindingsImpl.java:214)
    at org.hibernate.query.internal.AbstractProducedQuery.beforeQuery(AbstractProducedQuery.java:1496)
    at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1602)
    at org.hibernate.query.Query.getResultList(Query.java:165)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:126)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:88)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:155)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:143)
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137)
    at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:159)
    at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:138)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)
    ... 96 more

I am using models to store this stuff and this is the code that I am using. I know the IN is probably wrong but not sure what else would work

    @Query("SELECT updates FROM Update updates WHERE ?3 in(updates.software)")
    List<Update> findAllByResourceIdAndStatusEqualsAndSoftware(int resourceId, String status, String software, Sort sort);

Update model

@Getter
@Setter
@Entity
@Table(name = "update_table")
public class Update {

    public Update(String description, String filename, String version, String download, String name,
                  List<String> versions, List<String> software, Resource resource, String external) {
        this.downloads = 0;
        this.description = description;
        this.filename = filename;
        this.version = version;
        this.download = download;
        this.name = name;
        this.uploaded = LocalDateTime.now();
        this.versions = versions;
        this.software = software;
        this.resource = resource;
        this.external = external;
        this.status = "public";
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(nullable = false)
    private String description;

    @Column(nullable = false)
    private String filename;

    @ElementCollection
    private List<String> versions;

    @ElementCollection
    private List<String> software;

    @Column(nullable = false)
    private String download;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private LocalDateTime uploaded;

    @Column(nullable = false)
    private String version;

    @Column(nullable = false)
    private int downloads;

    @Column(nullable = false)
    private String external;

    @ManyToOne(fetch = FetchType.LAZY)
    private Resource resource;

    @Column(nullable = false)
    private String status;

    public Update() {

    }
}

Body:
You should exchange the order in in clause and transform your software parameter in List<String> .

 @Query("SELECT updates FROM Update updates WHERE software in ?3")
    List<Update> findAllByResourceIdAndStatusEqualsAndSoftware(int resourceId, String status, List<String> software, Sort sort);

also you should use @Param annotation instead of position.

Example:

 @Query("SELECT updates FROM Update updates WHERE software in :software")
    List<Update> findAllByResourceIdAndStatusEqualsAndSoftware(int resourceId, String status, @Param("software") List<String software>, Sort sort);


问:
how to get xml data from a sp that has for xml using sql helper
We are trying to get data to a file , which is prepared using "select...for XML"
The code fragment that we are trying is :

```<code>filename = "";
filename = txtFolderPath.Text + roww[0].ToString() + ".xml";
SqlParameter[] a = new SqlParameter[1];
a[0] = new SqlParameter("@p_document_no", DbType.String);
a[0].Value = roww[0].ToString();
dtxml = SqlHelper.ExecuteXmlReader(Properties.Settings.Default.ConStr,
      CommandType.StoredProcedure, "dbo.PR_GENERATE_INVOICE_XML", a);
</code>```

the error we get :

Error 3   The best overloaded method match for
  'SqlHelper.ExecuteXmlReader(System.Data.SqlClient.SqlConnection,
  System.Data.CommandType, string, params
  System.Data.SqlClient.SqlParameter[])' has some invalid arguments

In the stored procedure, some values are calculated before entering the select portion of the sp so running as sql text command will not produce the desired output.

Any ideas are welcomed

答:
You are not passing in a SqlConnection which is what the method wants, you're passing a connection string. Use that to create the connection.

try...

```<code>SqlConnection conn = new SqlConnection(Properties.Settings.Default.ConStr);
dtxml = SqlHelper.ExecuteXmlReader(conn,
      CommandType.StoredProcedure, "dbo.PR_GENERATE_INVOICE_XML", a);
</code>```

Body:
We are trying to get data to a file , which is prepared using "select...for XML"
The code fragment that we are trying is :

filename = "";
filename = txtFolderPath.Text + roww[0].ToString() + ".xml";
SqlParameter[] a = new SqlParameter[1];
a[0] = new SqlParameter("@p_document_no", DbType.String);
a[0].Value = roww[0].ToString();
dtxml = SqlHelper.ExecuteXmlReader(Properties.Settings.Default.ConStr,
      CommandType.StoredProcedure, "dbo.PR_GENERATE_INVOICE_XML", a);

the error we get :

Error 3   The best overloaded method match for
  'SqlHelper.ExecuteXmlReader(System.Data.SqlClient.SqlConnection,
  System.Data.CommandType, string, params
  System.Data.SqlClient.SqlParameter[])' has some invalid arguments

In the stored procedure, some values are calculated before entering the select portion of the sp so running as sql text command will not produce the desired output.

Any ideas are welcomed

Body:
You are not passing in a SqlConnection which is what the method wants, you're passing a connection string. Use that to create the connection.

try...

SqlConnection conn = new SqlConnection(Properties.Settings.Default.ConStr);
dtxml = SqlHelper.ExecuteXmlReader(conn,
      CommandType.StoredProcedure, "dbo.PR_GENERATE_INVOICE_XML", a);


问:
Firefox Geckodriver Issue - INTERNALERROR>....WebDriverException: Message: TypeError: browsingContext.currentWindowGlobal is null
My suite works well with Chrome and Edge, but does not work with firefox. It start and abruptly ends.

Tried diff versions of geckodriver (32/64), updated firefox browser - no luck

Logs:
Image with logs

答:
I had the same error while using geckodriver yet everything worked fine while using chromedriver.

I needed to use driver.switch_to.default_content() after switching to an iframe beforehand. I guess chromedriver doesn't have a problem if you don't specify it, but geckodriver does.


问:
Chaining of operators with .|> in Julia
I have an expression

```<code> [1:5;] .|> [x->x^2, inv, x->2*x, -, isodd]
</code>```

taken from Julia documentation.

The output is

```<code>5-element Vector{Real}:
    1
    0.5
    6
   -4
 true
</code>```

Can somebody explain the chain of operations on each elements 1:5 in detail.
I did not understand why 1 is converted to 1 and 5 is converted to true.

答:
What you are doing is equivalent to:

```<code>julia> (x -> x^2)(1)
1

julia> inv(2)
0.5

julia> (x -> 2x)(3)
6

julia> -(4)
-4

julia> isodd(5)
true
</code>```

i.e. you are broadcasting a container with five functions to it over a range with five elements. The first function is then applied to the first element of your range, the second function to the second element etc.

Title: Chaining of operators with .|> in Julia

Body:
I have an expression

 [1:5;] .|> [x->x^2, inv, x->2*x, -, isodd]

taken from Julia documentation.

The output is

5-element Vector{Real}:
    1
    0.5
    6
   -4
 true

Can somebody explain the chain of operations on each elements 1:5 in detail.
I did not understand why 1 is converted to 1 and 5 is converted to true.

Body:
What you are doing is equivalent to:

julia> (x -> x^2)(1)
1

julia> inv(2)
0.5

julia> (x -> 2x)(3)
6

julia> -(4)
-4

julia> isodd(5)
true

i.e. you are broadcasting a container with five functions to it over a range with five elements. The first function is then applied to the first element of your range, the second function to the second element etc.


问:
Convert object to array of prorperties
I need to convert object:

```<code>{
        middleName: null,
        name: "Test Name",
        university: {
            country: {
                code: "PL"
            },
            isGraduated: true,
            speciality: "Computer Science"
        }
    }
</code>```

to array:

```<code>[{
        key: "name",
        propertyValue: "Test Name",
    },
    {
        key: "middleName",
        propertyValue: null,
    },
    {
        key: "university.isGraduated",
        propertyValue: true,
    },
    {
        key: "university.speciality",
        propertyValue: "Computer Science",
    },
    {
        key: "university.country.code",
        propertyValue: "PL"
    }];
</code>```

I wrote algorithm, but it's pretty dummy, how can I improve it? Important, if object has nested object than I need to write nested object via dot (e.g university.contry: "value")

```<code>let arr = [];
    Object.keys(parsedObj).map((key) => {
        if (parsedObj[key] instanceof Object) {
            Object.keys(parsedObj[key]).map((keyNested) => {
                if (parsedObj[key][keyNested] instanceof Object) {
                    Object.keys(parsedObj[key][keyNested]).map((keyNestedNested) => {
                        arr.push({ 'key': key + '.' + keyNested + '.' + keyNestedNested, 'propertyValue': parsedObj[key][keyNested][keyNestedNested] })
                    })
                } else {
                    arr.push({ 'key': key + '.' + keyNested, 'propertyValue': parsedObj[key][keyNested] })
                }
            })
        } else {
            arr.push({ 'key': key, 'propertyValue': parsedObj[key] })
        }
    });
</code>```

Thanks

答:
I'd probably take a recursive approach, and I'd probably avoid unnecessary intermediary arrays (though unless the original object is massive, it doesn't matter). For instance (see comments):

```<code>function convert(obj, target = [], prefix = "") {
    // Loop through the object keys
    for (const key in obj) {
        // Only handle "own" properties
        if (Object.hasOwn(obj, key)) {
            const value = obj[key];
            // Get the full key for this property, including prefix
            const fullKey = prefix ? prefix + "." + key : key;
            if (value && typeof value === "object") {
                // It's an object...
                if (Array.isArray(value)) {
                    throw new Error(`Arrays are not valid`);
                } else {
                    // ...recurse, providing the key as the prefix
                    convert(value, target, fullKey);
                }
            } else {
                // Not an object, push it to the array
                target.push({key: fullKey, propertyValue: value});
            }
        }
    }
    // Return the result
    return target;
}
</code>```

Live Example:

const original = {
    middleName: null,
    name: "Test Name",
    university: {
        country: {
            code: "PL"
        },
        isGraduated: true,
        speciality: "Computer Science"
    }
};

function convert(obj, target = [], prefix = "") {
    // Loop through the object keys
    for (const key in obj) {
        // Only handle "own" properties
        if (Object.hasOwn(obj, key)) {
            const value = obj[key];
            // Get the full key for this property, including prefix
            const fullKey = prefix ? prefix + "." + key : key;
            if (value && typeof value === "object") {
                // It's an object...
                if (Array.isArray(value)) {
                    throw new Error(`Arrays are not valid`);
                } else {
                    // ...recurse, providing the key as the prefix
                    convert(value, target, fullKey);
                }
            } else {
                // Not an object, push it to the array
                target.push({key: fullKey, propertyValue: value});
            }
        }
    }
    // Return the result
    return target;
}
const result = convert(original, []);
console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
    max-height: 100% !important;
}</code>```

Note that I've assumed the order of the array entries isn't significant. The output you said you wanted is at odds with the standard order of JavaScript object properties (yes, they have an order now; no, it's not something I suggest relying on ). I've gone ahead and not worried about the order within an object.

Title: Convert object to array of prorperties

Body:
I need to convert object:

{
        middleName: null,
        name: "Test Name",
        university: {
            country: {
                code: "PL"
            },
            isGraduated: true,
            speciality: "Computer Science"
        }
    }

to array:

[{
        key: "name",
        propertyValue: "Test Name",
    },
    {
        key: "middleName",
        propertyValue: null,
    },
    {
        key: "university.isGraduated",
        propertyValue: true,
    },
    {
        key: "university.speciality",
        propertyValue: "Computer Science",
    },
    {
        key: "university.country.code",
        propertyValue: "PL"
    }];

I wrote algorithm, but it's pretty dummy, how can I improve it? Important, if object has nested object than I need to write nested object via dot (e.g university.contry: "value")

let arr = [];
    Object.keys(parsedObj).map((key) => {
        if (parsedObj[key] instanceof Object) {
            Object.keys(parsedObj[key]).map((keyNested) => {
                if (parsedObj[key][keyNested] instanceof Object) {
                    Object.keys(parsedObj[key][keyNested]).map((keyNestedNested) => {
                        arr.push({ 'key': key + '.' + keyNested + '.' + keyNestedNested, 'propertyValue': parsedObj[key][keyNested][keyNestedNested] })
                    })
                } else {
                    arr.push({ 'key': key + '.' + keyNested, 'propertyValue': parsedObj[key][keyNested] })
                }
            })
        } else {
            arr.push({ 'key': key, 'propertyValue': parsedObj[key] })
        }
    });

Thanks

Body:
I'd probably take a recursive approach, and I'd probably avoid unnecessary intermediary arrays (though unless the original object is massive, it doesn't matter). For instance (see comments):

function convert(obj, target = [], prefix = "") {
    // Loop through the object keys
    for (const key in obj) {
        // Only handle "own" properties
        if (Object.hasOwn(obj, key)) {
            const value = obj[key];
            // Get the full key for this property, including prefix
            const fullKey = prefix ? prefix + "." + key : key;
            if (value && typeof value === "object") {
                // It's an object...
                if (Array.isArray(value)) {
                    throw new Error(`Arrays are not valid`);
                } else {
                    // ...recurse, providing the key as the prefix
                    convert(value, target, fullKey);
                }
            } else {
                // Not an object, push it to the array
                target.push({key: fullKey, propertyValue: value});
            }
        }
    }
    // Return the result
    return target;
}

Live Example:

const original = {
    middleName: null,
    name: "Test Name",
    university: {
        country: {
            code: "PL"
        },
        isGraduated: true,
        speciality: "Computer Science"
    }
};

function convert(obj, target = [], prefix = "") {
    // Loop through the object keys
    for (const key in obj) {
        // Only handle "own" properties
        if (Object.hasOwn(obj, key)) {
            const value = obj[key];
            // Get the full key for this property, including prefix
            const fullKey = prefix ? prefix + "." + key : key;
            if (value && typeof value === "object") {
                // It's an object...
                if (Array.isArray(value)) {
                    throw new Error(`Arrays are not valid`);
                } else {
                    // ...recurse, providing the key as the prefix
                    convert(value, target, fullKey);
                }
            } else {
                // Not an object, push it to the array
                target.push({key: fullKey, propertyValue: value});
            }
        }
    }
    // Return the result
    return target;
}
const result = convert(original, []);
console.log(result);

.as-console-wrapper {
    max-height: 100% !important;
}

Note that I've assumed the order of the array entries isn't significant. The output you said you wanted is at odds with the standard order of JavaScript object properties (yes, they have an order now; no, it's not something I suggest relying on ). I've gone ahead and not worried about the order within an object.


问:
Python list comprehension: Unlist if list contains only one element
I have got the following function:

```<code>output_names = [output.name for output in session.get_outputs()]
</code>```

session.get_outputs() can return multiple multiple objects which I want to get the name property from. If the length of the list is 1, I want to output_names to be a value, not a list with a single value.

```<code>output_names = [output.name for output in session.get_outputs()]
if len(output_names) == 1:
    output_names = output_names[0]
</code>```

I could do it like this, but this feels like a code smell. It there a more elegant way to solve this?

答:
How about adjusting the way you construct output_names like:

```<code>outputs = session.get_outputs()
output_names = [output.name for output in outputs] if len(outputs)>1 else outputs.name
</code>```

That said, mixing data types is not desirable, imo.

Body:
I have got the following function:

output_names = [output.name for output in session.get_outputs()]

session.get_outputs() can return multiple multiple objects which I want to get the name property from. If the length of the list is 1, I want to output_names to be a value, not a list with a single value.

output_names = [output.name for output in session.get_outputs()]
if len(output_names) == 1:
    output_names = output_names[0]

I could do it like this, but this feels like a code smell. It there a more elegant way to solve this?

Body:
How about adjusting the way you construct output_names like:

outputs = session.get_outputs()
output_names = [output.name for output in outputs] if len(outputs)>1 else outputs.name

That said, mixing data types is not desirable, imo.


问:
Trigger Lambda function by S3 PUT in subfolder of undefined folder
I have an AWS Lambda function, that I want to trigger when a user uploads a file to a subfolder in their S3 directory.

Every user has its own folder inside the 'private/' prefix, but when the user is uploading a file, it's put in a subfolder. This means that the trigger prefix should be 'private/userID/subFolder/', but I can't find how to define that the userID could be anything.

I have tried making the prefix 'private/*/subFolder/', but that doesn't trigger anything. If I make the prefix 'private/', the function will be triggered unnecessarily.

What is the best way to do this?

答:
You have to create a rule for each user:</p>
```<code>private/userID1/subFolder
private/userID2/subFolder
private/userID3/subFolder
</code>```

Body:
You have to create a rule for each user:

private/userID1/subFolder
private/userID2/subFolder
private/userID3/subFolder


问:
Firestore React get document by URL
I have a question about the operation that can be used with firestore

I have a table displaying a list of documents. (url: localhost/dashboard/users)

When I click on a document in the list, I want to be redirected to a details page. (url: localhost/dashboard/user/1)

Except that with firestore, my url is represented in this form:
(url: localhost/dashboard/user/MuVsCLALiQPZuxnV3yyQ)

How do you get a details page with a "clean" URL.

Knowing that I want to be able to display the details of a user by going through the complete url and without necessarily going through the list

答:
If by "clean" you mean integers or shorter UIDs then you'll can store a field in user's Firestore document e.g. {shortUid: 1} (or set that short UID as document ID at first place) and then query based on the ID:

```<code>const userId = getIdFromURL();

const user = await getDocs(collection(db, "users"), where("shortUid", "==", userId))
</code>```

Using sequential IDs is not recommended with NoSQL databases like Firestore so do checkout Firestore Best Practices

Title: Firestore React get document by URL

Body:
If by "clean" you mean integers or shorter UIDs then you'll can store a field in user's Firestore document e.g. {shortUid: 1} (or set that short UID as document ID at first place) and then query based on the ID:

const userId = getIdFromURL();

const user = await getDocs(collection(db, "users"), where("shortUid", "==", userId))

Using sequential IDs is not recommended with NoSQL databases like Firestore so do checkout Firestore Best Practices