问:
Flutter: Page slide transition doesn't work only after Video welcome screen
TLDR; I added a custom page transition, sliding to the left. It works perfectly for every page in the App except the Welcome screen which contains only a video player. After the video ends, I get transferred to the desired page but the normal 'transition animation' happens instead of my custom one.

More info: I use Navigator.pushNamed(context, '/pagename') for my page travels. I created a custom transition, CustomPageRoute, which did not support named navigation. After a few searches I made it work and now supports both the cleanness of named navigation plus the transition animations plus the data transferring from page to page. All expect the welcome screen which just plays a video then after 3 seconds it pushes the Login page. Here is the code of the Welcome Page:

```<code>import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class WelcomePage extends StatefulWidget {
  const WelcomePage({Key? key}) : super(key: key);

  @override
  State<WelcomePage> createState() => _WelcomePageState();
}

class _WelcomePageState extends State<WelcomePage> {
  late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();

    _controller = VideoPlayerController.asset('assets/welcome_vid.mp4')
      ..initialize().then((_) {
        setState(() {});
      })
      ..setVolume(0.0);

    _playVideo();
  }

  void _playVideo() async {
    _controller.play();
    await Future.delayed(const Duration(seconds: 3))
        .then((_) => Navigator.pushNamed(context, '/login'));
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: Center(
          child: _controller.value.isInitialized
              ? AspectRatio(
                  aspectRatio: _controller.value.aspectRatio,
                  child: VideoPlayer(
                    _controller,
                  ),
                )
              : Container(),
        ));
  }
}
</code>```

Also, here is a sample of the named routes I use in main.dart:

```<code>  static Route onGenerateRoute(RouteSettings settings) {
    switch (settings.name) {
      case '/login':
        return CustomPageRoute(child: LoginPage(), settings: settings);
</code>```

Also, Flutter Doctor detected no problems, everything is up to date and I don't think any libraries overlap another. I even tried to change the destination if maybe somehow that affected anything but no.

Why doesn't it work?

Body:
TLDR; I added a custom page transition, sliding to the left. It works perfectly for every page in the App except the Welcome screen which contains only a video player. After the video ends, I get transferred to the desired page but the normal 'transition animation' happens instead of my custom one.

More info: I use Navigator.pushNamed(context, '/pagename') for my page travels. I created a custom transition, CustomPageRoute, which did not support named navigation. After a few searches I made it work and now supports both the cleanness of named navigation plus the transition animations plus the data transferring from page to page. All expect the welcome screen which just plays a video then after 3 seconds it pushes the Login page. Here is the code of the Welcome Page:

import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';

class WelcomePage extends StatefulWidget {
  const WelcomePage({Key? key}) : super(key: key);

  @override
  State<WelcomePage> createState() => _WelcomePageState();
}

class _WelcomePageState extends State<WelcomePage> {
  late VideoPlayerController _controller;

  @override
  void initState() {
    super.initState();

    _controller = VideoPlayerController.asset('assets/welcome_vid.mp4')
      ..initialize().then((_) {
        setState(() {});
      })
      ..setVolume(0.0);

    _playVideo();
  }

  void _playVideo() async {
    _controller.play();
    await Future.delayed(const Duration(seconds: 3))
        .then((_) => Navigator.pushNamed(context, '/login'));
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.white,
        body: Center(
          child: _controller.value.isInitialized
              ? AspectRatio(
                  aspectRatio: _controller.value.aspectRatio,
                  child: VideoPlayer(
                    _controller,
                  ),
                )
              : Container(),
        ));
  }
}

Also, here is a sample of the named routes I use in main.dart:

  static Route onGenerateRoute(RouteSettings settings) {
    switch (settings.name) {
      case '/login':
        return CustomPageRoute(child: LoginPage(), settings: settings);

Also, Flutter Doctor detected no problems, everything is up to date and I don't think any libraries overlap another. I even tried to change the destination if maybe somehow that affected anything but no.

Why doesn't it work?


来源: stackexchange

问:
When I import data to neo4j I got this error "AttributeError: 'NodeMatch' object has no attribute 'exists' "
The error is here

```<code>result1 = matcher.match("regain", name=str(date_time[0])).exists()
</code>```
```<code>**This is my code:**

import pandas as pd

from py2neo import Graph, Node, Relationship, NodeMatcher

graph = Graph("http://localhost:7474", username="neo4j", password='123456')
matcher = NodeMatcher(graph)

path = 'testdata.csv'
dates = pd.read_csv(path, names=['Head', 'Tail', 'none', 'fence', 'type'], header=None)
print(dates)

for ii in dates.index:
    date_time = dates.loc[ii].values

    result1 = matcher.match("regain", name=str(date_time[0])).exists()
    if not result1:

        head = Node("regain", name=str(date_time[0]))
        graph.create(head)
    else:
        head = matcher.match("regain").where(name=str(date_time[0])).first()

    result2 = matcher.match("regain", name=str(date_time[1])).exists()

</code>```

ContentLicense: CC BY-SA 4.0

Body:
The error is here

result1 = matcher.match("regain", name=str(date_time[0])).exists()

**This is my code:**

import pandas as pd

from py2neo import Graph, Node, Relationship, NodeMatcher

graph = Graph("http://localhost:7474", username="neo4j", password='123456')
matcher = NodeMatcher(graph)

path = 'testdata.csv'
dates = pd.read_csv(path, names=['Head', 'Tail', 'none', 'fence', 'type'], header=None)
print(dates)

for ii in dates.index:
    date_time = dates.loc[ii].values

    result1 = matcher.match("regain", name=str(date_time[0])).exists()
    if not result1:

        head = Node("regain", name=str(date_time[0]))
        graph.create(head)
    else:
        head = matcher.match("regain").where(name=str(date_time[0])).first()

    result2 = matcher.match("regain", name=str(date_time[1])).exists()


问:
GitLab Templating: Multiple before_script blocks in default?
This doesn't work correctly:

template1.yml

```<code>default:
   before_script:
      - echo "hello from one"
</code>```

template2.yml

```<code>default:
   before_script:
      - echo "hello from two"
</code>```

.gitlab-ci.yml (the actual pipeline)

```<code>include:
  - project: 'templates'
    file:
      - 'template1.yml'
      - 'template2.yml'

build1:
  stage: build
  script:
    - echo "hello from the pipeline"
</code>```

output (note the output from template1 is missing):

```<code>Hello from two
hello from the pipeline
</code>```

I understand that GitLab may believe that there is 'ambiguity' in the ordering when merging blocks in to before_script, but it could use the order specified in the 'include'
section of the pipeline.

Does anyone know of a way that I can arbitrarily include templates in my pipeline in such a way that they can contribute to the default 'before_script' block?

It all must run sequentially in the same container (be in the same 'stage')

For example, using yaml anchors requires us to specify the names of the anchors rather than just the file that the anchors were in, so that doesn't work...

Body:
This doesn't work correctly:

template1.yml

default:
   before_script:
      - echo "hello from one"

template2.yml

default:
   before_script:
      - echo "hello from two"

.gitlab-ci.yml (the actual pipeline)

include:
  - project: 'templates'
    file:
      - 'template1.yml'
      - 'template2.yml'

build1:
  stage: build
  script:
    - echo "hello from the pipeline"

output (note the output from template1 is missing):

Hello from two
hello from the pipeline

I understand that GitLab may believe that there is 'ambiguity' in the ordering when merging blocks in to before_script, but it could use the order specified in the 'include'
section of the pipeline.

Does anyone know of a way that I can arbitrarily include templates in my pipeline in such a way that they can contribute to the default 'before_script' block?

It all must run sequentially in the same container (be in the same 'stage')

For example, using yaml anchors requires us to specify the names of the anchors rather than just the file that the anchors were in, so that doesn't work...


问:
How to check if client device has a rear camera?
Is there a reliable way to check via JavaScript if the user is visiting a website with a device that has a rear camera?

My use case is this: I have AR content on my page. When the user has a desktop or laptop, I want to display a QR code containing a link that he can scan with a mobile device to use the AR feature. But when he uses a tablet or phone I want to directly open the link because his device is already AR capable.

I know I could check the screen resolution. But I think that would not work reliably for different browser window sizes.
The best option so far seems to be to parse the user agent for the string "mobile". But isn't there a cleaner way?


问:
Imported module is seen differently
I'm importing dayjs library in my own library.
I'm importing it with

import * as dayjs from 'dayjs';
import * as localeData from 'dayjs/plugin/localeData';
import * as objectSupport from 'dayjs/plugin/objectSupport';
import 'dayjs/locale/pl.js';
import {Dayjs} from 'dayjs';

console.log('--dayjs--', dayjs, dayjs.extend, localeData);
dayjs.extend(localeData);
dayjs.extend(objectSupport);

```
<p><img src="https://i.stack.imgur.com/NmanX.png" alt="Code" /></p>
<p>It works well in that monorepository as You can see in console log</p>
<p><img src="https://i.stack.imgur.com/TQ8RF.png" alt="In monorep" /></p>
<p>After that I publish it on npm as library using:</p>
```    "datetime:build": "ng build datetime  --configuration production",
    "datetime:publish": "cd dist/datetime && npm publish --access public",
```

After that I import that library in my other project in which I receive errors as You can see on other screenshot. Why is it interpreted differently? Both projects are in angular@15 (I'm making upgrade from angular@13 in which everything worked great).

Title: Imported module is seen differently

Body:
I'm importing dayjs library in my own library.
I'm importing it with

import * as dayjs from 'dayjs';
import * as localeData from 'dayjs/plugin/localeData';
import * as objectSupport from 'dayjs/plugin/objectSupport';
import 'dayjs/locale/pl.js';
import {Dayjs} from 'dayjs';

console.log('--dayjs--', dayjs, dayjs.extend, localeData);
dayjs.extend(localeData);
dayjs.extend(objectSupport);

It works well in that monorepository as You can see in console log

After that I publish it on npm as library using:

    "datetime:build": "ng build datetime  --configuration production",
    "datetime:publish": "cd dist/datetime && npm publish --access public",

After that I import that library in my other project in which I receive errors as You can see on other screenshot. Why is it interpreted differently? Both projects are in angular@15 (I'm making upgrade from angular@13 in which everything worked great).


问:
Apache CXF not working with waffle windows authentication framework
We are using waffle for NTLM login in our application. we are able to successfully achieve the windows authentication but with waffle, Apache CXF is not when Service.create method tries to get the WSDL file by hitting URL it gets a 401 error. please us to figure out how can we make cxf workable with waffles.

Your help will be appreciated.

we had already tried jcifs but it not working in our case.


问:
EventListener - proper way of validation springboot?
So I was reading about EventListener (beforeSave, afterSave, etc)  here, when it comes to validation, and I can't really figure it out why it is used and how.
For example, for my own app, for an entity named curse, I have a method validateCursa() included in curseService class that validate the details of a curse object and throws custom exceptions.

example:

CurseController:

```<code>    @PostMapping(path="/add") // Map ONLY POST Requests
    public @ResponseBody String addNewCursa (@Valid @RequestBody curse C2,
                                             BindingResult bindingResult)  {

       com.example.demo.models.curseService.validateCursa(C2);
       if(bindingResult.hasErrors()) {

           return "error";
       }
        curseService.addCursa(C2);
        return "Saved";
    }

</code>```

curseService:

```<code>public static void validateCursa(curse c){
   some validation here
}

public curse addCursa(curse c){

        return curseRepository.save(c);

    }
</code>```

So my question is: What really does that EventListener/validation do, when should it be used and why? Like, should I re-design my validation process and use these EventListeners?

Body:
So I was reading about EventListener (beforeSave, afterSave, etc)  here, when it comes to validation, and I can't really figure it out why it is used and how.
For example, for my own app, for an entity named curse, I have a method validateCursa() included in curseService class that validate the details of a curse object and throws custom exceptions.

example:

CurseController:

    @PostMapping(path="/add") // Map ONLY POST Requests
    public @ResponseBody String addNewCursa (@Valid @RequestBody curse C2,
                                             BindingResult bindingResult)  {

       com.example.demo.models.curseService.validateCursa(C2);
       if(bindingResult.hasErrors()) {

           return "error";
       }
        curseService.addCursa(C2);
        return "Saved";
    }

curseService:

public static void validateCursa(curse c){
   some validation here
}

public curse addCursa(curse c){

        return curseRepository.save(c);

    }

So my question is: What really does that EventListener/validation do, when should it be used and why? Like, should I re-design my validation process and use these EventListeners?


问:
Intercepting RadialController events at OS level
I’m trying to figure out if there is a way to intercept surface dial (or RadialController) events even when your application is in the background, and another one has the focus. Maybe using SetWindowsHookEx somehow?

My purpose is, since there is so very little support for surface dial at the moment in terms of applications, I was trying to create a background-ish service that intercepts surface dial events at OS level and sends/simulates input events to other applications. I have the simulation of input events in other applications controlled, and I know that I can get Mouse Events at OS level using SetWindowsHookEx, but I don’t know how to obtain surface dial input data at OS level..

There is very little to no information about Surface Dial programming, even less outside UWP. So I've tried basically everything I could put my hands on, but I could only find information about more standard input hardware like mouse and keyboard... no Radial Controller.

Note: I’m using Windows Forms with C# in Windows 11.


问:
Nest JS: httpService get request not firing when called
When calling the function getGeoCoding() the function starts and prints the message
"geo coding" to the console so I know the function is running. However this.httpService.get does not fire and returns nothing, not even an error. I have tried to write this function as many different ways as possible however nothing works. I'm trying to access the mapbox api. I know that my api key and search query are fine as I have tested the api in a JavaScript Node app and this returns the correct repsonse from the mapbox api. How can I get the get request to fire in Nest Js using the HttpModule and HttpService from the @nestjs/axios package? Thanks in advance.

Nest Js

```<code>@Injectable()
export class GeoCodingService {

    constructor(private readonly httpService: HttpService) {}

        async getGeoCoding(): Promise<any[]> {

        console.log("geo coding")

            const { data } = await firstValueFrom(

              this.httpService.get<any[]>(url).pipe(

                catchError((error: AxiosError) => {

                  console.log(error.response.data)

                  throw 'An error happened!';

                }),

              ),

            );

            return data;

          }

};
</code>```

JavaScript

```<code>const axios = require("axios");

const geoLocationSearch = async () => {

    try {
      let response = await axios.get(url);
      let to_return = await response.data;
      console.log(to_return);
  }
  catch(err) {
      console.log("Err")
  }

}

geoLocationSearch();
</code>```

Body:
When calling the function getGeoCoding() the function starts and prints the message
"geo coding" to the console so I know the function is running. However this.httpService.get does not fire and returns nothing, not even an error. I have tried to write this function as many different ways as possible however nothing works. I'm trying to access the mapbox api. I know that my api key and search query are fine as I have tested the api in a JavaScript Node app and this returns the correct repsonse from the mapbox api. How can I get the get request to fire in Nest Js using the HttpModule and HttpService from the @nestjs/axios package? Thanks in advance.

Nest Js

@Injectable()
export class GeoCodingService {

    constructor(private readonly httpService: HttpService) {}

        async getGeoCoding(): Promise<any[]> {

        console.log("geo coding")

            const { data } = await firstValueFrom(

              this.httpService.get<any[]>(url).pipe(

                catchError((error: AxiosError) => {

                  console.log(error.response.data)

                  throw 'An error happened!';

                }),

              ),

            );

            return data;

          }

};

JavaScript

const axios = require("axios");

const geoLocationSearch = async () => {

    try {
      let response = await axios.get(url);
      let to_return = await response.data;
      console.log(to_return);
  }
  catch(err) {
      console.log("Err")
  }

}

geoLocationSearch();


问:
Process Sub report on click of toggle (on demand) on Main report in Report Viewer (rdlc) Asp.net
Using ReportViewer we are trying to implement sub reports. Here is the code how we achieved it.

Page_Load:

```<code>IList<string> ilReportDSs = ReportViewer1.LocalReport.GetDataSourceNames();
for (iTables = 0; iTables < ds.Tables.Count; iTables++)
{
      ReportDataSource rdSource = new ReportDataSource(ilReportDSs[iTables], ds.Tables[iTables]);
      ReportViewer1.LocalReport.DataSources.Add(rdSource);
}
ReportViewer1.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SetSubDataSource);
</code>```

SetSubDataSource event:

```<code>public void SetSubDataSource(object sender, SubreportProcessingEventArgs e)
{
     DataSet dsSpData = GetSubReportResult();
     ReportDataSource datasource = new ReportDataSource("DataSet1", dsSpData.Tables[0]);
     e.DataSources.Add(datasource);
}
</code>```

We are able to see the sub report but this sub report gets processed at the Page_Load (first load) and not at the click of toggle at individual record level.

In the image marked in red is toggle button and marked in blue is sub report.

Is it possible to process the sub report record by record on click of expand button? Basically I want to call the "SetSubDataSource" method from my code above. Because it takes lot of time at the first load while is processing sub reports.

I checked many documents and didn't find any solution.

Body:
Using ReportViewer we are trying to implement sub reports. Here is the code how we achieved it.

Page_Load:

IList<string> ilReportDSs = ReportViewer1.LocalReport.GetDataSourceNames();
for (iTables = 0; iTables < ds.Tables.Count; iTables++)
{
      ReportDataSource rdSource = new ReportDataSource(ilReportDSs[iTables], ds.Tables[iTables]);
      ReportViewer1.LocalReport.DataSources.Add(rdSource);
}
ReportViewer1.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SetSubDataSource);

SetSubDataSource event:

public void SetSubDataSource(object sender, SubreportProcessingEventArgs e)
{
     DataSet dsSpData = GetSubReportResult();
     ReportDataSource datasource = new ReportDataSource("DataSet1", dsSpData.Tables[0]);
     e.DataSources.Add(datasource);
}

We are able to see the sub report but this sub report gets processed at the Page_Load (first load) and not at the click of toggle at individual record level.

In the image marked in red is toggle button and marked in blue is sub report.

Is it possible to process the sub report record by record on click of expand button? Basically I want to call the "SetSubDataSource" method from my code above. Because it takes lot of time at the first load while is processing sub reports.

I checked many documents and didn't find any solution.


问:
How to edit the longitude and latitude for an image MatPlotLib scatterplot with Seaborn?
I am trying to plot a scatter map on a map of Europe (overlay over a picture) using Pandas, Matplotlib and Seaborn.

I have the following code, however how can I adjust the image so that it reflects the longitude and latitude of the countries listed?

You can see an example of the image graph below.

```<code>import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Load the dataframe
df = pd.read_csv('data.csv')

# Create a list of unique cities
countries = df['country'].unique()

# Create a dictionary to map cities to coordinates
country_coordinates = {
    'CH': (46.8182, 8.2275),
    'FR': (46.2276, 2.2137),
    'IT': (41.8719, 12.5674),
    'DE': (51.1657, 10.4515),
    'RO': (45.943161, 24.96676),
    'ES': (40.4637, 3.7492),
    'CZ': (49.8175, 15.473),
    'BE': (50.5039, 4.4699),
    'AT': (47.5162, 14.5501),
    'AU': (-25.2744, 133.7751),
    'PE': (-9.1899, -75.0152),
    'LU': (49.8153, 6.1296),
    'RU': (61.52401, 105.318756),
    'BR': (-14.2350, -51.9253),
    'CF': (6.6111, 20.9394),
    'AR': (-38.416097, -63.616672),
    'LI': (47.14, 9.55),
    'BA': (43.915886, 17.679076),
    'TR': (38.963745, 35.243322),
    'PH': (12.879721, 121.774017),
    'CA': (56.130366, -106.346771),
    'GB': (55.378051, -3.435973),
    'US': (37.09024, -95.712891),
    'ID': (-0.789275, 113.921327),
    'SC': (-4.679574, 55.491977),
    'IN': (20.593684, 78.96288),
    'LR': (6.428055, -9.429499),
    'JM': (18.109581, -77.297508),
    'HU': (47.162494, 19.503304),
    'ET': (9.145, 40.489673),
    'NL': (52.132633, 5.291266),
    'UA': (48.379433, 31.16558)
}

# Create a list of x and y coordinates for the cities
x = [country_coordinates[country][1] for country in countries]
y = [country_coordinates[country][0] for country in countries]

# Create a list of frequencies for the cities
freq = df['country'].value_counts().tolist()

# Create a scatterplot with the cities and their frequencies
plt.scatter(x, y, s=freq, c='red', alpha=0.5)

# Add the map of Europe as the background
plt.imshow(plt.imread('Europe_map.png'))

# Set the title and labels
plt.title('Frequency Heatmap of European Countries')
plt.xlabel('Longitude')
plt.ylabel('Latitude')

# Show the plot
plt.show()
</code>```

Body:
I am trying to plot a scatter map on a map of Europe (overlay over a picture) using Pandas, Matplotlib and Seaborn.

I have the following code, however how can I adjust the image so that it reflects the longitude and latitude of the countries listed?

You can see an example of the image graph below.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Load the dataframe
df = pd.read_csv('data.csv')

# Create a list of unique cities
countries = df['country'].unique()

# Create a dictionary to map cities to coordinates
country_coordinates = {
    'CH': (46.8182, 8.2275),
    'FR': (46.2276, 2.2137),
    'IT': (41.8719, 12.5674),
    'DE': (51.1657, 10.4515),
    'RO': (45.943161, 24.96676),
    'ES': (40.4637, 3.7492),
    'CZ': (49.8175, 15.473),
    'BE': (50.5039, 4.4699),
    'AT': (47.5162, 14.5501),
    'AU': (-25.2744, 133.7751),
    'PE': (-9.1899, -75.0152),
    'LU': (49.8153, 6.1296),
    'RU': (61.52401, 105.318756),
    'BR': (-14.2350, -51.9253),
    'CF': (6.6111, 20.9394),
    'AR': (-38.416097, -63.616672),
    'LI': (47.14, 9.55),
    'BA': (43.915886, 17.679076),
    'TR': (38.963745, 35.243322),
    'PH': (12.879721, 121.774017),
    'CA': (56.130366, -106.346771),
    'GB': (55.378051, -3.435973),
    'US': (37.09024, -95.712891),
    'ID': (-0.789275, 113.921327),
    'SC': (-4.679574, 55.491977),
    'IN': (20.593684, 78.96288),
    'LR': (6.428055, -9.429499),
    'JM': (18.109581, -77.297508),
    'HU': (47.162494, 19.503304),
    'ET': (9.145, 40.489673),
    'NL': (52.132633, 5.291266),
    'UA': (48.379433, 31.16558)
}

# Create a list of x and y coordinates for the cities
x = [country_coordinates[country][1] for country in countries]
y = [country_coordinates[country][0] for country in countries]

# Create a list of frequencies for the cities
freq = df['country'].value_counts().tolist()

# Create a scatterplot with the cities and their frequencies
plt.scatter(x, y, s=freq, c='red', alpha=0.5)

# Add the map of Europe as the background
plt.imshow(plt.imread('Europe_map.png'))

# Set the title and labels
plt.title('Frequency Heatmap of European Countries')
plt.xlabel('Longitude')
plt.ylabel('Latitude')

# Show the plot
plt.show()


问:
getting an error when trying use a varibale from one file as an input to a function in a different file
i have this code in one file that is meant to pass the score_list variable to the run_game_over() in a seperate file Game_Over_Screen

```<code>from Game_Over_Screen import game_over
</code>```

leaderboard = True

```<code>from Game_Over_Screen import game_over
leaderboard = True

while leaderboard:
    print(score_list)
    game_over.run_game_over(score_list)
    leaderboard = False
    running = False
</code>```
```<code>this is the run_game_over() function
</code>```
```<code>class game_over(Buttons, ellipse_button):
    def run_game_over(self, score_list):
        self.go_animation()
        pygame.display.flip()
        global game_over
        game_over = True
        while game_over:
            Buttons.mouse_position(quit_icon)
            Buttons.mouseclick(quit_icon)
            Buttons.mouse_position(play_again_icon)
            Buttons.mouseclick(play_again_icon)
            for event in pygame.event.get():
                pass
</code>```

however when i run it i get the error:

```<code>Traceback (most recent call last):
  File "C:\Users\matty\Documents\Programming Project\uno-1130\uno\src\Start.py", line 35, in <module>
    game_over.run_game_over(score_list)
TypeError: run_game_over() missing 1 required positional argument: 'score_list'
</code>```

Im not sure why this isnt working as i thought id set it up for the score_list variable to be an input correctly but clearly that is not the case

Body:
i have this code in one file that is meant to pass the score_list variable to the run_game_over() in a seperate file Game_Over_Screen

from Game_Over_Screen import game_over

leaderboard = True

from Game_Over_Screen import game_over
leaderboard = True

while leaderboard:
    print(score_list)
    game_over.run_game_over(score_list)
    leaderboard = False
    running = False

this is the run_game_over() function

class game_over(Buttons, ellipse_button):
    def run_game_over(self, score_list):
        self.go_animation()
        pygame.display.flip()
        global game_over
        game_over = True
        while game_over:
            Buttons.mouse_position(quit_icon)
            Buttons.mouseclick(quit_icon)
            Buttons.mouse_position(play_again_icon)
            Buttons.mouseclick(play_again_icon)
            for event in pygame.event.get():
                pass

however when i run it i get the error:

Traceback (most recent call last):
  File "C:\Users\matty\Documents\Programming Project\uno-1130\uno\src\Start.py", line 35, in <module>
    game_over.run_game_over(score_list)
TypeError: run_game_over() missing 1 required positional argument: 'score_list'

Im not sure why this isnt working as i thought id set it up for the score_list variable to be an input correctly but clearly that is not the case


问:
Base64 Can't encode é special character
When we encode the string including the 'é' special character, it displays this error in the log.

login:jag Cannot convert org.mozilla.javascript.NativeArray@6da663da
to byte[]

The error is caused when running the

var encodedString = Base64Utils.encode(byteArray)

line.

var Base64Utils = Packages.org.apache.axiom.util.base64.Base64Utils;
var username = 'testuser';
var password = '431éa23';
var inputString = username + ":" + password;
new Log("stringmsg").info(inputString);
var byteArray = [];

for (var i = 0; i < inputString.length; ++i) {
    new Log("iterate").info(inputString.charCodeAt(i));
    byteArray.push(inputString.charCodeAt(i));
}
new Log("stringarray").info(byteArray);
var encodedString = Base64Utils.encode(byteArray);```

This is the code that I have run. I have tried with other special characters. They are working fine with other special characters. The issue is caused by this special character only. I have tried several methods, but those won't work out. What should I do to encode the string with this special character?

Title: Base64 Can't encode é special character

Body:
When we encode the string including the 'é' special character, it displays this error in the log.

login:jag Cannot convert org.mozilla.javascript.NativeArray@6da663da
to byte[]

The error is caused when running the

var encodedString = Base64Utils.encode(byteArray)

line.

var Base64Utils = Packages.org.apache.axiom.util.base64.Base64Utils;
var username = 'testuser';
var password = '431éa23';
var inputString = username + ":" + password;
new Log("stringmsg").info(inputString);
var byteArray = [];

for (var i = 0; i < inputString.length; ++i) {
    new Log("iterate").info(inputString.charCodeAt(i));
    byteArray.push(inputString.charCodeAt(i));
}
new Log("stringarray").info(byteArray);
var encodedString = Base64Utils.encode(byteArray);

This is the code that I have run. I have tried with other special characters. They are working fine with other special characters. The issue is caused by this special character only. I have tried several methods, but those won't work out. What should I do to encode the string with this special character?


问:
Loop over multiindex and get specific value -- Data cleaning o
i really need to solve a particular Problem with Multi index Dataframe

```<code>
| Doc_Number | Deliv_Number | Type  | Customer Name | Created_On | First_conf_deliv_date | Last_deliv_date | Goods Issue | Delivery_Group | Order_Quantity
| 134893847  | 1245678      | 2308  | ABC           |2019-03-04  | 2019-03-05            | 2019-03-22      | 2019-03-19  |      01        |   20
|            | 1245678      | 4567  | ABC           |2019-03-04  | 2019-03-05            | 2019-03-22      | 2019-03-19  |      01        |   20
|            | 3456789      | 4398  | ABC           |2020-03-04  | 2019-04-06            | 2019-04-16      | 2019-04-12  |      02        |   30
|2349586590  |....          | ...   | CDF
....
</code>```

if you look in the table above, you can see a Doc_Number as First Index and the Deliv_Number column as Second Index.

The Problem is:

I need to clean the data for each Doc_Numbers in my Table where a specific Type (Type Column) in this case 2308 equals another row in the same Doc_Number (134893847) with same Delivery_Number ( both have 1245678) and with same Order_Quantity (both have 20), but different Type Number in this case 2308 and 4567.

--> When both rows cancel each other out on the same Doc_Number, Deliv_Number and Quantity, return me the Doc_Numbers else Not.

There are also cases where Type 2308 occurs multiple times in a Doc_Number so i have to find multiple rows which are equal to the row with the Type 2308.

Example: You have 5 rows with Type 2308 --> so you have to find 5 matching rows. if just 4 rows with a different Type and equal Doc_Number, Deliv_Number and Quantity are matching do not return the Doc_Number.

i hope it is understandable.

i thought about pulling out the rows with the Type 2308 for each Doc_Number. Then deleting it in the Table, so you dont match with the same column -->  then check each row in the same Doc_Number for matching values and if so --> return me the Doc_Number. Something like that.

i have tried different ways to solve the Problem, but nothing really worked.

Maybe some of you guys can help me out.

Body:
i really need to solve a particular Problem with Multi index Dataframe

| Doc_Number | Deliv_Number | Type  | Customer Name | Created_On | First_conf_deliv_date | Last_deliv_date | Goods Issue | Delivery_Group | Order_Quantity
| 134893847  | 1245678      | 2308  | ABC           |2019-03-04  | 2019-03-05            | 2019-03-22      | 2019-03-19  |      01        |   20
|            | 1245678      | 4567  | ABC           |2019-03-04  | 2019-03-05            | 2019-03-22      | 2019-03-19  |      01        |   20
|            | 3456789      | 4398  | ABC           |2020-03-04  | 2019-04-06            | 2019-04-16      | 2019-04-12  |      02        |   30
|2349586590  |....          | ...   | CDF
....

if you look in the table above, you can see a Doc_Number as First Index and the Deliv_Number column as Second Index.

The Problem is:

I need to clean the data for each Doc_Numbers in my Table where a specific Type (Type Column) in this case 2308 equals another row in the same Doc_Number (134893847) with same Delivery_Number ( both have 1245678) and with same Order_Quantity (both have 20), but different Type Number in this case 2308 and 4567.

--> When both rows cancel each other out on the same Doc_Number, Deliv_Number and Quantity, return me the Doc_Numbers else Not.

There are also cases where Type 2308 occurs multiple times in a Doc_Number so i have to find multiple rows which are equal to the row with the Type 2308.

Example: You have 5 rows with Type 2308 --> so you have to find 5 matching rows. if just 4 rows with a different Type and equal Doc_Number, Deliv_Number and Quantity are matching do not return the Doc_Number.

i hope it is understandable.

i thought about pulling out the rows with the Type 2308 for each Doc_Number. Then deleting it in the Table, so you dont match with the same column -->  then check each row in the same Doc_Number for matching values and if so --> return me the Doc_Number. Something like that.

i have tried different ways to solve the Problem, but nothing really worked.

Maybe some of you guys can help me out.


问:
ReactJs lang formatting in VS code
Every time writing React Code, I need to select the language mode to React Js mode then only I am being able to save the file even if the file is saved as .jsx.

reinstalling vs done.

reinstalling prettier done.
Any other suggestions?

To be able to save files without needing to change the lang mode every time.

Title: ReactJs lang formatting in VS code


问:
How to update an object in a mongoose document that contains an array of objects
I have this mongoose Schema:

```<code>const shopSchema = new mongoose.Schema({
    user:{
        type:mongoose.Schema.Types.ObjectId,
        required:true,
        ref:'User'
    },
    title:{
        type:String,
        required:true
    },
    description:{
        type:String,
        required:true
    },
    appointments:[
        {
            'customerName':String,
            'service':String,
            'date':String,
            'active':{type:Boolean,
            default:true }
        },
    ]

});
</code>```

The field i am trying to work with is the appointments field.
one possible entry would be :

```<code>appointments: [
      {
        customerName: 'Takis Makis',
        service: 'Kourema',
        date: '12/12/2022',
        _id: ObjectId("63923aac73a0d02225738e69")
      },
      {
        customerName: 'Mixalis Mixaliotis',
        service: 'Lousimo',
        date: '01/-1/2023',
        _id: ObjectId("63923ac973a0d02225738e6d")
      },
</code>```

Now in my back end i have an update route (PATCH request) where  i get the shops id the customerName,service and date plus newCustomerName,newService,newDate and with that I am able to find the one appointment I need. After that I want to update the specific appointment and this is where I am stuck. Can anyone help ?

So far I have tried to find the specific appointment (which works)

```<code>//if appointments exists find the appointments with the customers name
    const customerAppointment = shop.appointments.filter(appointment=>{
         if(appointment.customerName===customerName && appointment.service===service && appointment.date === date)
         {
             return appointment
         }
    });
    //verify the appointment exists
    if(!customerAppointment.length){
        return res.status(400).json({message:`Appointment under name ${customerName}, for ${service} with date of ${date} does not exists on shop ${shop.title}`})
    }
</code>```

and then I need to update the appointment.This where I am stuck.I could create a new appointment then push it in the relevant shop and then delete the old one. But wouldn't it be better to update the old one ? and if so how ?
Thanks in advance

Body:
I have this mongoose Schema:

const shopSchema = new mongoose.Schema({
    user:{
        type:mongoose.Schema.Types.ObjectId,
        required:true,
        ref:'User'
    },
    title:{
        type:String,
        required:true
    },
    description:{
        type:String,
        required:true
    },
    appointments:[
        {
            'customerName':String,
            'service':String,
            'date':String,
            'active':{type:Boolean,
            default:true }
        },
    ]

});

The field i am trying to work with is the appointments field.
one possible entry would be :

appointments: [
      {
        customerName: 'Takis Makis',
        service: 'Kourema',
        date: '12/12/2022',
        _id: ObjectId("63923aac73a0d02225738e69")
      },
      {
        customerName: 'Mixalis Mixaliotis',
        service: 'Lousimo',
        date: '01/-1/2023',
        _id: ObjectId("63923ac973a0d02225738e6d")
      },

Now in my back end i have an update route (PATCH request) where  i get the shops id the customerName,service and date plus newCustomerName,newService,newDate and with that I am able to find the one appointment I need. After that I want to update the specific appointment and this is where I am stuck. Can anyone help ?

So far I have tried to find the specific appointment (which works)

//if appointments exists find the appointments with the customers name
    const customerAppointment = shop.appointments.filter(appointment=>{
         if(appointment.customerName===customerName && appointment.service===service && appointment.date === date)
         {
             return appointment
         }
    });
    //verify the appointment exists
    if(!customerAppointment.length){
        return res.status(400).json({message:`Appointment under name ${customerName}, for ${service} with date of ${date} does not exists on shop ${shop.title}`})
    }

and then I need to update the appointment.This where I am stuck.I could create a new appointment then push it in the relevant shop and then delete the old one. But wouldn't it be better to update the old one ? and if so how ?
Thanks in advance


问:
multi target build dependency issues
I have a solution which is to be built in net6.0 and netstandard2.0. I have been using the command

```<code>dotnet publish <path to solution> /p:Configuration=Release -o <binrel\net6.0> -v detailed --framework net6.0
</code>```

And the same solution is built in netstandard as well. The dependencies are referenced from respective framework folders as well. There is an indirect package reference of System.Private.ServiceModel.dll for net6.0 which should be picked from the net6.0 folder and another version of the same for netstandard build from netstandard folder. But the issue is, netstandard file is being considered for net6.0.

At compile time for the net6.0,

```<code>Unified primary reference "System.Reflection.DispatchProxy, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".
             Using this version instead of original version "4.0.4.0" in " dependencies\System.Private.ServiceModel.dll" because AutoUnify is 'true'.
             Resolved file path is "C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Ref\6.0.8\ref\net6.0\System.Reflection.DispatchProxy.dll".
             Reference found at search path location "{RawFileName}".
             This reference is not "CopyLocal" because at least one source item had "Private" set to "false" and no source items had "Private" set to "true".

Copying file from "Dependencies\System.Private.ServiceModel.dll" to "\bin\Release\net6.0\System.Private.ServiceModel.dll".
</code>```

The same in a working build:

```<code>Unified primary reference "System.Reflection.DispatchProxy, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".
             Using this version instead of original version "4.0.6.0" in "\Dependencies\net6.0\System.Private.ServiceModel.dll" because AutoUnify is 'true'.
             Resolved file path is "C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Ref\6.0.8\ref\net6.0\System.Reflection.DispatchProxy.dll".
             Reference found at search path location "{RawFileName}".
             This reference is not "CopyLocal" because at least one source item had "Private" set to "false" and no source items had "Private" set to "true".

Copying file from "Dependencies\net6.0\System.Private.ServiceModel.dll" to "\bin\Release\net6.0\System.Private.ServiceModel.dll".
</code>```

Question is without any changes to the project or in build server, why the dependency has been changed for the net6.0 file?

Title: multi target build dependency issues

Body:
I have a solution which is to be built in net6.0 and netstandard2.0. I have been using the command

dotnet publish <path to solution> /p:Configuration=Release -o <binrel\net6.0> -v detailed --framework net6.0

And the same solution is built in netstandard as well. The dependencies are referenced from respective framework folders as well. There is an indirect package reference of System.Private.ServiceModel.dll for net6.0 which should be picked from the net6.0 folder and another version of the same for netstandard build from netstandard folder. But the issue is, netstandard file is being considered for net6.0.

At compile time for the net6.0,

Unified primary reference "System.Reflection.DispatchProxy, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".
             Using this version instead of original version "4.0.4.0" in " dependencies\System.Private.ServiceModel.dll" because AutoUnify is 'true'.
             Resolved file path is "C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Ref\6.0.8\ref\net6.0\System.Reflection.DispatchProxy.dll".
             Reference found at search path location "{RawFileName}".
             This reference is not "CopyLocal" because at least one source item had "Private" set to "false" and no source items had "Private" set to "true".

Copying file from "Dependencies\System.Private.ServiceModel.dll" to "\bin\Release\net6.0\System.Private.ServiceModel.dll".

The same in a working build:

Unified primary reference "System.Reflection.DispatchProxy, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a".
             Using this version instead of original version "4.0.6.0" in "\Dependencies\net6.0\System.Private.ServiceModel.dll" because AutoUnify is 'true'.
             Resolved file path is "C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Ref\6.0.8\ref\net6.0\System.Reflection.DispatchProxy.dll".
             Reference found at search path location "{RawFileName}".
             This reference is not "CopyLocal" because at least one source item had "Private" set to "false" and no source items had "Private" set to "true".

Copying file from "Dependencies\net6.0\System.Private.ServiceModel.dll" to "\bin\Release\net6.0\System.Private.ServiceModel.dll".

Question is without any changes to the project or in build server, why the dependency has been changed for the net6.0 file?


问:
Fill multiple select's selecting one option
im build a backoffice in my internship and one of the request that my mentor has is: when he select one name from the dropdown, if that name is available in the other days, he wants to have a option that allow's him to fill the other dropdowns with the name from the first dropdown, i don't know if im explaining my self in a proper way but i will try to complete with images.
If someone wants to help me and need more details ask in the comments. Im using select2 for the dropdowns and simple php for the server side.
PS: Im doing it in php so i can't provide a fiddle ( i think ?) so im not asking for code, i just need some ideas on how to do that!


问:
Linux Kernel Hot(un)pluggable memory granularity with Dax
I'm currently working on DAX device driver for my device and stumbled upon a problem.
The device has it's own ram, which can be mmapped to any app with no problem.
What i want to do is to be able to give OS the memory my device doesn't use at the moment.
So if device has nothing to do, the memory can be utilized by OS.
I've researched the topic and found out that there's actually a possibility to do so:
https://docs.kernel.org/admin-guide/mm/memory-hotplug.html

The article mentioned above says that memory can be hotplugged on memory block granularity.
But how exactly one does so?

There's an utility called daxctl, which can actually map memory regions to OS from DAX device and back:

https://docs.pmem.io/ndctl-user-guide/daxctl-man-pages/daxctl-reconfigure-device

It actually works, but it disables device completely. This functionality was added in the patch:
https://lore.kernel.org/lkml/20190124231448.E102D18E@viggo.jf.intel.com/

So to map DAX device to OS, user required to use sysfs.

To make this work, management software must remove the device from
being controlled by the "Device DAX" infrastructure:

```<code>echo -n dax0.0 > /sys/bus/dax/drivers/device_dax/remove_id
echo -n dax0.0 > /sys/bus/dax/drivers/device_dax/unbind
</code>```

and then bind it to this new driver:

```<code>echo -n dax0.0 > /sys/bus/dax/drivers/kmem/new_id
echo -n dax0.0 > /sys/bus/dax/drivers/kmem/bind
</code>```

But with this approach it removes all memory from device.

Is there any possibility, maybe in recent kernels, to map only part of DAX device memory (several memory blocks, for example)?
If my device has 32Gib can i give to the os only 8Gib (or any arbitrary amount of memory on the memory block granularity)?

Maybe there's the other way to do so?

Ideally would be that my device managed it's memory blocks and on memory rank level and could hotplug 4Gib from rank0 and 8Gib from rank1, for example.

If small scale kernel modification is required it's ok.

Maybe that kmem driver can be modified to only map some of memory blocks from the device to OS.
I just don't have much expertise on the topic.

Highly appreciate any advice!

Body:
I'm currently working on DAX device driver for my device and stumbled upon a problem.
The device has it's own ram, which can be mmapped to any app with no problem.
What i want to do is to be able to give OS the memory my device doesn't use at the moment.
So if device has nothing to do, the memory can be utilized by OS.
I've researched the topic and found out that there's actually a possibility to do so:
https://docs.kernel.org/admin-guide/mm/memory-hotplug.html

The article mentioned above says that memory can be hotplugged on memory block granularity.
But how exactly one does so?

There's an utility called daxctl, which can actually map memory regions to OS from DAX device and back:

https://docs.pmem.io/ndctl-user-guide/daxctl-man-pages/daxctl-reconfigure-device

It actually works, but it disables device completely. This functionality was added in the patch:
https://lore.kernel.org/lkml/20190124231448.E102D18E@viggo.jf.intel.com/

So to map DAX device to OS, user required to use sysfs.

To make this work, management software must remove the device from
being controlled by the "Device DAX" infrastructure:

echo -n dax0.0 > /sys/bus/dax/drivers/device_dax/remove_id
echo -n dax0.0 > /sys/bus/dax/drivers/device_dax/unbind

and then bind it to this new driver:

echo -n dax0.0 > /sys/bus/dax/drivers/kmem/new_id
echo -n dax0.0 > /sys/bus/dax/drivers/kmem/bind

But with this approach it removes all memory from device.

Is there any possibility, maybe in recent kernels, to map only part of DAX device memory (several memory blocks, for example)?
If my device has 32Gib can i give to the os only 8Gib (or any arbitrary amount of memory on the memory block granularity)?

Maybe there's the other way to do so?

Ideally would be that my device managed it's memory blocks and on memory rank level and could hotplug 4Gib from rank0 and 8Gib from rank1, for example.

If small scale kernel modification is required it's ok.

Maybe that kmem driver can be modified to only map some of memory blocks from the device to OS.
I just don't have much expertise on the topic.

Highly appreciate any advice!


问:
Not able to get ip list for wafv2
I am trying to get ip set for wafv2 but getting following error:

```<code>File "/usr/local/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/usr/local/lib/python3.7/site-packages/botocore/client.py", line 649, in _make_api_call
    api_params, operation_model, context=request_context)
  File "/usr/local/lib/python3.7/site-packages/botocore/client.py", line 697, in _convert_to_request_dict
    api_params, operation_model)
  File "/usr/local/lib/python3.7/site-packages/botocore/validate.py", line 297, in serialize_to_request
    raise ParamValidationError(report=report.generate_report())
botocore.exceptions.ParamValidationError: Parameter validation failed:
Missing required parameter in input: "Scope"
</code>```

Not sure where to define scope.

```<code>    awsutils = DevtoolsAwsUtils()
    session = awsutils.assume_role(waf_arn)
    client_wafv2 = session.client('wafv2')
    ip_sets_dict_wafv2 = client_wafv2.list_ip_sets()
    print("ip_sets_dict_wafv2: ", ip_sets_dict_wafv2)
    ip_sets_wafv2 = ip_sets_dict_wafv2['IPSets']
    print("ip_sets_wafv2: ", ip_sets_wafv2)

</code>```

Title: Not able to get ip list for wafv2

Body:
I am trying to get ip set for wafv2 but getting following error:

File "/usr/local/lib/python3.7/site-packages/botocore/client.py", line 357, in _api_call
    return self._make_api_call(operation_name, kwargs)
  File "/usr/local/lib/python3.7/site-packages/botocore/client.py", line 649, in _make_api_call
    api_params, operation_model, context=request_context)
  File "/usr/local/lib/python3.7/site-packages/botocore/client.py", line 697, in _convert_to_request_dict
    api_params, operation_model)
  File "/usr/local/lib/python3.7/site-packages/botocore/validate.py", line 297, in serialize_to_request
    raise ParamValidationError(report=report.generate_report())
botocore.exceptions.ParamValidationError: Parameter validation failed:
Missing required parameter in input: "Scope"

Not sure where to define scope.

    awsutils = DevtoolsAwsUtils()
    session = awsutils.assume_role(waf_arn)
    client_wafv2 = session.client('wafv2')
    ip_sets_dict_wafv2 = client_wafv2.list_ip_sets()
    print("ip_sets_dict_wafv2: ", ip_sets_dict_wafv2)
    ip_sets_wafv2 = ip_sets_dict_wafv2['IPSets']
    print("ip_sets_wafv2: ", ip_sets_wafv2)


问:
SwiftUI: Custom binding that get value from @StateObject property is set back to old value after StateObject property change
I'm trying to implement a passcode view in iOS. I was following the guide here.

I'm trying to improve it a bit so it allows me to create a passcode by enter same passcode twice. I added a "state" property to the @StateObject and want to clear entered passcode after user input the passcode first time.

Here is my current code:

```<code>LockScreenModel.swift
====================
import Foundation

class LockScreenModel: ObservableObject {
    @Published var pin: String = ""
    @Published var showPin = false
    @Published var isDisabled = false
    @Published var state = LockScreenState.normal
}

enum LockScreenState: String, CaseIterable {
    case new
    case verify
    case normal
    case remove
}
====================

LockScreen.swift
====================
import SwiftUI

struct LockScreen: View {

    @StateObject var lockScreenModel = LockScreenModel()

    let initialState: LockScreenState
    var handler: (String, LockScreenState, (Bool) -> Void) -> Void

    var body: some View {
        VStack(spacing: 40) {
            Text(NSLocalizedString("lock.label.\(lockScreenModel.state.rawValue)", comment: "")).font(.title)
            ZStack {
                pinDots
                backgroundField
            }
            showPinStack
        }
        .onAppear(perform: {lockScreenModel.state = initialState})
        .onDisappear(perform: {
            lockScreenModel.pin = ""
            lockScreenModel.showPin = false
            lockScreenModel.isDisabled = false
            lockScreenModel.state = .normal
        })
    }

    private var pinDots: some View {
        HStack {
            Spacer()
            ForEach(0..<6) { index in
                Image(systemName: self.getImageName(at: index))
                    .font(.system(size: 30, weight: .thin, design: .default))
                Spacer()
            }
        }
    }

    private var backgroundField: some View {
        let boundPin = Binding<String>(get: { lockScreenModel.pin }, set: { newValue in
            if newValue.last?.isWholeNumber == true {
                lockScreenModel.pin = newValue
            }
            self.submitPin()
        })

        return TextField("", text: boundPin, onCommit: submitPin)
            .accentColor(.clear)
            .foregroundColor(.clear)
            .keyboardType(.numberPad)
            .disabled(lockScreenModel.isDisabled)
    }

    private var showPinStack: some View {
        HStack {
            Spacer()
            if !lockScreenModel.pin.isEmpty {
                showPinButton
            }
        }
        .frame(height: 20)
        .padding([.trailing])
    }

    private var showPinButton: some View {
        Button(action: {
            lockScreenModel.showPin.toggle()
        }, label: {
            lockScreenModel.showPin ?
            Image(systemName: "eye.slash.fill").foregroundColor(.primary) :
            Image(systemName: "eye.fill").foregroundColor(.primary)
        })
    }

    private func submitPin() {
        guard !lockScreenModel.pin.isEmpty else {
            lockScreenModel.showPin = false
            return
        }

        if lockScreenModel.pin.count == 6 {
            lockScreenModel.isDisabled = true
            handler(lockScreenModel.pin, lockScreenModel.state) { isSuccess in
                if isSuccess && lockScreenModel.state == .new {
                    lockScreenModel.state = .verify
                    lockScreenModel.pin = ""
                    lockScreenModel.isDisabled = false
                } else if !isSuccess {
                    lockScreenModel.pin = ""
                    lockScreenModel.isDisabled = false
                    print("this has to called after showing toast why is the failure")
                }
            }
        }

        // this code is never reached under  normal circumstances. If the user pastes a text with count higher than the
        // max digits, we remove the additional characters and make a recursive call.
        if lockScreenModel.pin.count > 6 {
            lockScreenModel.pin = String(lockScreenModel.pin.prefix(6))
            submitPin()
        }
    }

    private func getImageName(at index: Int) -> String {
        if index >= lockScreenModel.pin.count {
            return "circle"
        }

        if lockScreenModel.showPin {
            return lockScreenModel.pin.digits[index].numberString + ".circle"
        }

        return "circle.fill"
    }
}

extension String {
    var digits: [Int] {
        var result = [Int]()
        for char in self {
            if let number = Int(String(char)) {
                result.append(number)
            }
        }
        return result
    }
}

extension Int {
    var numberString: String {
        guard self < 10 else { return "0" }
        return String(self)
    }
}
====================

</code>```

The problem is the line lockScreenModel.state = .verify. If I include this line, the passcode TextField won't get cleared, but if I remove this line, the passcode TextField is cleared.

If I add a breakpoint in set method of boundPin, I can see after set pin to empty and state to verify, the set method of boundPin is called with newValue of the old pin which I have no idea why. If I only set pin to empty but don't set state to verify, that set method of boundPin won't get called which confuse me even more. I can't figure out which caused this strange behavior.

Body:
I'm trying to implement a passcode view in iOS. I was following the guide here.

I'm trying to improve it a bit so it allows me to create a passcode by enter same passcode twice. I added a "state" property to the @StateObject and want to clear entered passcode after user input the passcode first time.

Here is my current code:

LockScreenModel.swift
====================
import Foundation

class LockScreenModel: ObservableObject {
    @Published var pin: String = ""
    @Published var showPin = false
    @Published var isDisabled = false
    @Published var state = LockScreenState.normal
}

enum LockScreenState: String, CaseIterable {
    case new
    case verify
    case normal
    case remove
}
====================

LockScreen.swift
====================
import SwiftUI

struct LockScreen: View {

    @StateObject var lockScreenModel = LockScreenModel()

    let initialState: LockScreenState
    var handler: (String, LockScreenState, (Bool) -> Void) -> Void

    var body: some View {
        VStack(spacing: 40) {
            Text(NSLocalizedString("lock.label.\(lockScreenModel.state.rawValue)", comment: "")).font(.title)
            ZStack {
                pinDots
                backgroundField
            }
            showPinStack
        }
        .onAppear(perform: {lockScreenModel.state = initialState})
        .onDisappear(perform: {
            lockScreenModel.pin = ""
            lockScreenModel.showPin = false
            lockScreenModel.isDisabled = false
            lockScreenModel.state = .normal
        })
    }

    private var pinDots: some View {
        HStack {
            Spacer()
            ForEach(0..<6) { index in
                Image(systemName: self.getImageName(at: index))
                    .font(.system(size: 30, weight: .thin, design: .default))
                Spacer()
            }
        }
    }

    private var backgroundField: some View {
        let boundPin = Binding<String>(get: { lockScreenModel.pin }, set: { newValue in
            if newValue.last?.isWholeNumber == true {
                lockScreenModel.pin = newValue
            }
            self.submitPin()
        })

        return TextField("", text: boundPin, onCommit: submitPin)
            .accentColor(.clear)
            .foregroundColor(.clear)
            .keyboardType(.numberPad)
            .disabled(lockScreenModel.isDisabled)
    }

    private var showPinStack: some View {
        HStack {
            Spacer()
            if !lockScreenModel.pin.isEmpty {
                showPinButton
            }
        }
        .frame(height: 20)
        .padding([.trailing])
    }

    private var showPinButton: some View {
        Button(action: {
            lockScreenModel.showPin.toggle()
        }, label: {
            lockScreenModel.showPin ?
            Image(systemName: "eye.slash.fill").foregroundColor(.primary) :
            Image(systemName: "eye.fill").foregroundColor(.primary)
        })
    }

    private func submitPin() {
        guard !lockScreenModel.pin.isEmpty else {
            lockScreenModel.showPin = false
            return
        }

        if lockScreenModel.pin.count == 6 {
            lockScreenModel.isDisabled = true
            handler(lockScreenModel.pin, lockScreenModel.state) { isSuccess in
                if isSuccess && lockScreenModel.state == .new {
                    lockScreenModel.state = .verify
                    lockScreenModel.pin = ""
                    lockScreenModel.isDisabled = false
                } else if !isSuccess {
                    lockScreenModel.pin = ""
                    lockScreenModel.isDisabled = false
                    print("this has to called after showing toast why is the failure")
                }
            }
        }

        // this code is never reached under  normal circumstances. If the user pastes a text with count higher than the
        // max digits, we remove the additional characters and make a recursive call.
        if lockScreenModel.pin.count > 6 {
            lockScreenModel.pin = String(lockScreenModel.pin.prefix(6))
            submitPin()
        }
    }

    private func getImageName(at index: Int) -> String {
        if index >= lockScreenModel.pin.count {
            return "circle"
        }

        if lockScreenModel.showPin {
            return lockScreenModel.pin.digits[index].numberString + ".circle"
        }

        return "circle.fill"
    }
}

extension String {
    var digits: [Int] {
        var result = [Int]()
        for char in self {
            if let number = Int(String(char)) {
                result.append(number)
            }
        }
        return result
    }
}

extension Int {
    var numberString: String {
        guard self < 10 else { return "0" }
        return String(self)
    }
}
====================

The problem is the line lockScreenModel.state = .verify. If I include this line, the passcode TextField won't get cleared, but if I remove this line, the passcode TextField is cleared.

If I add a breakpoint in set method of boundPin, I can see after set pin to empty and state to verify, the set method of boundPin is called with newValue of the old pin which I have no idea why. If I only set pin to empty but don't set state to verify, that set method of boundPin won't get called which confuse me even more. I can't figure out which caused this strange behavior.


问:
How to make conditional import work in React JS?
I have three pages in my react website that have the same layout and different content. I've made an array within a js file to map through the content, but I don't want to duplicate my code to another component.

The point is the I need the variable name to be the same, so I can map it.

I can get what I need with require matching the page url, but since I read it's not a good practice in react due to performance issues, I'm trying to accomplish it with import with no sucess though.

```<code>let pagedata = [];
if (matchpage1) {
    pagedata = require("./data").page1data;
} else if (matchpage2) {
    pagedata = require("./data").page2data;
} else if (matchpage3) {
    pagedata = require("./data").page3data;
}

return (

pagedata.map((item) => {

</code>```

I've read the react documentation, searched a lot, tried a lot of code, but nothing works if I try a simiçar aproach with import and lazy.

```<code>let pagedata = [];
if (matchpage1) {
    pagedata = React.lazy(() => import('./pagedata1'));
} else if (matchpage2) {
    pagedata = React.lazy(() => import('./pagedata2'));
} else if (matchpage3) {
   pagedata = React.lazy(() => import('./pagedata3'));
}

</code>```

What am I doing wrong?
Thank you so much for your attention.

Body:
I have three pages in my react website that have the same layout and different content. I've made an array within a js file to map through the content, but I don't want to duplicate my code to another component.

The point is the I need the variable name to be the same, so I can map it.

I can get what I need with require matching the page url, but since I read it's not a good practice in react due to performance issues, I'm trying to accomplish it with import with no sucess though.

let pagedata = [];
if (matchpage1) {
    pagedata = require("./data").page1data;
} else if (matchpage2) {
    pagedata = require("./data").page2data;
} else if (matchpage3) {
    pagedata = require("./data").page3data;
}

return (

pagedata.map((item) => {

I've read the react documentation, searched a lot, tried a lot of code, but nothing works if I try a simiçar aproach with import and lazy.

let pagedata = [];
if (matchpage1) {
    pagedata = React.lazy(() => import('./pagedata1'));
} else if (matchpage2) {
    pagedata = React.lazy(() => import('./pagedata2'));
} else if (matchpage3) {
   pagedata = React.lazy(() => import('./pagedata3'));
}

What am I doing wrong?
Thank you so much for your attention.


问:
I am getting null as result in useSelector from react redux toolkit
and also useEffect also not working in my file. i tried many way but useEffect not working. if i comments everything file and try then useEffect working else not working.
and also i am getting null value from

```<code>const { currentVideo } = useSelector((state) => state.video);
</code>```

this is my useEffect ->

```<code>useEffect(() => {
    const fetchData = async () => {
      try {
        const videoRes = await axiosInstance.get(`/videos/find/${path}`, {
          withCredentials: true,
        });
        // console.log(videoRes);
        const updatedView = await axiosInstance.put(`videos/view/${path}`);
        // console.log(updatedView.data, "view is updating");
        const channelRes = await axiosInstance.get(
          `/users/find/${videoRes.data.userId}`,
          { withCredentials: true }
        );
        setChannel(channelRes.data);
        dispatch(fetchSuccess(videoRes.data));
      } catch (err) {
        console.log(err);
        return "opps something went wrong!";
      }
    };
    fetchData();
  }, [path, dispatch]);

</code>```

here i am getting null value

```<code>const Video = () => {
  const { currentUser } = useSelector((state) => state.user);
  const { currentVideo } = useSelector((state) => state.video);
  const dispatch = useDispatch();
  const path = useLocation().pathname.split("/")[2];
  // console.log(currentVideo); // getting null
  const [channel, setChannel] = useState({});
</code>```

and my full video.jsx is

```<code>
import React, { useEffect, useState } from "react";
import styled from "styled-components";
import ThumbUpOutlinedIcon from "@mui/icons-material/ThumbUpOutlined";
import ThumbDownOffAltOutlinedIcon from "@mui/icons-material/ThumbDownOffAltOutlined";
import ReplyOutlinedIcon from "@mui/icons-material/ReplyOutlined";
import AddTaskOutlinedIcon from "@mui/icons-material/AddTaskOutlined";
import ThumbUpIcon from "@mui/icons-material/ThumbUp";
import ThumbDownIcon from "@mui/icons-material/ThumbDown";
import Comments from "../components/Comments";
import { useDispatch, useSelector } from "react-redux";
import { useLocation } from "react-router-dom";
import axios from "axios";
import { fetchSuccess, like, dislike } from "../redux/videoSlice";
import axiosInstance from "../axios";
import { subscription } from "../redux/userSlice";
import Recommendation from "../components/Recommendation";

import { format } from "timeago.js";

const Video = () => {
  const { currentUser } = useSelector((state) => state.user);
  const { currentVideo } = useSelector((state) => state.video);
  const dispatch = useDispatch();
  const path = useLocation().pathname.split("/")[2];
  // console.log(currentVideo); // getting null
  const [channel, setChannel] = useState({});

  /*
  // console.log(path); ok hai video user id aa rahi hai.
  // its working its getting all the data.
  const test = async () => {
    const isWorking = await axios.get(
      "http://localhost:5000/api/videos/find/63931e44de7c22e61c4ffd6c"
      );
      console.log(isWorking.data);
      console.log(isWorking.data.videoUrl);
    };
    const videoRes = test();
    console.log(videoRes);

    */

  // {withCredentials: true}
  useEffect(() => {
    const fetchData = async () => {
      try {
        const videoRes = await axiosInstance.get(`/videos/find/${path}`, {
          withCredentials: true,
        });
        // console.log(videoRes);
        const updatedView = await axiosInstance.put(`videos/view/${path}`);
        // console.log(updatedView.data, "view is updating");
        const channelRes = await axiosInstance.get(
          `/users/find/${videoRes.data.userId}`,
          { withCredentials: true }
        );
        setChannel(channelRes.data);
        dispatch(fetchSuccess(videoRes.data));
      } catch (err) {
        console.log(err);
        return "opps something went wrong!";
      }
    };
    fetchData();
  }, [path, dispatch]);

  const handleLike = async () => {
    try {
      await axiosInstance.put(`/users/like/${currentVideo._id}`, {
        withCredentials: true,
      });
      dispatch(like(currentUser._id));
    } catch (err) {
      console.log(err);
      return "opps something went wrong!";
    }
  };
  const handleDislike = async () => {
    try {
      await axiosInstance.put(`/users/dislike/${currentVideo._id}`, {
        withCredentials: true,
      });
      dispatch(dislike(currentUser._id));
    } catch (err) {
      console.log(err);
    }
  };
  const handleSub = async () => {
    currentUser.subscribedUsers.includes(channel._id)
      ? await axiosInstance.put(`/users/unsub/${channel._id}`, {
          withCredentials: true,
        })
      : await axiosInstance.put(`/users/sub/${channel._id}`, {
          withCredentials: true,
        });
    dispatch(subscription(channel._id));
  };

  if (!currentUser) return "Loading....";
  return (
    <Container>
      <Content>
        <VideoWrapper>
          <VideoFrame src={currentVideo?.videoUrl} controls />
        </VideoWrapper>
        <Title>{currentVideo?.title}</Title>
        <Details>
          <Info>
            {currentVideo?.views} views •{format(currentVideo?.createdAt)}
          </Info>
          <Buttons>
            <Button onClick={() => handleLike()}>
              {currentVideo?.likes.includes(currentUser._id) ? (
                <ThumbUpIcon />
              ) : (
                <ThumbUpOutlinedIcon />
              )}{" "}
              {currentVideo?.likes.length}
            </Button>
            <Button onClick={() => handleDislike()}>
              {currentVideo?.dislikes.includes(currentUser._id) ? (
                <ThumbDownIcon />
              ) : (
                <ThumbDownOffAltOutlinedIcon />
              )}
              Dislike
            </Button>
            <Button>
              <ReplyOutlinedIcon /> Share
            </Button>
            <Button>
              <AddTaskOutlinedIcon /> Save
            </Button>
          </Buttons>
        </Details>
        <Hr />
        <Channel>
          <ChannelInfo>
            <Image src={channel.img} />

            <ChannelDetail>
              <ChannelName>{channel.name}</ChannelName>
              <ChannelCounter>{channel.subscribers} subscribers</ChannelCounter>
              <Description>{currentVideo?.desc}</Description>
            </ChannelDetail>
          </ChannelInfo>
          <Subscribe onClick={handleSub}>
            {currentUser.subscribedUsers.includes(channel._id)
              ? "SUBSCRIBED"
              : "SUBSCRIBE"}
          </Subscribe>
        </Channel>
        <Hr />
        <Comments videoId={currentVideo?._id} />
      </Content>
      <Recommendation tags={currentVideo?.tags} />
    </Container>
  );
};

export default Video;

</code>```

and this is my redux videoslice file videoSlice.js

```<code>import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  currentVideo: null,
  loading: false,
  error: false,
};

export const videoSlice = createSlice({
  name: "video",
  initialState,
  reducers: {
    fetchStart: (state) => {
      state.loading = true;
    },
    fetchSuccess: (state, action) => {
      state.loading = false;
      state.currentVideo = action.payload;
    },
    fetchFailure: (state) => {
      state.loading = false;
      state.error = true;
    },
    like: (state, action) => {
      if (!state.currentVideo.likes.includes(action.payload)) {
        state.currentVideo.likes.push(action.payload);
        state.currentVideo.dislikes.splice(
          state.currentVideo.dislikes.findIndex(
            (userId) => userId === action.payload
          ),
          1
        );
      }
    },
    dislike: (state, action) => {
      if (!state.currentVideo.dislikes.includes(action.payload)) {
        state.currentVideo.dislikes.push(action.payload);
        state.currentVideo.likes.splice(
          state.currentVideo.likes.findIndex(
            (userId) => userId === action.payload
          ),
          1
        );
      }
    },

    views: (state, action) => {
      if (state.currentVideo.views.includes(action.payload)) {
        state.currentVideo.views.push(action.payload);
      }
    },
  },
});

export const { fetchStart, fetchSuccess, fetchFailure, like, dislike, views } =
  videoSlice.actions;

export default videoSlice.reducer;

</code>```

in browser i am also getting null

i am trying to call my api and render data. but useeffect not working in my code. also from useSelector i am getting null value.

Body:
and also useEffect also not working in my file. i tried many way but useEffect not working. if i comments everything file and try then useEffect working else not working.
and also i am getting null value from

const { currentVideo } = useSelector((state) => state.video);

this is my useEffect ->

useEffect(() => {
    const fetchData = async () => {
      try {
        const videoRes = await axiosInstance.get(`/videos/find/${path}`, {
          withCredentials: true,
        });
        // console.log(videoRes);
        const updatedView = await axiosInstance.put(`videos/view/${path}`);
        // console.log(updatedView.data, "view is updating");
        const channelRes = await axiosInstance.get(
          `/users/find/${videoRes.data.userId}`,
          { withCredentials: true }
        );
        setChannel(channelRes.data);
        dispatch(fetchSuccess(videoRes.data));
      } catch (err) {
        console.log(err);
        return "opps something went wrong!";
      }
    };
    fetchData();
  }, [path, dispatch]);

here i am getting null value

const Video = () => {
  const { currentUser } = useSelector((state) => state.user);
  const { currentVideo } = useSelector((state) => state.video);
  const dispatch = useDispatch();
  const path = useLocation().pathname.split("/")[2];
  // console.log(currentVideo); // getting null
  const [channel, setChannel] = useState({});

and my full video.jsx is

import React, { useEffect, useState } from "react";
import styled from "styled-components";
import ThumbUpOutlinedIcon from "@mui/icons-material/ThumbUpOutlined";
import ThumbDownOffAltOutlinedIcon from "@mui/icons-material/ThumbDownOffAltOutlined";
import ReplyOutlinedIcon from "@mui/icons-material/ReplyOutlined";
import AddTaskOutlinedIcon from "@mui/icons-material/AddTaskOutlined";
import ThumbUpIcon from "@mui/icons-material/ThumbUp";
import ThumbDownIcon from "@mui/icons-material/ThumbDown";
import Comments from "../components/Comments";
import { useDispatch, useSelector } from "react-redux";
import { useLocation } from "react-router-dom";
import axios from "axios";
import { fetchSuccess, like, dislike } from "../redux/videoSlice";
import axiosInstance from "../axios";
import { subscription } from "../redux/userSlice";
import Recommendation from "../components/Recommendation";

import { format } from "timeago.js";

const Video = () => {
  const { currentUser } = useSelector((state) => state.user);
  const { currentVideo } = useSelector((state) => state.video);
  const dispatch = useDispatch();
  const path = useLocation().pathname.split("/")[2];
  // console.log(currentVideo); // getting null
  const [channel, setChannel] = useState({});

  /*
  // console.log(path); ok hai video user id aa rahi hai.
  // its working its getting all the data.
  const test = async () => {
    const isWorking = await axios.get(
      "http://localhost:5000/api/videos/find/63931e44de7c22e61c4ffd6c"
      );
      console.log(isWorking.data);
      console.log(isWorking.data.videoUrl);
    };
    const videoRes = test();
    console.log(videoRes);

    */

  // {withCredentials: true}
  useEffect(() => {
    const fetchData = async () => {
      try {
        const videoRes = await axiosInstance.get(`/videos/find/${path}`, {
          withCredentials: true,
        });
        // console.log(videoRes);
        const updatedView = await axiosInstance.put(`videos/view/${path}`);
        // console.log(updatedView.data, "view is updating");
        const channelRes = await axiosInstance.get(
          `/users/find/${videoRes.data.userId}`,
          { withCredentials: true }
        );
        setChannel(channelRes.data);
        dispatch(fetchSuccess(videoRes.data));
      } catch (err) {
        console.log(err);
        return "opps something went wrong!";
      }
    };
    fetchData();
  }, [path, dispatch]);

  const handleLike = async () => {
    try {
      await axiosInstance.put(`/users/like/${currentVideo._id}`, {
        withCredentials: true,
      });
      dispatch(like(currentUser._id));
    } catch (err) {
      console.log(err);
      return "opps something went wrong!";
    }
  };
  const handleDislike = async () => {
    try {
      await axiosInstance.put(`/users/dislike/${currentVideo._id}`, {
        withCredentials: true,
      });
      dispatch(dislike(currentUser._id));
    } catch (err) {
      console.log(err);
    }
  };
  const handleSub = async () => {
    currentUser.subscribedUsers.includes(channel._id)
      ? await axiosInstance.put(`/users/unsub/${channel._id}`, {
          withCredentials: true,
        })
      : await axiosInstance.put(`/users/sub/${channel._id}`, {
          withCredentials: true,
        });
    dispatch(subscription(channel._id));
  };

  if (!currentUser) return "Loading....";
  return (
    <Container>
      <Content>
        <VideoWrapper>
          <VideoFrame src={currentVideo?.videoUrl} controls />
        </VideoWrapper>
        <Title>{currentVideo?.title}</Title>

          <Info>
            {currentVideo?.views} views •{format(currentVideo?.createdAt)}
          </Info>
          <Buttons>
            <Button onClick={() => handleLike()}>
              {currentVideo?.likes.includes(currentUser._id) ? (
                <ThumbUpIcon />
              ) : (
                <ThumbUpOutlinedIcon />
              )}{" "}
              {currentVideo?.likes.length}
            </Button>
            <Button onClick={() => handleDislike()}>
              {currentVideo?.dislikes.includes(currentUser._id) ? (
                <ThumbDownIcon />
              ) : (
                <ThumbDownOffAltOutlinedIcon />
              )}
              Dislike
            </Button>
            <Button>
              <ReplyOutlinedIcon /> Share
            </Button>
            <Button>
              <AddTaskOutlinedIcon /> Save
            </Button>
          </Buttons>

        <Channel>
          <ChannelInfo>
            <Image src={channel.img} />

            <ChannelDetail>
              <ChannelName>{channel.name}</ChannelName>
              <ChannelCounter>{channel.subscribers} subscribers</ChannelCounter>
              <Description>{currentVideo?.desc}</Description>
            </ChannelDetail>
          </ChannelInfo>
          <Subscribe onClick={handleSub}>
            {currentUser.subscribedUsers.includes(channel._id)
              ? "SUBSCRIBED"
              : "SUBSCRIBE"}
          </Subscribe>
        </Channel>

        <Comments videoId={currentVideo?._id} />
      </Content>
      <Recommendation tags={currentVideo?.tags} />
    </Container>
  );
};

export default Video;

and this is my redux videoslice file videoSlice.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  currentVideo: null,
  loading: false,
  error: false,
};

export const videoSlice = createSlice({
  name: "video",
  initialState,
  reducers: {
    fetchStart: (state) => {
      state.loading = true;
    },
    fetchSuccess: (state, action) => {
      state.loading = false;
      state.currentVideo = action.payload;
    },
    fetchFailure: (state) => {
      state.loading = false;
      state.error = true;
    },
    like: (state, action) => {
      if (!state.currentVideo.likes.includes(action.payload)) {
        state.currentVideo.likes.push(action.payload);
        state.currentVideo.dislikes.splice(
          state.currentVideo.dislikes.findIndex(
            (userId) => userId === action.payload
          ),
          1
        );
      }
    },
    dislike: (state, action) => {
      if (!state.currentVideo.dislikes.includes(action.payload)) {
        state.currentVideo.dislikes.push(action.payload);
        state.currentVideo.likes.splice(
          state.currentVideo.likes.findIndex(
            (userId) => userId === action.payload
          ),
          1
        );
      }
    },

    views: (state, action) => {
      if (state.currentVideo.views.includes(action.payload)) {
        state.currentVideo.views.push(action.payload);
      }
    },
  },
});

export const { fetchStart, fetchSuccess, fetchFailure, like, dislike, views } =
  videoSlice.actions;

export default videoSlice.reducer;

in browser i am also getting null

i am trying to call my api and render data. but useeffect not working in my code. also from useSelector i am getting null value.


问:
Can't get attribute 'script1' on <module '__main__' (built-in)>
I'm attempting to simultaneously run two scripts with Multiprocessing.

I'm not sure why, but I'm getting the above error message from the code below:

```<code>import sys
import os
import multiprocessing as mp

def script1():
 os.system("FBREF_Teams.py")

def script2():
 os.system("FBREF_Players.py")

if __name__ == '__main__':
 p1 = mp.Process(target=script1)
 p2 = mp.Process(target=script2)
 p1.start()
 p2.start()
 p1.join()
 p2.join()
</code>```

I tried switching from Multiprocessing to Multiprocess and I get the following error instead:
NameError: name 'os' is not defined

I also tried to import FBREF_Teams to check if it is located in the correct place, which was successful.

Body:
I'm attempting to simultaneously run two scripts with Multiprocessing.

I'm not sure why, but I'm getting the above error message from the code below:

import sys
import os
import multiprocessing as mp

def script1():
 os.system("FBREF_Teams.py")

def script2():
 os.system("FBREF_Players.py")

if __name__ == '__main__':
 p1 = mp.Process(target=script1)
 p2 = mp.Process(target=script2)
 p1.start()
 p2.start()
 p1.join()
 p2.join()

I tried switching from Multiprocessing to Multiprocess and I get the following error instead:
NameError: name 'os' is not defined

I also tried to import FBREF_Teams to check if it is located in the correct place, which was successful.


问:
Can't create an area below graph. Failed to convert yearMonth to axis units
I have a dataframe imported from google analytics that shows yearMonth and users

yearMonth
users

202112
139

202201
241

202202
286

The yearMonth then gets converted to datetime and then period since I still want the yearMonth format:

```<code>df["ga:yearMonth"] = pd.to_datetime(df['ga:yearMonth'],format='%Y%m').dt.to_period('M')
</code>```

(https://i.stack.imgur.com/fwCTT.png)

Now I want to make a simple line chart of this with an area beneath the chart with the users on the y-axis and the months and their respective years (Dec 2021, Jan 2022, ..) on the x-axis.

I've tried using matplotlib's fill_between()

```<code>ax = df.plot(x="ga:yearMonth", y="ga:users")

ax.fill_between(x="ga:yearMonth", y1="ga:users")
</code>```

But this outputted:

ConversionError: Failed to convert value(s) to axis units: 'ga:yearMonth'

while still plotting
(https://i.stack.imgur.com/76J5c.png)

I've also tried not changing yearMonth to period to see if it works but it still gives the same error.

Would greatly appreciate the assistance.

Body:
I have a dataframe imported from google analytics that shows yearMonth and users

yearMonth
users

202112
139

202201
241

202202
286

The yearMonth then gets converted to datetime and then period since I still want the yearMonth format:

df["ga:yearMonth"] = pd.to_datetime(df['ga:yearMonth'],format='%Y%m').dt.to_period('M')

(https://i.stack.imgur.com/fwCTT.png)

Now I want to make a simple line chart of this with an area beneath the chart with the users on the y-axis and the months and their respective years (Dec 2021, Jan 2022, ..) on the x-axis.

I've tried using matplotlib's fill_between()

ax = df.plot(x="ga:yearMonth", y="ga:users")

ax.fill_between(x="ga:yearMonth", y1="ga:users")

But this outputted:

ConversionError: Failed to convert value(s) to axis units: 'ga:yearMonth'

while still plotting
(https://i.stack.imgur.com/76J5c.png)

I've also tried not changing yearMonth to period to see if it works but it still gives the same error.

Would greatly appreciate the assistance.


问:
Export charts from all Excel worksheets with VBA
Sorry for the basic question, but I am new to VBA, and I would like to run a code to export all charts from all worksheets from an excel file as .svg files named according to the worksheet. I am trying to use the following code below adapted from here, however, it currently only exports a few charts, and only from some worksheets, with the addition of three unreadable svg exports as well. ("This XML file does not appear to have any style information associated with it. The document tree is shown below.")

Any help would be appreciated to know what to change in order to have the code run well.

Thank you very much in advance!

```<code>Sub ExportAllCharts()
    Dim objShell As Object
    Dim objWindowsFolder As Object
    Dim strWindowsFolder As String
    Dim objSheet As Excel.Worksheet
    Dim objChartObject As Excel.ChartObject
    Dim objChart As Excel.Chart

    'Select a Windows folder
    Set objShell = CreateObject("Shell.Application")
    Set objWindowsFolder = objShell.BrowseForFolder(0, "Select a Windows folder:", 0, "")

    If Not objWindowsFolder Is Nothing Then
       strWindowsFolder = objWindowsFolder.self.Path & "\"

       For i = ThisWorkbook.Worksheets.Count To 1 Step -1
           Set objSheet = ThisWorkbook.Worksheets(i)

           If objSheet.ChartObjects.Count > 0 Then
              For Each objChartObject In objSheet.ChartObjects
                  Set objChart = objChartObject.Chart
                  objChart.Export strWindowsFolder & objChart.Name & ".svg"
              Next
          End If
       Next
   End If
End Sub
</code>```

Body:
Sorry for the basic question, but I am new to VBA, and I would like to run a code to export all charts from all worksheets from an excel file as .svg files named according to the worksheet. I am trying to use the following code below adapted from here, however, it currently only exports a few charts, and only from some worksheets, with the addition of three unreadable svg exports as well. ("This XML file does not appear to have any style information associated with it. The document tree is shown below.")

Any help would be appreciated to know what to change in order to have the code run well.

Thank you very much in advance!

Sub ExportAllCharts()
    Dim objShell As Object
    Dim objWindowsFolder As Object
    Dim strWindowsFolder As String
    Dim objSheet As Excel.Worksheet
    Dim objChartObject As Excel.ChartObject
    Dim objChart As Excel.Chart

    'Select a Windows folder
    Set objShell = CreateObject("Shell.Application")
    Set objWindowsFolder = objShell.BrowseForFolder(0, "Select a Windows folder:", 0, "")

    If Not objWindowsFolder Is Nothing Then
       strWindowsFolder = objWindowsFolder.self.Path & "\"

       For i = ThisWorkbook.Worksheets.Count To 1 Step -1
           Set objSheet = ThisWorkbook.Worksheets(i)

           If objSheet.ChartObjects.Count > 0 Then
              For Each objChartObject In objSheet.ChartObjects
                  Set objChart = objChartObject.Chart
                  objChart.Export strWindowsFolder & objChart.Name & ".svg"
              Next
          End If
       Next
   End If
End Sub


问:
How to set Nexus proxy Gitlab package registry?
I have a Gitlab package registry which has some .aar artifacts with Maven type. And I want to add a proxy with a global Nexus maven group.
I create a maven2 proxy repository, and name is gitlab-proxy, remote storage url is https://xxxx.xxxx.com/api/v4/projects/xxx/packages/maven, authentication type is Username, the username and password corresponding to the username and token of a read and write gitlab package token.
State shows online-available but finds nothing artifacts.

I disable the authentication but it changes nothing.


问:
Azure Site Recovery Planner - Bandwidth check error
I am running the Azure Site Recovery planner tool to provide us with some information for our local VMware environment, so we can later setup Azure Site Recovery.

I'm having problems with the Bandwidth checker command which is failing to give me the bandwidth we would require to Azure

Here is the command I run:

```<code>ASRDeploymentPlanner.exe -Operation GetThroughput -Directory "C:\AzureSiteRecovery\PlannerTool\ProfileData" -Virtualization VMware -VMListFile "C:\AzureSiteRecovery\PlannerTool\ProfileVMList.txt" -StorageAccountName MyStorage -StorageAccountKey XXXXXXXXXXXX
</code>```

Here's the error I get:

```<code>VMWARE TO AZURE ASR DEPLOYMENT PLANNER

Finding achievable throughput from server 'MyServer' to Azure storage account 'MyStorage'. It might take from few minutes to hours based upon bandwidth availability and number of VMs in the given filename. Please wait...

Creating VHDs
Uploading VHD files to storage account: MyStorage...
Error in uploading files. Failed to calculate achievable throughput.

Possible reasons:

STORAGE_COMMUNICATION_ERROR. Unable to communicate to Azure Storage blob. Check network connectivity to Azure and if bandwidth from on-premises to Azure is very low.
Deleting 'asrvhdfile*' files from storage account...
Successfully deleted files.
Deleting 'asrvhdfile*' files from local machine...
Successfully deleted the files.
Get throughput operation failed.
</code>```

I can see its placing the VHD files in the Blob storage so there is a connection there.

It seems the same issue as this post:
https://learn.microsoft.com/en-us/answers/questions/529111/storage-communication-error-unable-to-communicate.html

However I have no idea where to enter the code they mentioned in the Azure site recovery planner tool.

I have excluded this vm from any proxies and checked the firewall url and ports required are allowed.

A speed test shows 80MB up and down

Running an AZ speed test PowerShell test shows I'm getting about 24 MS response times from my Azure region

I can upload files to the blob storage manually using Azure Storage Explorer, and see an upload of 80mbps

I have also tested this tool in a hyper v environment (home lab) and have the same error

Has anyone had any experience with this issue or have any suggestions I can try, thanks in advance.

Body:
I am running the Azure Site Recovery planner tool to provide us with some information for our local VMware environment, so we can later setup Azure Site Recovery.

I'm having problems with the Bandwidth checker command which is failing to give me the bandwidth we would require to Azure

Here is the command I run:

ASRDeploymentPlanner.exe -Operation GetThroughput -Directory "C:\AzureSiteRecovery\PlannerTool\ProfileData" -Virtualization VMware -VMListFile "C:\AzureSiteRecovery\PlannerTool\ProfileVMList.txt" -StorageAccountName MyStorage -StorageAccountKey XXXXXXXXXXXX

Here's the error I get:

VMWARE TO AZURE ASR DEPLOYMENT PLANNER

Finding achievable throughput from server 'MyServer' to Azure storage account 'MyStorage'. It might take from few minutes to hours based upon bandwidth availability and number of VMs in the given filename. Please wait...

Creating VHDs
Uploading VHD files to storage account: MyStorage...
Error in uploading files. Failed to calculate achievable throughput.

Possible reasons:

STORAGE_COMMUNICATION_ERROR. Unable to communicate to Azure Storage blob. Check network connectivity to Azure and if bandwidth from on-premises to Azure is very low.
Deleting 'asrvhdfile*' files from storage account...
Successfully deleted files.
Deleting 'asrvhdfile*' files from local machine...
Successfully deleted the files.
Get throughput operation failed.

I can see its placing the VHD files in the Blob storage so there is a connection there.

It seems the same issue as this post:
https://learn.microsoft.com/en-us/answers/questions/529111/storage-communication-error-unable-to-communicate.html

However I have no idea where to enter the code they mentioned in the Azure site recovery planner tool.

I have excluded this vm from any proxies and checked the firewall url and ports required are allowed.

A speed test shows 80MB up and down

Running an AZ speed test PowerShell test shows I'm getting about 24 MS response times from my Azure region

I can upload files to the blob storage manually using Azure Storage Explorer, and see an upload of 80mbps

I have also tested this tool in a hyper v environment (home lab) and have the same error

Has anyone had any experience with this issue or have any suggestions I can try, thanks in advance.