问:
Determining which part of a JSON Schema a given word belongs to with monaco
I'm using the monaco editor for validating JSON in accordance with a custom schema, such as is described in this Playground example.

Next, I'd like to customize a hover event whose behavior depends on which part of the schema is being hovered over. I can easily add a hover event that knows what word I'm hovering over, by just adding some code like this:

```<code>monaco.languages.registerHoverProvider('json', {
  provideHover: function(model, position) {
    // get the word that the cursor is currently hovering over
    var word = model.getWordAtPosition(position);
    var wordRange = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);

    return {
      contents: [{ value: 'This word is: ' + word.word }],
      range: wordRange
    };
  }
});
</code>```

But what I also need to know is the schema path-- something like this, but with a properly functioning getSchemaPart():

```<code>function getSchemaPart(model, position) {
  return ['http://myserver/bar-schema.json#', 'p1'].join('/');  // How do I do this properly?
}

monaco.languages.registerHoverProvider('json', {
  provideHover: function(model, position) {
    // get the word that the cursor is currently hovering over
    var word = model.getWordAtPosition(position);
    var wordRange = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);

    var schemaPart = getSchemaPart(model, position);

    return {
      contents: [{ value: 'This word is: ' + word.word + ' and its schema part is ' + schemaPart }],
      range: wordRange
    };
  }
});

</code>```

Clearly, Monaco already knows this information since it's needed for validation. Is there any way to fetch it in my hover event?

Alternatively, is there a clean way to use some other library and feed it the entire JSON value, and then figure out what schema part applies to the particular position that is being hovered over? This latter approach seems feasible in theory but challenging when considering that there may be whitespace in the input which the parser ignores, and therefore it requires mapping positions to tokens to schema parts.

Body:
I'm using the monaco editor for validating JSON in accordance with a custom schema, such as is described in this Playground example.

Next, I'd like to customize a hover event whose behavior depends on which part of the schema is being hovered over. I can easily add a hover event that knows what word I'm hovering over, by just adding some code like this:

monaco.languages.registerHoverProvider('json', {
  provideHover: function(model, position) {
    // get the word that the cursor is currently hovering over
    var word = model.getWordAtPosition(position);
    var wordRange = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);

    return {
      contents: [{ value: 'This word is: ' + word.word }],
      range: wordRange
    };
  }
});

But what I also need to know is the schema path-- something like this, but with a properly functioning getSchemaPart():

function getSchemaPart(model, position) {
  return ['http://myserver/bar-schema.json#', 'p1'].join('/');  // How do I do this properly?
}

monaco.languages.registerHoverProvider('json', {
  provideHover: function(model, position) {
    // get the word that the cursor is currently hovering over
    var word = model.getWordAtPosition(position);
    var wordRange = new monaco.Range(position.lineNumber, word.startColumn, position.lineNumber, word.endColumn);

    var schemaPart = getSchemaPart(model, position);

    return {
      contents: [{ value: 'This word is: ' + word.word + ' and its schema part is ' + schemaPart }],
      range: wordRange
    };
  }
});

Clearly, Monaco already knows this information since it's needed for validation. Is there any way to fetch it in my hover event?

Alternatively, is there a clean way to use some other library and feed it the entire JSON value, and then figure out what schema part applies to the particular position that is being hovered over? This latter approach seems feasible in theory but challenging when considering that there may be whitespace in the input which the parser ignores, and therefore it requires mapping positions to tokens to schema parts.


来源: stackexchange

问:
while using proc_open(), my time stamp to terminate the function is not working properly
I am having issues with my php code. I am executing c++rom fffff code using proc_open() in php.

```<code>//from another function I'm calling this function with parameters execute("code.exe", $STDIN, 0.02, 268435456 * 2);
//my c++ code is already executed to .exe file.

function execute($cmd, $stdin, $timeout, $memoryout)
{
    $descriptorspec = [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']];
    $timer = microtime(true);
    $TL = false;
    $ML = 0;
    $stdout = '';

    $process = proc_open($cmd, $descriptorspec, $pipes);

    fwrite($pipes[0], $stdin);
    fclose($pipes[0]);

    while(!feof($pipes[1]))
    {
        if($timer + $timeout < microtime(true))
        {
            $TL = true;
            break;
        }

        $ML = max($ML, memory_get_usage());

        $stdout .= fread($pipes[1], 1);// . "<br/>";

        if($timer + $timeout < microtime(true))
        {
            $TL = true;
            break;
        }
    }

    $status = proc_get_status($process);

    if(!$status['running'])
        if($status['exitcode'] !== 0) $stdout = 'code:RE';
    if($TL) $stdout = 'code:TL';
    if($ML > $memoryout) $stdout = 'code:ML';

    $pid = proc_get_status($process)['pid'];
    strstr(PHP_OS, 'WIN') ? exec("taskkill /F /T /PID $pid") : exec("kill -9 $pid");

    fclose($pipes[1]);
    proc_close($process);

    return $stdout;
}
</code>```

So, when my c++ code is correctly written, there is no problem, but when i've written something like "while(1);" in my c++ code, my php code does not terminate. while(!feof($pipes[1])) cycle loops forever and I don't know what to do.

I've tried to use getrusage() instead of time stamp but it was worse.

ContentLicense: CC BY-SA 4.0

Body:
I am having issues with my php code. I am executing c++rom fffff code using proc_open() in php.

//from another function I'm calling this function with parameters execute("code.exe", $STDIN, 0.02, 268435456 * 2);
//my c++ code is already executed to .exe file.

function execute($cmd, $stdin, $timeout, $memoryout)
{
    $descriptorspec = [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']];
    $timer = microtime(true);
    $TL = false;
    $ML = 0;
    $stdout = '';

    $process = proc_open($cmd, $descriptorspec, $pipes);

    fwrite($pipes[0], $stdin);
    fclose($pipes[0]);

    while(!feof($pipes[1]))
    {
        if($timer + $timeout < microtime(true))
        {
            $TL = true;
            break;
        }

        $ML = max($ML, memory_get_usage());

        $stdout .= fread($pipes[1], 1);// . "
";

        if($timer + $timeout < microtime(true))
        {
            $TL = true;
            break;
        }
    }

    $status = proc_get_status($process);

    if(!$status['running'])
        if($status['exitcode'] !== 0) $stdout = 'code:RE';
    if($TL) $stdout = 'code:TL';
    if($ML > $memoryout) $stdout = 'code:ML';

    $pid = proc_get_status($process)['pid'];
    strstr(PHP_OS, 'WIN') ? exec("taskkill /F /T /PID $pid") : exec("kill -9 $pid");

    fclose($pipes[1]);
    proc_close($process);

    return $stdout;
}

So, when my c++ code is correctly written, there is no problem, but when i've written something like "while(1);" in my c++ code, my php code does not terminate. while(!feof($pipes[1])) cycle loops forever and I don't know what to do.

I've tried to use getrusage() instead of time stamp but it was worse.


问:
Questions about Pintura image\video editor
I am currently evaluating Pintura image and video editor and I had a couple of questions

a. regarding the image editor and SDK:
If I have an image of a person with his T-Shirt, how can I change the color of just the T-Shirt ? Can I superimpose an image on top of the t-shirt in the image?
Can I "pre-define" editable text areas on the image which can be later edited by someone else in the image editor?

b. Similarly  with respect to video editor and SDK:
If I have an video of a person with his T-Shirt, can I change the color of just the T-Shirt ? Can I superimpose a user provided image on top of the tshirt in the video?

Would the community have an input?


问:
Environment variable is not always printed correctly
When I write such script in simple Jenkins pipeline:

```<code>pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo "${env.HOMEPATH}"
            }
        }
    }
}
</code>```

I receive this output:

```<code>Started by user USER_1
Replayed #36
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in C:\Users\USER_1\AppData\Local\Jenkins\.jenkins\workspace\2nd_pipeline
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] echo
\Users\USER_1
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS
</code>```

However when I write in pipeline script only this:

```<code>echo "${env.HOMEPATH}"
</code>```

I receive only this:

```<code>Started by user USER_1
Replayed #37
[Pipeline] Start of Pipeline
[Pipeline] echo
null
[Pipeline] End of Pipeline
Finished: SUCCESS
</code>```

My question is why when I write only a single line in pipeline script to print env.HOMEPATH I receive null, but when I use pipeline block the variable is printed correctly? HOMEPATH is a variable defined on my the only one node (master) so it has been also injected to Jenkins environment variables.

Body:
When I write such script in simple Jenkins pipeline:

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                echo "${env.HOMEPATH}"
            }
        }
    }
}

I receive this output:

Started by user USER_1
Replayed #36
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in C:\Users\USER_1\AppData\Local\Jenkins\.jenkins\workspace\2nd_pipeline
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] echo
\Users\USER_1
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
Finished: SUCCESS

However when I write in pipeline script only this:

echo "${env.HOMEPATH}"

I receive only this:

Started by user USER_1
Replayed #37
[Pipeline] Start of Pipeline
[Pipeline] echo
null
[Pipeline] End of Pipeline
Finished: SUCCESS

My question is why when I write only a single line in pipeline script to print env.HOMEPATH I receive null, but when I use pipeline block the variable is printed correctly? HOMEPATH is a variable defined on my the only one node (master) so it has been also injected to Jenkins environment variables.


问:
Header section not displaying in collectionview programmatically
```<code>import UIKit

class UserProfileController : UICollectionViewController, UICollectionViewDelegateFlowLayout{

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = .white

        //NEED TO UPDATE: GET USERNAME TO AND SET NAVTITLE
        fetchUser()

        //UPDATE ALL USER PAGE INFO IN

        collectionView?.register(UICollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")
    }

    fileprivate func fetchUser(){
        //Assumed loged in get user ID
        //guard let uid = currentUser?.uid else {return}

        //NEED TO UPDATE: GET USERNAME FROM USER ID HASH
        let username = "User Profile"
        navigationItem.title = username
    }

    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerId", for: indexPath)

        header.backgroundColor = .green

        return header
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: view.frame.width, height: 200)
    }
}
</code>```

I just programmatically set an header, register it also gave it size by using referencesizeforheader. But it will not display on the screen. I also use this controller on the tab bar. In Scene delegate ı made the rootController of this tabbar controller. In the code side ı think there is no problem but ı can't see any difference. Could you help me please ?

Body:
import UIKit

class UserProfileController : UICollectionViewController, UICollectionViewDelegateFlowLayout{

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = .white

        //NEED TO UPDATE: GET USERNAME TO AND SET NAVTITLE
        fetchUser()

        //UPDATE ALL USER PAGE INFO IN

        collectionView?.register(UICollectionViewCell.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "headerId")
    }

    fileprivate func fetchUser(){
        //Assumed loged in get user ID
        //guard let uid = currentUser?.uid else {return}

        //NEED TO UPDATE: GET USERNAME FROM USER ID HASH
        let username = "User Profile"
        navigationItem.title = username
    }

    override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "headerId", for: indexPath)

        header.backgroundColor = .green

        return header
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: view.frame.width, height: 200)
    }
}

I just programmatically set an header, register it also gave it size by using referencesizeforheader. But it will not display on the screen. I also use this controller on the tab bar. In Scene delegate ı made the rootController of this tabbar controller. In the code side ı think there is no problem but ı can't see any difference. Could you help me please ?


问:
Parquet 2.4+ and PyArrow 10.0.1 - Attempting to switch pyarrow column from string to datetime
I attempted to follow the advice of Converting string timestamp to datetime using pyarrow , however my formatting seems to not be accepted by pyarrow

```<code>import pyarrow as pa
import pyarrow.parquet as pq
import pyarrow.compute as pc

table = pa.table({'n_legs': [2, 2, 4, 4, 5, 100],

                  'query_start_time': ["2022-12-30T19:02:40.466",
                                       "2022-12-30T19:02:40.466",
                                       "2022-12-30T19:02:40.466",
                                       "2022-12-30T19:02:40.466",
                                       "2022-12-30T19:02:40.466",
                                       "2022-12-30T19:02:40.466"]})

pc.strptime(table.column("query_start_time"), format='%Y-%m-%dT%H:%M:%S.%f', unit='ms')

writer = pq.ParquetWriter('example.parquet', table.schema)
writer.write_table(table)
writer.close()
</code>```

I've attempted removing the T , adding a Z at the end of the formatter and string.. seems instead I need to ..?

```<code>Traceback (most recent call last):
  File "/home/emcp/Dev/temp_pyarrow/main.py", line 16, in <module>
    pc.strptime(table.column("query_start_time"), format='%Y-%m-%d %H:%M:%S.%f', unit='ms')
  File "/home/emcp/Dev/temp_pyarrow/venv/lib/python3.10/site-packages/pyarrow/compute.py", line 255, in wrapper
    return func.call(args, options, memory_pool)
  File "pyarrow/_compute.pyx", line 355, in pyarrow._compute.Function.call
  File "pyarrow/error.pxi", line 144, in pyarrow.lib.pyarrow_internal_check_status
  File "pyarrow/error.pxi", line 100, in pyarrow.lib.check_status
pyarrow.lib.ArrowInvalid: Failed to parse string: '2022-12-30T19:02:40.466' as a scalar of type timestamp[ms]
</code>```

Do I need to manually convert the datetime value into an integer column and THEN change the column again?

EDIT: When I strip the .%f and change units to units='s' it seems to not error.. I am looking into that now

Body:
I attempted to follow the advice of Converting string timestamp to datetime using pyarrow , however my formatting seems to not be accepted by pyarrow

import pyarrow as pa
import pyarrow.parquet as pq
import pyarrow.compute as pc

table = pa.table({'n_legs': [2, 2, 4, 4, 5, 100],

                  'query_start_time': ["2022-12-30T19:02:40.466",
                                       "2022-12-30T19:02:40.466",
                                       "2022-12-30T19:02:40.466",
                                       "2022-12-30T19:02:40.466",
                                       "2022-12-30T19:02:40.466",
                                       "2022-12-30T19:02:40.466"]})

pc.strptime(table.column("query_start_time"), format='%Y-%m-%dT%H:%M:%S.%f', unit='ms')

writer = pq.ParquetWriter('example.parquet', table.schema)
writer.write_table(table)
writer.close()

I've attempted removing the T , adding a Z at the end of the formatter and string.. seems instead I need to ..?

Traceback (most recent call last):
  File "/home/emcp/Dev/temp_pyarrow/main.py", line 16, in <module>
    pc.strptime(table.column("query_start_time"), format='%Y-%m-%d %H:%M:%S.%f', unit='ms')
  File "/home/emcp/Dev/temp_pyarrow/venv/lib/python3.10/site-packages/pyarrow/compute.py", line 255, in wrapper
    return func.call(args, options, memory_pool)
  File "pyarrow/_compute.pyx", line 355, in pyarrow._compute.Function.call
  File "pyarrow/error.pxi", line 144, in pyarrow.lib.pyarrow_internal_check_status
  File "pyarrow/error.pxi", line 100, in pyarrow.lib.check_status
pyarrow.lib.ArrowInvalid: Failed to parse string: '2022-12-30T19:02:40.466' as a scalar of type timestamp[ms]

Do I need to manually convert the datetime value into an integer column and THEN change the column again?

EDIT: When I strip the .%f and change units to units='s' it seems to not error.. I am looking into that now


问:
everything is okay unless I press the backspace key, then I have viewed the file and strings are not for human reading
If I have made a wrong letter and I wanted to deleted by hitting the backspace key, It keeps printing a language that can not be read by a human.</p>
```<code>#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

void main(void)
{
    FILE *poointer;
    poointer= fopen("TestingXX.txt","w");
    char ch;

     while ( (ch=getche()) != '\r')
        {
            putc(ch,poointer);
        }

    fclose(poointer);

}
</code>```

Body:
If I have made a wrong letter and I wanted to deleted by hitting the backspace key, It keeps printing a language that can not be read by a human.

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>

void main(void)
{
    FILE *poointer;
    poointer= fopen("TestingXX.txt","w");
    char ch;

     while ( (ch=getche()) != '\r')
        {
            putc(ch,poointer);
        }

    fclose(poointer);

}


问:
Compatibility interval for the weight of someone of specified height
I have a pandas data frame df with observed weights and heights (df.weight and df.height resp.)

I am trying to use linear regression (predicting weight from height) with Pymc3 to find an 89% compatibility interval for the weight of an 140cm tall individual.

This is my setup so far

```<code>with pm.Model() as q1_model:
    # specify the model
    alpha = pm.Normal('alpha', mu=45, sd=100)
    beta = pm.Normal('beta', mu=0, sd=10)
    sigma = pm.Uniform('sigma', lower=0, upper=50)
    weight = pm.Normal('weight', mu=alpha + beta * df.height_c, sd=sigma, observed=df.weight)

    # find the posterior distribution of the weight
    trace = pm.sample(1000)
</code>```

where df.height_c is df.height - df.height.mean(). But I'm not sure how to get the interval. I tried:

```<code>pm.hdi(trace.alpha + (140 - df.height.mean()) * trace.beta, 0.89)
</code>```

which gives [35.0, 36.6] but I think this is just an interval for the mean height mu of an 140cm person, not for height itself. The actual interval is supposedly meant to be [29.1, 42.8] confirming my suspicion here.

```<code></code>```

Body:
I have a pandas data frame df with observed weights and heights (df.weight and df.height resp.)

I am trying to use linear regression (predicting weight from height) with Pymc3 to find an 89% compatibility interval for the weight of an 140cm tall individual.

This is my setup so far

with pm.Model() as q1_model:
    # specify the model
    alpha = pm.Normal('alpha', mu=45, sd=100)
    beta = pm.Normal('beta', mu=0, sd=10)
    sigma = pm.Uniform('sigma', lower=0, upper=50)
    weight = pm.Normal('weight', mu=alpha + beta * df.height_c, sd=sigma, observed=df.weight)

    # find the posterior distribution of the weight
    trace = pm.sample(1000)

where df.height_c is df.height - df.height.mean(). But I'm not sure how to get the interval. I tried:

pm.hdi(trace.alpha + (140 - df.height.mean()) * trace.beta, 0.89)

which gives [35.0, 36.6] but I think this is just an interval for the mean height mu of an 140cm person, not for height itself. The actual interval is supposedly meant to be [29.1, 42.8] confirming my suspicion here.


问:
How to run initialize when switching view in Gluon mobile
I am using gluon mobile to build my app and I want to update the home window when switching to it with the view.getAppManager.goHome() but unlike setting a new scene in javafx this does not run the initialize function in my home controller.

At first I tried fixing it by changing the scene like in javafx but because the of the way that gluon mobile works it discards a lot of the benefits of the API, like the App bar and so on. I was hoping that there is an easy way to run initialize when switching a view. Another fix I tried is to make my update method public and run it through my other view controller but because I cannot make it satatic, I got nullPointerExeptions when making a new HomePresenter.myUpdateToHomeView.  Does Someone know how to work around this?


问:
Unable to deploy 11ty site via Netlify due to fsevents platform error
I'm trying to deploy my 11ty site via Netlify using Github for the continuous deployment however I'm unable to due to the following error:

```<code>8:12:37 PM: npm ERR! code EBADPLATFORM
8:12:37 PM: npm ERR! notsup Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin"} (current: {"os":"linux","arch":"x64"})
8:12:37 PM: npm ERR! notsup Valid OS:    darwin
8:12:37 PM: npm ERR! notsup Valid Arch:  undefined
8:12:37 PM: npm ERR! notsup Actual OS:   linux
8:12:37 PM: Failed during stage 'building site': Build script returned non-zero exit code: 1 (https://ntl.fyi/exit-code-1)
8:12:37 PM: npm ERR! notsup Actual Arch: x64
8:12:37 PM: npm ERR! A complete log of this run can be found in:
8:12:37 PM: npm ERR!     /opt/buildhome/.npm/_logs/2023-01-02T20_12_36_805Z-debug-0.log
8:12:37 PM: Error during NPM install
8:12:37 PM: Build was terminated: Build script returned non-zero exit code: 1
8:12:37 PM: Failing build: Failed to build site
8:12:37 PM: Finished processing build request in 11.045830236s
</code>```

I've tried deleting the package-lock.json file along with the node_modules directory and then re-triggering the deployment but that still throws the same error.

I've also added --omit=optional flag to the npm install command but still no luck.

I develop locally on my Mac and from what I can tell the fsevents package is installed via a separate dependancy to do with file watching. I think it's installed due to the below section of the package-lock.json file (hence why I thought the --omit=optional flag would solve the issue):

```<code>"node_modules/chokidar": {
      "version": "3.5.3",
      "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz",
      "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==",
      "funding": [
        {
          "type": "individual",
          "url": "https://paulmillr.com/funding/"
        }
      ],
      "dependencies": {
        "anymatch": "~3.1.2",
        "braces": "~3.0.2",
        "glob-parent": "~5.1.2",
        "is-binary-path": "~2.1.0",
        "is-glob": "~4.0.1",
        "normalize-path": "~3.0.0",
        "readdirp": "~3.6.0"
      },
      "engines": {
        "node": ">= 8.10.0"
      },
      "optionalDependencies": {
        "fsevents": "~2.3.2"
      }
    },
</code>```

Has anyone seen this before and know of a fix?

Thanks in advance!

Body:
I'm trying to deploy my 11ty site via Netlify using Github for the continuous deployment however I'm unable to due to the following error:

8:12:37 PM: npm ERR! code EBADPLATFORM
8:12:37 PM: npm ERR! notsup Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin"} (current: {"os":"linux","arch":"x64"})
8:12:37 PM: npm ERR! notsup Valid OS:    darwin
8:12:37 PM: npm ERR! notsup Valid Arch:  undefined
8:12:37 PM: npm ERR! notsup Actual OS:   linux
8:12:37 PM: Failed during stage 'building site': Build script returned non-zero exit code: 1 (https://ntl.fyi/exit-code-1)
8:12:37 PM: npm ERR! notsup Actual Arch: x64
8:12:37 PM: npm ERR! A complete log of this run can be found in:
8:12:37 PM: npm ERR!     /opt/buildhome/.npm/_logs/2023-01-02T20_12_36_805Z-debug-0.log
8:12:37 PM: Error during NPM install
8:12:37 PM: Build was terminated: Build script returned non-zero exit code: 1
8:12:37 PM: Failing build: Failed to build site
8:12:37 PM: Finished processing build request in 11.045830236s

I've tried deleting the package-lock.json file along with the node_modules directory and then re-triggering the deployment but that still throws the same error.

I've also added --omit=optional flag to the npm install command but still no luck.

I develop locally on my Mac and from what I can tell the fsevents package is installed via a separate dependancy to do with file watching. I think it's installed due to the below section of the package-lock.json file (hence why I thought the --omit=optional flag would solve the issue):

"node_modules/chokidar": {
      "version": "3.5.3",
      "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz",
      "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==",
      "funding": [
        {
          "type": "individual",
          "url": "https://paulmillr.com/funding/"
        }
      ],
      "dependencies": {
        "anymatch": "~3.1.2",
        "braces": "~3.0.2",
        "glob-parent": "~5.1.2",
        "is-binary-path": "~2.1.0",
        "is-glob": "~4.0.1",
        "normalize-path": "~3.0.0",
        "readdirp": "~3.6.0"
      },
      "engines": {
        "node": ">= 8.10.0"
      },
      "optionalDependencies": {
        "fsevents": "~2.3.2"
      }
    },

Has anyone seen this before and know of a fix?

Thanks in advance!


问:
Key error in flask web app - (KeyError: <weakref at 0x0000023357A05F80; to 'Flask' at 0x00000233559F45E0>)
I’m coding a web app using flask, I’ve connected to an external database service using the correct syntax (so the URI in the code is removed for obvious reasons additionally the secret key will not be "replace-later" in final product). I want to know if there is any way to  pinpoint what is causing the key error? The libraries I’m using for the web app are flask, flask-wtf, flask-sqlalchemy; additionally as I want to connect to a Postgres’s db I have downloaded Postgres utilities from the Postgres website and I have a DB host service available too . What could be the solution to this error?

Here is the main app code, this contains app logic and whatnot:

```<code>from models import *

app = Flask(__name__)
app.secret_key = 'replace-later'

app.config['SQLALCHEMY_DATABASE_URI']='**REMOVED**'
db = SQLAlchemy(app)

@app.route("/", methods=['GET','POST'])
def index():

    reg_form = RegistrationForm()
    if reg_form.validate_on_submit():
        username = reg_form.username.data
        password = reg_form.password.data

        user_object = User.query.filter_by(username=username).first()
        if user_object:
            return "Username has been taken"

        user = User(username=username, password=password)
        db.session.add(user)
        db.session.commit()
        return "Added to DB"
</code>```

Here is the link to the the db model which interacts with the database I have set up as well as the main app file in order to add user's usernames and passwords:

```<code>from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model):
    """ User model """

    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(25), unique=True, nullable=False)
    password = db.Column(db.String(), nullable=False)
</code>```

here is an image of the traceback and the error: image

I have resolved this issue by removing the duplicate "db" variable from both files and moving the database table model (class User) to the main python file (first one shown).

This however presents a new problem now I am trying to add a custom validator to another file I have for form logic this however with the previous changes gives me basically the same error. Here is the code I've ended up on.

There are 3 files:

This is the main web-app logic file containing routes and etc:

```<code>from wtform_fields import *
from libs import Flask, render_template

app = Flask(__name__)
app.secret_key = 'replace-later'

app.config['SQLALCHEMY_DATABASE_URI']='**REMOVED**'

# database model
db = SQLAlchemy(app)

class User(db.Model):
    """ User model """

    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(25), unique=True, nullable=False)
    password = db.Column(db.String(), nullable=False)

@app.route("/", methods=['GET','POST'])
def index():

    reg_form = RegistrationForm()

    if reg_form.validate_on_submit():
        username = reg_form.username.data
        password = reg_form.password.data

        user = User(username=username, password=password)
        db.session.add(user)
        db.session.commit()
        return "Added to DB"

    return render_template("index.html", form=reg_form)

if __name__ == "__main__":

    app.run(debug=True)
</code>```

This is the libs file which holds all the imported libraries - This was created as i thought this might be causing the error

from flask import Flask, render_template

from flask_sqlalchemy import SQLAlchemy

from flask_wtf import FlaskForm

from wtforms import StringField, PasswordField, SubmitField

from wtforms.validators import InputRequired, Length, EqualTo, ValidationError

This is the form logic file:

```<code>from libs import SQLAlchemy, FlaskForm, StringField, PasswordField, SubmitField, InputRequired, Length, EqualTo, ValidationError
from application import User

class RegistrationForm(FlaskForm):
    '''Registration Form'''

    username = StringField('username_label',
                            validators=[InputRequired(message="Username Required"),
                            Length(min=4, max=25, message="Username must be between 4-20 charecters.")]
                            )
    password = PasswordField('password_label',
                            validators=[InputRequired(message="Password Required"),
                            Length(min=8, max=25, message="Password must be between 8-25 charecters.")]
                            )
    conf_pswd = PasswordField('conf_pswd_label',
                            validators=[InputRequired(message="Retype Password"),
                            EqualTo('password', message="Passwords must match")]
                            )

    submit_button = SubmitField('create')

    def validate_username(self, username):
        user_object = User.query.filter_by(username=username.data).first()
        if user_object:
            raise ValidationError("Username already exists")
</code>```

This is the traceback for the error in the edited files: Traceback

My question is how can I firstly roll back the code back to the first instance (I'm using git so I am sure this is in some way possible) then resolve the key error in the first instance so that the DB model is in a separate file also that there is no libs file; Additionally if how would I be able to adapt the code in the second instance to match the first (This is optional as I have a general idea on how to do it but help would be appreciated).  Also are there any suggestions as to how I could tidy up my code so it's more understandable and formatted.

The main question is how do I fix the KeyError (In the first instance)?

I've tried just about everything - checking for memory leaks checking for duplicate keys and variables and stuff like that. When the issue is resolved I want the program to be able to add users and their passwords to the Database as well as allowing the fields to be checked using a custom validator - and other validators I may add.

Body:
I’m coding a web app using flask, I’ve connected to an external database service using the correct syntax (so the URI in the code is removed for obvious reasons additionally the secret key will not be "replace-later" in final product). I want to know if there is any way to  pinpoint what is causing the key error? The libraries I’m using for the web app are flask, flask-wtf, flask-sqlalchemy; additionally as I want to connect to a Postgres’s db I have downloaded Postgres utilities from the Postgres website and I have a DB host service available too . What could be the solution to this error?

Here is the main app code, this contains app logic and whatnot:

from models import *

app = Flask(__name__)
app.secret_key = 'replace-later'

app.config['SQLALCHEMY_DATABASE_URI']='**REMOVED**'
db = SQLAlchemy(app)

@app.route("/", methods=['GET','POST'])
def index():

    reg_form = RegistrationForm()
    if reg_form.validate_on_submit():
        username = reg_form.username.data
        password = reg_form.password.data

        user_object = User.query.filter_by(username=username).first()
        if user_object:
            return "Username has been taken"

        user = User(username=username, password=password)
        db.session.add(user)
        db.session.commit()
        return "Added to DB"

Here is the link to the the db model which interacts with the database I have set up as well as the main app file in order to add user's usernames and passwords:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class User(db.Model):
    """ User model """

    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(25), unique=True, nullable=False)
    password = db.Column(db.String(), nullable=False)

here is an image of the traceback and the error: image

I have resolved this issue by removing the duplicate "db" variable from both files and moving the database table model (class User) to the main python file (first one shown).

This however presents a new problem now I am trying to add a custom validator to another file I have for form logic this however with the previous changes gives me basically the same error. Here is the code I've ended up on.

There are 3 files:

This is the main web-app logic file containing routes and etc:

from wtform_fields import *
from libs import Flask, render_template

app = Flask(__name__)
app.secret_key = 'replace-later'

app.config['SQLALCHEMY_DATABASE_URI']='**REMOVED**'

# database model
db = SQLAlchemy(app)

class User(db.Model):
    """ User model """

    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(25), unique=True, nullable=False)
    password = db.Column(db.String(), nullable=False)

@app.route("/", methods=['GET','POST'])
def index():

    reg_form = RegistrationForm()

    if reg_form.validate_on_submit():
        username = reg_form.username.data
        password = reg_form.password.data

        user = User(username=username, password=password)
        db.session.add(user)
        db.session.commit()
        return "Added to DB"

    return render_template("index.html", form=reg_form)

if __name__ == "__main__":

    app.run(debug=True)

This is the libs file which holds all the imported libraries - This was created as i thought this might be causing the error

from flask import Flask, render_template

from flask_sqlalchemy import SQLAlchemy

from flask_wtf import FlaskForm

from wtforms import StringField, PasswordField, SubmitField

from wtforms.validators import InputRequired, Length, EqualTo, ValidationError

This is the form logic file:

from libs import SQLAlchemy, FlaskForm, StringField, PasswordField, SubmitField, InputRequired, Length, EqualTo, ValidationError
from application import User

class RegistrationForm(FlaskForm):
    '''Registration Form'''

    username = StringField('username_label',
                            validators=[InputRequired(message="Username Required"),
                            Length(min=4, max=25, message="Username must be between 4-20 charecters.")]
                            )
    password = PasswordField('password_label',
                            validators=[InputRequired(message="Password Required"),
                            Length(min=8, max=25, message="Password must be between 8-25 charecters.")]
                            )
    conf_pswd = PasswordField('conf_pswd_label',
                            validators=[InputRequired(message="Retype Password"),
                            EqualTo('password', message="Passwords must match")]
                            )

    submit_button = SubmitField('create')

    def validate_username(self, username):
        user_object = User.query.filter_by(username=username.data).first()
        if user_object:
            raise ValidationError("Username already exists")

This is the traceback for the error in the edited files: Traceback

My question is how can I firstly roll back the code back to the first instance (I'm using git so I am sure this is in some way possible) then resolve the key error in the first instance so that the DB model is in a separate file also that there is no libs file; Additionally if how would I be able to adapt the code in the second instance to match the first (This is optional as I have a general idea on how to do it but help would be appreciated).  Also are there any suggestions as to how I could tidy up my code so it's more understandable and formatted.

The main question is how do I fix the KeyError (In the first instance)?

I've tried just about everything - checking for memory leaks checking for duplicate keys and variables and stuff like that. When the issue is resolved I want the program to be able to add users and their passwords to the Database as well as allowing the fields to be checked using a custom validator - and other validators I may add.


问:
How do I show the menu bar window programmatically in Swiftui?
I'm trying to programmatically open MenuBarExtra in Swift on macOS using a global keyboard shortcut. I've already setup all the code for the keyboard shortcut but I can't figure out how to show/hide the MenuBarExtra using SwiftUI. Is there a way of doing so in native SwiftUI which I can't seem to find? Otherwise, is there a way of doing so via AppKit?

I've defined my menubar app the in the following way:

```<code>MenuBarExtra("Title", image: "sample_icon", content: {
      ContentView()
         .preferredColorScheme(.dark)
})
</code>```

Body:
I'm trying to programmatically open MenuBarExtra in Swift on macOS using a global keyboard shortcut. I've already setup all the code for the keyboard shortcut but I can't figure out how to show/hide the MenuBarExtra using SwiftUI. Is there a way of doing so in native SwiftUI which I can't seem to find? Otherwise, is there a way of doing so via AppKit?

I've defined my menubar app the in the following way:

MenuBarExtra("Title", image: "sample_icon", content: {
      ContentView()
         .preferredColorScheme(.dark)
})


问:
Linux Python Discord.py Error: Unable to get local issuer certificate
I am trying to write a simple Discord bot in Ubuntu 22.04. I have written the code below:

```<code>import discord
from discord.ext import commands,tasks
import os
from dotenv import load_dotenv

load_dotenv()
# Get the API token from the .env file.
DISCORD_TOKEN = os.getenv("discord_token")
intents = discord.Intents().all()
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='.',intents=intents)

ffmpeg_options = {
    'options': '-vn'
}

@bot.command(name='join', help='Tells the bot to join the voice channel')
async def join(ctx):
    if not ctx.message.author.voice:
        await ctx.send("{} is not connected to a voice channel".format(ctx.message.author.name))
        return
    else:
        channel = ctx.message.author.voice.channel
    await channel.connect()
@bot.command(name='leave', help='To make the bot leave the voice channel')
async def leave(ctx):
    voice_client = ctx.message.guild.voice_client
    if voice_client.is_connected():
        await voice_client.disconnect()
    else:
        await ctx.send("The bot is not connected to a voice channel.")

@bot.command(name="teiku", help="teikuuuuuuuu")
async def teiku(ctx):
        try :
            server = ctx.message.guild
            voice_channel = server.voice_client

            async with ctx.typing():
                voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source="teiku.com/teiku"))
        except:
            await ctx.send("The bot is not connected to a voice channel.")

if __name__ == "__main__" :
    bot.run(DISCORD_TOKEN)
</code>```

Upon running the bot in a Python virtual environment, I receive the following error:

aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')]

After some checking, including these links here, here, here, and here, I determined that this error means the SSL certificates on my computer are not correct. However, nearly all answers are for Windows or Mac machines, not Linux, or involve using Anaconda (this is a straight Python install with no Anaconda and all packages used were installed from pip the old-fashioned way).

I attempted to use pip to update certifi, download the SSL certificates from Discord manually, and various other solutions to update SSL certificates or obtain them locally.

What I expected to happen:

The bot will launch successfully and connect to Discord

What actually happened:

The above-quoted error appeared, with no changes from each attempted solution

[Note: The link to teiku.com in the code above is not real. In my code it is a URL-shortened link to a .wav file, but this is not allowed on stackoverflow, so I replaced the link with another. It is not relevant to the question.]

Body:
I am trying to write a simple Discord bot in Ubuntu 22.04. I have written the code below:

import discord
from discord.ext import commands,tasks
import os
from dotenv import load_dotenv

load_dotenv()
# Get the API token from the .env file.
DISCORD_TOKEN = os.getenv("discord_token")
intents = discord.Intents().all()
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='.',intents=intents)

ffmpeg_options = {
    'options': '-vn'
}

@bot.command(name='join', help='Tells the bot to join the voice channel')
async def join(ctx):
    if not ctx.message.author.voice:
        await ctx.send("{} is not connected to a voice channel".format(ctx.message.author.name))
        return
    else:
        channel = ctx.message.author.voice.channel
    await channel.connect()
@bot.command(name='leave', help='To make the bot leave the voice channel')
async def leave(ctx):
    voice_client = ctx.message.guild.voice_client
    if voice_client.is_connected():
        await voice_client.disconnect()
    else:
        await ctx.send("The bot is not connected to a voice channel.")

@bot.command(name="teiku", help="teikuuuuuuuu")
async def teiku(ctx):
        try :
            server = ctx.message.guild
            voice_channel = server.voice_client

            async with ctx.typing():
                voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source="teiku.com/teiku"))
        except:
            await ctx.send("The bot is not connected to a voice channel.")

if __name__ == "__main__" :
    bot.run(DISCORD_TOKEN)

Upon running the bot in a Python virtual environment, I receive the following error:

aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')]

After some checking, including these links here, here, here, and here, I determined that this error means the SSL certificates on my computer are not correct. However, nearly all answers are for Windows or Mac machines, not Linux, or involve using Anaconda (this is a straight Python install with no Anaconda and all packages used were installed from pip the old-fashioned way).

I attempted to use pip to update certifi, download the SSL certificates from Discord manually, and various other solutions to update SSL certificates or obtain them locally.

What I expected to happen:

The bot will launch successfully and connect to Discord

What actually happened:

The above-quoted error appeared, with no changes from each attempted solution

[Note: The link to teiku.com in the code above is not real. In my code it is a URL-shortened link to a .wav file, but this is not allowed on stackoverflow, so I replaced the link with another. It is not relevant to the question.]


问:
Disabling relaxation: it will not work with multiple definitions
i'm a beginner to coding and yesterday i code a simple light up led in C programming , it works in Atmel Studio, however the next day it has these errors from the picture shown. My code is

```<code>#define F_CPU 1600000UL
#include <avr/io.h>
#include <util/delay.h>
int main(void)
{
    DDRB=0xFF;

    while (1)
    {
        PORTB |= 0b0000100;

        }
}

</code>```

Can anyone help me? Thanks.Error

I'm not sure how as I keep trying to find help from internet, but it couldnt help me

Body:
i'm a beginner to coding and yesterday i code a simple light up led in C programming , it works in Atmel Studio, however the next day it has these errors from the picture shown. My code is

#define F_CPU 1600000UL
#include <avr/io.h>
#include <util/delay.h>
int main(void)
{
    DDRB=0xFF;

    while (1)
    {
        PORTB |= 0b0000100;

        }
}

Can anyone help me? Thanks.Error

I'm not sure how as I keep trying to find help from internet, but it couldnt help me


问:
Is there a way to support all paths in a Nestjs Gateway using the ws module?
I want my Gateway to be able to receive connections from any path as I'm going to receive user id as parameter. I'm using the ws module.

Example:

ws://localhost:3000/12345

another example:

ws://localhost:3000/54321

I put @WebSocketGateway({ path: '*' }) but it doesn't work. Here is my Gateway:

```<code>@WebSocketGateway({ path: '*' })
export class CacheGateway implements OnGatewayConnection {
  private readonly logger: Logger = new Logger(CacheGateway.name);
  private readonly clients: { [key: string]: WebSocket } = {};

  public handleConnection(@ConnectedSocket() client: WebSocket): void {
    const userID = client.url?.slice(1);
    if (userID) {
      this.clients[userID] = client;
      this.logger.log(
        `User Connected: ${userID}. At: ${new Date().toISOString()}`,
      );
    } else {
      this.logger.log('Anonymous user connected');
    }
  }
}
</code>```

Body:
I want my Gateway to be able to receive connections from any path as I'm going to receive user id as parameter. I'm using the ws module.

Example:

ws://localhost:3000/12345

another example:

ws://localhost:3000/54321

I put @WebSocketGateway({ path: '*' }) but it doesn't work. Here is my Gateway:

@WebSocketGateway({ path: '*' })
export class CacheGateway implements OnGatewayConnection {
  private readonly logger: Logger = new Logger(CacheGateway.name);
  private readonly clients: { [key: string]: WebSocket } = {};

  public handleConnection(@ConnectedSocket() client: WebSocket): void {
    const userID = client.url?.slice(1);
    if (userID) {
      this.clients[userID] = client;
      this.logger.log(
        `User Connected: ${userID}. At: ${new Date().toISOString()}`,
      );
    } else {
      this.logger.log('Anonymous user connected');
    }
  }
}


问:
Get image of icon from css in a Angular app
how can I retrieve the image of an icon from the given css below? (see the pic)

This icon is in a 3th party npm lib in an angular application, but I cant find any trace of this image by finding svg, png, jpg file or finding by 'music' keyword under the node_modules dir ... no any help just content: "\e94e"

Thanks for the answers in advance.
Csaba


问:
.NET Core System.UnauthorizedAccessException: Access to the path is denied
I'm trying to write a file to a pdf folder under wwwroot but I get an error

UnauthorizedAccessException: Access to the path is denied

I'm using the iText library

```<code>    private readonly IWebHostEnvironment webHostEnvironment;
    private string webRootPath;
    private string contentRootPath;
    private string path;

    public Pdf(IWebHostEnvironment webHostEnvironment)
    {
        this.webHostEnvironment = webHostEnvironment;
        webRootPath = webHostEnvironment.WebRootPath;
        contentRootPath = webHostEnvironment.ContentRootPath;
        path = Path.Combine(contentRootPath, "wwwroot", "pdf");
    }

    public void CreatePDF()
    {
        PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new FileStream(path, FileMode.Create, FileAccess.Write)));
        Document document = new Document(pdfDocument);

        String line = "Hello! Welcome to iTextPdf";
        document.Add(new Paragraph(line));
        document.Close();

        Console.WriteLine("Awesome PDF just got created.");
    }
</code>```

In .NET 4.6, giving write permissions to IIS_IUSRS under the Security tab of the system folder used to resolve writing issues.

What's the equivalent procedure and user object for .NET Core?

I'm running my project on Windows 10 with Visual Studio 2022 and the launch profile for debugging under project properties is "Project".

Body:
I'm trying to write a file to a pdf folder under wwwroot but I get an error

UnauthorizedAccessException: Access to the path is denied

I'm using the iText library

    private readonly IWebHostEnvironment webHostEnvironment;
    private string webRootPath;
    private string contentRootPath;
    private string path;

    public Pdf(IWebHostEnvironment webHostEnvironment)
    {
        this.webHostEnvironment = webHostEnvironment;
        webRootPath = webHostEnvironment.WebRootPath;
        contentRootPath = webHostEnvironment.ContentRootPath;
        path = Path.Combine(contentRootPath, "wwwroot", "pdf");
    }

    public void CreatePDF()
    {
        PdfDocument pdfDocument = new PdfDocument(new PdfWriter(new FileStream(path, FileMode.Create, FileAccess.Write)));
        Document document = new Document(pdfDocument);

        String line = "Hello! Welcome to iTextPdf";
        document.Add(new Paragraph(line));
        document.Close();

        Console.WriteLine("Awesome PDF just got created.");
    }

In .NET 4.6, giving write permissions to IIS_IUSRS under the Security tab of the system folder used to resolve writing issues.

What's the equivalent procedure and user object for .NET Core?

I'm running my project on Windows 10 with Visual Studio 2022 and the launch profile for debugging under project properties is "Project".


问:
All I need is the text on the label should switch with the click event
I am trying a matching game. I want the text on the label should be "?". and after being clicked it should show the text</p>
```<code>      private void checkmatch()
        {
 or each         fach (Label lbl in tableLayoutPanel1.Controls)
            {
                if (lbl.Visible == false)
                {

                    lbl.Text = "?";
                    lbl.Visible = true;
                }
            }

        }
</code>```

Body:
I am trying a matching game. I want the text on the label should be "?". and after being clicked it should show the text

      private void checkmatch()
        {
 or each         fach (Label lbl in tableLayoutPanel1.Controls)
            {
                if (lbl.Visible == false)
                {

                    lbl.Text = "?";
                    lbl.Visible = true;
                }
            }

        }


问:
How to add a QStackLayout to only part of an application?
I need a method to have several pages on one application like QStackLayout does but I need to to only cover part of my window such as the example below:

The current method I can think of is have several frames and then just disabling and setting then to not be visible, however I need this app to be memory efficient and I don't believe that this solution will lead to that.

And just to make sure, will QStackedLayout be memory efficient so I can have quite a lot of pages in it, e.g. 30+ with each qwidget having 30-40 gui components/widgets, or will it be more efficient to have the several Qframe and then disabling and making them invisible and setting another one to be enabled and visible.

Do the widgets become disabled when they are not visible because I do not want a user to miss click a visible button and they somehow click a button they cant see which is in another qwidget?


问:
Diferent way then use apply(function)?
I have been working with 2 datasets.
The first one is always right, it have client_id and client_store_id.
But, usually one client is registered to one store, but sometimes, they can be registered in more stores.

The second dataset, is sells, and because some informations come from human typing, the store number can be wrong.

So what I´m doing now, is using apply function, to scan row by row filtering by df_clients, but I´m sure that is not the most efficient way to do it. But I´m out of ideas how to solve it.

This is what the function does:

filter the clients list to see how many stores the customer is registered

check if the client_store is the same of sell_store

if length is one, is ok.

if length is 0, use the store_id where it has register, but if has more the one, use the first one

```<code>def sells_ajust(sell):
    store_sell = sell['store_id']
    client_id_sell = sell['client_id']

    f = df_clients[(df_clients.client_id==client_id_sell)]
    if len(f)>1:
        f2 = f[(f.store_id==store_sell)] # store_id where client is registred
        if len(f2) > 1: # When client has two register in one store
            print("trouble, check it")
        elif len(f2) == 1: # When store where client buy it is the one registered
            sell['name'] = f['name'].iloc[0] #Give the registered name to sell dataframe
        elif len(f2) ==0: # When client is not registred to store that sold
            if len(f) == 1: # if client has only one store registerd
                sell['store_id'] = f['store_id'].iloc[0] # Give the registered StoreId to sell dataframe
                sell['name'] = f['name'].iloc[0]
            else:
                f = f[f['status']!='inactive'] #Check if the client register is inactive for that store
                if len(f)==1: #Try again
                    sell['store_id'] = f['store_id'].iloc[0] # Give the registered StoreId to sell dataframe
                    sell['name'] = f['name'].iloc[0]

    elif len(f)==1: # IF the client has oly one store registered
        sell['name'] = f['name'].iloc[0]
        sell['store_id'] = f['store_id'].iloc[0]

    #I DIDNT NEED ANOTHER CONDITION BECAUSE IT ALWAYS SOLVE THE PROBLEM
    return sell
</code>```

My data has about 140000 rows of sells each year around 40 stores, it has registered almost 100K clients.

I can say that this can resume all problems

df_clients
enter image description here

df_sells

enter image description here

What i need to figure out at the end is:
enter image description here

I hope i could give all information about it.
Thank you for helping me. I´m sorry if is too confusing, or if i miss spelling something.

Title: Diferent way then use apply(function)?

Body:
I have been working with 2 datasets.
The first one is always right, it have client_id and client_store_id.
But, usually one client is registered to one store, but sometimes, they can be registered in more stores.

The second dataset, is sells, and because some informations come from human typing, the store number can be wrong.

So what I´m doing now, is using apply function, to scan row by row filtering by df_clients, but I´m sure that is not the most efficient way to do it. But I´m out of ideas how to solve it.

This is what the function does:

filter the clients list to see how many stores the customer is registered

check if the client_store is the same of sell_store

if length is one, is ok.

if length is 0, use the store_id where it has register, but if has more the one, use the first one

def sells_ajust(sell):
    store_sell = sell['store_id']
    client_id_sell = sell['client_id']

    f = df_clients[(df_clients.client_id==client_id_sell)]
    if len(f)>1:
        f2 = f[(f.store_id==store_sell)] # store_id where client is registred
        if len(f2) > 1: # When client has two register in one store
            print("trouble, check it")
        elif len(f2) == 1: # When store where client buy it is the one registered
            sell['name'] = f['name'].iloc[0] #Give the registered name to sell dataframe
        elif len(f2) ==0: # When client is not registred to store that sold
            if len(f) == 1: # if client has only one store registerd
                sell['store_id'] = f['store_id'].iloc[0] # Give the registered StoreId to sell dataframe
                sell['name'] = f['name'].iloc[0]
            else:
                f = f[f['status']!='inactive'] #Check if the client register is inactive for that store
                if len(f)==1: #Try again
                    sell['store_id'] = f['store_id'].iloc[0] # Give the registered StoreId to sell dataframe
                    sell['name'] = f['name'].iloc[0]

    elif len(f)==1: # IF the client has oly one store registered
        sell['name'] = f['name'].iloc[0]
        sell['store_id'] = f['store_id'].iloc[0]

    #I DIDNT NEED ANOTHER CONDITION BECAUSE IT ALWAYS SOLVE THE PROBLEM
    return sell

My data has about 140000 rows of sells each year around 40 stores, it has registered almost 100K clients.

I can say that this can resume all problems

df_clients
enter image description here

df_sells

enter image description here

What i need to figure out at the end is:
enter image description here

I hope i could give all information about it.
Thank you for helping me. I´m sorry if is too confusing, or if i miss spelling something.


问:
Statsmodels package is not letting me inherit a function. I get unexpected keyword argument even though the function needs an input parameter
so the way the FTestAnovaPower function works is, it takes 5 parameter but one need to be left as None and the function calculates whichever argument is left as None. My problems is, i want to generate a list of values for one parameter (the one thats None) while keeping the other values constant, hence the for loop.

`

```<code>class smpl_pwr(statsmodels.stats.power.FTestAnovaPower):

    def __init__(self, effect_size=None, nobs=None, alpha=None, power=None, k_groups=None, vals = None):
        #super().__init__(effect_size, nobs, alpha, power, k_groups)

        X_func = statsmodels.stats.power.FTestAnovaPower()

        self.effect_size = effect_size
        self.nobs = nobs
        self.alpha = alpha
        self.power = power
        self.k_groups = k_groups
        self.vals = vals

    def new_lst(self):

        smpl_size = []
        for x in vals:
            smpl_size.append(X_func.solve_power(self, effect_size, nobs, alpha, k_groups, power=x))

        return smpl_size
</code>```

`

I want to be able to generate a list or an array of values but all i get memory address.

Body:
so the way the FTestAnovaPower function works is, it takes 5 parameter but one need to be left as None and the function calculates whichever argument is left as None. My problems is, i want to generate a list of values for one parameter (the one thats None) while keeping the other values constant, hence the for loop.

`

class smpl_pwr(statsmodels.stats.power.FTestAnovaPower):

    def __init__(self, effect_size=None, nobs=None, alpha=None, power=None, k_groups=None, vals = None):
        #super().__init__(effect_size, nobs, alpha, power, k_groups)

        X_func = statsmodels.stats.power.FTestAnovaPower()

        self.effect_size = effect_size
        self.nobs = nobs
        self.alpha = alpha
        self.power = power
        self.k_groups = k_groups
        self.vals = vals

    def new_lst(self):

        smpl_size = []
        for x in vals:
            smpl_size.append(X_func.solve_power(self, effect_size, nobs, alpha, k_groups, power=x))

        return smpl_size

`

I want to be able to generate a list or an array of values but all i get memory address.


问:
Complicated string manipulation in pandas without regex
I just looped over a pandas column to it from out[156] to out[157] in the image attached below.

Now I have another column that is very complicated, is it possible to achieve the same thing without using regex (I am completely unfamiliar with regex)? I basically want the figures in float format (eg. 9ft 2in to the equivalent in inches) but there are so many different ways it was entered.

I would appreciate any advice.


问:
Python Zybooks lab issue
A common year in the modern Gregorian Calendar consists of 365 days. In reality, Earth takes longer to rotate around the sun. To account for the difference in time, every 4 years, a leap year takes place. A leap year is when a year has 366 days: An extra day, February 29th. The requirements for a given year to be a leap year are:

The year must be divisible by 4

If the year is a century year (1700, 1800, etc.), the year must be evenly divisible by 400; therefore, both 1700 and 1800 are not leap years

Some example leap years are 1600, 1712, and 2016.

Write a program that takes in a year and determines the number of days in February for that year.

Ex: If the input is:

1712
the output is:

1712 has 29 days in February.
Ex: If the input is:

1913
the output is:

1913 has 28 days in February.

I am working on this zyBooks lab, and everything checks out while testing. The issue is when I submit I get an error :TypeError: argument of type 'int' is not iterable. Here is my code:

```<code>def days_in_feb(year):
    if '00' in year:
        if int(year) % 400 == 0:
            return True
        else:
            return False

    if int(year) % 4 != 0:
        return False
    else:
        return True

if __name__ == '__main__':
    year = input()
    feb = days_in_feb(year)
    if days_in_feb(year) is True:
        print(f'{year} has 29 days in February.')
    else:
        print(f'{year} has 28 days in February.')
</code>```

It seems the auto grader doesnt like the way I have things arranged, but I am new to python so I couldnt tell you where it things its trying to iterate other than "if '00' in year"

Title: Python Zybooks lab issue

Body:
A common year in the modern Gregorian Calendar consists of 365 days. In reality, Earth takes longer to rotate around the sun. To account for the difference in time, every 4 years, a leap year takes place. A leap year is when a year has 366 days: An extra day, February 29th. The requirements for a given year to be a leap year are:

The year must be divisible by 4

If the year is a century year (1700, 1800, etc.), the year must be evenly divisible by 400; therefore, both 1700 and 1800 are not leap years

Some example leap years are 1600, 1712, and 2016.

Write a program that takes in a year and determines the number of days in February for that year.

Ex: If the input is:

1712
the output is:

1712 has 29 days in February.
Ex: If the input is:

1913
the output is:

1913 has 28 days in February.

I am working on this zyBooks lab, and everything checks out while testing. The issue is when I submit I get an error :TypeError: argument of type 'int' is not iterable. Here is my code:

def days_in_feb(year):
    if '00' in year:
        if int(year) % 400 == 0:
            return True
        else:
            return False

    if int(year) % 4 != 0:
        return False
    else:
        return True

if __name__ == '__main__':
    year = input()
    feb = days_in_feb(year)
    if days_in_feb(year) is True:
        print(f'{year} has 29 days in February.')
    else:
        print(f'{year} has 28 days in February.')

It seems the auto grader doesnt like the way I have things arranged, but I am new to python so I couldnt tell you where it things its trying to iterate other than "if '00' in year"


问:
List recursive with checkbox component data into parent component update values
Help to list recursive with checkbox component data into parent component update values:

Parent File:

```<code><TreeVue :items="props.allModules" :selectedItems="userForm.userModules"/>
</code>```

TreeVue File:

```<code><template>
    <div v-for="item in items" :key="item.name" class="overflow-hidden rounded-lg bg-gray-50">
        <div class="px-4 py-5 sm:p-6" >
            <div class="flex items-center ">
                <input :id="item.id" type="checkbox" :value="item.id" v-model="props.selectedItems" class="w-6 h-6 text-blue-600 bg-gray-100 rounded border-gray-300 focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600">
                <label for="default-checkbox" class="ml-2 text-sm font-medium text-gray-900 dark:text-gray-300">{{ item.name  }}</label>
            </div>
            <div v-if="item.children" class="ml-5">
                <Tree :items="item.children" :selectedItems="selectedItems" />
            </div>
        </div>
    </div>
</template>

<script setup>
    import { defineProps } from "vue";

    const props = defineProps({
        items: Object,
        selectedItems: Object,
    });
</script>
</code>```

ConsoleLog:

```<code>app.js:7839 [Vue warn] Set operation on key "selectedItems" failed: target is readonly. Proxy {items: Proxy, selectedItems: Proxy}
</code>```

I need to update parent value after selected item on child TreeVue.

I read something about Emit, but I don't know how to implement it, because I'm new to Vue.

Body:
Help to list recursive with checkbox component data into parent component update values:

Parent File:

<TreeVue :items="props.allModules" :selectedItems="userForm.userModules"/>

TreeVue File:

<template>

                <input :id="item.id" type="checkbox" :value="item.id" v-model="props.selectedItems" class="w-6 h-6 text-blue-600 bg-gray-100 rounded border-gray-300 focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600">
                {{ item.name  }}

                <Tree :items="item.children" :selectedItems="selectedItems" />

</template>

ConsoleLog:

app.js:7839 [Vue warn] Set operation on key "selectedItems" failed: target is readonly. Proxy {items: Proxy, selectedItems: Proxy}

I need to update parent value after selected item on child TreeVue.

I read something about Emit, but I don't know how to implement it, because I'm new to Vue.


问:
how to create a new electron browser window
I am trying to open a new electron window when I press a button, but I can't create it.
Here is the code I used and didn't work:

```<code>//creates a new window
//

const createChapterWindow = () => {
  // Create the browser window.
print('started window');

  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      preload: path.join(__dirname, 'preload.js'),
    },
  });
  print('step 1 finished')

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'chapter.html'));

  // Open the DevTools.
  mainWindow.webContents.openDevTools();
print('finished window')
};

//calls browser window
createChapterWindow();

}

function print(text){
  console.log(`\n\n\n${text}\n\n\n`)
}
</code>```

I copied most of this code from the part where I create the main window, so that might be the issue.

Body:
I am trying to open a new electron window when I press a button, but I can't create it.
Here is the code I used and didn't work:

//creates a new window
//

const createChapterWindow = () => {
  // Create the browser window.
print('started window');

  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      preload: path.join(__dirname, 'preload.js'),
    },
  });
  print('step 1 finished')

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, 'chapter.html'));

  // Open the DevTools.
  mainWindow.webContents.openDevTools();
print('finished window')
};

//calls browser window
createChapterWindow();

}

function print(text){
  console.log(`\n\n\n${text}\n\n\n`)
}

I copied most of this code from the part where I create the main window, so that might be the issue.


问:
JPA Embeddable bidirectional
What's the correct way to create bidirectional 1to1 mapping using Embeddable annotation? This one throws error
"EmpId has no persistent id property: Emp.id"

```<code>@Entity
public class Per implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "per_id")
    private Long id;

    @OneToOne
    @JoinColumn(name = "per_id", referencedColumnName = "emp_id")
    private Emp emp;

}

@Embeddable
public class EmpId implements Serializable {
    private static final long serialVersionUID = 1L;

    @OneToOne(mappedBy = "emp")
    private Per per;

}

@Entity
public class Emp implements Serializable {
    @EmbeddedId
    private EmpId id;
}
</code>```

I'd like to operate entities like

```<code>per.getEmp();
emp.getId().getPer();
</code>```

Title: JPA Embeddable bidirectional

Body:
What's the correct way to create bidirectional 1to1 mapping using Embeddable annotation? This one throws error
"EmpId has no persistent id property: Emp.id"

@Entity
public class Per implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "per_id")
    private Long id;

    @OneToOne
    @JoinColumn(name = "per_id", referencedColumnName = "emp_id")
    private Emp emp;

}

@Embeddable
public class EmpId implements Serializable {
    private static final long serialVersionUID = 1L;

    @OneToOne(mappedBy = "emp")
    private Per per;

}

@Entity
public class Emp implements Serializable {
    @EmbeddedId
    private EmpId id;
}

I'd like to operate entities like

per.getEmp();
emp.getId().getPer();


问:
i want to search inside the inline mode in my telegram bot
I have done the inline Mode in my telegram bot but i can't search within it ...and it keeps giving me this error:

```<code>telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: RESULTS_TOO_MUCH
</code>```

what I've done is :
`

```<code>@bot.inline_handler(func=lambda query : True)
def default_query(inline_query:InlineQuery):
    service_id_list = []
    list_of_result = []
    n = 1
    for i in service_dict :
        service_name = i
        service_id = service_dict[i]
        service_id_list.append(f"{service_id}")
        # print(service_id)
        r = InlineQueryResultArticle(n, service_name, InputTextMessageContent(f'{service_name}\n{service_id}'))
        list_of_result.append(r)
        n = n + 1
    print(list_of_result)
    bot.answer_inline_query(inline_query.id,list_of_result,next_offset=49)
```
`
```

Body:
I have done the inline Mode in my telegram bot but i can't search within it ...and it keeps giving me this error:

telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: RESULTS_TOO_MUCH

what I've done is :
`

@bot.inline_handler(func=lambda query : True)
def default_query(inline_query:InlineQuery):
    service_id_list = []
    list_of_result = []
    n = 1
    for i in service_dict :
        service_name = i
        service_id = service_dict[i]
        service_id_list.append(f"{service_id}")
        # print(service_id)
        r = InlineQueryResultArticle(n, service_name, InputTextMessageContent(f'{service_name}\n{service_id}'))
        list_of_result.append(r)
        n = n + 1
    print(list_of_result)
    bot.answer_inline_query(inline_query.id,list_of_result,next_offset=49)
```
`


问:
Getting MariaDB ModuleNotFoundError in Python
The error happens at the import line in the Python code.

```<code>sys.path.append("/usr/local/Cellar/mariadb-connector-c/3.3.3")
sys.path.append("/usr/local/Cellar/mariadb-connector-c")

import mariadb
</code>```

I already have the mariadb and mariadb-1.1.5.post3.dist-info added to the sys.path, I can see it when I do a print (sys.path)

The error message I am getting is : Exception has occurred: ModuleNotFoundError No module named 'mariadb._mariadb'

pip show mariadb returns:

```<code>Name: mariadb
Version: 1.1.5.post3
Summary: Python MariaDB extension
Home-page: https://www.github.com/mariadb-corporation/mariadb-connector-python
Author: Georg Richter
Author-email:
License: LGPL 2.1
Location: /Users/melinda.walker/GitHub/bi-ingestion-scripts/venv/lib/python3.9/site-packages
Requires: packaging
Required-by:
</code>```

I am also using a virtual environment.
My  python --version is : Python 3.9.16

I used brew install mariadb-connector-c to install mariadb-connector-c.

It is similar to issues: Installing mariadb 1.1.3 package on Python and Python import Mariadb: 'ModuleNotFoundError'.

I tried what Georg suggested: pip3 uninstall mariadb and pip3 install --no-cache mariadb but I am still getting that error.

Body:
The error happens at the import line in the Python code.

sys.path.append("/usr/local/Cellar/mariadb-connector-c/3.3.3")
sys.path.append("/usr/local/Cellar/mariadb-connector-c")

import mariadb

I already have the mariadb and mariadb-1.1.5.post3.dist-info added to the sys.path, I can see it when I do a print (sys.path)

The error message I am getting is : Exception has occurred: ModuleNotFoundError No module named 'mariadb._mariadb'

pip show mariadb returns:

Name: mariadb
Version: 1.1.5.post3
Summary: Python MariaDB extension
Home-page: https://www.github.com/mariadb-corporation/mariadb-connector-python
Author: Georg Richter
Author-email:
License: LGPL 2.1
Location: /Users/melinda.walker/GitHub/bi-ingestion-scripts/venv/lib/python3.9/site-packages
Requires: packaging
Required-by:

I am also using a virtual environment.
My  python --version is : Python 3.9.16

I used brew install mariadb-connector-c to install mariadb-connector-c.

It is similar to issues: Installing mariadb 1.1.3 package on Python and Python import Mariadb: 'ModuleNotFoundError'.

I tried what Georg suggested: pip3 uninstall mariadb and pip3 install --no-cache mariadb but I am still getting that error.


问:
Saving models from keras tuner results
After training a model I typically save the top 10 models:

```<code>models = tuner.get_best_models(num_models=10)
</code>```

I would like to save all models created instead. Is there a way to do that?

Title: Saving models from keras tuner results

Body:
After training a model I typically save the top 10 models:

models = tuner.get_best_models(num_models=10)

I would like to save all models created instead. Is there a way to do that?


问:
Zipping many files with JSZip is crashing
I am having a problem using JSZip to zip files and any help is greatly appreciated.

Basically, I am working on an application where users can upload a directory containing multiple files. An individual file will never be more than 2GB and most are much smaller (~10MB), but there can be thousands of files in a directory so the total size could be 20GB+.What I want to do is use JSZip to zip the files into a single zip file and then upload that single zip file to AWS S3. The problem is, my browser is crashing when I start testing with a larger number of files. When I tried with a directory containing 1000 files for a total size of ~8GB, my browser crashes and I see a Error code: SBOX_FATAL_MEMORY_EXCEEDED error. This error happens before I make it to the uploading step.

I am letting users upload files with a HTML input and saving the file in memory before the zipping and uploading happens. Here is the code I'm using to zip the files:

```<code>        const zip = new JSZip();

        files.forEach((file) => {
            zip.file(file.name, file)
        });

        zip.generateAsync({ type: "blob" })
            .then((content) => uploadToS3(content))
</code>```

It seems like storing the files and the zip in memory is too much for my machine to handle and I'm sure some of my users will have smaller machines than I do. Any ideas on how I can implement this would be very helpful.

Thanks!

Body:
I am having a problem using JSZip to zip files and any help is greatly appreciated.

Basically, I am working on an application where users can upload a directory containing multiple files. An individual file will never be more than 2GB and most are much smaller (~10MB), but there can be thousands of files in a directory so the total size could be 20GB+.What I want to do is use JSZip to zip the files into a single zip file and then upload that single zip file to AWS S3. The problem is, my browser is crashing when I start testing with a larger number of files. When I tried with a directory containing 1000 files for a total size of ~8GB, my browser crashes and I see a Error code: SBOX_FATAL_MEMORY_EXCEEDED error. This error happens before I make it to the uploading step.

I am letting users upload files with a HTML input and saving the file in memory before the zipping and uploading happens. Here is the code I'm using to zip the files:

        const zip = new JSZip();

        files.forEach((file) => {
            zip.file(file.name, file)
        });

        zip.generateAsync({ type: "blob" })
            .then((content) => uploadToS3(content))

It seems like storing the files and the zip in memory is too much for my machine to handle and I'm sure some of my users will have smaller machines than I do. Any ideas on how I can implement this would be very helpful.

Thanks!


问:
Firebase auth in env file or in Config Vars Heroku
I have these rules in Firebase Realtime Database:

```<code>{
  "rules": {
      ".read":"auth.uid === 'my-service-worker'",
      ".write": false
  }
}
</code>```

I wish that only my Discord bot has access to read the data. I've found that Admin SDK could be helpful for me:

https://firebase.google.com/docs/database/admin/start

But I have a problem with this. Here, I have a json file, and the code will read the entire file.

I've uploaded my bot to Heroku and connected it via GitHub. To not expose sensible info, like private keys, instead of pushing this data to GitHub, I insert such data in the Config Vars section of the Heroku dashboard, or locally when I work with a test bot, I put all of these data in a .env file.

I'm confused about how to do that with Admin SDK info. Is there any simpler way, to configure this?  For example, I wish to use auth data just like my DISCORD_BOT token variable, or CLIENT_ID variable from my .env file (and from the Config Vars section when deployed). In the code, I wish to access these variables like in this example:

```<code>client.login(process.env.BOT_TOKEN);
</code>```

To be more specific, I need to access this data, from Heroku's Var Configs:

```<code>{
  "type": "",
  "project_id": "",
  "private_key_id": "",
  "private_key": "-----BEGIN PRIVATE KEY-----\",
  "client_email": "",
  "client_id": "",
  "auth_uri": "",
  "token_uri": "",
  "auth_provider_x509_cert_url": "",
  "client_x509_cert_url": ""
}
</code>```

Currently, this is in json file. I can't upload this file on GitHub, because the private key will be exposed.

So, instead of:

```<code>    var serviceAccount = require(path.resolve(__dirname, 'serviceAccountKey.json'));
.......
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    // The database URL depends on the location of the database
    databaseURL: "...",
    databaseAuthVariableOverride: {
      uid: "my-service-worker"
    }
  });
</code>```

I wish to use .env variables one by one?

Body:
I have these rules in Firebase Realtime Database:

{
  "rules": {
      ".read":"auth.uid === 'my-service-worker'",
      ".write": false
  }
}

I wish that only my Discord bot has access to read the data. I've found that Admin SDK could be helpful for me:

https://firebase.google.com/docs/database/admin/start

But I have a problem with this. Here, I have a json file, and the code will read the entire file.

I've uploaded my bot to Heroku and connected it via GitHub. To not expose sensible info, like private keys, instead of pushing this data to GitHub, I insert such data in the Config Vars section of the Heroku dashboard, or locally when I work with a test bot, I put all of these data in a .env file.

I'm confused about how to do that with Admin SDK info. Is there any simpler way, to configure this?  For example, I wish to use auth data just like my DISCORD_BOT token variable, or CLIENT_ID variable from my .env file (and from the Config Vars section when deployed). In the code, I wish to access these variables like in this example:

client.login(process.env.BOT_TOKEN);

To be more specific, I need to access this data, from Heroku's Var Configs:

{
  "type": "",
  "project_id": "",
  "private_key_id": "",
  "private_key": "-----BEGIN PRIVATE KEY-----\",
  "client_email": "",
  "client_id": "",
  "auth_uri": "",
  "token_uri": "",
  "auth_provider_x509_cert_url": "",
  "client_x509_cert_url": ""
}

Currently, this is in json file. I can't upload this file on GitHub, because the private key will be exposed.

So, instead of:

    var serviceAccount = require(path.resolve(__dirname, 'serviceAccountKey.json'));
.......
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    // The database URL depends on the location of the database
    databaseURL: "...",
    databaseAuthVariableOverride: {
      uid: "my-service-worker"
    }
  });

I wish to use .env variables one by one?


问:
How can I implement an easy CAPTCHA in Next.js?
I created my own website using next.js and react. Since I live in Germany and must follow GDPR (EU General Data Protection Regulation) I need an alternative to google reCaptcha to protect my Contact form and Comment Forms against bots. I searched a lot but unfortunately, I could not find any cost free alternative to google reCaptcha...

So I thought about implementing my own rather "simplistic" captcha solution in which I would randomly generate some numbers and ask a simple math question.Additionally, I would implement some honey pots in the form to misslead bots.

It should work fine for my small website, but I have no idea how to validate form input data (math question and honey pot fields) on the backend site of next.js.

My question is:
How can I implement a simple captcha solution (like: please answer the following question: what is x+y? ) using next.js?


问:
Does Audio works with props and if does not, is there an alternative to add multiple different sounds to a react component?
I been trying to put different audio files in a react component that has been imported to a main folder App.js. it works jut fine for the first audio but it repeats the same audio file.
It works if I do it like this but i want it to play different audio files on each component:

```<code>import song from "../Songs/song-one.wav"
const SoundFiles = (props) => {
    const audio = new Audio(song);
    const playPause = () => {
    audio.paused ? start() : stop()
    }
return(
    <div>
    <button onClick={playPause}><CgPlayPauseO/></button>
</div>)}

export default SoundFiles:

import Beats from './components/beats';
import SoundFiles from './components/SoundFiles';

const App = () => {
    return (
<div className='beat-container'>
    <Beats>Beat 1 <SoundFiles></Beats>
    <Beats>Beat 2 <SoundFiles></Beats>
</div>

)}
</code>```

I actually tried to create another folder like SoundFiles called it SoundFiles2 with the same content and just replace the song file but it kept playing the same audio file form the first folder

my Audio folder looks like this:
song-one.wav
song-two.wav

I have try to use props but that did not work

```<code>const SoundFiles = (props) => {
    const audio = new Audio(`../Sound/song-${props.sound}.wav`);
    const playPause = () => {
    audio.paused ? start() : stop()
    }
return(
    <div>
    <button onClick={playPause}><CgPlayPauseO/></button>
</div>)}
export default SoundFiles:

import Beats from './components/beats';
import SoundFiles from './components/SoundFiles';
const App = () => {
     return (
<div className='beat-container'>
    <Beats>Beat 1 <SoundFiles sound="one"/></Beats>
    <Beats>Beat 2 <SoundFiles sound="two"/></Beats>
</div> )}
</code>```

any idea on how to put the audio on its corresponding component

Body:
I been trying to put different audio files in a react component that has been imported to a main folder App.js. it works jut fine for the first audio but it repeats the same audio file.
It works if I do it like this but i want it to play different audio files on each component:

import song from "../Songs/song-one.wav"
const SoundFiles = (props) => {
    const audio = new Audio(song);
    const playPause = () => {
    audio.paused ? start() : stop()
    }
return(

    <button onClick={playPause}><CgPlayPauseO/></button>

)}

export default SoundFiles:

import Beats from './components/beats';
import SoundFiles from './components/SoundFiles';

const App = () => {
    return (

    <Beats>Beat 1 <SoundFiles></Beats>
    <Beats>Beat 2 <SoundFiles></Beats>

)}

I actually tried to create another folder like SoundFiles called it SoundFiles2 with the same content and just replace the song file but it kept playing the same audio file form the first folder

my Audio folder looks like this:
song-one.wav
song-two.wav

I have try to use props but that did not work

const SoundFiles = (props) => {
    const audio = new Audio(`../Sound/song-${props.sound}.wav`);
    const playPause = () => {
    audio.paused ? start() : stop()
    }
return(

    <button onClick={playPause}><CgPlayPauseO/></button>

)}
export default SoundFiles:

import Beats from './components/beats';
import SoundFiles from './components/SoundFiles';
const App = () => {
     return (

    <Beats>Beat 1 <SoundFiles sound="one"/></Beats>
    <Beats>Beat 2 <SoundFiles sound="two"/></Beats>

 )}

any idea on how to put the audio on its corresponding component


问:
Computing render time for blender animation
For a project I need to be able to estimate render time for a given blender file animation. I use Blender Python API for rendering.

To estimate the total render time I’m thinking to render a sample frame (for example first frame), measure the time it takes then multiply it by number of frames to get the total render time for that animation.

This approach is based on the assumption that render time for all the frames in an animation is about the same. Is that true or it varies across frames for example depending on what’s in each frame?

Also if there is a better approach for estimating the total render time please let me know.


问:
Problem with Udemy tutorial: getting 'Error while evaluating UIControl Callback.'
I am going through the Udemy course "Learn image processing and GUIs while having fun in MATLAB". I'm trying to create the GUI to plot lines of random numbers. I'm troubleshooting this bit of code:

`% --- Executes on button press in MakeThePlot.

function MakeThePlot_Callback(hObject, eventdata, handles)

numCol = str2double( get(handles.numLines,'string') );

disp('A')

There is a dot next to the last line indicating (I guess) that I'm only working with the MakeThePlot function. If I do NOT have the line beginning with "numCol" in the file, it runs perfectly, displaying A in the console every time I hit the "MakeThePlot' button in the GUI. Add in the one line, and it throws the error I give in the title. AFAIK I'm following the instructor's steps exactly. What am I doing wrong? THanks in advance.

I'm not sure what to add to what I gave above. I tried putting in only one line of the instructor's code in the function to keep it simple. I expected it to do nothing but display 'A' in the console.