问:
Error: Unable to load spec files quite likely because they rely on `browser` object that is not fully initialized. Facing error after updating chrome
I have updated the chrome version and passed the same version in the config.js file as below, but I'm facing the error while running the tests. Please help me here

wdio-common-config.js file

```<code>const drivers = {
    chrome: { version: '108.0.5359.71' }
};
</code>```

Error:

ERROR @wdio/runner: Error: Unable to load spec files quite likely because they rely on browser object that is not fully initialised.
[0-0] browser object has only capabilities and some flags like isMobile.
[0-0] Helper files that use other browser commands have to be moved to before hook.
Spec file(s): file:///C:/Users/rajits/E2E/spr-mpo-end-2-end-tests-redesign/spec/mpo/alsMijnSituatieVerandert/alsMijnSituatieVerandert.js
Error: Error: Cannot find module 'C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\file:\C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\spec\mpo\alsMijnSituatieVerandert\alsMijnSituatieVerandert.js'
Require stack:

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules\mocha\lib\nodejs\esm-utils.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules\mocha\lib\mocha.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules\mocha\index.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules@wdio\mocha-framework\build\index.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules@wdio\utils\build\utils.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules@wdio\utils\build\initialisePlugin.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules@wdio\utils\build\index.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules@wdio\runner\build\index.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules@wdio\local-runner\build\run.js

Tried to degrade the chrome version, but its still same

Body:
I have updated the chrome version and passed the same version in the config.js file as below, but I'm facing the error while running the tests. Please help me here

wdio-common-config.js file

const drivers = {
    chrome: { version: '108.0.5359.71' }
};

Error:

ERROR @wdio/runner: Error: Unable to load spec files quite likely because they rely on browser object that is not fully initialised.
[0-0] browser object has only capabilities and some flags like isMobile.
[0-0] Helper files that use other browser commands have to be moved to before hook.
Spec file(s): file:///C:/Users/rajits/E2E/spr-mpo-end-2-end-tests-redesign/spec/mpo/alsMijnSituatieVerandert/alsMijnSituatieVerandert.js
Error: Error: Cannot find module 'C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\file:\C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\spec\mpo\alsMijnSituatieVerandert\alsMijnSituatieVerandert.js'
Require stack:

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules\mocha\lib\nodejs\esm-utils.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules\mocha\lib\mocha.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules\mocha\index.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules@wdio\mocha-framework\build\index.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules@wdio\utils\build\utils.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules@wdio\utils\build\initialisePlugin.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules@wdio\utils\build\index.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules@wdio\runner\build\index.js

C:\Users\rajits\E2E\spr-mpo-end-2-end-tests-redesign\node_modules@wdio\local-runner\build\run.js

Tried to degrade the chrome version, but its still same


来源: stackexchange

问:
Hover aware slider on mobile how to keep it functional?
i have a video preview that built from thumbnail, and launch a slider of multiple frames on hover.
its working exellent on desktop, but on mobile its not working.

This is the function:

```<code>`if (jQuery(window).width() > 470) {
    jQuery(document).ready(function($){
    $('img').on('mouseover', function() {
        var self = this,
            i = 0,
            images = $(this).data('mouseover').split('||');

        (function nextImage() {
            var next = images[i++ % images.length].split('#');
            $(self).data('timeout', setTimeout(function() {
                self.src = next[0];
                nextImage();
            }, next[1] || 500));
        })();

    }).on('mouseout', function() {
        clearTimeout($(this).data('timeout'));
        this.src = $(this).attr('src');
    });
});
} else {
    jQuery(document).ready(function($){
    $('img').on('ontouchstart touchmove', function() {
        var self = this,
            i = 0,
            images = $(this).data('ontouchstart touchmove').split('||');

        (function nextImage() {
            var next = images[i++ % images.length].split('#');
            $(self).data('timeout', setTimeout(function() {
                self.src = next[0];
                nextImage();
            }, next[1] || 500));
        })();

    }).on('touchend', function() {
        clearTimeout($(this).data('timeout'));
        this.src = $(this).attr('src');
    });
});

}
`

This is the HTML:

`<img id="img-slider" src="image1.jpg" data-mouseover="image2.jpg||image3.jpg||image4.jpg" />`

And this is the CSS:

`
#img-slider{
    height: 117px;
    width: 100%;
    object-fit: cover;
    opacity: 0;
}
#img-slider:hover{
    opacity: 1;
}

@media only screen and (max-width: 600px) {
  #img-slider {
    height:150px;
  }
}`

</code>```

On the console, i get this error (only on mobile):
enter image description here

I tried to make some changes in the original code (the one for destop) and make it work on mobile, but faild.
how can i make it work? and why i get the error only on second split function?
Thanks

Tried to make a mouseover fuction working on mobile.

ContentLicense: CC BY-SA 4.0

Body:
i have a video preview that built from thumbnail, and launch a slider of multiple frames on hover.
its working exellent on desktop, but on mobile its not working.

This is the function:

`if (jQuery(window).width() > 470) {
    jQuery(document).ready(function($){
    $('img').on('mouseover', function() {
        var self = this,
            i = 0,
            images = $(this).data('mouseover').split('||');

        (function nextImage() {
            var next = images[i++ % images.length].split('#');
            $(self).data('timeout', setTimeout(function() {
                self.src = next[0];
                nextImage();
            }, next[1] || 500));
        })();

    }).on('mouseout', function() {
        clearTimeout($(this).data('timeout'));
        this.src = $(this).attr('src');
    });
});
} else {
    jQuery(document).ready(function($){
    $('img').on('ontouchstart touchmove', function() {
        var self = this,
            i = 0,
            images = $(this).data('ontouchstart touchmove').split('||');

        (function nextImage() {
            var next = images[i++ % images.length].split('#');
            $(self).data('timeout', setTimeout(function() {
                self.src = next[0];
                nextImage();
            }, next[1] || 500));
        })();

    }).on('touchend', function() {
        clearTimeout($(this).data('timeout'));
        this.src = $(this).attr('src');
    });
});

}
`

This is the HTML:

`<img id="img-slider" src="image1.jpg" data-mouseover="image2.jpg||image3.jpg||image4.jpg" />`

And this is the CSS:

`
#img-slider{
    height: 117px;
    width: 100%;
    object-fit: cover;
    opacity: 0;
}
#img-slider:hover{
    opacity: 1;
}

@media only screen and (max-width: 600px) {
  #img-slider {
    height:150px;
  }
}`

On the console, i get this error (only on mobile):
enter image description here

I tried to make some changes in the original code (the one for destop) and make it work on mobile, but faild.
how can i make it work? and why i get the error only on second split function?
Thanks

Tried to make a mouseover fuction working on mobile.


问:
How to use absolute pack uri in wpf usercontrol properly?
I am still a beginner to wpf applications.
I am using a absolute pack uri in my user control to prevent the error of cannot find resources in the xaml viewer.

I use this code to access my resource dictionary in the root folder of the project.

```<code><UserControl.Resources>
<ResourceDictionary Source="pack://application:,,,/ApplicationResources.xaml"/>
</UserControl.Resources>
</code>```

This usercontrol is located in Pages => SelectFolder =>SelectFolderPage.xaml

Location of the usercontrol:

ApplicationResources.xaml is located

Location of ApplicationResources.xaml document.

I use this usercontrol in MainWindow.xaml which is located in the root directory of the project.

Location of MainWindow.xaml

The error is like this:
I import the user control SelectFolderPage.xaml to MainWindow.xaml.
It shows that it cannot find ApplicationResources.xaml.

Image of the error

But in the SelectFolderPage.xaml page every thing seems to be alright.  Image.

The temporal solution I found was to copy the complete path and replace the source of the resource dictionary. But this is not the solution I am looking for, this application needs to be run in different devices with different paths.

Another solution I tried before is to use the relative path, but it did not work. Because MainWindow.xaml is located in the root directory and "SelectFolderPage.xaml" is located in the sub directory, so I am not sure if this is the factor causing the relative path to not work.

Body:
I am still a beginner to wpf applications.
I am using a absolute pack uri in my user control to prevent the error of cannot find resources in the xaml viewer.

I use this code to access my resource dictionary in the root folder of the project.

<UserControl.Resources>
<ResourceDictionary Source="pack://application:,,,/ApplicationResources.xaml"/>
</UserControl.Resources>

This usercontrol is located in Pages => SelectFolder =>SelectFolderPage.xaml

Location of the usercontrol:

ApplicationResources.xaml is located

Location of ApplicationResources.xaml document.

I use this usercontrol in MainWindow.xaml which is located in the root directory of the project.

Location of MainWindow.xaml

The error is like this:
I import the user control SelectFolderPage.xaml to MainWindow.xaml.
It shows that it cannot find ApplicationResources.xaml.

Image of the error

But in the SelectFolderPage.xaml page every thing seems to be alright.  Image.

The temporal solution I found was to copy the complete path and replace the source of the resource dictionary. But this is not the solution I am looking for, this application needs to be run in different devices with different paths.

Another solution I tried before is to use the relative path, but it did not work. Because MainWindow.xaml is located in the root directory and "SelectFolderPage.xaml" is located in the sub directory, so I am not sure if this is the factor causing the relative path to not work.


问:
Send Promise response from Swift - React native Native modules
I implemented a native module on React Native. When I'm calling a function from RN it will call the Swift module to get the response.

```<code>const response = await voiceRecognizing();
console.log('Response from Native module', response);
</code>```

Now I have an issue with the Swift module. When I'm sending a Promise response with the below code it's working fine, Since resolve and reject are available as argument. So that I can able to send a response

```<code>@objc(voiceRecognizing:withRejecter:)
func voiceRecognizing(resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
  let resultsDict = [
      "success" : true
    ];
    resolve([resultsDict])
}
</code>```

But I'm calling some async function inside Swift So that I wanna to use DispatchQueue.global So Inside DispatchQueue, When I use resolve([resultsDict]) it's throwing error.

```<code>@objc(voiceRecognizing:withRejecter:)
func voiceRecognizing(resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {

     DispatchQueue.global(qos: .userInitiated).async {
          let result = self.recognizeFromMic()
 let resultsDict = [
      "result" : result
    ];
          resolve([resultsDict])
      }
}
</code>```

I'm not that much familiar with developing native modules in Swift.  Any suggestions on how to overcome this issue? Thanks in Advance

Body:
I implemented a native module on React Native. When I'm calling a function from RN it will call the Swift module to get the response.

const response = await voiceRecognizing();
console.log('Response from Native module', response);

Now I have an issue with the Swift module. When I'm sending a Promise response with the below code it's working fine, Since resolve and reject are available as argument. So that I can able to send a response

@objc(voiceRecognizing:withRejecter:)
func voiceRecognizing(resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
  let resultsDict = [
      "success" : true
    ];
    resolve([resultsDict])
}

But I'm calling some async function inside Swift So that I wanna to use DispatchQueue.global So Inside DispatchQueue, When I use resolve([resultsDict]) it's throwing error.

@objc(voiceRecognizing:withRejecter:)
func voiceRecognizing(resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {

     DispatchQueue.global(qos: .userInitiated).async {
          let result = self.recognizeFromMic()
 let resultsDict = [
      "result" : result
    ];
          resolve([resultsDict])
      }
}

I'm not that much familiar with developing native modules in Swift.  Any suggestions on how to overcome this issue? Thanks in Advance


问:
How can ı fix error of TypeError: startfile: filepath should be string, bytes or os.PathLike, not tuple
I assigned the website link I got from the database to a variable and I want to open this variable with the webbrowser module, but it gives an error

```<code>
connection = mysql.connector.connect(host="localhost", user="root", password="password",database="database")
cursor = connection.cursor()

cursor.execute("select spotify_link from users where user_name=%s",[login_user_name_entry.get()])
spotify_link=cursor.fetchone()

def open_profile_spotify_link():
    if spotify_link==None:
        messagebox.showerror("Error",message="No link information has been entered here by the user")
    else:
        webbrowser.open(spotify_link)

</code>```

I want the link that I assigned to the variable to be opened, how can I do it?

the error i got : TypeError: startfile: filepath should be string, bytes or os.PathLike, not tuple

Body:
I assigned the website link I got from the database to a variable and I want to open this variable with the webbrowser module, but it gives an error

connection = mysql.connector.connect(host="localhost", user="root", password="password",database="database")
cursor = connection.cursor()

cursor.execute("select spotify_link from users where user_name=%s",[login_user_name_entry.get()])
spotify_link=cursor.fetchone()

def open_profile_spotify_link():
    if spotify_link==None:
        messagebox.showerror("Error",message="No link information has been entered here by the user")
    else:
        webbrowser.open(spotify_link)

I want the link that I assigned to the variable to be opened, how can I do it?

the error i got : TypeError: startfile: filepath should be string, bytes or os.PathLike, not tuple


问:
is it possible two type of authentication restapi webservice in spring boot?
Accutly I work on Project with Jwt Authentication and I add a webservice for another project call that. and want to add Basic authentication for this service but another service must be work with jwt, is it possible we have two type authentication on spring boot?

this is my SecurityConfigurer for jwt and I want to add basic authentication.

```<code>@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {

private JwtRequestFilter jwtRequestFilter;
private Environment environment;
private UserService userService;
private BCryptPasswordEncoder bCryptPasswordEncoder;

@Autowired
public SecurityConfigurer(Environment environment, UserService userService, BCryptPasswordEncoder bCryptPasswordEncoder, JwtRequestFilter jwtRequestFilter)
{
    this.environment = environment;
    this.userService = userService;
    this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    this.jwtRequestFilter = jwtRequestFilter;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);
}

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf().disable()
            .authorizeRequests().antMatchers("/api/v1/users/authentication").permitAll()
            .antMatchers("/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .exceptionHandling()
            .and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    httpSecurity.cors();
}

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}
</code>```

}

Body:
Accutly I work on Project with Jwt Authentication and I add a webservice for another project call that. and want to add Basic authentication for this service but another service must be work with jwt, is it possible we have two type authentication on spring boot?

this is my SecurityConfigurer for jwt and I want to add basic authentication.

@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {

private JwtRequestFilter jwtRequestFilter;
private Environment environment;
private UserService userService;
private BCryptPasswordEncoder bCryptPasswordEncoder;

@Autowired
public SecurityConfigurer(Environment environment, UserService userService, BCryptPasswordEncoder bCryptPasswordEncoder, JwtRequestFilter jwtRequestFilter)
{
    this.environment = environment;
    this.userService = userService;
    this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    this.jwtRequestFilter = jwtRequestFilter;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userService).passwordEncoder(bCryptPasswordEncoder);
}

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf().disable()
            .authorizeRequests().antMatchers("/api/v1/users/authentication").permitAll()
            .antMatchers("/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .exceptionHandling()
            .and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    httpSecurity.cors();
}

@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

}


问:
Installing packages (npm)...npm ERR! code EHOSTUNREACH
npm ERR! syscall connect
npm ERR! errno EHOSTUNREACH
npm ERR! request to https://registry.npmjs.org/thunky fallied,reason: connect EHOSTUNREACH 2000:4700:8393:88e2:e439:41d:6810:1023:443
npm ERR! A complete log of this run can be found in:
npm ERR!

Package install failed, see above.
The Schematic failed, see above.

Angular installing problem


问:
401 when receiving participants from the server, how to decide?
I want the site to display the number of participants from the server on the site, I kind of passed all the headers with a token, but I still get a 401 error

Here is my code:
`

```<code><?php $json_options = [ "http" => [ "method" => "GET", "header" => "Authorization: token" ] ];
$json_context = stream_context_create($json_options);
$json_get = file_get_contents('https://discordapp.com/api/guilds/SERVER-ID/members?limit=1000', false, $json_context);
$json_decode = json_decode($json_get, true);

echo count($json_decode); ?>
</code>```

`

I tried to recreate the token on the application page

Body:
I want the site to display the number of participants from the server on the site, I kind of passed all the headers with a token, but I still get a 401 error

Here is my code:
`

<?php $json_options = [ "http" => [ "method" => "GET", "header" => "Authorization: token" ] ];
$json_context = stream_context_create($json_options);
$json_get = file_get_contents('https://discordapp.com/api/guilds/SERVER-ID/members?limit=1000', false, $json_context);
$json_decode = json_decode($json_get, true);

echo count($json_decode); ?>

`

I tried to recreate the token on the application page


问:
using Environment variable in yml in combination with if expression
Can someone tell me what I am doing wrong?
ENV_VAR may or may not be defined.
I would like 'time' to take a value depending on this variable. Can someone suggest me a proper solution? I tried this:</p>
```<code>time: {{ 45000 if (${ENV_VAR} is not defined or ${ENV_VAR} == 'false') else 20000 }}
</code>```

Body:
Can someone tell me what I am doing wrong?
ENV_VAR may or may not be defined.
I would like 'time' to take a value depending on this variable. Can someone suggest me a proper solution? I tried this:

time: {{ 45000 if (${ENV_VAR} is not defined or ${ENV_VAR} == 'false') else 20000 }}


问:
Setting up Rascal on VSCode
I have been having trouble installing the Rascal plugin on VSCode, but I can't seem to get the rascal terminal to work or even being able to setup a working Rascal project on VSCode. Please I need a step by step process of properly installing Rascal on VSCode

I tried installing the Rascal extension on VSCode but it doesn't work instead it suggested I download the Rascal VSIX file, but after downloading the file and adding it as an extension on VSCode I still couldn't get the Rascal terminal or generate a working Rascal project.

Title: Setting up Rascal on VSCode


问:
Hide GET Parameters
I am using External Radius Portal in Tp-Link Omada Controller structure

Parameters come as get when creating external connection during connection.

There is information that I do not want to appear on this link. (IP, port, mac address information poses a security risk)

Is there a way to get the method as POST instead of GET?

I want to GET the parameters in the background as a method POST ..

Current:

http://external.com/index.php?target==XX.XX.XX.XX&targetPort=808X&clientMac=00-XX-F8-86-XX-8E&clientIp=XX.XX.XX.XX&apMac=XX-D4-F7-XX-DF-B0&gatewayMac=&scheme=http&ssidName=XXXWiFi&vid=&radioId=1&originUrl=http%3A%2F%2Fwww.google.com.tr%2F&hostname=192.168.X.X%3A8043&serverPort=808X

I want:

http://external.com/index.php

Title: Hide GET Parameters


问:
Unstable lightgbm results on every new process when I restarted the server
This is the python code I used for generating trees from my data.

params = {
    'objective': 'binary',
    'deterministic': True,
    'force_row_wise': True,
    'num_threads': 8,
    'learning_rate': 0.05,
    'max_depth': 3,
    'tree_learner': 'data',
    'boosting_type': 'gbdt',
    'feature_fraction': 0.7,
    'bagging_fraction': 0.8,
    'bagging_freq': 5,
    'verbose': -1,
    'seed': 8,
}
random.seed(8)
np.random.seed(8)

dataset = lgb.Dataset(X, y)
bst = lgb.train(params, dataset, 10, keep_training_booster=True)
trees = bst.dump_model()["tree_info"]

```

I was testing it out on my local macbook M2 machine with a flask server.

The code does give me stable result when I run the algorithm in a row without restarting the process.

The instability happens when every time I reboot the server

I've tested out every possible instruction in https://lightgbm.readthedocs.io/en/latest/Parameters.html

I've even tried setting the random seed of python / numpy, but it doesn't work

I've also disabled parallelism by setting num_threads to 1, but it doesn't help

Body:
This is the python code I used for generating trees from my data.

params = {
    'objective': 'binary',
    'deterministic': True,
    'force_row_wise': True,
    'num_threads': 8,
    'learning_rate': 0.05,
    'max_depth': 3,
    'tree_learner': 'data',
    'boosting_type': 'gbdt',
    'feature_fraction': 0.7,
    'bagging_fraction': 0.8,
    'bagging_freq': 5,
    'verbose': -1,
    'seed': 8,
}
random.seed(8)
np.random.seed(8)

dataset = lgb.Dataset(X, y)
bst = lgb.train(params, dataset, 10, keep_training_booster=True)
trees = bst.dump_model()["tree_info"]

I was testing it out on my local macbook M2 machine with a flask server.

The code does give me stable result when I run the algorithm in a row without restarting the process.

The instability happens when every time I reboot the server

I've tested out every possible instruction in https://lightgbm.readthedocs.io/en/latest/Parameters.html

I've even tried setting the random seed of python / numpy, but it doesn't work

I've also disabled parallelism by setting num_threads to 1, but it doesn't help


问:
Github action to check if PR is older than 3 days from creation date
I am new to GitHub action. I want to check if PR is older than 3 days and then perform the job. basically updating env value
I tried this script which is not working

name: Find old PR
on:
  #schedule job every day at 1 am IST (UTC +5:30)
  schedule:
    - cron: '25 09 * * *'
    - cron: '*/5 * * * *'. # For testing
  workflow_dispatch:

env:
  BRANCH_NAME: ${{ github.event.pull_request.head.ref }} # get branch name from pull request
  PR_NUMBER: ${{ github.event.pull_request.number }}
  AZURE_WEBAPP_NAME: ${{ github.event.pull_request.head.repo.name }} # add GTCRM- prefix to branch name
  AZURE_WEBAPP_PACKAGE_PATH: '.'      # set this to the path to your web app project, defaults to the repository root
  NODE_VERSION: '18-lts'                # set this to the node version to use
  RESOURCE_GROUP: test-${{ github.event.pull_request.number }}-rg # add GTCRM- prefix to branch name
  PR_IS_OLD: false
permissions:
  contents: read
  pull-requests: write
  actions: write

jobs:
  # to get list of all 3 days old PRs
  schedule:
    runs-on: ubuntu-latest
    if: github.event_name == 'schedule'
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Get list of all 3 days old PRs
        id: get-old-prs
        uses: actions/github-script@v5
        with:
          script: |
            const { data: prs } = await github.pulls.list({
            owner: context.repo.owner,
            repo: context.repo.repo,
            state: 'open',
            sort: 'updated',
            direction: 'desc',
            per_page: 100
            })
            const oldPrs = prs.filter(pr => {
            const prDate = new Date(pr.updated_at)
            const today = new Date()
            const diffTime = Math.abs(today - prDate)
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
            return diffDays >= 3
            })
            return oldPrs.map(pr => pr.number)

      # Comment on PRs that are 3 days old
      - name: Comment on PRs that are 3 days old
        uses: actions/github-script@v5
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            const oldPrs = ${{ steps.get-old-prs.outputs.result }}
            oldPrs.forEach(pr => {
            github.issues.createComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: pr,
                body: 'This PR is 3 days old. Please update it or preview of deploy will be deleted.'
            })
            })
```


问:
Transfer learning (or fine-tuning) pre-trained model on non-text data
I am currently fine-tuning a sentiment analysis bert-based model using PyTorch Trainer from hugging face. So far, so good.

I have easily managed to fine-tune the model on my text data. However, I'd like to conduct an ablation study to see how the inclusion of linguistic features impacts the model's performance.

In other words, how the inclusion of, e.g., comment length, type-to-token ratio, and other features (stored in my dataset in a separate column) affects the performance of my model.

This is what my data kind of looks like:

Text
Type-token ratio

Hi, my name is...
1.0

I cannot believe I did not...
0.95

In the specific case above, for instance, I would like to fine-tune the model on the text column but also on the Type-token ratio one.

I know that some people concatenate the two columns into a string, but I am not sure that is the correct method. Is there a more methodologically sound way of doing this?

I was not able to find much information about it.

EDIT:

(The below code works and, ideally, it should also include the TTR column.)

This is my code:

```<code>dataset = pd.read_csv('/content/gdrive/MyDrive/.../data_train.csv')
train_roberta = dataset[['text_lower', 'label']].sample(frac=0.75)
validation_roberta = dataset[['text_lower', 'label']].drop(train_roberta.index)
train_roberta = train_roberta.dropna()
validation_roberta = validation_roberta.dropna()
train = Dataset.from_pandas(train_roberta, preserve_index=False)
validation = Dataset.from_pandas(validation_roberta, preserve_index=False)

tokenizer = AutoTokenizer.from_pretrained("a_model/a_bert_like_model")

def tokenize_function(example):
    return tokenizer(example["text_lower"], padding="max_length", truncation=True)

tokenized_train_dataset = train.map(tokenize_function, batched=True)
tokenized_test_dataset = validation.map(tokenize_function, batched=True)
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
import os
os.environ["WANDB_DISABLED"] = "true"
training_args = TrainingArguments("test-trainer", evaluation_strategy="epoch")   # default arguments for fine-tuning
model = AutoModelForSequenceClassification.from_pretrained("a_model/a_bert_like_model", num_labels=3)

def compute_metrics(eval_preds):   # compute accuracy and f1-score
    metric = load_metric("glue", "mrpc")
    logits, labels = eval_preds
    predictions = np.argmax(logits, axis=-1)
    return metric.compute(predictions=predictions, references=labels)

trainer = Trainer(   # specifying trainer class
    model,
    training_args,
    train_dataset=tokenized_train_dataset,
    eval_dataset=tokenized_test_dataset,
    data_collator=data_collator,
    tokenizer=tokenizer,
    compute_metrics=compute_metrics,
)

trainer.train()  # starts fine-tuning
</code>```

Body:
I am currently fine-tuning a sentiment analysis bert-based model using PyTorch Trainer from hugging face. So far, so good.

I have easily managed to fine-tune the model on my text data. However, I'd like to conduct an ablation study to see how the inclusion of linguistic features impacts the model's performance.

In other words, how the inclusion of, e.g., comment length, type-to-token ratio, and other features (stored in my dataset in a separate column) affects the performance of my model.

This is what my data kind of looks like:

Text
Type-token ratio

Hi, my name is...
1.0

I cannot believe I did not...
0.95

In the specific case above, for instance, I would like to fine-tune the model on the text column but also on the Type-token ratio one.

I know that some people concatenate the two columns into a string, but I am not sure that is the correct method. Is there a more methodologically sound way of doing this?

I was not able to find much information about it.

EDIT:

(The below code works and, ideally, it should also include the TTR column.)

This is my code:

dataset = pd.read_csv('/content/gdrive/MyDrive/.../data_train.csv')
train_roberta = dataset[['text_lower', 'label']].sample(frac=0.75)
validation_roberta = dataset[['text_lower', 'label']].drop(train_roberta.index)
train_roberta = train_roberta.dropna()
validation_roberta = validation_roberta.dropna()
train = Dataset.from_pandas(train_roberta, preserve_index=False)
validation = Dataset.from_pandas(validation_roberta, preserve_index=False)

tokenizer = AutoTokenizer.from_pretrained("a_model/a_bert_like_model")

def tokenize_function(example):
    return tokenizer(example["text_lower"], padding="max_length", truncation=True)

tokenized_train_dataset = train.map(tokenize_function, batched=True)
tokenized_test_dataset = validation.map(tokenize_function, batched=True)
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
import os
os.environ["WANDB_DISABLED"] = "true"
training_args = TrainingArguments("test-trainer", evaluation_strategy="epoch")   # default arguments for fine-tuning
model = AutoModelForSequenceClassification.from_pretrained("a_model/a_bert_like_model", num_labels=3)

def compute_metrics(eval_preds):   # compute accuracy and f1-score
    metric = load_metric("glue", "mrpc")
    logits, labels = eval_preds
    predictions = np.argmax(logits, axis=-1)
    return metric.compute(predictions=predictions, references=labels)

trainer = Trainer(   # specifying trainer class
    model,
    training_args,
    train_dataset=tokenized_train_dataset,
    eval_dataset=tokenized_test_dataset,
    data_collator=data_collator,
    tokenizer=tokenizer,
    compute_metrics=compute_metrics,
)

trainer.train()  # starts fine-tuning


问:
openssl error 6 at 1 depth lookup: unable to decode issuer public key
I am unable to verify my certificate chains which are generated with post quantum schemes like dilithium2,dilithium2_aes while I was able to verify with classical schemes like RSA, ECDSA. I am using OQS openssl libraryto generate my certificate chains.

Following is my verification command.

openssl verify -CAfile CA.pem combined.pem

CA.pem is the root CA certificate file and combined.pem is a single certificate containing intermediate certificate and server certificate.

After running the above mentioned command, following is my output.

enter image description here

As per output, I think CA certificate is being verified but not intermediate certificate and server certificate.


问:
How to initialize variables by other varialble's value when defining store in Pinia?
I am attempting to use Pinia to reserve some global data, and I define a pinia store like this:

import { defineStore } from 'pinia';

export class TreeNode {
    constructor(data, parent = null) {
        this.data = data;
        this.parent = parent;
        this.children = [];
    }
}

export const useXXXStore = defineStore('xxx', {
    state: () => ({
        root: new TreeNode('data', null),
        current_node: this.root,
    }),
})
```
<p>However, I got this error message after running this program:</p>
```XXXStore.js?b287:16 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'root')
    at state (BoardStateStore.js?b287:16:1)
    at setup (pinia.mjs?b318:1196:1)
    at eval (pinia.mjs?b318:1436:1)
    at EffectScope.run (reactivity.esm-bundler.js?89dc:34:1)
    at eval (pinia.mjs?b318:1436:1)
    at EffectScope.run (reactivity.esm-bundler.js?89dc:34:1)
    at createSetupStore (pinia.mjs?b318:1434:1)
    at createOptionsStore (pinia.mjs?b318:1224:1)
    at useStore (pinia.mjs?b318:1708:1)
    at setup (BoardBox.vue?169e:43:1)
```

How do I initialize current_node with the value of root in vue.js?

Is there any function like constructor where I can initialize the value of the variables?

Body:
I am attempting to use Pinia to reserve some global data, and I define a pinia store like this:

import { defineStore } from 'pinia';

export class TreeNode {
    constructor(data, parent = null) {
        this.data = data;
        this.parent = parent;
        this.children = [];
    }
}

export const useXXXStore = defineStore('xxx', {
    state: () => ({
        root: new TreeNode('data', null),
        current_node: this.root,
    }),
})

However, I got this error message after running this program:

XXXStore.js?b287:16 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'root')
    at state (BoardStateStore.js?b287:16:1)
    at setup (pinia.mjs?b318:1196:1)
    at eval (pinia.mjs?b318:1436:1)
    at EffectScope.run (reactivity.esm-bundler.js?89dc:34:1)
    at eval (pinia.mjs?b318:1436:1)
    at EffectScope.run (reactivity.esm-bundler.js?89dc:34:1)
    at createSetupStore (pinia.mjs?b318:1434:1)
    at createOptionsStore (pinia.mjs?b318:1224:1)
    at useStore (pinia.mjs?b318:1708:1)
    at setup (BoardBox.vue?169e:43:1)

How do I initialize current_node with the value of root in vue.js?

Is there any function like constructor where I can initialize the value of the variables?


问:
Index is not redirecting to home via session.php and authentication
HOME.php

```<code><?php
   require_once './assets/php/session.php';
   echo '```';
   print_r($data);
?>
Logout
```
<p>SESSION.php</p>
```<?php

  session_start();
  require_once 'auth.php';
  $cuser = new Auth();

  if(!isset($_SESSION['user'])){
    header('location:index.php');
    die;
  }

  $cemail = $_SESSION['user'];

  $data = $cuser->currentUser($cemail);

?>
```
<p>AUTH METHOD</p>
```    public function currentUser($email){
        $sql = "SELECT * FROM users WHERE email=:email AND deleted !=0";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute(['email'=>$email]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        return $row;
    }
```

I'm trying to display all the details of user on it's home page via session.php but my index.php is not redirecting me on the same

Body:
HOME.php

<?php
   require_once './assets/php/session.php';
   echo '
';
   print_r($data);
?>
Logout

SESSION.php

<?php

  session_start();
  require_once 'auth.php';
  $cuser = new Auth();

  if(!isset($_SESSION['user'])){
    header('location:index.php');
    die;
  }

  $cemail = $_SESSION['user'];

  $data = $cuser->currentUser($cemail);

?>

AUTH METHOD

    public function currentUser($email){
        $sql = "SELECT * FROM users WHERE email=:email AND deleted !=0";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute(['email'=>$email]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        return $row;
    }

I'm trying to display all the details of user on it's home page via session.php but my index.php is not redirecting me on the same


问:
docker-desktop EXTERNAL_IP <none>
I am trying to follow this helm introduction: https://github.com/IBM/helm101
After changing the service from LoadBalancer to NodePort I don't know how can I reach the website.

With following the kubectl instructions I got the following address:

```<code>export NODE_PORT=$(kubectl get --namespace helm-demo -o jsonpath="{.spec.ports[0].nodePort}" services helm-demo-guestbook)
export NODE_IP=$(kubectl get nodes --namespace helm-demo -o jsonpath="{.items[0].status.addresses[0].address}")
echo http://$NODE_IP:$NODE_PORT
</code>```

the provided address:

```<code>http://192.168.65.4:32113
</code>```

What I was thinking the problem might be that the EXTERNAL_IP field for docker-desktop is <none>
kubectl get nodes -o wide

```<code>NAME             STATUS   ROLES           AGE     VERSION   INTERNAL-IP    EXTERNAL-IP   OS-IMAGE         KERNEL-VERSION                      CONTAINER-RUNTIME
docker-desktop   Ready    control-plane   4d18h   v1.25.2   192.168.65.4   <none>        Docker Desktop   5.10.16.3-microsoft-standard-WSL2   docker://20.10.21
</code>```

Title: docker-desktop EXTERNAL_IP <none>

Body:
I am trying to follow this helm introduction: https://github.com/IBM/helm101
After changing the service from LoadBalancer to NodePort I don't know how can I reach the website.

With following the kubectl instructions I got the following address:

export NODE_PORT=$(kubectl get --namespace helm-demo -o jsonpath="{.spec.ports[0].nodePort}" services helm-demo-guestbook)
export NODE_IP=$(kubectl get nodes --namespace helm-demo -o jsonpath="{.items[0].status.addresses[0].address}")
echo http://$NODE_IP:$NODE_PORT

the provided address:

http://192.168.65.4:32113

What I was thinking the problem might be that the EXTERNAL_IP field for docker-desktop is <none>
kubectl get nodes -o wide

NAME             STATUS   ROLES           AGE     VERSION   INTERNAL-IP    EXTERNAL-IP   OS-IMAGE         KERNEL-VERSION                      CONTAINER-RUNTIME
docker-desktop   Ready    control-plane   4d18h   v1.25.2   192.168.65.4   <none>        Docker Desktop   5.10.16.3-microsoft-standard-WSL2   docker://20.10.21


问:
CMake: add_compile_options adds options to ZERO_CHECK on Windows
In my CMakeLists.txt on Windows, I want to set flags for all targets. So I use add_compile_options to add these flags and use cmake -G "Visual Studio 17 2022"  to generate the solution file. Unfortunately, the flags from add_compile_options are applied to the ZERO_CHECK target which causes problems. For example, setting /MP through this method leads to an error.

I don't want to set these flags repeatedly on each target. Is there a way to tell CMake to not apply these flags to ZERO_CHECK? Or, is there a better way to apply these flags to all targets other than ZERO_CHECK?


问:
Snowflake CI CD using GITLAB yaml file
As part of a project, I need to setup snowflake CI CD using GITLAB and deploy my script to different environments, I have been able to get information about snowflake CI CD from GITHUB and Azure DEVOPS, but could not find any information about how to set up CI CD using GITLAB.

In order to deploy my script to different environments, I was expecting a yml file that can help me with Snowflake CI CD using GITLAB.

Title: Snowflake CI CD using GITLAB yaml file


问:
How to render blade component with JS?
So, I have blade component, called answerInput. It has incoming parameters and some logic inside.
When I'm rendering it as usual - by manually adding tag into DOM tree, everything works fine:

```<code><x-answer-input type="radio"></x-answer-input>
</code>```

And after render, I get following code:

```<code><div class="mb-4 row">
    <div class="group col">
        <label for="name" class="form-label">Answer name</label>
        <input type="text" class="form-control" id="name" name="name[]">
    </div>
    <input type="radio" class="col input">
</div>
</code>```

But I need to add this component dynamically, using JS function:

```<code>        let addAnswer = () => {
            let answer = document.createElement("x-answer-input");
            answer.setAttribute('type', getParamValue());
            answers.appendChild(answer);
        }
</code>```

Function adds element to the DOM tree, but it doesn't seem to be processed by Blade, because finally, there still only the template tag in document.

```<code><x-answer-input type="radio"></x-answer-input>
</code>```

Title: How to render blade component with JS?

Body:
So, I have blade component, called answerInput. It has incoming parameters and some logic inside.
When I'm rendering it as usual - by manually adding tag into DOM tree, everything works fine:

<x-answer-input type="radio"></x-answer-input>

And after render, I get following code:

        Answer name
        <input type="text" class="form-control" id="name" name="name[]">

    <input type="radio" class="col input">

But I need to add this component dynamically, using JS function:

        let addAnswer = () => {
            let answer = document.createElement("x-answer-input");
            answer.setAttribute('type', getParamValue());
            answers.appendChild(answer);
        }

Function adds element to the DOM tree, but it doesn't seem to be processed by Blade, because finally, there still only the template tag in document.

<x-answer-input type="radio"></x-answer-input>


问:
nav mesh agent changing the position of my gameobject
I am spawning my animals after the game runs. When ı add nav mesh agent to my animal prefab it turns out the old position.

Here is my Code:

```<code>public class GeneralScript : MonoBehaviour
{
public GameObject Deer;
private int deernum1 = 0
private int num;

private bool cond1 = true;
private bool cond2 = true;

void Start()
{
    StartCoroutine(spawnanimalsatposition1());

}

IEnumerator spawnanimalsatposition1()
{
    yield return new WaitForSeconds(3f);
    while (cond1)
    {
        Vector3 position1 = new Vector3(Random.Range(300,495), 1, Random.Range(5, 495));
        position1.y = Terrain.activeTerrain.SampleHeight(position1) +
        Terrain.activeTerrain.GetPosition().y;
        position1.y += 1.2f;
        Instantiate(Deer, position1, Quaternion.Euler(-90, 0, 0));

        deernum1++;
        if (deernum1 > 6)
        {
            cond1 = false;
        }

    }
}
</code>```

Example of my Issue: Normal
Broken

Does anyone know why is this happening and how to fix it.

Body:
I am spawning my animals after the game runs. When ı add nav mesh agent to my animal prefab it turns out the old position.

Here is my Code:

public class GeneralScript : MonoBehaviour
{
public GameObject Deer;
private int deernum1 = 0
private int num;

private bool cond1 = true;
private bool cond2 = true;

void Start()
{
    StartCoroutine(spawnanimalsatposition1());

}

IEnumerator spawnanimalsatposition1()
{
    yield return new WaitForSeconds(3f);
    while (cond1)
    {
        Vector3 position1 = new Vector3(Random.Range(300,495), 1, Random.Range(5, 495));
        position1.y = Terrain.activeTerrain.SampleHeight(position1) +
        Terrain.activeTerrain.GetPosition().y;
        position1.y += 1.2f;
        Instantiate(Deer, position1, Quaternion.Euler(-90, 0, 0));

        deernum1++;
        if (deernum1 > 6)
        {
            cond1 = false;
        }

    }
}

Example of my Issue: Normal
Broken

Does anyone know why is this happening and how to fix it.


问:
how to access state's values in handleClick method inside a functional component in React
So I want handleCLick to do nothing if selected length >= 4, But when i try to access selected inside handleClick i am getting an empty object. Please help me, im pulling my hairs over this

```<code>function App() {
  const [data, setData] = useState([]);
  const [selected, setSelected] = useState({});

  useEffect(() => {
    getData();
  }, []);

  const handleClick = (e) => {
    let selectedId = e.target.id;
    if (!selectedId) {
      selectedId = e.target.parentElement.id;
    }
    setSelected((prev) => {
      return {
        ...prev,
        [selectedId]: true,
      };
    });
  };

  const getData = async () => {
    let resData = null;

    try {
      const res = await axios.get("https://dummyjson.com/products");
      if (res.status === 200) {
        resData = res.data.products;
      }
    } catch (err) {
      alert("Something went wrong please check the api");
    } finally {
      if (resData) {
        resData.forEach((ele) => {
          ele.key = ele.id;
          ele.compare = (
            <Button id={ele.id} type="primary" onClick={(e) => handleClick(e)}>
              Compare
            </Button>
          );
        });
        setData(resData);
      }
    }
  };

  return (
    <div className="App">
      <Router>
        <Navbar />
        <div className="main">
          <Sidebar />
          <Routes>
            <Route path="/" element={<Products data={data} />}></Route>
            <Route
              path="/compareproducts"
              element={<CompareProducts />}
            ></Route>
          </Routes>
        </div>
      </Router>
    </div>
  );
}

export default App;
</code>```

I tried setting a variable outside handleClick function with selected states value but that didnt work out.

Body:
So I want handleCLick to do nothing if selected length >= 4, But when i try to access selected inside handleClick i am getting an empty object. Please help me, im pulling my hairs over this

function App() {
  const [data, setData] = useState([]);
  const [selected, setSelected] = useState({});

  useEffect(() => {
    getData();
  }, []);

  const handleClick = (e) => {
    let selectedId = e.target.id;
    if (!selectedId) {
      selectedId = e.target.parentElement.id;
    }
    setSelected((prev) => {
      return {
        ...prev,
        [selectedId]: true,
      };
    });
  };

  const getData = async () => {
    let resData = null;

    try {
      const res = await axios.get("https://dummyjson.com/products");
      if (res.status === 200) {
        resData = res.data.products;
      }
    } catch (err) {
      alert("Something went wrong please check the api");
    } finally {
      if (resData) {
        resData.forEach((ele) => {
          ele.key = ele.id;
          ele.compare = (
            <Button id={ele.id} type="primary" onClick={(e) => handleClick(e)}>
              Compare
            </Button>
          );
        });
        setData(resData);
      }
    }
  };

  return (

      <Router>
        <Navbar />

          <Sidebar />
          <Routes>
            <Route path="/" element={<Products data={data} />}></Route>
            <Route
              path="/compareproducts"
              element={<CompareProducts />}
            ></Route>
          </Routes>

      </Router>

  );
}

export default App;

I tried setting a variable outside handleClick function with selected states value but that didnt work out.


问:
QtCreator - QtQuickStudioComponents no such file - macos
I've developed a custom UI in Qt Design Studio and now I would like to import it in QtCreator in order to attach the backend code to it. I used ArcItems and Arrows in the UI and once imported into QtCreator they are providing these errors:

Component with path /Users/xxx/Qt/6.2.4/macos/qml/QtQuick/Studio/Components/ArcItem.qml could not be created

/System/Library/Frameworks/QtQuickStudioComponents.framework/Versions/A/QtQuickStudioComponents (no such file)

module QtQuick.Studio.Components is not installed

I've already followed the steps suggested in the Qt documentation at this link and tried to copy the Studio folder of Qt Design Studio into Qt as described in this answer  but both the solutions are not working.

Could you please help me in understanding if there's something wrong in what I'm trying to do or if there is any missing configuration in the code?

Thanks in advance!


问:
How to create a loop in df which is based on several conditions in order to create several new columns?
I have this df -

```<code>
    Row Amount  1   2   3   Goal 1  Goal 2  Goal 3  Weight 1    Weight 2    Weight 3
 0    0      0  0   0   0        5       6       7       100          90          80
 1    1      4  1   0   0        5       6       7       100          90          80
 2    2      0  1   1   0        5       6       7       100          90          80
 3    3      2  1   1   1        5       6       7       100          90          80
 4    4      0  1   1   1        5       6       7       100          90          80
 5    5      0  1   1   1        5       6       7       100          90          80
 6    6      1  1   1   1        5       6       7       100          90          80
 7    7      0  1   1   1        5       6       7       100          90          80
 8    8      2  1   1   1        5       6       7       100          90          80
 9    9      0  1   1   1        5       6       7       100          90          80
10   10      0  1   1   1        5       6       7       100          90          80
11   11      0  1   1   1        5       6       7       100          90          80
12   12      0  1   1   1        5       6       7       100          90          80
13   13      5  1   1   1        5       6       7       100          90          80
</code>```

I'll try to explain about the columns -
1,2,3 are boxes.
The goal is to fill the boxes.
For each box, there is a different goal (Goal 1/2/3).
Amount means the number of pieces we need to fill into the boxes.
The values inside 1/2/3 are 0 or 1. Only when it's 1 then we can fill into that specific box, otherwise, we can't.
There are several more conditions:

Once the Amount is greater than 0, then we need to try to fill this amount into 3 different boxes, if not possible, then we need to try to fill this amount into 2 different boxes, and if not possible then to 1 box.

If that is not possible, then we need to try and fill in Amount-1, if not possible then Amount -2 and so on.

We need to choose the boxes to fill in by 3 conditions - we still didn't reach their goal, the value inside their column is 1 (and not 0) and also we need to take into account the Weights - so for example, let's say we can fill into Box 1 and Box 2 do the prob that we choose Box 1 is 100/190 and the prob we choose Box 2 is 90/190.

The output should be 3 new columns with updated Boxes status -> starting from 0 until we reach their final goal or the maximum amount we can fill.

To be honest I don't even know from to start. I'm a beginner at python.
I assume we need to create sort of a function with a loop which based on several conditions to solve it.

Hopefully, I've managed to explain myself.
I'll appreciate any help :)

The full code:

```<code>seed(1)
np.random.seed(1)

Range = np.arange(0,14,1)

A={
    0:2,
    1:2,
    2:2,
    3:2,
    4:3,
    5:3,
    6:3,
    7:2,
    8:2,
    9:5,
    10:5,
    11:5,
    12:5,
    13:5
}

Table = pd.DataFrame({"Row": Range})
Table["Intervals"]=(Table["Row"]%14).map(A)
group = Table['Intervals'].ne(Table['Intervals'].shift()).cumsum()
Table['Counter'] = Table.groupby(group).cumcount().mod(Table['Intervals']).add(1)
Table["Complete"]=np.where(Table["Counter"]==Table["Intervals"],1,0)
Table["Amount"]=Table["Complete"] * np.random.choice([1,2,3,4,5],size=len(Table), p=[0.2,0.2,0.2,0.2,0.2])

Table["1"]=np.where(Table["Row"]>=1,1,0)
Table["2"]=np.where(Table["Row"]>=2,1,0)
Table["3"]=np.where(Table["Row"]>=3,1,0)

Table["Goal 1"]=5
Table["Goal 2"]=6
Table["Goal 3"]=7

Table["Weight 1"]=100
Table["Weight 2"]=90
Table["Weight 3"]=80

Table[["Row","Amount","1","2","3",
       "Goal 1","Goal 2","Goal 3",
       "Weight 1","Weight 2","Weight 3"
      ]]
</code>```

Body:
I have this df -

    Row Amount  1   2   3   Goal 1  Goal 2  Goal 3  Weight 1    Weight 2    Weight 3
 0    0      0  0   0   0        5       6       7       100          90          80
 1    1      4  1   0   0        5       6       7       100          90          80
 2    2      0  1   1   0        5       6       7       100          90          80
 3    3      2  1   1   1        5       6       7       100          90          80
 4    4      0  1   1   1        5       6       7       100          90          80
 5    5      0  1   1   1        5       6       7       100          90          80
 6    6      1  1   1   1        5       6       7       100          90          80
 7    7      0  1   1   1        5       6       7       100          90          80
 8    8      2  1   1   1        5       6       7       100          90          80
 9    9      0  1   1   1        5       6       7       100          90          80
10   10      0  1   1   1        5       6       7       100          90          80
11   11      0  1   1   1        5       6       7       100          90          80
12   12      0  1   1   1        5       6       7       100          90          80
13   13      5  1   1   1        5       6       7       100          90          80

I'll try to explain about the columns -
1,2,3 are boxes.
The goal is to fill the boxes.
For each box, there is a different goal (Goal 1/2/3).
Amount means the number of pieces we need to fill into the boxes.
The values inside 1/2/3 are 0 or 1. Only when it's 1 then we can fill into that specific box, otherwise, we can't.
There are several more conditions:

Once the Amount is greater than 0, then we need to try to fill this amount into 3 different boxes, if not possible, then we need to try to fill this amount into 2 different boxes, and if not possible then to 1 box.

If that is not possible, then we need to try and fill in Amount-1, if not possible then Amount -2 and so on.

We need to choose the boxes to fill in by 3 conditions - we still didn't reach their goal, the value inside their column is 1 (and not 0) and also we need to take into account the Weights - so for example, let's say we can fill into Box 1 and Box 2 do the prob that we choose Box 1 is 100/190 and the prob we choose Box 2 is 90/190.

The output should be 3 new columns with updated Boxes status -> starting from 0 until we reach their final goal or the maximum amount we can fill.

To be honest I don't even know from to start. I'm a beginner at python.
I assume we need to create sort of a function with a loop which based on several conditions to solve it.

Hopefully, I've managed to explain myself.
I'll appreciate any help :)

The full code:

seed(1)
np.random.seed(1)

Range = np.arange(0,14,1)

A={
    0:2,
    1:2,
    2:2,
    3:2,
    4:3,
    5:3,
    6:3,
    7:2,
    8:2,
    9:5,
    10:5,
    11:5,
    12:5,
    13:5
}

Table = pd.DataFrame({"Row": Range})
Table["Intervals"]=(Table["Row"]%14).map(A)
group = Table['Intervals'].ne(Table['Intervals'].shift()).cumsum()
Table['Counter'] = Table.groupby(group).cumcount().mod(Table['Intervals']).add(1)
Table["Complete"]=np.where(Table["Counter"]==Table["Intervals"],1,0)
Table["Amount"]=Table["Complete"] * np.random.choice([1,2,3,4,5],size=len(Table), p=[0.2,0.2,0.2,0.2,0.2])

Table["1"]=np.where(Table["Row"]>=1,1,0)
Table["2"]=np.where(Table["Row"]>=2,1,0)
Table["3"]=np.where(Table["Row"]>=3,1,0)

Table["Goal 1"]=5
Table["Goal 2"]=6
Table["Goal 3"]=7

Table["Weight 1"]=100
Table["Weight 2"]=90
Table["Weight 3"]=80

Table[["Row","Amount","1","2","3",
       "Goal 1","Goal 2","Goal 3",
       "Weight 1","Weight 2","Weight 3"
      ]]


问:
Making table rows using for loop
I'm trying to make table rows using for-loop and setting the text from a list but it repeats the list from the beginning and not displaying the next batch of list elements.

Creating row header

```<code>String[] tableHeader = {"Session ID", "Date & Time", "Syllabary", "Mistakes", "Score", "Time", "Wrong Characters", "User ID"};
TableRow rowHead = new TableRow(this);
for (String text : tableHeader) {
    TextView columns = new TextView(this);
    columns.setLayoutParams(new TableRow.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    columns.setTextColor(Color.RED);
    columns.setTextSize(18);
    columns.setPadding(5, 5, 5, 5);
    columns.setText(text);

    rowHead.addView(columns);
}
tableLayout.addView(rowHead);
</code>```

sessionList contains:

```<code>[5, 12/10/2022 12:04:08 AM, 10 chars hira, 5, 5, 00m:05s, [ら, た, ら, ら, は], 1,
4, 12/09/2022 10:10:36 PM, 10 chars hira, 5, 5, 00m:04s, [わ, な, あ, な, あ], 1,
2, 12/09/2022 07:39:14 PM, 10 chars kata, 7, 3, 00m:05s, [ハ, ラ, ア, マ, ハ, マ, ヤ], 1]
</code>```

Creating rows

```<code>for (int rowCount = 0; rowCount < allSession.size(); rowCount++) { // creates 3 rows
      TableRow row = new TableRow(this);

      for (int columnCount = 0; columnCount < sessionList.size(); columnCount++) {
            TextView columns = new TextView(this);
            columns.setLayoutParams(new TableRow.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            columns.setGravity(Gravity.CENTER);
            columns.setTextColor(Color.BLACK);
            columns.setTextSize(18);
            columns.setPadding(5, 5, 5, 5);
            columns.setText(sessionList.get(columnCount)); // always starts at the beginning

            row.addView(columns);
      }
      tableLayout.addView(row);

}
</code>```

Output

Title: Making table rows using for loop

Body:
I'm trying to make table rows using for-loop and setting the text from a list but it repeats the list from the beginning and not displaying the next batch of list elements.

Creating row header

String[] tableHeader = {"Session ID", "Date & Time", "Syllabary", "Mistakes", "Score", "Time", "Wrong Characters", "User ID"};
TableRow rowHead = new TableRow(this);
for (String text : tableHeader) {
    TextView columns = new TextView(this);
    columns.setLayoutParams(new TableRow.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    columns.setTextColor(Color.RED);
    columns.setTextSize(18);
    columns.setPadding(5, 5, 5, 5);
    columns.setText(text);

    rowHead.addView(columns);
}
tableLayout.addView(rowHead);

sessionList contains:

[5, 12/10/2022 12:04:08 AM, 10 chars hira, 5, 5, 00m:05s, [ら, た, ら, ら, は], 1,
4, 12/09/2022 10:10:36 PM, 10 chars hira, 5, 5, 00m:04s, [わ, な, あ, な, あ], 1,
2, 12/09/2022 07:39:14 PM, 10 chars kata, 7, 3, 00m:05s, [ハ, ラ, ア, マ, ハ, マ, ヤ], 1]

Creating rows

for (int rowCount = 0; rowCount < allSession.size(); rowCount++) { // creates 3 rows
      TableRow row = new TableRow(this);

      for (int columnCount = 0; columnCount < sessionList.size(); columnCount++) {
            TextView columns = new TextView(this);
            columns.setLayoutParams(new TableRow.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            columns.setGravity(Gravity.CENTER);
            columns.setTextColor(Color.BLACK);
            columns.setTextSize(18);
            columns.setPadding(5, 5, 5, 5);
            columns.setText(sessionList.get(columnCount)); // always starts at the beginning

            row.addView(columns);
      }
      tableLayout.addView(row);

}

Output


问:
UIkit back to root navigation view controller programmatically
my problem is somewhere in my app I want to redirect my root navigation view
but I didn't.

in my scene delegate

```<code> func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let windowScene = (scene as? UIWindowScene) else { return }
        window = UIWindow(frame: windowScene.coordinateSpace.bounds)
        window?.windowScene = windowScene
        window?.rootViewController = UINavigationController(rootViewController: ViewController())
        window?.makeKeyAndVisible()

    }
</code>```

when I want to redirect my rootViewController I used

```<code>self.navigationController?.popToRootViewController(animated: true)
</code>```

but didn't work.

this code redirect me just my ViewController. there is no navigation bar, navigation bar buttons ect.

can anyone help me ?

i have tried everything in this
link

there is no solution for me.

i want to add some pictures about my code:

here is my sceneDelegate

here is my go to root function

i want to see this screen after the go root function

however I see this...

Body:
my problem is somewhere in my app I want to redirect my root navigation view
but I didn't.

in my scene delegate

 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        guard let windowScene = (scene as? UIWindowScene) else { return }
        window = UIWindow(frame: windowScene.coordinateSpace.bounds)
        window?.windowScene = windowScene
        window?.rootViewController = UINavigationController(rootViewController: ViewController())
        window?.makeKeyAndVisible()

    }

when I want to redirect my rootViewController I used

self.navigationController?.popToRootViewController(animated: true)

but didn't work.

this code redirect me just my ViewController. there is no navigation bar, navigation bar buttons ect.

can anyone help me ?

i have tried everything in this
link

there is no solution for me.

i want to add some pictures about my code:

here is my sceneDelegate

here is my go to root function

i want to see this screen after the go root function

however I see this...


问:
electron: --openssl-legacy-provider is not allowed in NODE_OPTIONS
I want create electron app with vue js but I can't start :
I execute this code for run my app :
"cross-env NODE_OPTIONS='--openssl-legacy-provider' vue-cli-service electron:serve"

Return an error : electron: --openssl-legacy-provider is not allowed in NODE_OPTIONS

I have tried to change node version (18.2.1 / 18.2.0 / 19.2.0 / 17.9.1) It's same

More information :

  "dependencies": {
    "core-js": "^3.8.3",
    "cross-env": "^7.0.3",
    "vue": "^3.2.13"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "electron": "^13.0.0",
    "electron-devtools-installer": "^3.1.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3",
    "vue-cli-plugin-electron-builder": "~2.1.1"
  },
```


问:
Firebase Phone Verification in Laravel 9 Inertia.js not working
I want to verify a user's phone number but Firebase phone verification did not send a verification code after successful Recaptcha. Below is my code.

```<code>// Import firebase stuff
import {
  getAuth,
  RecaptchaVerifier,
  signInWithPhoneNumber,
} from "firebase/auth";

const auth = getAuth();
auth.languageCode = "en";

onMounted(() => {
  render();
});

// Render recaptcha widget
const render = () => {
  window.recaptchaVerifier = new RecaptchaVerifier(
    "recaptcha-container",
    {
      size: "normal",
      callback: (response) => {
        console.log(response);
      },
      "expired-callback": () => {
        console.log("expired-callback");
      },
    },
    auth
  );
  recaptchaVerifier.render().then((widgetId) => {
    window.recaptchaWidgetId = widgetId;
    console.log("widgetId", widgetId);
  });
};

// Send verification code to a user's phone number
const sendSMSCode = () => {
  const appVerifier = window.recaptchaVerifier;
  signInWithPhoneNumber(auth, inputPhone.value, appVerifier)
    .then((confirmationResult) => {
      window.confirmationResult = confirmationResult;
      console.log("confirmationResult", confirmationResult);
    })
    .catch((error) => {
      console.log("error", error);
    });
};

// HTML code
  <CardBox :class="cardClass" is-form @submit.prevent="sendSMSCode">
        <FormValidationErrors />

        <FormField
          label="Phone number"
          label-for="phone"
          help="Please enter your phone number"
        >
          <input
            type="text"
            id="phone"
            required
            autocomplete="off"
            v-model="inputPhone"
          />
        </FormField>
        <FormField
          label="Verification Code"
          label-for="code"
          help="Please enter a 6-digital code we sent to your phone number"
        >
          <FormControl
            v-model="inputCode"
            :icon="mdiAsterisk"
            type="text"
            id="code"
            autocomplete="off"
            :min="6"
            :max="6"
          />
        </FormField>
        <div id="recaptcha-container"></div>

        <BaseDivider />

        <div class="flex items-center justify-between">
          <BaseButton type="submit" color="warning" label="Send Code" />
        </div>
      </CardBox>
</code>```

After sending the phone number sent,confirmation result did get returned but Recaptcha widget get re-rendered and the OTP code not sent successfully. Why is that? Did I miss something?

Body:
I want to verify a user's phone number but Firebase phone verification did not send a verification code after successful Recaptcha. Below is my code.

// Import firebase stuff
import {
  getAuth,
  RecaptchaVerifier,
  signInWithPhoneNumber,
} from "firebase/auth";

const auth = getAuth();
auth.languageCode = "en";

onMounted(() => {
  render();
});

// Render recaptcha widget
const render = () => {
  window.recaptchaVerifier = new RecaptchaVerifier(
    "recaptcha-container",
    {
      size: "normal",
      callback: (response) => {
        console.log(response);
      },
      "expired-callback": () => {
        console.log("expired-callback");
      },
    },
    auth
  );
  recaptchaVerifier.render().then((widgetId) => {
    window.recaptchaWidgetId = widgetId;
    console.log("widgetId", widgetId);
  });
};

// Send verification code to a user's phone number
const sendSMSCode = () => {
  const appVerifier = window.recaptchaVerifier;
  signInWithPhoneNumber(auth, inputPhone.value, appVerifier)
    .then((confirmationResult) => {
      window.confirmationResult = confirmationResult;
      console.log("confirmationResult", confirmationResult);
    })
    .catch((error) => {
      console.log("error", error);
    });
};

// HTML code
  <CardBox :class="cardClass" is-form @submit.prevent="sendSMSCode">
        <FormValidationErrors />

        <FormField
          label="Phone number"
          label-for="phone"
          help="Please enter your phone number"
        >
          <input
            type="text"
            id="phone"
            required
            autocomplete="off"
            v-model="inputPhone"
          />
        </FormField>
        <FormField
          label="Verification Code"
          label-for="code"
          help="Please enter a 6-digital code we sent to your phone number"
        >
          <FormControl
            v-model="inputCode"
            :icon="mdiAsterisk"
            type="text"
            id="code"
            autocomplete="off"
            :min="6"
            :max="6"
          />
        </FormField>

        <BaseDivider />

          <BaseButton type="submit" color="warning" label="Send Code" />

      </CardBox>

After sending the phone number sent,confirmation result did get returned but Recaptcha widget get re-rendered and the OTP code not sent successfully. Why is that? Did I miss something?


问:
Using branch name dynamically from GitHub README file
I have a GitHub repo with Azure RM templates ready for deployments.
I included in my repo's README file links that refer to a certain template in my repo and opens the Azure Portal with the template loaded and ready for deployment. the branch name master is hardcoded:
href=https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2Forg%2Frepo-name%2Fmaster%2Fazure%2Ftemplate.json

I want to make the branch name dynamic, which means if I click the README link from branch 'develop' for instance, the link will be:
href=https://portal.azure.com/#create/Microsoft.Template/uri/https%3A%2F%2Fraw.githubusercontent.com%2Forg%2Frepo-name%2Fdevelop%2Fazure%2Ftemplate.json

I don't want to use GitHub Actions for this, I am looking for some kind of environment variable that can be reached from anywhere in the repo, describing the current branch.


问:
Excel/VBA: trigger actions on mouse movements over regions in Map charts
On Excel charts I can trigger actions on mouse movements over elements (eg. a bar) using some VBA instructions:

MouseMove event for getting x and y mouse position (MS doc)

GetChartElement method for getting the index of the element (MS doc)

However the GetChartElement gives an error 445 (object doesn't support this action), although this exception doesn't seem documented.

As workaround, for the map charts, I'm considering to use WinAPI to mouse click on the chart on every movement, triggering the Select event which directly passes the element IDs. However this causes flickering and I had to disable the unwanted double-clicks.

Any better alternatives?


问:
Map repeating element
There is code that checks for the presence of two or more objects in an array. When I add an object from obj to the map array, it looks to see if this object exists, if not, it displays the message "There is no object, we will add" and then adds this object, but if there is "The object already exists".
When there are two identical objects in the array, it still says that it is not there
What could be the problem?</p>
```<code>let obj = [
    {id:1,title:1, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/1.png"},
    {id:1,title:1, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/1.png"},
    // {id:2,title:2, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/2.png"},
    // {id:3,title:3, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/3.png"},
    // {id:4,title:4, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/4.png"},
    // {id:5,title:5, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/5.png"},
    // {id:6,title:6, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/6.png"},
    // {id:6,title:6, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/6.png"},
]

let map = new Map()
for(let i=0;i<obj.length;i++){
    if(map.has(obj[i])){
        console.log('Object already exists')
    }else{
        console.log('There is no object, we will add')
        map.set(obj[i])
    }
}

console.log(map)
</code>```

Title: Map repeating element

Body:
There is code that checks for the presence of two or more objects in an array. When I add an object from obj to the map array, it looks to see if this object exists, if not, it displays the message "There is no object, we will add" and then adds this object, but if there is "The object already exists".
When there are two identical objects in the array, it still says that it is not there
What could be the problem?

let obj = [
    {id:1,title:1, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/1.png"},
    {id:1,title:1, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/1.png"},
    // {id:2,title:2, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/2.png"},
    // {id:3,title:3, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/3.png"},
    // {id:4,title:4, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/4.png"},
    // {id:5,title:5, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/5.png"},
    // {id:6,title:6, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/6.png"},
    // {id:6,title:6, img:"https://www.zonkpro.ru/zonk/assets/dice/mini/6.png"},
]

let map = new Map()
for(let i=0;i<obj.length;i++){
    if(map.has(obj[i])){
        console.log('Object already exists')
    }else{
        console.log('There is no object, we will add')
        map.set(obj[i])
    }
}

console.log(map)


问:
Fullcalendar not rendering events
I'm using the FullCalendar Angular version with a .net core backend.

I am using the event stream and it is bringing back the events nicely whenever I change dates etc.

But the events are not rendering on the calender.

This is the output from my api:

```<code>[{"id":"83220","title":"Tiffany in Office","start":"2022/12/12 09:30 AM","end":"2022/12/12 10:00 AM"},
{"id":"83338","title":"Jamed","start":"2022/12/12 02:00 PM","end":"2022/12/12 03:00 PM"},
{"id":"83465","title":"IAG in Office","start":"2022/12/12 11:30 AM","end":"2022/12/12 12:30 PM"}]
</code>```

And these are my calendar options:

```<code>smallCalendarOptions: CalendarOptions = {
  initialView: 'timeGridDay',
  height: '100%',
  allDaySlot: true,
  displayEventTime: true,
  nowIndicator: true,
  events: this.loadSmallEvents.bind(this)
};
</code>```

I'm on Angular 13 using FullCalendar 5.11.3 with daygrid, interaction and timegrid installed.

Title: Fullcalendar not rendering events

Body:
I'm using the FullCalendar Angular version with a .net core backend.

I am using the event stream and it is bringing back the events nicely whenever I change dates etc.

But the events are not rendering on the calender.

This is the output from my api:

[{"id":"83220","title":"Tiffany in Office","start":"2022/12/12 09:30 AM","end":"2022/12/12 10:00 AM"},
{"id":"83338","title":"Jamed","start":"2022/12/12 02:00 PM","end":"2022/12/12 03:00 PM"},
{"id":"83465","title":"IAG in Office","start":"2022/12/12 11:30 AM","end":"2022/12/12 12:30 PM"}]

And these are my calendar options:

smallCalendarOptions: CalendarOptions = {
  initialView: 'timeGridDay',
  height: '100%',
  allDaySlot: true,
  displayEventTime: true,
  nowIndicator: true,
  events: this.loadSmallEvents.bind(this)
};

I'm on Angular 13 using FullCalendar 5.11.3 with daygrid, interaction and timegrid installed.


问:
How to add a state properly so a link is displaying when I click on the button?
I have created react component as follows:

```<code>import { string, oneOf, func, bool } from "prop-types"
import Icon, { icons } from "design-system/components/icon"
import * as Styled from "./Accordion.styled"

const Accordion = ({
  href,
  text,
  iconStart,
  variant,
  color,
  size,
  active,
  onClick,
  content,
}) =>
(
  <Styled.Component
    as={href ? `a` : `button`}
    variant={variant}
    color={color}
    size={size}
    href={href}
    onClick={onClick}
    content={content}
  >

<Styled.Text variant={variant} color={color} active={active}>
      {text}
</Styled.Text>
<Styled.Icon>
    <Icon name={iconStart} size={size} />
</Styled.Icon>
<Styled.Content>
    {href}
</Styled.Content>
  </Styled.Component>
);

Accordion.propTypes = {
  text: string.isRequired,
  href: string,
  iconStart: oneOf(Object.keys(icons)),
  variant: oneOf(["fill", "border", "text", "textLine"]),
  color: oneOf(["primary", "black", "white"]),
  size: oneOf(["small", "medium", "large"]),
  active: bool,
  onClick: func,
  content: string,
}

Accordion.defaultProps = {
  href: null,
  iconStart: null,
  variant: "fill",
  color: "primary",
  size: "medium",
  active: null,
  onClick: null,
}

export default Accordion
</code>```

I would like it to work in a way that when I click on ,,Options", below it displays a set of links to another pages.
So far, I have managed to add onclick function, but I think I might need a different state to handle it so it displays below?
Could you please kidnly advise ?

In attachment, you can see how it looks right now.

Appreciate your help.

Regards,
Emilia

Body:
I have created react component as follows:

import { string, oneOf, func, bool } from "prop-types"
import Icon, { icons } from "design-system/components/icon"
import * as Styled from "./Accordion.styled"

const Accordion = ({
  href,
  text,
  iconStart,
  variant,
  color,
  size,
  active,
  onClick,
  content,
}) =>
(

  </Styled.Component>
);

Accordion.propTypes = {
  text: string.isRequired,
  href: string,
  iconStart: oneOf(Object.keys(icons)),
  variant: oneOf(["fill", "border", "text", "textLine"]),
  color: oneOf(["primary", "black", "white"]),
  size: oneOf(["small", "medium", "large"]),
  active: bool,
  onClick: func,
  content: string,
}

Accordion.defaultProps = {
  href: null,
  iconStart: null,
  variant: "fill",
  color: "primary",
  size: "medium",
  active: null,
  onClick: null,
}

export default Accordion

I would like it to work in a way that when I click on ,,Options", below it displays a set of links to another pages.
So far, I have managed to add onclick function, but I think I might need a different state to handle it so it displays below?
Could you please kidnly advise ?

In attachment, you can see how it looks right now.

Appreciate your help.

Regards,
Emilia


问:
AssertionError: Audio source must be entered before listening, are you using ``source`` outside of a ``with`` statement?
I am getting this error for taking the voice instruction:

```<code>File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\speech_recognition\__init__.py", line 651, in listen
    assert source.stream is not None, "Audio source must be entered before listening, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?"
AssertionError: Audio source must be entered before listening, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?
</code>```

Here's the code:

import speech_recognition as mic
import pyttsx3
import pywhatkit
import datetime
import wikipedia

assistant = pyttsx3.init()

listener= mic.Recognizer()

def respond(text):
    assistant.say(text)
    assistant.runAndWait()

def inputInstructions():

    with mic.Microphone() as source:

        listener.pause_threshold = 1
        print(source)
        speech = listener.listen(source)

    instruction = listener.recognize_google(speech)
    instruction = instruction.lower()

    if("stark") in instruction:
        instruction = instruction.replace('stark',"")
        print(instruction)

    return instruction
```

I tried the above code but it is not working

Body:
I am getting this error for taking the voice instruction:

File "C:\Users\hp\AppData\Local\Programs\Python\Python310\lib\site-packages\speech_recognition\__init__.py", line 651, in listen
    assert source.stream is not None, "Audio source must be entered before listening, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?"
AssertionError: Audio source must be entered before listening, see documentation for ``AudioSource``; are you using ``source`` outside of a ``with`` statement?

Here's the code:

import speech_recognition as mic
import pyttsx3
import pywhatkit
import datetime
import wikipedia

assistant = pyttsx3.init()

listener= mic.Recognizer()

def respond(text):
    assistant.say(text)
    assistant.runAndWait()

def inputInstructions():

    with mic.Microphone() as source:

        listener.pause_threshold = 1
        print(source)
        speech = listener.listen(source)

    instruction = listener.recognize_google(speech)
    instruction = instruction.lower()

    if("stark") in instruction:
        instruction = instruction.replace('stark',"")
        print(instruction)

    return instruction

I tried the above code but it is not working


问:
convert json to table and avoid memory error
I have a large json file with 38 GB as this structure:

```<code>{"Text": [

    {
        "a" : 6,
        "b" : 2022,
        "c" : 11,
        "d" : "2022-11-24",
        "e" : "567",
        "f" : "ww",
        "i" : "00",
        "j" : 4,
        "k" : "y",
        "l" : null,
        "m" : 3,
        "n" : 7,
        "o" : "54",
        "b" : null,
        "q" : "yes",
        "r" : 77,
        "c" : "yes",
        "t" : 6,
        "y" : 8,
        "v" : "yy",
        "w" : "yy",
        "x" : "o",
        "y" : "100                                                                                ",

        "z" : "r"

    },{...},{....}

    ]}
</code>```

so I have created this code to convert the json to dataFrame, but I get memory error.

```<code> df=pd.DataFrame([])
with open('data.json',encoding='utf-8-sig') as f:
    l=f.read()
    c=json.loads(l)
    v=list(c.keys())[0]
    data=(c[v])

    for line in itertools.islice(data,2):
        json_nor=json_normalize(line)
        df=df.append(json_nor, ignore_index = True)
</code>```

any advice how to convert them and avoid memory error?

Body:
I have a large json file with 38 GB as this structure:

{"Text": [

    {
        "a" : 6,
        "b" : 2022,
        "c" : 11,
        "d" : "2022-11-24",
        "e" : "567",
        "f" : "ww",
        "i" : "00",
        "j" : 4,
        "k" : "y",
        "l" : null,
        "m" : 3,
        "n" : 7,
        "o" : "54",
        "b" : null,
        "q" : "yes",
        "r" : 77,
        "c" : "yes",
        "t" : 6,
        "y" : 8,
        "v" : "yy",
        "w" : "yy",
        "x" : "o",
        "y" : "100                                                                                ",

        "z" : "r"

    },{...},{....}

    ]}

so I have created this code to convert the json to dataFrame, but I get memory error.

 df=pd.DataFrame([])
with open('data.json',encoding='utf-8-sig') as f:
    l=f.read()
    c=json.loads(l)
    v=list(c.keys())[0]
    data=(c[v])

    for line in itertools.islice(data,2):
        json_nor=json_normalize(line)
        df=df.append(json_nor, ignore_index = True)

any advice how to convert them and avoid memory error?


问:
Using ffmpeng in swift code using PythonKit
I have a python script that uses ffmpeng. I installed it using brew install ffmpeg. If I run the python script on python IDE it runs perfectly.

But I wanted to run this python script on my macOS app, so using PythonKit I tried running it:

```<code>static func make_audio(dict: [String: String]) {
        let sys = Python.import("sys")
        let dirPath = "/Users/seungjunlee/PycharmProjects/pythonProject8"
        sys.path.append(dirPath)
        let Media = Python.import("audio")
        Media.make_audio(PythonObject(dict))
    }
</code>```

But if I run above function it keep saying cannot find ffmpeng. So I installed ffmpeng again in current directory.(macOS app project). But I'm still getting error.

I already spent several hours fixing can't find ffmpeng bug appearing when running the python script on Python IDE. The solution was installing it using command brew install ffmpeg. But now it appearing again when I try to run the script in swift code.

Can anyone help me with this? Thanks.

Body:
I have a python script that uses ffmpeng. I installed it using brew install ffmpeg. If I run the python script on python IDE it runs perfectly.

But I wanted to run this python script on my macOS app, so using PythonKit I tried running it:

static func make_audio(dict: [String: String]) {
        let sys = Python.import("sys")
        let dirPath = "/Users/seungjunlee/PycharmProjects/pythonProject8"
        sys.path.append(dirPath)
        let Media = Python.import("audio")
        Media.make_audio(PythonObject(dict))
    }

But if I run above function it keep saying cannot find ffmpeng. So I installed ffmpeng again in current directory.(macOS app project). But I'm still getting error.

I already spent several hours fixing can't find ffmpeng bug appearing when running the python script on Python IDE. The solution was installing it using command brew install ffmpeg. But now it appearing again when I try to run the script in swift code.

Can anyone help me with this? Thanks.


问:
Angular Material Datepicker CSS issue
For some strange reason my calendar CSS is being messed up randomly. Unfortunately I cant provide an sample on how to reproduce this error as Im not sure what I do to make it look like this.

Normally it looks like this:

Anyone got any tips on how to avoid this problem?

Title: Angular Material Datepicker CSS issue


问:
FileNotFoundError: [WinError 3] The system cannot find the path specified: './train'
train_datagen = ImageDataGenerator(rescale=1./255, rotation_range=10, zoom_range=0.1, horizontal_flip=False,fill_mode="nearest")
test_datagen = ImageDataGenerator(rescale=1./255, rotation_range=10,zoom_range=0.1, horizontal_flip=False,fill_mode="nearest")
training_set = train_datagen.flow_from_directory('./train', target_size=(150, 150), batch_size=40, class_mode='categorical')
test_set = test_datagen.flow_from_directory('./test', target_size=(150, 150), batch_size=40, class_mode='categorical')
print(len(training_set.filenames))

I tried giving dataset directory but it didn't workout for me


问:
How to load data into lightening data table component using response from GraphQL query (wire call)
I have a requirement to load data using the graphQL response into the lightening data table.I am able to fetch the response from the grapghQL query into the js . I just need to map the corresponding fields to the data column and populate the table.The below is the dummy code. I have the response from grapgql in an object format just have to assign the value and populate the column headers and value. Could someone help me achieve this .Any pointers would help.

LigteningDataTable.html

```<code><lightning-datatable
                key-field="id"
                data={data}
                hide-checkbox-column="true"
                columns={columns}>
</lightning-datatable>

LigteningDataTable.js
```
import { LightningElement, api, wire } from 'lwc';
import { CapabilityMixin } from 'laf/pageCapability';
import { gql, unstable_graphql } from 'lightning/uiGraphQLApi';
export default class ServiceDocumentListComponent extends CapabilityMixin(LightningElement) {

    get data(){
     return [...Array(100)].map((_, index) => {
                return {
                    name: ` (${index})`,
                    website: 'www.salesforce.com1ß',
                    amount: Math.floor(Math.random() * 100),
                    phone: `${Math.floor(Math.random() * 9000000000) + 1000000000}`,
                    closeAt: new Date(
                        Date.now() + 86400000 * Math.ceil(Math.random() * 20)
                    ),
                };
            });

    }

    get fields() {
    [
        { label: 'Label', fieldName: 'name' , wrapText: true },
        { label: 'Website', fieldName: 'website', type: 'url' , wrapText: true },
        { label: 'Phone', fieldName: 'phone', type: 'phone' , wrapText: true },
        { label: 'Balance', fieldName: 'amount', type: 'currency', wrapText: true },
        { label: 'CloseAt', fieldName: 'closeAt', type: 'date', wrapText: true  },
     ];
    }

```
</code>```

Body:
I have a requirement to load data using the graphQL response into the lightening data table.I am able to fetch the response from the grapghQL query into the js . I just need to map the corresponding fields to the data column and populate the table.The below is the dummy code. I have the response from grapgql in an object format just have to assign the value and populate the column headers and value. Could someone help me achieve this .Any pointers would help.

LigteningDataTable.html

<lightning-datatable
                key-field="id"
                data={data}
                hide-checkbox-column="true"
                columns={columns}>
</lightning-datatable>

LigteningDataTable.js
```
import { LightningElement, api, wire } from 'lwc';
import { CapabilityMixin } from 'laf/pageCapability';
import { gql, unstable_graphql } from 'lightning/uiGraphQLApi';
export default class ServiceDocumentListComponent extends CapabilityMixin(LightningElement) {

    get data(){
     return [...Array(100)].map((_, index) => {
                return {
                    name: ` (${index})`,
                    website: 'www.salesforce.com1ß',
                    amount: Math.floor(Math.random() * 100),
                    phone: `${Math.floor(Math.random() * 9000000000) + 1000000000}`,
                    closeAt: new Date(
                        Date.now() + 86400000 * Math.ceil(Math.random() * 20)
                    ),
                };
            });

    }

    get fields() {
    [
        { label: 'Label', fieldName: 'name' , wrapText: true },
        { label: 'Website', fieldName: 'website', type: 'url' , wrapText: true },
        { label: 'Phone', fieldName: 'phone', type: 'phone' , wrapText: true },
        { label: 'Balance', fieldName: 'amount', type: 'currency', wrapText: true },
        { label: 'CloseAt', fieldName: 'closeAt', type: 'date', wrapText: true  },
     ];
    }

```


问:
How to get the value of x and y in react-native-draggable
Hello I've been searching for the solution for so long and still found nothing (even asked gptChat). The problem is that I want to save the x and y position of my draggable in my props.setPositionX and props.setPositionY, I was thinking using the moveX and moveY propreties was the right way to do it. But it is not because every time my app reloads all the data from firebase all my notes are in a completely different places.

here is what console.log(y) looks like :

```<code>{"_accountsForMovesUpTo": 6859182, "dx": -7.734375, "dy": 159.8876953125, "moveX": 148.7109375, "moveY": 206.4990234375, "numberActiveTouches": 0, "stateID": 0.2076494697380279, "vx": -0.010340073529411764, "vy": 0.021254595588235295, "x0": 156.4453125, "y0": 46.611328125}```

I tried by saving dx + d0 or tried with eventGesture but was never able to find the right way to save the position of my daggable.

(I am using this npm: https://www.npmjs.com/package/react-native-draggable)

and here is my react native code :
```
```<Draggable
      onDragRelease={(x, y) => {
        props.settouchedId(props.id)
        console.log("id depuis note : " + props.id)
        // console.log('x:', x)
        //I think I should use only y
        console.log(y)
        console.log('MOVEX:', y['moveX'])
        console.log('MOVEY:', y['moveY'])
        console.log('NUMBERACTIVETOUCHES:', y['numberActiveTouches'])
        console.log('X0:', y['x0'])
        console.log('Y0:', y['y0'])
        console.log('DX:', y['dx'])
        console.log('DY:', y['dy'])
        console.log('x ADDITION:', y['x0'] + y['dx'])
        console.log('y ADDITION:', y['y0'] + y['dy'])
        //IL ME SEMBLE QUE C'EST MOVEX ET MOVEY QUI ME DONNE LA POSITION DE LA NOTE

        props.setpositionX(y['moveX'])
        props.setpositionY(y['moveY'])

      }}
      x={props.x}
      y={props.y}
    >
      <View style={styles.shadow}>
        <View style={{
          backgroundColor: props.color,
          width: 150,
          height: 50,
          textAlign: 'center',
          borderWidth: 2,
          borderColor: 'black',
          borderRadius: 10,
          alignItems: 'center',
          justifyContent: 'center',
        }}>
          <Text style={styles.text}>{props.text}</Text>
        </View>
      </View>
    </Draggable>
```
``````

Body:
Hello I've been searching for the solution for so long and still found nothing (even asked gptChat). The problem is that I want to save the x and y position of my draggable in my props.setPositionX and props.setPositionY, I was thinking using the moveX and moveY propreties was the right way to do it. But it is not because every time my app reloads all the data from firebase all my notes are in a completely different places.

here is what console.log(y) looks like :

{"_accountsForMovesUpTo": 6859182, "dx": -7.734375, "dy": 159.8876953125, "moveX": 148.7109375, "moveY": 206.4990234375, "numberActiveTouches": 0, "stateID": 0.2076494697380279, "vx": -0.010340073529411764, "vy": 0.021254595588235295, "x0": 156.4453125, "y0": 46.611328125}```

I tried by saving dx + d0 or tried with eventGesture but was never able to find the right way to save the position of my daggable.

(I am using this npm: https://www.npmjs.com/package/react-native-draggable)

and here is my react native code :

<Draggable
      onDragRelease={(x, y) => {
        props.settouchedId(props.id)
        console.log("id depuis note : " + props.id)
        // console.log('x:', x)
        //I think I should use only y
        console.log(y)
        console.log('MOVEX:', y['moveX'])
        console.log('MOVEY:', y['moveY'])
        console.log('NUMBERACTIVETOUCHES:', y['numberActiveTouches'])
        console.log('X0:', y['x0'])
        console.log('Y0:', y['y0'])
        console.log('DX:', y['dx'])
        console.log('DY:', y['dy'])
        console.log('x ADDITION:', y['x0'] + y['dx'])
        console.log('y ADDITION:', y['y0'] + y['dy'])
        //IL ME SEMBLE QUE C'EST MOVEX ET MOVEY QUI ME DONNE LA POSITION DE LA NOTE

        props.setpositionX(y['moveX'])
        props.setpositionY(y['moveY'])

      }}
      x={props.x}
      y={props.y}
    >
      <View style={styles.shadow}>
        <View style={{
          backgroundColor: props.color,
          width: 150,
          height: 50,
          textAlign: 'center',
          borderWidth: 2,
          borderColor: 'black',
          borderRadius: 10,
          alignItems: 'center',
          justifyContent: 'center',
        }}>
          <Text style={styles.text}>{props.text}</Text>
        </View>
      </View>
    </Draggable>


问:
Installing solc0.8.9 for solidity
I am taking a  Solidity course on Udemy.
In the lesson, I had to install solc0.8.9.
The lesson guide

mkdir inbox-updated

cd inbox-updated

npm init _y

npm install solc@0.8.9 web3 mocha ganache-cli@truffle/hdwallet-provider

at step 4, after I put the line on git Bash, github asks me to authorize to 'Git Credential Manager'. Then after authorized I get some error message.

```<code>npm ERR! code 128
npm ERR! An unknown git error occurred
npm ERR! command git --no-replace-objects ls-remote ssh://git@github.com/truffle/hdwallet-provider.git
npm ERR! git@github.com: Permission denied (publickey).
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.
</code>```

Can someone help me to figure out.

```<code>install solc0.8.9 web3 mocha ganache-cli@truffle/hdwallet-provider
</code>```

2023/01/11 It's solved by myself.

Title: Installing solc0.8.9 for solidity

Body:
I am taking a  Solidity course on Udemy.
In the lesson, I had to install solc0.8.9.
The lesson guide

mkdir inbox-updated

cd inbox-updated

npm init _y

npm install solc@0.8.9 web3 mocha ganache-cli@truffle/hdwallet-provider

at step 4, after I put the line on git Bash, github asks me to authorize to 'Git Credential Manager'. Then after authorized I get some error message.

npm ERR! code 128
npm ERR! An unknown git error occurred
npm ERR! command git --no-replace-objects ls-remote ssh://git@github.com/truffle/hdwallet-provider.git
npm ERR! git@github.com: Permission denied (publickey).
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.

Can someone help me to figure out.

install solc0.8.9 web3 mocha ganache-cli@truffle/hdwallet-provider

2023/01/11 It's solved by myself.


问:
only print modal content in html
I only want to print modal content in my website while click print button. But whole body value is shown in print preview after clicking print button.

```<code><body>
<div class="app">
    <p>This is paragraph</p>
    <modal>
        <div class=modal_content>
            <div id="modal_head">
                <p>head inside modal</p>
            </div>
            <div id="modal_content">
                <p>Content inside modal</p>
            </div>
        </div>
    </modal>
    <button class="print_invoice">Print</button>
</div>

<script>
    $(document).on("click", ".print_invoice", function () {
      const section = $("body");
      const modalBody = $("#modal_content").detach();
      const content = $("#app").detach();
      section.append(modalBody);
      window.print();
      section.empty();
      section.append(content);
      $(".modal_content").append(modalBody);
    });
</script>
</body>
</code>```

How to solve this? Anybody help please?

Title: only print modal content in html

Body:
I only want to print modal content in my website while click print button. But whole body value is shown in print preview after clicking print button.

This is paragraph

    <modal>

head inside modal

Content inside modal

    </modal>
    <button class="print_invoice">Print</button>

How to solve this? Anybody help please?