问:
Stopping audio when an animation is done
When all my animations have finished, I wanted the audio to stop. Currently, the audio starts after a delayed amount of seconds and also ends after a specific set time.

The way I am doing it is I have a setTimeout function in javascript to stop (pause) the audio from playing after a certain time. This time is manually inputted by timing all my animations in my project. It functions and stops the music after 104 seconds.

The animation

```<code>#logo {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  opacity: 0;
  z-index: 2;
  animation: logo 10s ease-out 9s;
  animation-play-state: paused;
  display: none;
}

@keyframes logo {
  0% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(2);
  }
  90% {
    opacity: 1;
  }

  100% {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.1);
  }
}

#logo img {
  width: inherit;
}
</code>```

and this is the JS

```<code>  setTimeout(function () {
    musicElement.play();
    console.log("Audio played now, when the Star Wars logo flies in");
  }, 8400);
</code>```

The setTimeout is inside another function.

Body:
When all my animations have finished, I wanted the audio to stop. Currently, the audio starts after a delayed amount of seconds and also ends after a specific set time.

The way I am doing it is I have a setTimeout function in javascript to stop (pause) the audio from playing after a certain time. This time is manually inputted by timing all my animations in my project. It functions and stops the music after 104 seconds.

The animation

#logo {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  opacity: 0;
  z-index: 2;
  animation: logo 10s ease-out 9s;
  animation-play-state: paused;
  display: none;
}

@keyframes logo {
  0% {
    opacity: 1;
    transform: translate(-50%, -50%) scale(2);
  }
  90% {
    opacity: 1;
  }

  100% {
    opacity: 0;
    transform: translate(-50%, -50%) scale(0.1);
  }
}

#logo img {
  width: inherit;
}

and this is the JS

  setTimeout(function () {
    musicElement.play();
    console.log("Audio played now, when the Star Wars logo flies in");
  }, 8400);

The setTimeout is inside another function.


来源: stackexchange

问:
Maxvalue function modification
I am trying to modify my function

```<code>def maxvalue(values):
    """
    Function that receives a list/array and returns the index of the maximum
    value in that sequence
    """
    try:
        max_value = max(values)
    except TypeError:
        raise TypeError("Only numerical values are allowed")  # raise an exception if the value is not float or integer

    indices = []
    for idx, val in enumerate(values):
        if val == max_value:
            indices.append(idx)
    return indices
</code>```

Such that it will still return the index of the maximum value in the sequence as well as the TypeError.
I have another function, sumvalues which does this

```<code>def sumvalues(values):
    """
    Function that receives a list/arrary and returns the sum of the values in that
    sequence
    """
    total = 0.0
    for value in values:
        try:
            total += value
        except TypeError: #Values are still sumed up, if non-numercial are detected, prints the message
            print("Only numerical values are allowed")
    return total
</code>```

calling the maxvalue function:

```<code>print(maxvalue([1,2,3,3,"e"]))
</code>```

should output:

```<code>Only numerical values are allowed

[2,3]
</code>```

ContentLicense: CC BY-SA 4.0

Title: Maxvalue function modification

Body:
I am trying to modify my function

def maxvalue(values):
    """
    Function that receives a list/array and returns the index of the maximum
    value in that sequence
    """
    try:
        max_value = max(values)
    except TypeError:
        raise TypeError("Only numerical values are allowed")  # raise an exception if the value is not float or integer

    indices = []
    for idx, val in enumerate(values):
        if val == max_value:
            indices.append(idx)
    return indices

Such that it will still return the index of the maximum value in the sequence as well as the TypeError.
I have another function, sumvalues which does this

def sumvalues(values):
    """
    Function that receives a list/arrary and returns the sum of the values in that
    sequence
    """
    total = 0.0
    for value in values:
        try:
            total += value
        except TypeError: #Values are still sumed up, if non-numercial are detected, prints the message
            print("Only numerical values are allowed")
    return total

calling the maxvalue function:

print(maxvalue([1,2,3,3,"e"]))

should output:

Only numerical values are allowed

[2,3]


问:
CocoaPods could not find compatible versions for pod "GTMSessionFetcher/Core"
CocoaPods could not find compatible versions for pod "GTMSessionFetcher/Core"
`

```<code>[!] CocoaPods could not find compatible versions for pod "GTMSessionFetcher/Core":
  In Podfile:
    firebase_auth (from `.symlinks/plugins/firebase_auth/ios`) was resolved to 4.2.0, which depends on
      Firebase/Auth (= 10.3.0) was resolved to 10.3.0, which depends on
        FirebaseAuth (~> 10.3.0) was resolved to 10.3.0, which depends on
          GTMSessionFetcher/Core (< 4.0, >= 2.1)

    mobile_scanner (from `.symlinks/plugins/mobile_scanner/ios`) was resolved to 0.0.1, which depends on
      GoogleMLKit/BarcodeScanning (~> 3.2.0) was resolved to 3.2.0, which depends on
        MLKitBarcodeScanning (~> 2.2.0) was resolved to 2.2.0, which depends on

</code>```

`

Body:
CocoaPods could not find compatible versions for pod "GTMSessionFetcher/Core"
`

[!] CocoaPods could not find compatible versions for pod "GTMSessionFetcher/Core":
  In Podfile:
    firebase_auth (from `.symlinks/plugins/firebase_auth/ios`) was resolved to 4.2.0, which depends on
      Firebase/Auth (= 10.3.0) was resolved to 10.3.0, which depends on
        FirebaseAuth (~> 10.3.0) was resolved to 10.3.0, which depends on
          GTMSessionFetcher/Core (< 4.0, >= 2.1)

    mobile_scanner (from `.symlinks/plugins/mobile_scanner/ios`) was resolved to 0.0.1, which depends on
      GoogleMLKit/BarcodeScanning (~> 3.2.0) was resolved to 3.2.0, which depends on
        MLKitBarcodeScanning (~> 2.2.0) was resolved to 2.2.0, which depends on

`


问:
How do you connect use pyodbc to connect to MS SQL server when password has escape characters
I'm writing a connection string in Python that connects to a MS SQL Server database.  I am using pyodbc.  Previously, I had used SqlAlchemy and that worked fine.  However, I'd like to NOT use SQLAlchemy because I'd like to keep things simple.

The problem is, when I try to create a connect string and the password has "\" (escape character) in it (mine has two), something happens when the password string is passed from pyodbc to the underlying SQL Server ODBC driver and my login fails.

I've tried all sorts of url encoding and I still can't get it to work.

I'm sure this problem has been solved before, but I can't seem to find any solution that's pertinent to my use-case.

Any help would be appreciated!


问:
Rewrite rules stops working tried flushing on events but didn't worked
i used to do url rewriting on wordpress for this i use a code that works perfectly but after sometime it stops working and give 404 error then i do Permalink setting to save once again and it works; everytime it stops i do premalink save setting and it works but didn't figured out how to solve this issue permanently.

url rewrite code

```<code>//rewrite rules
function custom_add_rewrite_rule(){

    $posts = get_posts( array( 'numberposts' => -1, 'post_type' => 'post') );

    if( $posts ){

        foreach($posts as $post ){

            add_rewrite_rule(
                $post->post_name . '/download/?$',
                'index.php?name=' . $post->post_name . '&post_action=download&post_id=' . $post->ID,
                'top'
            );
        }
    }

}
</code>```

above code is on function.php

and to solve i tried by flushing rules on every post save/update for this i used below code

```<code>//flush reqrite rule on post/update
add_action( 'save_post', 'my_save_post_function' );
function my_save_post_function( $post_id ) {
  $maybe_some_extra_logic = true; // if applicable
  if ( $maybe_some_extra_logic && ! has_action( 'shutdown', 'my_flush_rewrite_rules' ) ) {
    add_action( 'shutdown', 'my_flush_rewrite_rules', 9999 ); // set suitable priority
  }
}

function my_flush_rewrite_rules() {
  flush_rewrite_rules();
}
</code>```

but didn't worked.

Body:
i used to do url rewriting on wordpress for this i use a code that works perfectly but after sometime it stops working and give 404 error then i do Permalink setting to save once again and it works; everytime it stops i do premalink save setting and it works but didn't figured out how to solve this issue permanently.

url rewrite code

//rewrite rules
function custom_add_rewrite_rule(){

    $posts = get_posts( array( 'numberposts' => -1, 'post_type' => 'post') );

    if( $posts ){

        foreach($posts as $post ){

            add_rewrite_rule(
                $post->post_name . '/download/?$',
                'index.php?name=' . $post->post_name . '&post_action=download&post_id=' . $post->ID,
                'top'
            );
        }
    }

}

above code is on function.php

and to solve i tried by flushing rules on every post save/update for this i used below code

//flush reqrite rule on post/update
add_action( 'save_post', 'my_save_post_function' );
function my_save_post_function( $post_id ) {
  $maybe_some_extra_logic = true; // if applicable
  if ( $maybe_some_extra_logic && ! has_action( 'shutdown', 'my_flush_rewrite_rules' ) ) {
    add_action( 'shutdown', 'my_flush_rewrite_rules', 9999 ); // set suitable priority
  }
}

function my_flush_rewrite_rules() {
  flush_rewrite_rules();
}

but didn't worked.


问:
python vtkCutter Original Cell IDs
I am using a vtkCutter to cut an unstructured grid with triangles on. Is there a way to get the original cell Ids that were cut, or even better a mapping between the triangles Ids and original cell Ids? The selector filter has an array vtkOriginalCellIds which would be exactly what I need.</p>
```<code>import vtk

# Create points
points = vtk.vtkPoints()
points.SetNumberOfPoints(8)
points.SetPoint(0,[-.5,-.5,-.5])
points.SetPoint(1,[ .5,-.5,-.5])
points.SetPoint(2,[ .5, .5,-.5])
points.SetPoint(3,[-.5, .5,-.5])
points.SetPoint(4,[-.5,-.5, .5])
points.SetPoint(5,[ .5,-.5, .5])
points.SetPoint(6,[ .5, .5, .5])
points.SetPoint(7,[-.5, .5, .5])

# Create Unstructured Grid and add Cells
ugrid = vtk.vtkUnstructuredGrid()
if vtk.VTK_MAJOR_VERSION <= 9:
    ugrid.Allocate(2)
else:
    ugrid.AllocateExact(2,8)
ugrid.InsertNextCell(vtk.VTK_QUAD,4,[4,5,6,7])
ugrid.InsertNextCell(vtk.VTK_HEXAHEDRON,8,[0,1,2,3,4,5,6,7])
ugrid.SetPoints(points)

# Set up a cutter and cut the grid
cutter=vtk.vtkCutter()
cutter.SetCutFunction(plane)
cutter.SetInputData(ugrid)
cutter.GenerateTrianglesOn()
cutter.Update()

# Get map of cut cell ids and original ids?
cell_id_map = cutter.GetOutput().GetCellData().GetArray('vtkOriginalCellIds')

</code>```

Title: python vtkCutter Original Cell IDs

Body:
I am using a vtkCutter to cut an unstructured grid with triangles on. Is there a way to get the original cell Ids that were cut, or even better a mapping between the triangles Ids and original cell Ids? The selector filter has an array vtkOriginalCellIds which would be exactly what I need.

import vtk

# Create points
points = vtk.vtkPoints()
points.SetNumberOfPoints(8)
points.SetPoint(0,[-.5,-.5,-.5])
points.SetPoint(1,[ .5,-.5,-.5])
points.SetPoint(2,[ .5, .5,-.5])
points.SetPoint(3,[-.5, .5,-.5])
points.SetPoint(4,[-.5,-.5, .5])
points.SetPoint(5,[ .5,-.5, .5])
points.SetPoint(6,[ .5, .5, .5])
points.SetPoint(7,[-.5, .5, .5])

# Create Unstructured Grid and add Cells
ugrid = vtk.vtkUnstructuredGrid()
if vtk.VTK_MAJOR_VERSION <= 9:
    ugrid.Allocate(2)
else:
    ugrid.AllocateExact(2,8)
ugrid.InsertNextCell(vtk.VTK_QUAD,4,[4,5,6,7])
ugrid.InsertNextCell(vtk.VTK_HEXAHEDRON,8,[0,1,2,3,4,5,6,7])
ugrid.SetPoints(points)

# Set up a cutter and cut the grid
cutter=vtk.vtkCutter()
cutter.SetCutFunction(plane)
cutter.SetInputData(ugrid)
cutter.GenerateTrianglesOn()
cutter.Update()

# Get map of cut cell ids and original ids?
cell_id_map = cutter.GetOutput().GetCellData().GetArray('vtkOriginalCellIds')


问:
Apache VHost not working but seems to be configured correctly: Mac Os Ventura
The Problem

I've been trying to setup apache on my mac. I installed apache using brew and everything seems to work except when I actually try to navigate the url with my browser.
Anytime I navigate to http://parenting.localhost/ I just get a 404 error. To make things even more odd, if I just go to http://localhost/ (not using the vhost) it still writes the logs to the vhost log files. Clearly something is wrong, I just can't figure it out. Any help would be appreciated.

My Environment

My /usr/local/etc/httpd/extra/httpd-vhosts.conf:

```<code><VirtualHost *:80>
    ServerName parenting.localhost
    ServerAlias parenting.localhost.com

    DocumentRoot "/Users/joshteam/PhpstormProjects/parenting/public"
    <Directory /Users/joshteam/PhpstormProjects/parenting/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog /Users/joshteam/PhpstormProjects/parenting/storage/logs/error.log
    CustomLog /Users/joshteam/PhpstormProjects/parenting/storage/logs/access.log combined
</VirtualHost>
</code>```

My /etc/hosts:

```<code>127.0.0.1       parenting.localhost
127.0.0.1       parenting.localhost.com
</code>```

I ensure the VHOST is enabled currently:

```<code>$ httpd -t -D DUMP_VHOSTS
VirtualHost configuration:
*:80                   parenting.localhost (/usr/local/etc/httpd/extra/httpd-vhosts.conf:24)
</code>```

What I'm Trying To Do
To navigate to http://parenting.localhost/ and for apache to execute the appropriate index.php within the vhost configuration. Instead I get a 404.

Body:
The Problem

I've been trying to setup apache on my mac. I installed apache using brew and everything seems to work except when I actually try to navigate the url with my browser.
Anytime I navigate to http://parenting.localhost/ I just get a 404 error. To make things even more odd, if I just go to http://localhost/ (not using the vhost) it still writes the logs to the vhost log files. Clearly something is wrong, I just can't figure it out. Any help would be appreciated.

My Environment

My /usr/local/etc/httpd/extra/httpd-vhosts.conf:

<VirtualHost *:80>
    ServerName parenting.localhost
    ServerAlias parenting.localhost.com

    DocumentRoot "/Users/joshteam/PhpstormProjects/parenting/public"
    <Directory /Users/joshteam/PhpstormProjects/parenting/public>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog /Users/joshteam/PhpstormProjects/parenting/storage/logs/error.log
    CustomLog /Users/joshteam/PhpstormProjects/parenting/storage/logs/access.log combined
</VirtualHost>

My /etc/hosts:

127.0.0.1       parenting.localhost
127.0.0.1       parenting.localhost.com

I ensure the VHOST is enabled currently:

$ httpd -t -D DUMP_VHOSTS
VirtualHost configuration:
*:80                   parenting.localhost (/usr/local/etc/httpd/extra/httpd-vhosts.conf:24)

What I'm Trying To Do
To navigate to http://parenting.localhost/ and for apache to execute the appropriate index.php within the vhost configuration. Instead I get a 404.


问:
Geoserver Layer Preview downloads a WMS file instead of showing preview in OpenLayers - Running Geoserver 2.21
Using Kubernetes with the repository: docker.io/kartoza/geoserver.
Geoserver 2.21

Layer Previews not working for a majority for layer previews - I get a downloaded WMS file and a java.lang.NullPointerException  error

I have been trying to view layer previews which should have given me a preview of a layer but instead I get a blank page and a downloaded was file containing the following:-

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE ServiceExceptionReport SYSTEM "https://geoserver.staging.rcdo.co.uk/geoserver/schemas/wms/1.1.1/WMS_exception_1_1_1.dtd"> <ServiceExceptionReport version="1.1.1" >   <ServiceException>
      java.lang.NullPointerException
</ServiceException></ServiceExceptionReport>
</code>```

Body:
Using Kubernetes with the repository: docker.io/kartoza/geoserver.
Geoserver 2.21

Layer Previews not working for a majority for layer previews - I get a downloaded WMS file and a java.lang.NullPointerException  error

I have been trying to view layer previews which should have given me a preview of a layer but instead I get a blank page and a downloaded was file containing the following:-

<?xml version="1.0" encoding="UTF-8" standalone="no"?><!DOCTYPE ServiceExceptionReport SYSTEM "https://geoserver.staging.rcdo.co.uk/geoserver/schemas/wms/1.1.1/WMS_exception_1_1_1.dtd"> <ServiceExceptionReport version="1.1.1" >   <ServiceException>
      java.lang.NullPointerException
</ServiceException></ServiceExceptionReport>


问:
cbis-ddsm files names don't match the names in the train/test csv files
I've downloaded the CBIS-DDSM data from the cancer imaging archive and its descriptive train/test csv files. However, I noticed that the names of the dcm files do not match the ones found in the csv files.
For example, a file named Mass-Training_P_00001_LEFT_CC/../1-1.dcm is found as Training_P_00001_LEFT_CC/../000000.dcm in the descriptive csv.

For those who have used this dataset before, how did you handle this?

Thank you for your help.


问:
Blank Screen when running npm build and only error is 'Uncaught TypeError: Expected parameter accessToken'
This is my first time using the Contentful API to create a blog. When I run it in my local environment with npm start, it works and looks great. When I try to run this through Vercel, Netlify, or Github Pages, there is only a blank screen with this error message in console.
error message in console

I have tried reworking my client.js file, adding in the environment variables from my .env.development file to the host sites, changing the homepage to numerous things, everything has no effect on the blank screen of my build. Here are screenshots of my client.js:

```<code>import * as contentful from "contentful"

export const client = contentful.createClient({
    space: process.env.REACT_APP_SPACE_ID,
    accessToken: process.env.REACT_APP_ACCESS_TOKEN
})
</code>```

.env.development code:

```<code>REACT_APP_SPACE_ID=************
REACT_APP_ACCESS_TOKEN=*************************
</code>```

and my package.json:

```<code>{
  "homepage": ".",
  "name": "chasing-ravens",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@chakra-ui/icons": "^2.0.13",
    "@chakra-ui/react": "^2.4.2",
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "contentful": "^9.2.14",
    "dompurify": "^2.4.1",
    "framer-motion": "^6.5.1",
    "marked": "^4.2.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.4.4",
    "react-scripts": "5.0.1",
    "sass": "^1.56.2",
    "swiper": "^8.4.5",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "gh-pages": "^4.0.0"
  }
}

</code>```

Any help would be so appreciated, I feel like I am going in circles here.

Body:
This is my first time using the Contentful API to create a blog. When I run it in my local environment with npm start, it works and looks great. When I try to run this through Vercel, Netlify, or Github Pages, there is only a blank screen with this error message in console.
error message in console

I have tried reworking my client.js file, adding in the environment variables from my .env.development file to the host sites, changing the homepage to numerous things, everything has no effect on the blank screen of my build. Here are screenshots of my client.js:

import * as contentful from "contentful"

export const client = contentful.createClient({
    space: process.env.REACT_APP_SPACE_ID,
    accessToken: process.env.REACT_APP_ACCESS_TOKEN
})

.env.development code:

REACT_APP_SPACE_ID=************
REACT_APP_ACCESS_TOKEN=*************************

and my package.json:

{
  "homepage": ".",
  "name": "chasing-ravens",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@chakra-ui/icons": "^2.0.13",
    "@chakra-ui/react": "^2.4.2",
    "@emotion/react": "^11.10.5",
    "@emotion/styled": "^11.10.5",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "contentful": "^9.2.14",
    "dompurify": "^2.4.1",
    "framer-motion": "^6.5.1",
    "marked": "^4.2.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.4.4",
    "react-scripts": "5.0.1",
    "sass": "^1.56.2",
    "swiper": "^8.4.5",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "gh-pages": "^4.0.0"
  }
}

Any help would be so appreciated, I feel like I am going in circles here.


问:
API Gateway generated SDK issue: "No such host is known"
I generated a Java SDK via the API Gateway and created a Maven project with this as a dependency.

When I run the app to hit one of the APIs it throws the following error:

`

```<code>Exception in thread "main" com.amazonaws.SdkClientException: Unable to execute HTTP request: No such host is known (******.execute-api.eu-west-1.amazonaws.com)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleRetryableException(AmazonHttpClient.java:1189)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1135)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:784)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:752)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:726)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:686)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:668)
    at com.amazonaws.client.ClientHandlerImpl.doInvoke(ClientHandlerImpl.java:204)
    at com.amazonaws.client.ClientHandlerImpl.invoke(ClientHandlerImpl.java:185)
    at com.amazonaws.client.ClientHandlerImpl.execute(ClientHandlerImpl.java:93)
    at com.amazonaws.opensdk.protect.client.SdkClientHandler.execute(SdkClientHandler.java:42)
    at com.pps.configuration.api.ConfigurationClient.getAllProductClasses(ConfigurationClient.java:103)
    at connection.main(MainClass.java:25)
Caused by: java.net.UnknownHostException: No such host is known (******.execute-api.eu-west-1.amazonaws.com)
    at java.base/java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
    at java.base/java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:929)
    at java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1515)
    at java.base/java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:848)
    at java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1505)
    at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1364)
    at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1298)
    at com.amazonaws.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:27)
    at com.amazonaws.http.DelegatingDnsResolver.resolve(DelegatingDnsResolver.java:38)
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:112)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:374)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.amazonaws.http.conn.ClientConnectionManagerFactory$Handler.invoke(ClientConnectionManagerFactory.java:76)
    at com.amazonaws.http.conn.$Proxy3.connect(Unknown Source)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at com.amazonaws.http.apache.client.impl.SdkHttpClient.execute(SdkHttpClient.java:72)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1311)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1127)
</code>```

`

I've tried rebuilding the SDK, but still no fix.

Body:
I generated a Java SDK via the API Gateway and created a Maven project with this as a dependency.

When I run the app to hit one of the APIs it throws the following error:

`

Exception in thread "main" com.amazonaws.SdkClientException: Unable to execute HTTP request: No such host is known (******.execute-api.eu-west-1.amazonaws.com)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleRetryableException(AmazonHttpClient.java:1189)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1135)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:784)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:752)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:726)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:686)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:668)
    at com.amazonaws.client.ClientHandlerImpl.doInvoke(ClientHandlerImpl.java:204)
    at com.amazonaws.client.ClientHandlerImpl.invoke(ClientHandlerImpl.java:185)
    at com.amazonaws.client.ClientHandlerImpl.execute(ClientHandlerImpl.java:93)
    at com.amazonaws.opensdk.protect.client.SdkClientHandler.execute(SdkClientHandler.java:42)
    at com.pps.configuration.api.ConfigurationClient.getAllProductClasses(ConfigurationClient.java:103)
    at connection.main(MainClass.java:25)
Caused by: java.net.UnknownHostException: No such host is known (******.execute-api.eu-west-1.amazonaws.com)
    at java.base/java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
    at java.base/java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:929)
    at java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1515)
    at java.base/java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:848)
    at java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1505)
    at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1364)
    at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1298)
    at com.amazonaws.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:27)
    at com.amazonaws.http.DelegatingDnsResolver.resolve(DelegatingDnsResolver.java:38)
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:112)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:374)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at com.amazonaws.http.conn.ClientConnectionManagerFactory$Handler.invoke(ClientConnectionManagerFactory.java:76)
    at com.amazonaws.http.conn.$Proxy3.connect(Unknown Source)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at com.amazonaws.http.apache.client.impl.SdkHttpClient.execute(SdkHttpClient.java:72)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1311)
    at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1127)

`

I've tried rebuilding the SDK, but still no fix.


问:
React Native Socket.IO-client only connecting to server in one location
I am using Socket.io for realtime with react native and it is not connecting to localhost.
My api works as it connects in one point and I am able to console log and see the proper response.

```<code>
import io from "socket.io-client"

export const socket = io.connect('https://urlgeneratedbylocaltunnel')

</code>```

This is how I am connecting in a util component and then I am importing this in other components as so.

```<code>import {socket} from '../../util/socket'

</code>```

in one component I am able to console log the message using the following code
`

```<code>useEffect(()=>{
  console.log(socket)
  socket.on('some_event', message=> {

     console.log(message)

  })
},[socket])

In the other component I am using the same exact code except when I console.log(socket) it says  connected:false and in the component where I can see the code connected is true. What could be a possible reason for this that it is connecting in one component but not the other?

I console.log(socket) in one component and it says connected:true but in the other it says connected:false and I am unable to listen to the events.
</code>```

Body:
I am using Socket.io for realtime with react native and it is not connecting to localhost.
My api works as it connects in one point and I am able to console log and see the proper response.

import io from "socket.io-client"

export const socket = io.connect('https://urlgeneratedbylocaltunnel')

This is how I am connecting in a util component and then I am importing this in other components as so.

import {socket} from '../../util/socket'

in one component I am able to console log the message using the following code
`

useEffect(()=>{
  console.log(socket)
  socket.on('some_event', message=> {

     console.log(message)

  })
},[socket])

In the other component I am using the same exact code except when I console.log(socket) it says  connected:false and in the component where I can see the code connected is true. What could be a possible reason for this that it is connecting in one component but not the other?

I console.log(socket) in one component and it says connected:true but in the other it says connected:false and I am unable to listen to the events.


问:
Adding child elements to a HorizontalStackLayout causes "A cycle occurred while laying out the GUI" error
Im following allong the Youtube Series "Beyond Monkey" and on part 8, my XAML wont render at runtime (project compiles fine), hitting an error:

A cycle occurred while laying out the GUI.

Ive literally copied and pasted the code from the github repo to check its correct, but it still doesn't like it. I've pulled out bits of XAML everywhere until it builds and it seems it doesn't like the icon XAML:

```<code> <!-- Likes -->
 <HorizontalStackLayout
 Spacing="6"
 VerticalOptions="Center">

   <Image
    Source="imglike.png"
    WidthRequest="16"
    HeightRequest="16" />

    <Label
    Style="{StaticResource RegularLightText14}"
    Text="{Binding TheVideo.LikesCount, Mode=OneWay}" />

 </HorizontalStackLayout>
</code>```

If I strip the image and label out of the Horizontal Stack Layout it works, but as soon as I try to add any content to them, app.g.i.cs blows up with an unhandled exception

A cycle occurred while laying out the GUI.

Layout cycle detected.  Layout could not complete.

The XAML looks ok to me and obviously works for the author, so I'm guessing is something unrelated that a XAML n00b like myself doesn't understand.

Anyone have any ideas?

Thanks

Body:
Im following allong the Youtube Series "Beyond Monkey" and on part 8, my XAML wont render at runtime (project compiles fine), hitting an error:

A cycle occurred while laying out the GUI.

Ive literally copied and pasted the code from the github repo to check its correct, but it still doesn't like it. I've pulled out bits of XAML everywhere until it builds and it seems it doesn't like the icon XAML:

 <HorizontalStackLayout
 Spacing="6"
 VerticalOptions="Center">

   <Image
    Source="imglike.png"
    WidthRequest="16"
    HeightRequest="16" />

 </HorizontalStackLayout>

If I strip the image and label out of the Horizontal Stack Layout it works, but as soon as I try to add any content to them, app.g.i.cs blows up with an unhandled exception

A cycle occurred while laying out the GUI.

Layout cycle detected.  Layout could not complete.

The XAML looks ok to me and obviously works for the author, so I'm guessing is something unrelated that a XAML n00b like myself doesn't understand.

Anyone have any ideas?

Thanks


问:
Git adds my all folders except client folder
I have a node.js app and an additional client folder for front end.
Unfortunately, I'm unable to add my client subfolders to my repositories(.gitignore checked). Probably because the client folder has its own package.json file. How can I add the subfiles of the client folder? My folder structure as follows;

enter image description here


问:
How to just render a Vue template in a Docker container?
I want to use a Docker multi-stage build with Vue.js in the first stage and a Web server in the second.

Starting with the official node image from Docker Hub, I'm trying to:

either install the relevant packages (vue and vuetify@3.0.4 which I need for v-data-table; I'm not sure if I should install them globally or not, or if it even makes much difference in this use case) and run node render.mjs with render.mjs written by me and containing imports of necessary stuff from those packages,

or go the Vue CLI way, create a Vue project and see what's possible from there (with the obstacle that it's designed to run interactively – in npm init vue -y the -y is apparently ignored; people filed an issue and came up with some shenanigans in the comments but I'm not sure it's the best solution).

I just want one or a couple of templates (or vnodes, or whatever ends up working) to be rendered in the first stage, copy the results (HTML documents) to the second stage and have no Vue.js running on containers created from the final image (one with the Web server). (I'm fine with some scripts being required on the client side. If I'm not mistaken, that's how Vuetify's data-table can work, load initial data from a totally separate database and provide CRUD functionality.)

What should I put in my Dockerfile (and possibly in render.mjs) for the first stage?


问:
has anyone determined how to make excel show a significant digit if it's a zero
Excel truncates my whole integer data and does not show the tenths place (i.e., shows 4 instead of 4.0). I don't want to increase the decimal place as not all data should show the x.0 place.

The round function does not work - won't round 4 to 4.0.
Excel help says to use this formula: =ROUND(B18,2-LEN(INT(B18))), but doesn't work if ending digit is 0.


问:
How to use TASM compiler in CLion C++
There is a task in which I need to use code from .asm file in CLion C++ with TASM compiler. What I need to write in cmake file to complete the task?

cmake:

```<code>cmake_minimum_required(VERSION 3.23)
project(untitled1)
enable_language(C ASM)
set(CMAKE_CXX_STANDARD 14)

add_executable(untitled1 main.cpp)

</code>```

Title: How to use TASM compiler in CLion C++

Body:
There is a task in which I need to use code from .asm file in CLion C++ with TASM compiler. What I need to write in cmake file to complete the task?

cmake:

cmake_minimum_required(VERSION 3.23)
project(untitled1)
enable_language(C ASM)
set(CMAKE_CXX_STANDARD 14)

add_executable(untitled1 main.cpp)


问:
Command injection possible with subprocess shell=False?
I have an API which, long story short, runs a custom command on a remote machine (I'll call it custom_command). The app is run via subprocess with shell=False. The command is run and arguments may be programmatically appended to it based on input to an API. IE:

End-user runs curl https://rest-api-address -d {"add_do_this": true}

Server runs subprocess.Popen(["custom_command", "--do-this"], shell=False)

The end users have asked for the ability to append custom arguments when invoking the command by entering a raw string, ie:

curl https://rest-api-address -d {"add_do_this": true, "custom_args": "--custom-arg1 val1 --custom-arg2 val2"}

Server runs subprocess.Popen(["custom_command", "--do-this", "--custom-arg1", "val1", "--custom-arg2", "val2"], shell=False)

I'm reluctant to allow them to enter a raw string b/c of command injection fears, but if I take the string, shlex.split it, and extend the original command, is there still a risk of injection if shell=False? Or any other security risk? The documentation seems to imply no and I haven't been able to create one in my testing, but something about this feels risky, and I'm not sure if I'm being too paranoid.

https://rest-api-address -d {"add_do_this": true, "custom_args": "--custom-arg1 val1;echo 'HAHA' --custom-arg2 val2"}

Did not cause injection


问:
Yolo V5 counting objects that trespass two lines
I'm self learning python programmer with beginning/intermediate knowledge. I'm trying to write a code to identify the 'holes' in a strawberry field and I`m using the yolov5 on a custom dataset.
I tried to make a code to identify the object that trespass two lines and count it.

For example, is the first line doesn`t identify the object the second line could identify and update the counter. If the first line identify the object the second line couldn't identify and update the counter. I'm using the condition if/elif but sometimes the two lines identify the same object and update de counter with with the same object identified.

This is my code:

```<code>import numpy as np
import torch
import cv2

cap=cv2.VideoCapture("C:/Users/re.herrigfurlane/Desktop/Yolo V5/holes.mp4")

path='C:/Users/re.herrigfurlane/Desktop/Yolo V5/best_holes.pt'

model = torch.hub.load('C:/Users/re.herrigfurlane/Desktop/Yolo V5', 'custom', path, source='local', device='cpu')

b=model.names[0] = 'Hole'

size=640

count=0
counter=0

color=(0,0,255)

cy1=300
cy2=180
offset=7
while True:
    ret,img=cap.read()

    count += 1
    if count % 0.5 != 0: #4 is the number of frames that will be skip
        continue
    img=cv2.resize(img,(800,600))
    cv2.line(img,(0,cy1),(799,cy1),(0,0,255),3) # 79 is the pixel located on X axis of the video
    cv2.line(img,(0,cy2),(799,cy2),(0,0,255),3) # 79 is the pixel located on X axis of the video

    results=model(img,size)
    a=results.pandas().xyxy[0] #Showing the results of the identification
    #print(a) #Print the results of the identification as a table
    for index,row in results.pandas().xyxy[0].iterrows():
        x1=int(row['xmin'])
        y1=int(row['ymin'])
        x2=int(row['xmax'])
        y2=int(row['ymax'])
        d=(row['class'])

        if d==0: # your class
           cv2.rectangle(img,(x1,y1),(x2,y2),(255,0,0),2)
           rectx1,recty1=((x1+x2)/2, (y1+y2)/2)
           rectcenter=int(rectx1),int(recty1)
           cx=rectcenter[0]
           cy=rectcenter[1]
           cv2.circle(img,(cx,cy),3,(0,0,255),-1)

        #cv2.putText(img,str(b),(x1,y1),cv2.FONT_HERSHEY_PLAIN,2,(255,0,0),2)

           if cy<(cy2+offset) and cy>(cy2-offset):
                counter+=1
                cv2.line(img,(0,cy2),(799,cy2),(255,0,255),3)
                print(counter)
                cv2.putText(img,str(counter),(x2,y2),cv2.FONT_HERSHEY_PLAIN,2,(0,255,255),2)

           elif cy<(cy1+offset) and cy>(cy1-offset):
                cv2.line(img,(0,cy1),(799,cy1),(255,0,255),3)
                counter+=1
                print(counter)
                cv2.putText(img,str(counter),(x2,y2),cv2.FONT_HERSHEY_PLAIN,2,(0,255,255),2)

    cv2.imshow("IMG",img)
    if cv2.waitKey(1)&0xFF==27:
        break
cap.release()
cv2.destroyAllWindows()
</code>```

The cv1 line is the bottom and cv2 is the upper

I'd like if possible a help to solve this question, I don't have a lot of knowledge using python programming, I tried to find an answer in forums and youtube without success.

Body:
I'm self learning python programmer with beginning/intermediate knowledge. I'm trying to write a code to identify the 'holes' in a strawberry field and I`m using the yolov5 on a custom dataset.
I tried to make a code to identify the object that trespass two lines and count it.

For example, is the first line doesn`t identify the object the second line could identify and update the counter. If the first line identify the object the second line couldn't identify and update the counter. I'm using the condition if/elif but sometimes the two lines identify the same object and update de counter with with the same object identified.

This is my code:

import numpy as np
import torch
import cv2

cap=cv2.VideoCapture("C:/Users/re.herrigfurlane/Desktop/Yolo V5/holes.mp4")

path='C:/Users/re.herrigfurlane/Desktop/Yolo V5/best_holes.pt'

model = torch.hub.load('C:/Users/re.herrigfurlane/Desktop/Yolo V5', 'custom', path, source='local', device='cpu')

b=model.names[0] = 'Hole'

size=640

count=0
counter=0

color=(0,0,255)

cy1=300
cy2=180
offset=7
while True:
    ret,img=cap.read()

    count += 1
    if count % 0.5 != 0: #4 is the number of frames that will be skip
        continue
    img=cv2.resize(img,(800,600))
    cv2.line(img,(0,cy1),(799,cy1),(0,0,255),3) # 79 is the pixel located on X axis of the video
    cv2.line(img,(0,cy2),(799,cy2),(0,0,255),3) # 79 is the pixel located on X axis of the video

    results=model(img,size)
    a=results.pandas().xyxy[0] #Showing the results of the identification
    #print(a) #Print the results of the identification as a table
    for index,row in results.pandas().xyxy[0].iterrows():
        x1=int(row['xmin'])
        y1=int(row['ymin'])
        x2=int(row['xmax'])
        y2=int(row['ymax'])
        d=(row['class'])

        if d==0: # your class
           cv2.rectangle(img,(x1,y1),(x2,y2),(255,0,0),2)
           rectx1,recty1=((x1+x2)/2, (y1+y2)/2)
           rectcenter=int(rectx1),int(recty1)
           cx=rectcenter[0]
           cy=rectcenter[1]
           cv2.circle(img,(cx,cy),3,(0,0,255),-1)

        #cv2.putText(img,str(b),(x1,y1),cv2.FONT_HERSHEY_PLAIN,2,(255,0,0),2)

           if cy<(cy2+offset) and cy>(cy2-offset):
                counter+=1
                cv2.line(img,(0,cy2),(799,cy2),(255,0,255),3)
                print(counter)
                cv2.putText(img,str(counter),(x2,y2),cv2.FONT_HERSHEY_PLAIN,2,(0,255,255),2)

           elif cy<(cy1+offset) and cy>(cy1-offset):
                cv2.line(img,(0,cy1),(799,cy1),(255,0,255),3)
                counter+=1
                print(counter)
                cv2.putText(img,str(counter),(x2,y2),cv2.FONT_HERSHEY_PLAIN,2,(0,255,255),2)

    cv2.imshow("IMG",img)
    if cv2.waitKey(1)&0xFF==27:
        break
cap.release()
cv2.destroyAllWindows()

The cv1 line is the bottom and cv2 is the upper

I'd like if possible a help to solve this question, I don't have a lot of knowledge using python programming, I tried to find an answer in forums and youtube without success.


问:
Failed to retrieve data from /webhdfs/v1/?op=LISTSTATUS: Server Error
```<code>vijay@ubuntu:~$ start-all.sh
WARNING: Attempting to start all Apache Hadoop daemons as vijay in 10 seconds.
WARNING: This is not a recommended production deployment configuration.
WARNING: Use CTRL-C to abort.
Starting namenodes on [localhost]
localhost: namenode is running as process 22733.  Stop it first and ensure /tmp/hadoop-vijay-namenode.pid file is empty before retry.
Starting datanodes
localhost: datanode is running as process 22866.  Stop it first and ensure /tmp/hadoop-vijay-datanode.pid file is empty before retry.
Starting secondary namenodes [ubuntu]
ubuntu: secondarynamenode is running as process 23072.  Stop it first and ensure /tmp/hadoop-vijay-secondarynamenode.pid file is empty before retry.
Starting resourcemanager
Starting nodemanagers
vijay@ubuntu:~$ jps
23072 SecondaryNameNode
22866 DataNode
22733 NameNode
24447 Jps
</code>```

enter image description here

I am facing hadoop web console error
Currently installed java version "19.0.1" 2022-10-18 and Hadoop 3.3.4

Body:
vijay@ubuntu:~$ start-all.sh
WARNING: Attempting to start all Apache Hadoop daemons as vijay in 10 seconds.
WARNING: This is not a recommended production deployment configuration.
WARNING: Use CTRL-C to abort.
Starting namenodes on [localhost]
localhost: namenode is running as process 22733.  Stop it first and ensure /tmp/hadoop-vijay-namenode.pid file is empty before retry.
Starting datanodes
localhost: datanode is running as process 22866.  Stop it first and ensure /tmp/hadoop-vijay-datanode.pid file is empty before retry.
Starting secondary namenodes [ubuntu]
ubuntu: secondarynamenode is running as process 23072.  Stop it first and ensure /tmp/hadoop-vijay-secondarynamenode.pid file is empty before retry.
Starting resourcemanager
Starting nodemanagers
vijay@ubuntu:~$ jps
23072 SecondaryNameNode
22866 DataNode
22733 NameNode
24447 Jps

enter image description here

I am facing hadoop web console error
Currently installed java version "19.0.1" 2022-10-18 and Hadoop 3.3.4


问:
Flutter http.dart get request to Infura Ipfs API does not download the files in the output directory
I have to download the files from ipfs inside a temporary Directory and load that files from that.
I'm using this one: https://docs.infura.io/infura/networks/ipfs/http-api-methods/get

and i referred to the param: output [Optional] - The path where the output should be stored.

```<code>Future<int> downloadItemIPFS(String hash,String localFolder) async {
  String username = FlutterConfig.get('INFURA_PROJECT_ID');
  String password = FlutterConfig.get('INFURA_API_SECRET');
  String basicAuth = 'Basic ${base64.encode(utf8.encode("$username:$password"))}';
  String tmpPath = await temporaryDirectoryPath;
  Directory dir = await Directory("$tmpPath/$localFolder").create();
  var url = Uri.https('ipfs.infura.io:5001','/api/v0/get',{'arg':hash ,'output': dir.path});
  var request = http.MultipartRequest("POST", url);
  request.headers['Authorization'] = basicAuth;
  var response = await request.send();
  var result = await http.Response.fromStream(response);
  return result.statusCode;
}

Future<List<FileSystemEntity>> getDownloadedFiles(String folder) async {
  String tmpPath = await temporaryDirectoryPath;
  Directory dir = Directory("$tmpPath/$folder");
  List<FileSystemEntity> out = dir.listSync();
  return out;
}
</code>```

the response returns 200 but the dyrectory seems empty

Edited code

```<code>Future<int> downloadItemIPFS(String hash,String localFolder) async {
  String username = FlutterConfig.get('INFURA_PROJECT_ID');
  String password = FlutterConfig.get('INFURA_API_SECRET');
  String basicAuth = 'Basic ${base64.encode(utf8.encode("$username:$password"))}';
  String tmpPath = await temporaryDirectoryPath;
  Directory('$tmpPath/$localFolder').create();
  var list = List<int>.generate(100, (i) => i)..shuffle();
  List<int> names = list.take(5).toList();
  String name = '';
  for (int i = 0; i<names.length; i++) {
    name += names[i].toString();
  }
  print("generated file named: $name");
  var url = Uri.https('ipfs.infura.io:5001','/api/v0/get',{'arg':hash,'output': '$tmpPath/$localFolder'});
  Response response = await http.post(url, headers: {HttpHeaders.authorizationHeader: basicAuth},);
  print("Body content: ${response.body}");
  await File("$tmpPath/$localFolder/$name.txt").writeAsBytes(response.bodyBytes);
  return response.statusCode;
}

Future<List<FileSystemEntity>> getDownloadedFiles(String folder) async {
  String tmpPath = await temporaryDirectoryPath;
  Directory dir = Directory("$tmpPath/$folder/");
  final List<FileSystemEntity> out = await dir.list().toList();
  print("sono dentro getDownloadedFiles in helpefunctions.dart OUT: ${out.length}");
  return out;
}
</code>```

response format img

Body:
I have to download the files from ipfs inside a temporary Directory and load that files from that.
I'm using this one: https://docs.infura.io/infura/networks/ipfs/http-api-methods/get

and i referred to the param: output [Optional] - The path where the output should be stored.

Future<int> downloadItemIPFS(String hash,String localFolder) async {
  String username = FlutterConfig.get('INFURA_PROJECT_ID');
  String password = FlutterConfig.get('INFURA_API_SECRET');
  String basicAuth = 'Basic ${base64.encode(utf8.encode("$username:$password"))}';
  String tmpPath = await temporaryDirectoryPath;
  Directory dir = await Directory("$tmpPath/$localFolder").create();
  var url = Uri.https('ipfs.infura.io:5001','/api/v0/get',{'arg':hash ,'output': dir.path});
  var request = http.MultipartRequest("POST", url);
  request.headers['Authorization'] = basicAuth;
  var response = await request.send();
  var result = await http.Response.fromStream(response);
  return result.statusCode;
}

Future<List<FileSystemEntity>> getDownloadedFiles(String folder) async {
  String tmpPath = await temporaryDirectoryPath;
  Directory dir = Directory("$tmpPath/$folder");
  List<FileSystemEntity> out = dir.listSync();
  return out;
}

the response returns 200 but the dyrectory seems empty

Edited code

Future<int> downloadItemIPFS(String hash,String localFolder) async {
  String username = FlutterConfig.get('INFURA_PROJECT_ID');
  String password = FlutterConfig.get('INFURA_API_SECRET');
  String basicAuth = 'Basic ${base64.encode(utf8.encode("$username:$password"))}';
  String tmpPath = await temporaryDirectoryPath;
  Directory('$tmpPath/$localFolder').create();
  var list = List<int>.generate(100, (i) => i)..shuffle();
  List<int> names = list.take(5).toList();
  String name = '';
  for (int i = 0; i<names.length; i++) {
    name += names[i].toString();
  }
  print("generated file named: $name");
  var url = Uri.https('ipfs.infura.io:5001','/api/v0/get',{'arg':hash,'output': '$tmpPath/$localFolder'});
  Response response = await http.post(url, headers: {HttpHeaders.authorizationHeader: basicAuth},);
  print("Body content: ${response.body}");
  await File("$tmpPath/$localFolder/$name.txt").writeAsBytes(response.bodyBytes);
  return response.statusCode;
}

Future<List<FileSystemEntity>> getDownloadedFiles(String folder) async {
  String tmpPath = await temporaryDirectoryPath;
  Directory dir = Directory("$tmpPath/$folder/");
  final List<FileSystemEntity> out = await dir.list().toList();
  print("sono dentro getDownloadedFiles in helpefunctions.dart OUT: ${out.length}");
  return out;
}

response format img


问:
Avoid deadlock on Firebird
I would like to avoid DeadLock issue in code. I read the way is to use FOR UPDATE WITH LOCK also FbTransactionBehavior.Wait. But my second transaction, despite it is waiting for the first one to finish, always dies by DeadLock.

I wrote a very simple test to illustrate my issue, I pasted the test here below, easier than trying to explain with words (I guess)

The goal is to complete both transactions. The test result is a bit bizarre, the second transaction waits until the first one finishes but also dies. I expect both transactions completes (if it is possible)

tx1
tx2
Comments

tx starts
_
_

_
tx starts
_

Read id=6
_
_

Update id=6
_
_

_
Read id=6
<- tx2 Locked, it's ok, waiting for commit

Commit
_
<- tx2 unlocked

_
_
<- tx2 deadlock :(

using FirebirdSql.Data.FirebirdClient;

namespace fireb;

public class UnitTest1
{
    [Fact]
    public void Test1()
    {
        // tx 1 starts
        using var connection1 = new FbConnection("database=localhost:demo.fdb;user=sysdba;password=masterkey");
        connection1.Open();
        using var transaction1 = connection1.BeginTransaction(
            new FbTransactionOptions() { TransactionBehavior = FbTransactionBehavior.Wait, WaitTimeout = TimeSpan.FromSeconds(5) });

        // tx 2 starts
        using var connection2 = new FbConnection("database=localhost:demo.fdb;user=sysdba;password=masterkey");
        connection2.Open();
        using var transaction2 = connection2.BeginTransaction(
            new FbTransactionOptions() { TransactionBehavior = FbTransactionBehavior.Wait, WaitTimeout = TimeSpan.FromSeconds(30) });

        // updating on tx1
        using var command_pre1 = new FbCommand("select * from demo where id = 6 FOR UPDATE WITH LOCK;", connection1, transaction1);
        command_pre1.ExecuteReader().Read();
        using var command1 = new FbCommand("update demo set foobar = 'pp1' where id = 6;", connection1, transaction1);
        command1.ExecuteNonQuery();

        // commit in 10''
        Action myCommit = () => {
            transaction1.Commit();
            transaction1.Dispose();
            command_pre1.Dispose();
            command1.Dispose();
            connection1.Close();
            connection1.Dispose();
        };

        var aTimer = new System.Timers.Timer(10000);
        aTimer.Elapsed += (a,b) => myCommit();
        aTimer.AutoReset = false;
        aTimer.Enabled = true;

        // updating tx2
        using var command_pre2 = new FbCommand("select * from demo where id = 6 FOR UPDATE WITH LOCK;", connection2, transaction2);
        command_pre2.ExecuteReader().Read();  // <--- here dies. How to avoid?
        using var command2 = new FbCommand("update demo set foobar = 'pp2' where id = 6;", connection2, transaction2);
        command2.ExecuteNonQuery();

        // Commit tx 2
        transaction2.Commit();

    }

```
<p>This is the error:</p>
<blockquote>
<p>FirebirdSql.Data.FirebirdClient.FbException : deadlock
update conflicts with concurrent update
concurrent transaction number is 67
---- FirebirdSql.Data.Common.IscException : deadlock
update conflicts with concurrent update</p>
</blockquote>
<h5>End of question</h5>
<hr />
<p><strong>If you want to reproduce:</strong></p>
<p>To create the table ...</p>
<pre class="lang-cs prettyprint-override"><code>    // from here just arranging database and data

    public UnitTest1()
    {
        // Just to create database, table and row
        // CreaBd();
        // CreaTaula();
        // InsertData();
    }

    private static void CreaTaula()
    {
        using var connection = new FbConnection("database=localhost:demo.fdb;user=sysdba;password=masterkey");
        connection.Open();
        using var transaction = connection.BeginTransaction(System.Data.IsolationLevel.RepeatableRead);
        using var command = new FbCommand(
            "create table demo (id int primary key, foobar varchar(20) character set utf8); ",
            connection, transaction);
        command.ExecuteNonQuery();
        transaction.Commit();
    }

    private static void InsertData()
    {
        using var connection = new FbConnection("database=localhost:demo.fdb;user=sysdba;password=masterkey");
        connection.Open();
        using var transaction = connection.BeginTransaction(System.Data.IsolationLevel.RepeatableRead);
        using var command = new FbCommand(
            "insert into demo values (6, 'FooBar');",
            connection, transaction);
        command.ExecuteNonQuery();
        transaction.Commit();
    }

    private static void CreaBd()
    {
        FbConnectionStringBuilder builder = new FbConnectionStringBuilder();
        builder.DataSource = "localhost";
        builder.UserID = "sysdba";
        builder.Password = "masterkey";
        builder.Database = "demo.fdb";
        builder.ServerType = FbServerType.Default;

        FbConnection.CreateDatabase(builder.ConnectionString);
    }
}

</code>```

If you want to run firebird in docker

docker run -d \
    --name firebird \
    -p 3050:3050 \
    -e "ISC_PASSWORD=masterkey" \
    -v /Users/dani/tmp/fireb/dockerdb:/databases \
    jacobalberty/firebird
```

Title: Avoid deadlock on Firebird

Body:
I would like to avoid DeadLock issue in code. I read the way is to use FOR UPDATE WITH LOCK also FbTransactionBehavior.Wait. But my second transaction, despite it is waiting for the first one to finish, always dies by DeadLock.

I wrote a very simple test to illustrate my issue, I pasted the test here below, easier than trying to explain with words (I guess)

The goal is to complete both transactions. The test result is a bit bizarre, the second transaction waits until the first one finishes but also dies. I expect both transactions completes (if it is possible)

tx1
tx2
Comments

tx starts
_
_

_
tx starts
_

Read id=6
_
_

Update id=6
_
_

_
Read id=6
<- tx2 Locked, it's ok, waiting for commit

Commit
_
<- tx2 unlocked

_
_
<- tx2 deadlock :(

using FirebirdSql.Data.FirebirdClient;

namespace fireb;

public class UnitTest1
{
    [Fact]
    public void Test1()
    {
        // tx 1 starts
        using var connection1 = new FbConnection("database=localhost:demo.fdb;user=sysdba;password=masterkey");
        connection1.Open();
        using var transaction1 = connection1.BeginTransaction(
            new FbTransactionOptions() { TransactionBehavior = FbTransactionBehavior.Wait, WaitTimeout = TimeSpan.FromSeconds(5) });

        // tx 2 starts
        using var connection2 = new FbConnection("database=localhost:demo.fdb;user=sysdba;password=masterkey");
        connection2.Open();
        using var transaction2 = connection2.BeginTransaction(
            new FbTransactionOptions() { TransactionBehavior = FbTransactionBehavior.Wait, WaitTimeout = TimeSpan.FromSeconds(30) });

        // updating on tx1
        using var command_pre1 = new FbCommand("select * from demo where id = 6 FOR UPDATE WITH LOCK;", connection1, transaction1);
        command_pre1.ExecuteReader().Read();
        using var command1 = new FbCommand("update demo set foobar = 'pp1' where id = 6;", connection1, transaction1);
        command1.ExecuteNonQuery();

        // commit in 10''
        Action myCommit = () => {
            transaction1.Commit();
            transaction1.Dispose();
            command_pre1.Dispose();
            command1.Dispose();
            connection1.Close();
            connection1.Dispose();
        };

        var aTimer = new System.Timers.Timer(10000);
        aTimer.Elapsed += (a,b) => myCommit();
        aTimer.AutoReset = false;
        aTimer.Enabled = true;

        // updating tx2
        using var command_pre2 = new FbCommand("select * from demo where id = 6 FOR UPDATE WITH LOCK;", connection2, transaction2);
        command_pre2.ExecuteReader().Read();  // <--- here dies. How to avoid?
        using var command2 = new FbCommand("update demo set foobar = 'pp2' where id = 6;", connection2, transaction2);
        command2.ExecuteNonQuery();

        // Commit tx 2
        transaction2.Commit();

    }

This is the error:

FirebirdSql.Data.FirebirdClient.FbException : deadlock
update conflicts with concurrent update
concurrent transaction number is 67
---- FirebirdSql.Data.Common.IscException : deadlock
update conflicts with concurrent update

End of question

If you want to reproduce:

To create the table ...

    // from here just arranging database and data

    public UnitTest1()
    {
        // Just to create database, table and row
        // CreaBd();
        // CreaTaula();
        // InsertData();
    }

    private static void CreaTaula()
    {
        using var connection = new FbConnection("database=localhost:demo.fdb;user=sysdba;password=masterkey");
        connection.Open();
        using var transaction = connection.BeginTransaction(System.Data.IsolationLevel.RepeatableRead);
        using var command = new FbCommand(
            "create table demo (id int primary key, foobar varchar(20) character set utf8); ",
            connection, transaction);
        command.ExecuteNonQuery();
        transaction.Commit();
    }

    private static void InsertData()
    {
        using var connection = new FbConnection("database=localhost:demo.fdb;user=sysdba;password=masterkey");
        connection.Open();
        using var transaction = connection.BeginTransaction(System.Data.IsolationLevel.RepeatableRead);
        using var command = new FbCommand(
            "insert into demo values (6, 'FooBar');",
            connection, transaction);
        command.ExecuteNonQuery();
        transaction.Commit();
    }

    private static void CreaBd()
    {
        FbConnectionStringBuilder builder = new FbConnectionStringBuilder();
        builder.DataSource = "localhost";
        builder.UserID = "sysdba";
        builder.Password = "masterkey";
        builder.Database = "demo.fdb";
        builder.ServerType = FbServerType.Default;

        FbConnection.CreateDatabase(builder.ConnectionString);
    }
}

If you want to run firebird in docker

docker run -d \
    --name firebird \
    -p 3050:3050 \
    -e "ISC_PASSWORD=masterkey" \
    -v /Users/dani/tmp/fireb/dockerdb:/databases \
    jacobalberty/firebird


问:
Cannot create a dataframe, importing different tickets from Quandl
I am fairly new with Python. I am trying to create a dataframe to analyse some stocks I have been checking out.
I am using this code to try and iterate over the list of tickers I have to create a unique dataframe with all the entries in the said list.

```<code> tickers = [list of tickers]
data = pd.DataFrame()
for t in tickers:
    mydata = quandl.get('WIKI/'.join(t),start_date = '2017-1-1', end_date= '2022-12-12')
    data[t]= mydata['Adj. Close']

data
</code>```

The code returns a Quandl error saying I have submitted an incorrect dataset code. It is clear to me that the error is in the WIKI/x part of the .get function. But I cannot work around how to iterate using the tickers I have.

Body:
I am fairly new with Python. I am trying to create a dataframe to analyse some stocks I have been checking out.
I am using this code to try and iterate over the list of tickers I have to create a unique dataframe with all the entries in the said list.

 tickers = [list of tickers]
data = pd.DataFrame()
for t in tickers:
    mydata = quandl.get('WIKI/'.join(t),start_date = '2017-1-1', end_date= '2022-12-12')
    data[t]= mydata['Adj. Close']

data

The code returns a Quandl error saying I have submitted an incorrect dataset code. It is clear to me that the error is in the WIKI/x part of the .get function. But I cannot work around how to iterate using the tickers I have.


问:
HttpsURLConnection does not work behind proxy with docker
I'm trying to download file form AWS S3 with Java application on Docker container.

The application works perfectly without Docker but on a docker container i have error : java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407 authenticationrequired"

All tests are done behind the same proxy with authentication

if URL is Amazon S3 and running without container : it work

if URL is not Amazon S3 and running without container : it work

if URL is Amazon S3 and running on docker container : it doesn’t work

if URL is not Amazon S3 and running on docker container : it work

All URLs arereached with WGET from the docker container without problem:

        System.setProperty("https.proxyHost", "host");
        System.setProperty("https.proxyPort", "port");
        System.setProperty("https.proxyUser", "user");
        System.setProperty("https.proxyPassword","password");

        String url = "https://exampl.com/url";
        HttpsURLConnection cnx = (HttpsURLConnection) new URL(url).openConnection();
        InputStream inputStream = cnx.getInputStream();
        OutputStream outputStream = new FileOutputStream("file");

        byte[] buffer = new byte[2048];

        int length;

        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
```

do you have please any idea ?
Thank you

Body:
I'm trying to download file form AWS S3 with Java application on Docker container.

The application works perfectly without Docker but on a docker container i have error : java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407 authenticationrequired"

All tests are done behind the same proxy with authentication

if URL is Amazon S3 and running without container : it work

if URL is not Amazon S3 and running without container : it work

if URL is Amazon S3 and running on docker container : it doesn’t work

if URL is not Amazon S3 and running on docker container : it work

All URLs arereached with WGET from the docker container without problem:

        System.setProperty("https.proxyHost", "host");
        System.setProperty("https.proxyPort", "port");
        System.setProperty("https.proxyUser", "user");
        System.setProperty("https.proxyPassword","password");

        String url = "https://exampl.com/url";
        HttpsURLConnection cnx = (HttpsURLConnection) new URL(url).openConnection();
        InputStream inputStream = cnx.getInputStream();
        OutputStream outputStream = new FileOutputStream("file");

        byte[] buffer = new byte[2048];

        int length;

        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }

do you have please any idea ?
Thank you


问:
Lack of autocompletion
I have the following situation.

This is the example code:

```<code> interface DataOne {
   age: number;
   name: string;
 }

 interface DataTwo {
   email: string;
 }

 type Options<T extends boolean> = T extends true ? DataOne : DataTwo;

 function hasKey<K extends string | number | symbol>(key: K, object: unknown): object is { [_ in K]: unknown } {
  return typeof object === "object" && object !== null && key in object;
}

function useData(props: {data?: []}){

  const isKeyExist = hasKey("age", props.data?.length && props.data[0]);

  const [example, setExample] = useState<Options<typeof isKeyExist>[]>(props.data &&
  props.data.length ? props.data : [])

  let dataAutocomplete: Options<typeof isKeyExist>;

  //Data autocomplete dont have autocompletion
  dataAutocomplete = example[0]
}
</code>```

I check if the property "age" exist on "props.data" with the help of the "hasKey" function which I found and based on the result determined which one of the interfaces to use.

The problem is that when I use "typeof" with the variable "isKeyExist" I dont have any kind of autocompletion when I try to see what properties contains the variable "dataAutocomplete".

But if I use true or false directly inside the "Options type" the code is working correctly.

Can someone explain to me where I'm wrong and what I can improve to work properly without explicitly setting true or false.

Title: Lack of autocompletion

Body:
I have the following situation.

This is the example code:

 interface DataOne {
   age: number;
   name: string;
 }

 interface DataTwo {
   email: string;
 }

 type Options<T extends boolean> = T extends true ? DataOne : DataTwo;

 function hasKey<K extends string | number | symbol>(key: K, object: unknown): object is { [_ in K]: unknown } {
  return typeof object === "object" && object !== null && key in object;
}

function useData(props: {data?: []}){

  const isKeyExist = hasKey("age", props.data?.length && props.data[0]);

  const [example, setExample] = useState<Options<typeof isKeyExist>[]>(props.data &&
  props.data.length ? props.data : [])

  let dataAutocomplete: Options<typeof isKeyExist>;

  //Data autocomplete dont have autocompletion
  dataAutocomplete = example[0]
}

I check if the property "age" exist on "props.data" with the help of the "hasKey" function which I found and based on the result determined which one of the interfaces to use.

The problem is that when I use "typeof" with the variable "isKeyExist" I dont have any kind of autocompletion when I try to see what properties contains the variable "dataAutocomplete".

But if I use true or false directly inside the "Options type" the code is working correctly.

Can someone explain to me where I'm wrong and what I can improve to work properly without explicitly setting true or false.


问:
celery.five module issue in celery 5.2.7 version
below error coming in internal files of "django_celery_beat/managers.py and django_celery_beat/models.py".
`from celery.five import items
ModuleNotFoundError: No module named 'celery.five'

I'm using celery version 5.2.7, django-celery-beat 1.5.0, can anyone please let me know how to proceed?

I can't change the version i'm using as i know it's working fine for celery version <5.x


问:
npm publish looks for package.json at disk root
Current npm version: 8.19.2

Command npm publish --registry "https://some-private-registry.com" running from package home.

Produces the following error:

```<code>npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent                                                                                npm ERR! A complete log of this run can be found in:
npm ERR!     <somewhere>
</code>```

I tried passing current folder as argument, i.e. npm publish "C:\path-to-folder" --registry "https://some-private-registry.com" running from package home, but with no success - the error stays the same. npm prefix correctly returns current folder.

For some reason - which I cannot understand - publish searches for package.json at disk root. Which is also important, npm unpublsh and npm install work without any issue.

Debug log also doesn't provide any sufficient information except above error.

Is there anything I might miss which could be causing the problem?
Thanks!

Body:
Current npm version: 8.19.2

Command npm publish --registry "https://some-private-registry.com" running from package home.

Produces the following error:

npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent                                                                                npm ERR! A complete log of this run can be found in:
npm ERR!     <somewhere>

I tried passing current folder as argument, i.e. npm publish "C:\path-to-folder" --registry "https://some-private-registry.com" running from package home, but with no success - the error stays the same. npm prefix correctly returns current folder.

For some reason - which I cannot understand - publish searches for package.json at disk root. Which is also important, npm unpublsh and npm install work without any issue.

Debug log also doesn't provide any sufficient information except above error.

Is there anything I might miss which could be causing the problem?
Thanks!


问:
Pods file is red
The pods inside the Pods file are red, I tried installing cocoapods and it installed with no problems but the file is still red and I can't run the code. please help I'm new to this

This is a picture of the file

Title: Pods file is red


问:
Why setAttribute() always convert the textContent into textcontent?
Sorry for poor English.
As title, I am trying to make a DOM operation. The goal is the creation of 'good' with a JavaScript function. But always got '

My coding is here:

```<code>    function createDiv(tagname,attributes){//division
        let _div = document.createElement(tagname);
        if(attributes) {

            for (name in attributes){
                console.log(name,attributes[name]);
                _div.setAttribute(name,attributes[name]);
            }
        }
        console.log(_div);
        return _div;
    }

    item[4] = dom.createDiv("div",{id:"item4",textContent:"good"});
</code>```

I hope to get the output as '
' but always get '
'. The difference is the uppercase and lowercase in the attribute 'textContent', that caused missing the 'good' in HTML.

Anyone can point out what's the matter or modify my code, please.

Body:
Sorry for poor English.
As title, I am trying to make a DOM operation. The goal is the creation of 'good' with a JavaScript function. But always got '

My coding is here:

    function createDiv(tagname,attributes){//division
        let _div = document.createElement(tagname);
        if(attributes) {

            for (name in attributes){
                console.log(name,attributes[name]);
                _div.setAttribute(name,attributes[name]);
            }
        }
        console.log(_div);
        return _div;
    }

    item[4] = dom.createDiv("div",{id:"item4",textContent:"good"});

I hope to get the output as '
' but always get '
'. The difference is the uppercase and lowercase in the attribute 'textContent', that caused missing the 'good' in HTML.

Anyone can point out what's the matter or modify my code, please.


问:
WebDriverWait always getting TimeoutException
```<code>WebDriverWait(driver,15).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='usernameInput-input']"))).send_keys("username")
time.sleep(random.uniform(3,5))
WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='password-input']"))).send_keys("password")
time.sleep(random.uniform(3,5))
WebDriverWait(driver,8).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='signIn']/span"))).click()
time.sleep(random.uniform(8,10))
WebDriverWait(driver,12).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='question']"))).text

</code>```

I have this code written where it will automate login process and to help with the website not detecting automation I included random sleep time in between. The problem I am currently running into is that sometimes the code will jump from

WebDriverWait(driver,15).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='usernameInput']"))).send_keys("username")

to

WebDriverWait(driver,12).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='question']"))).text

which shouldn't happen as to get to this element you would first have to click the sign in that will move you onto the next page which has it so python will throw the error TimeoutException

Is there something wrong with my code or should I be using a different kind of Expected Conditions?

Body:
WebDriverWait(driver,15).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='usernameInput-input']"))).send_keys("username")
time.sleep(random.uniform(3,5))
WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='password-input']"))).send_keys("password")
time.sleep(random.uniform(3,5))
WebDriverWait(driver,8).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='signIn']/span"))).click()
time.sleep(random.uniform(8,10))
WebDriverWait(driver,12).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='question']"))).text

I have this code written where it will automate login process and to help with the website not detecting automation I included random sleep time in between. The problem I am currently running into is that sometimes the code will jump from

WebDriverWait(driver,15).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='usernameInput']"))).send_keys("username")

to

WebDriverWait(driver,12).until(EC.visibility_of_element_located((By.XPATH, "//*[@id='question']"))).text

which shouldn't happen as to get to this element you would first have to click the sign in that will move you onto the next page which has it so python will throw the error TimeoutException

Is there something wrong with my code or should I be using a different kind of Expected Conditions?


问:
Olingo V2 - Referential Constraint check on entities' properties
I am using Olingo 2.0.11 on top of Hibernate. I've built relationship between entities and the navigation property works fine by define the @OneToOne annotation to entities' properties:

```<code>public class MetaClass {
@OneToOne(mappedBy = "metaClassEntity", cascade = {CascadeType.MERGE, CascadeType.REFRESH}, optional = false)
private MetaClassReport metaClassReport;
}

public class MetaClassReport {
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = MetaClass.class)
@JoinColumns({
            @JoinColumn(name = "meta_class", referencedColumnName = "id", insertable = false, updatable = false),
            @JoinColumn(name = "tenant_id", referencedColumnName = "tenant_id", insertable = false, updatable = false)})
    private MetaClass metaClassEntity;
}
</code>```

and the Edm looks like (notice the navigation property):

```<code><EntityType Name="MetaClassReport">
                <Key>
                    <PropertyRef Name="Id"></PropertyRef>
                    <PropertyRef Name="TenantId"></PropertyRef>
                </Key>
                <Property Name="AppCode" Type="Edm.String" Nullable="true" MaxLength="50"></Property>
                <Property Name="CreateTime" Type="Edm.DateTime" Nullable="false"></Property>
                <Property Name="Creator" Type="Edm.String" Nullable="false" MaxLength="36"></Property>
                <Property Name="DataRelation" Type="Edm.String" Nullable="true" MaxLength="20"></Property>
                <Property Name="Id" Type="Edm.String" Nullable="false" MaxLength="22"></Property>
                <Property Name="JoinGeneral" Type="Edm.String" Nullable="true" MaxLength="255"></Property>
                <Property Name="Links" Type="Edm.String" Nullable="true" MaxLength="255"></Property>
                <Property Name="MainEntity" Type="Edm.String" Nullable="true" MaxLength="22"></Property>
                <Property Name="MetaClass" Type="Edm.String" Nullable="false" MaxLength="22"></Property>
                <Property Name="MicroServiceCode" Type="Edm.String" Nullable="true" MaxLength="50"></Property>
                <Property Name="Modifier" Type="Edm.String" Nullable="true" MaxLength="36"></Property>
                <Property Name="ModifyTime" Type="Edm.DateTime" Nullable="true"></Property>
                <Property Name="QuerySchema" Type="Edm.String" Nullable="true" MaxLength="22"></Property>
                <Property Name="Version" Type="Edm.Int32" Nullable="false"></Property>
                <Property Name="TenantId" Type="Edm.String" Nullable="false" MaxLength="36"></Property>
                <NavigationProperty Name="MetaClassDetails" Relationship="default.MetaClass_MetaClassReport_One_One0" FromRole="MetaClassReport" ToRole="MetaClass"></NavigationProperty>
            </EntityType>

            <Association Name="MetaClass_MetaClassReport_One_One0">
                <End Type="default.MetaClass" Multiplicity="1" Role="MetaClass"></End>
                <End Type="default.MetaClassReport" Multiplicity="0..1" Role="MetaClassReport"></End>
                <ReferentialConstraint>
                    <Principal Role="MetaClass">
                        <PropertyRef Name="Id"></PropertyRef>
                        <PropertyRef Name="TenantId"></PropertyRef>
                    </Principal>
                    <Dependent Role="MetaClassReport">
                        <PropertyRef Name="MetaClass"></PropertyRef>
                        <PropertyRef Name="TenantId"></PropertyRef>
                    </Dependent>
                </ReferentialConstraint>
            </Association>

</code>```

Now I have the requirement to do the referential check when update MetaClassReport associated to a MetaClass by:

```<code>localhost:8080/odata/MetaClassReports
</code>```

and the body is:

```<code>{
    "Id": "7s",
    "YtenantId": "1qaz2wsx",
    "Links": "",
    "Version": 1,
    "CreateTime": "2022-12-31T18:59:59",
    "Creator": "chenhem",
    "MetaClassDetails": {
        "Id": "5s",
        "YtenantId": "1qaz2wsx",
        "LegacyId": "12121212",
        "TableName": "classTable",
        "TableType": 0,
        "Uri": "aa.bb.testmetaclass",
        "Name": "testmetaclass",
        "MetaComponentId": "11111111111",
        "Version": 1,
        "CreateTime": "2022-12-31T18:59:59",
        "Creator": "chenhem"
    }
}
</code>```

then I notice that Olingo would not check the reference constraint between MetaClass and MetaClass report, the MetaClass will be inserted into DB no matter the "MetaClass":"1s" exists in MetaClass table or not.

I am wondering if the <ReferentialConstraint> in Edm is just an illustration, or indeed it will do some effects just because I missed some configuration or implementation?

If the <ReferentialConstraint> is just a metadata illustration, then how should I implement such a key reference value check? (DB foreign key is not an option for me), thanks in advance.

Body:
I am using Olingo 2.0.11 on top of Hibernate. I've built relationship between entities and the navigation property works fine by define the @OneToOne annotation to entities' properties:

public class MetaClass {
@OneToOne(mappedBy = "metaClassEntity", cascade = {CascadeType.MERGE, CascadeType.REFRESH}, optional = false)
private MetaClassReport metaClassReport;
}

public class MetaClassReport {
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = MetaClass.class)
@JoinColumns({
            @JoinColumn(name = "meta_class", referencedColumnName = "id", insertable = false, updatable = false),
            @JoinColumn(name = "tenant_id", referencedColumnName = "tenant_id", insertable = false, updatable = false)})
    private MetaClass metaClassEntity;
}

and the Edm looks like (notice the navigation property):

<EntityType Name="MetaClassReport">
                <Key>
                    <PropertyRef Name="Id"></PropertyRef>
                    <PropertyRef Name="TenantId"></PropertyRef>
                </Key>
                <Property Name="AppCode" Type="Edm.String" Nullable="true" MaxLength="50"></Property>
                <Property Name="CreateTime" Type="Edm.DateTime" Nullable="false"></Property>
                <Property Name="Creator" Type="Edm.String" Nullable="false" MaxLength="36"></Property>
                <Property Name="DataRelation" Type="Edm.String" Nullable="true" MaxLength="20"></Property>
                <Property Name="Id" Type="Edm.String" Nullable="false" MaxLength="22"></Property>
                <Property Name="JoinGeneral" Type="Edm.String" Nullable="true" MaxLength="255"></Property>
                <Property Name="Links" Type="Edm.String" Nullable="true" MaxLength="255"></Property>
                <Property Name="MainEntity" Type="Edm.String" Nullable="true" MaxLength="22"></Property>
                <Property Name="MetaClass" Type="Edm.String" Nullable="false" MaxLength="22"></Property>
                <Property Name="MicroServiceCode" Type="Edm.String" Nullable="true" MaxLength="50"></Property>
                <Property Name="Modifier" Type="Edm.String" Nullable="true" MaxLength="36"></Property>
                <Property Name="ModifyTime" Type="Edm.DateTime" Nullable="true"></Property>
                <Property Name="QuerySchema" Type="Edm.String" Nullable="true" MaxLength="22"></Property>
                <Property Name="Version" Type="Edm.Int32" Nullable="false"></Property>
                <Property Name="TenantId" Type="Edm.String" Nullable="false" MaxLength="36"></Property>
                <NavigationProperty Name="MetaClassDetails" Relationship="default.MetaClass_MetaClassReport_One_One0" FromRole="MetaClassReport" ToRole="MetaClass"></NavigationProperty>
            </EntityType>

            <Association Name="MetaClass_MetaClassReport_One_One0">
                <End Type="default.MetaClass" Multiplicity="1" Role="MetaClass"></End>
                <End Type="default.MetaClassReport" Multiplicity="0..1" Role="MetaClassReport"></End>
                <ReferentialConstraint>
                    <Principal Role="MetaClass">
                        <PropertyRef Name="Id"></PropertyRef>
                        <PropertyRef Name="TenantId"></PropertyRef>
                    </Principal>
                    <Dependent Role="MetaClassReport">
                        <PropertyRef Name="MetaClass"></PropertyRef>
                        <PropertyRef Name="TenantId"></PropertyRef>
                    </Dependent>
                </ReferentialConstraint>
            </Association>

Now I have the requirement to do the referential check when update MetaClassReport associated to a MetaClass by:

localhost:8080/odata/MetaClassReports

and the body is:

{
    "Id": "7s",
    "YtenantId": "1qaz2wsx",
    "Links": "",
    "Version": 1,
    "CreateTime": "2022-12-31T18:59:59",
    "Creator": "chenhem",
    "MetaClassDetails": {
        "Id": "5s",
        "YtenantId": "1qaz2wsx",
        "LegacyId": "12121212",
        "TableName": "classTable",
        "TableType": 0,
        "Uri": "aa.bb.testmetaclass",
        "Name": "testmetaclass",
        "MetaComponentId": "11111111111",
        "Version": 1,
        "CreateTime": "2022-12-31T18:59:59",
        "Creator": "chenhem"
    }
}

then I notice that Olingo would not check the reference constraint between MetaClass and MetaClass report, the MetaClass will be inserted into DB no matter the "MetaClass":"1s" exists in MetaClass table or not.

I am wondering if the <ReferentialConstraint> in Edm is just an illustration, or indeed it will do some effects just because I missed some configuration or implementation?

If the <ReferentialConstraint> is just a metadata illustration, then how should I implement such a key reference value check? (DB foreign key is not an option for me), thanks in advance.


问:
How to combine q-input/ q-edit with Yjs to manage cursor position when co-editing
I figured out how sync text value between clients using Yjs but I still can't handle cursor pos after text update. I use quasar framework so I can't apply one of this recomended text-editors by Yjs documentation. I do not need and special binding like characters size, color, bolding and on.

this is what I've got up to now

<q-input
 :modelValue="article"
 debounce="1000"
 ref="editor"
 type="textarea"
 @update:modelValue=" (e) => {
  updateText(article, e )
 }"
 @focus="showCursor()"
/>

```

So as you see the main problem is the setting cursor pos after update.

First because update model is earlier then dom-el re-render and second is that someone could changed value while you still write the text.

Body:
I figured out how sync text value between clients using Yjs but I still can't handle cursor pos after text update. I use quasar framework so I can't apply one of this recomended text-editors by Yjs documentation. I do not need and special binding like characters size, color, bolding and on.

this is what I've got up to now

<q-input
 :modelValue="article"
 debounce="1000"
 ref="editor"
 type="textarea"
 @update:modelValue=" (e) => {
  updateText(article, e )
 }"
 @focus="showCursor()"
/>

So as you see the main problem is the setting cursor pos after update.

First because update model is earlier then dom-el re-render and second is that someone could changed value while you still write the text.


问:
WebSocket is closed before the connection is established
i want to use jsonwebtoken, but after i've tried implement it, it gives me this error:WebSocket is closed before the connection is established.

I cant see whats wrong with the code. im not able to do anything on the localhost as it looses connection all the time.

Client
chat.js

```<code> const socket = io({
    extraheaders: {
      token : sessionStorage
    }
    });
</code>```

Server
app.js

```<code>

io.use((socket, next) => {
  const {token}= socket.handshake.auth.headers;
  if (token && token ===sessionStorage){
    return next();
  }
  next(new Error('Pls login again'))

 .on('connection', function(socket) {
  console.log(token)
    // Connection now authenticated to receive further events
    socket.on('message', function(message) {
        io.emit('message', message);
        console.log(socket.handshake.auth.headers)

    });

[![Localstorage][1]][1]

  [1]: https://i.stack.imgur.com/YewlR.png
</code>```

Body:
i want to use jsonwebtoken, but after i've tried implement it, it gives me this error:WebSocket is closed before the connection is established.

I cant see whats wrong with the code. im not able to do anything on the localhost as it looses connection all the time.

Client
chat.js

 const socket = io({
    extraheaders: {
      token : sessionStorage
    }
    });

Server
app.js

io.use((socket, next) => {
  const {token}= socket.handshake.auth.headers;
  if (token && token ===sessionStorage){
    return next();
  }
  next(new Error('Pls login again'))

 .on('connection', function(socket) {
  console.log(token)
    // Connection now authenticated to receive further events
    socket.on('message', function(message) {
        io.emit('message', message);
        console.log(socket.handshake.auth.headers)

    });

[![Localstorage][1]][1]

  [1]: https://i.stack.imgur.com/YewlR.png


问:
How to use matplotlib.pyplot.colorbar for None values in loop?
```<code>    raise RuntimeError('No mappable was found to use for colorbar '

</code>```

some scatter plots in loop are empty and having None values (correctly). as i'm plotting around 100 scatter in loop, i have colorbar error when scatter is empty.
the only way is elimination :
plt.colorbar() from my code.which is not a solution.

```<code>
T1 = []
T2 = []
T3 = []
for ii, (xe,ye) in enumerate(zip(T1,T2)):
            plt.scatter([xe]*len(ye),ye, c=T3[ii],cmap='Paired',s=100,vmin=0,vmax=1,marker="x")
        plt.colorbar()
        plt.gca().xaxis.set_major_locator(MaxNLocator(integer=True))
        plt.savefig(f"plot/{mac}- Test{a1}-delta{b1}.svg",format='svg', bbox_inches='tight')
        plt.clf()

</code>```

I want my scatter keeps plotting and ignore the Runtime error.
or keeps ploting the colorbar regardless of value None.

Body:
    raise RuntimeError('No mappable was found to use for colorbar '

some scatter plots in loop are empty and having None values (correctly). as i'm plotting around 100 scatter in loop, i have colorbar error when scatter is empty.
the only way is elimination :
plt.colorbar() from my code.which is not a solution.

T1 = []
T2 = []
T3 = []
for ii, (xe,ye) in enumerate(zip(T1,T2)):
            plt.scatter([xe]*len(ye),ye, c=T3[ii],cmap='Paired',s=100,vmin=0,vmax=1,marker="x")
        plt.colorbar()
        plt.gca().xaxis.set_major_locator(MaxNLocator(integer=True))
        plt.savefig(f"plot/{mac}- Test{a1}-delta{b1}.svg",format='svg', bbox_inches='tight')
        plt.clf()

I want my scatter keeps plotting and ignore the Runtime error.
or keeps ploting the colorbar regardless of value None.


问:
Using factors when integer reference column already exists
Say I have a dataframe as such, obtained by reading a csv file:

```<code>    DF1<-data.frame(ID = c(1,2,3,4),
Names = c('John','Bob','Hannah','Mark'))
</code>```

I want to factorize the names of the second column, as they take a finite amount of values. Nevertheless, an "ID" column already exists, composed of integers which uniquely identify any name in the second.

Is

```<code>DF1$Names<-factor(DF1$Names)
</code>```

the correct approach, hence "disregarding" the ID column for the matter, or am I missing something?

EDIT: Sorry everyone, I'll try to be more specific: when factorizing a character column, for which every element is ALREADY uniquely identified in another column by integers ("ID"), should I consider the "ID" in any way during the factorization? My doubt comes from the fact that, as I read in the documentation, factorizing something means giving it an integer reference, which in my case already exists.

Thanks

Body:
Say I have a dataframe as such, obtained by reading a csv file:

    DF1<-data.frame(ID = c(1,2,3,4),
Names = c('John','Bob','Hannah','Mark'))

I want to factorize the names of the second column, as they take a finite amount of values. Nevertheless, an "ID" column already exists, composed of integers which uniquely identify any name in the second.

Is

DF1$Names<-factor(DF1$Names)

the correct approach, hence "disregarding" the ID column for the matter, or am I missing something?

EDIT: Sorry everyone, I'll try to be more specific: when factorizing a character column, for which every element is ALREADY uniquely identified in another column by integers ("ID"), should I consider the "ID" in any way during the factorization? My doubt comes from the fact that, as I read in the documentation, factorizing something means giving it an integer reference, which in my case already exists.

Thanks