问:
How to use fixtures with POM and run the tests in serial mode
```<code>//mytest.js
const {test , expect} = require('../fixtures/basePage.js');

test.describe.serial('First playwright test @smoke @sanity',  () => {

   test.beforeAll(async ({browser} ) =>{
    let page = {};
    page = await browser.newPage(); //Create a new Page instance

  });

   test('Open application', async ( {loginPO}) => {

        await loginPO.goToLoginScreen();
        expect(await loginPO.checkLoginScreenIsDisplayed(), 'Login
        screen is displayed').toBeTruthy;
      });

    test('Login into the application with a user with customer role', async ({loginPO,contractsPO } ) => {

        await loginPO.login(username, passsword);
        expect(await contractsPO.checkContractsScreenIsDisplayed(), 'Contracts Screen is displayed').toBeTruthy;
      });

//basepage.js
const base = require ('@playwright/test');

exports.test = base.test.extend({

    loginPO: async({page}, use)=>{
        await use(new LoginPO(page));
    },

    contractsPO: async({page}, use)=>{
        await use(new ContractsPO(page));
    },

    legalPO: async({page}, use)=>{
        await use(new LegalLinksPO(page));
    },

    dataEnv : data()

});

exports.expect = base.expect;
</code>```

I tried to run the tests sequentially where the state should be preserved. But i see a new browser open for each test in the test file. I am using fixtures for POM to execute the tests.
Can anyone tell me how to use fixtures in serial mode ?

Body:
//mytest.js
const {test , expect} = require('../fixtures/basePage.js');

test.describe.serial('First playwright test @smoke @sanity',  () => {

   test.beforeAll(async ({browser} ) =>{
    let page = {};
    page = await browser.newPage(); //Create a new Page instance

  });

   test('Open application', async ( {loginPO}) => {

        await loginPO.goToLoginScreen();
        expect(await loginPO.checkLoginScreenIsDisplayed(), 'Login
        screen is displayed').toBeTruthy;
      });

    test('Login into the application with a user with customer role', async ({loginPO,contractsPO } ) => {

        await loginPO.login(username, passsword);
        expect(await contractsPO.checkContractsScreenIsDisplayed(), 'Contracts Screen is displayed').toBeTruthy;
      });

//basepage.js
const base = require ('@playwright/test');

exports.test = base.test.extend({

    loginPO: async({page}, use)=>{
        await use(new LoginPO(page));
    },

    contractsPO: async({page}, use)=>{
        await use(new ContractsPO(page));
    },

    legalPO: async({page}, use)=>{
        await use(new LegalLinksPO(page));
    },

    dataEnv : data()

});

exports.expect = base.expect;

I tried to run the tests sequentially where the state should be preserved. But i see a new browser open for each test in the test file. I am using fixtures for POM to execute the tests.
Can anyone tell me how to use fixtures in serial mode ?


来源: stackexchange

问:
aws_s3.query_export_to_s3 PostgreSQL RDS extension split exported files via program parameter
I am trying to split data exported from S3 with a line limit.

With psql's COPY command this can be done by passing the output to TO PROGRAM 'split -l [number_of_lines]'.

Can I somehow pass the above PROGRAM parameter to .query_export_to_s3's option parameter and split the queried data into cvs?

I found this answer that was never completed.

ContentLicense: CC BY-SA 4.0


问:
related to getting data in frontend from backend
server part

```<code>router.get("/getuserdata",verifyuser,(req,res)=>{
 res.json({user:req.rootuser});
console.log(req.rootuser);
})
</code>```

frontend part

```<code> const callabout=async ()=>{
   try{
       const res=await fetch("http://localhost:8800/api/users/getuserdata",{
        mode:"no-cors",
         method:"GET",
         headers:{
          Accept:"appllication/json",
           "Content-Type":"application/json"
       },
         credentials:"include",

      })

    const data=await res.json();
    console.log(data);

      if(!res.status===200){
     const error=new Error(res.error);
     throw error;

     }}
     catch(err){
     console.log(err);
     navigate("/Login")
    }

     }

</code>```

i want my user data in my front end after login but its not giving data.An error is occuring "unexepexted end of input" while compiling through const data = await res.json(); in frontend part.
please help me

Body:
server part

router.get("/getuserdata",verifyuser,(req,res)=>{
 res.json({user:req.rootuser});
console.log(req.rootuser);
})

frontend part

 const callabout=async ()=>{
   try{
       const res=await fetch("http://localhost:8800/api/users/getuserdata",{
        mode:"no-cors",
         method:"GET",
         headers:{
          Accept:"appllication/json",
           "Content-Type":"application/json"
       },
         credentials:"include",

      })

    const data=await res.json();
    console.log(data);

      if(!res.status===200){
     const error=new Error(res.error);
     throw error;

     }}
     catch(err){
     console.log(err);
     navigate("/Login")
    }

     }

i want my user data in my front end after login but its not giving data.An error is occuring "unexepexted end of input" while compiling through const data = await res.json(); in frontend part.
please help me


问:
Extracting m3u8 link location with python from scraped links
I'm working at a python script which is scraping the sitemap.xml from a website, it's taking the links and then is parsing every link.
The scraper is checking if a og:video tag exist in the header, If og:video is present, is accessing the link and extract the m3u8 link.
The issue is that the script is not able to load m3u8 location. I really appreciate your help in this project.
Code:

```<code>import csv
import os
from selenium import webdriver
import requests
from bs4 import BeautifulSoup
import time

# Set the path to the ChromeDriver executable
driver = webdriver.Chrome()

# Read the sitemap XML file
response = requests.get('https://www.webcamromania.ro/post-sitemap.xml')
soup = BeautifulSoup(response.content, 'xml')

# Extract the links from the sitemap
links = []
for loc in soup.find_all('loc'):
    link = loc.text
    if not any(link.endswith(ext) for ext in ['.jpg', '.png']):
        links.append(link)

# Create a CSV file to store the data

with open('C:/Users/USER/Desktop/data.csv', 'w', newline='', encoding='utf-8') as csvfile:
    fieldnames = ['link', 'title', 'description', 'og_image', 'og_video', 'm3u8']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

# Iterate over the links and extract the data
for link in links[155:161]:
    driver.get(link)
    html = driver.page_source
    soup = BeautifulSoup(html, 'html.parser')

    # Extract the title and description
    title = soup.find('title').text
    description = soup.find('meta', {'name': 'description'})['content']

    # Write the data to the CSV file
    with open('C:/Users/USERNAME/Desktop/data.csv', 'a', newline='', encoding='utf-8') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writerow({'link': link, 'title': title, 'description': description, 'og_image': og_image, 'og_video': og_video, 'm3u8': m3u8})

# Close the webdriver
driver.close()
</code>```

to be able to extract the m3u8 link location

Body:
I'm working at a python script which is scraping the sitemap.xml from a website, it's taking the links and then is parsing every link.
The scraper is checking if a og:video tag exist in the header, If og:video is present, is accessing the link and extract the m3u8 link.
The issue is that the script is not able to load m3u8 location. I really appreciate your help in this project.
Code:

import csv
import os
from selenium import webdriver
import requests
from bs4 import BeautifulSoup
import time

# Set the path to the ChromeDriver executable
driver = webdriver.Chrome()

# Read the sitemap XML file
response = requests.get('https://www.webcamromania.ro/post-sitemap.xml')
soup = BeautifulSoup(response.content, 'xml')

# Extract the links from the sitemap
links = []
for loc in soup.find_all('loc'):
    link = loc.text
    if not any(link.endswith(ext) for ext in ['.jpg', '.png']):
        links.append(link)

# Create a CSV file to store the data

with open('C:/Users/USER/Desktop/data.csv', 'w', newline='', encoding='utf-8') as csvfile:
    fieldnames = ['link', 'title', 'description', 'og_image', 'og_video', 'm3u8']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()

# Iterate over the links and extract the data
for link in links[155:161]:
    driver.get(link)
    html = driver.page_source
    soup = BeautifulSoup(html, 'html.parser')

    # Extract the title and description
    title = soup.find('title').text
    description = soup.find('meta', {'name': 'description'})['content']

    # Write the data to the CSV file
    with open('C:/Users/USERNAME/Desktop/data.csv', 'a', newline='', encoding='utf-8') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writerow({'link': link, 'title': title, 'description': description, 'og_image': og_image, 'og_video': og_video, 'm3u8': m3u8})

# Close the webdriver
driver.close()

to be able to extract the m3u8 link location


问:
plotly's FigureWidget does not respect display order when used with ipywidgets
I am doing a project where I need to display two images, followed by interactively drawing a bounding box on the displayed image. Before getting that far, I am unable to get the images displayed correctly inside jupyterlab together with ipywidgets. The problem is illustrated with 2 widgets inside a hbox. The button should be placed above the images, but when rendered the button is placed below the images.

To reproduce this problem, you can use any test images.

```<code>import ipywidgets as widgets
from IPython.display import display, clear_output
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
from PIL import Image

#Create two widgets to illustrate the problem

button = widgets.Button(description = 'test')

imageData = Image.open('sampleImage.jpg')
imageAnnotationSubplots = make_subplots(rows = 1, cols = 2)
imageAnnotationSubplots.add_trace(px.imshow(imageData).data[0], row = 1, col=1)
imageAnnotationSubplots.add_trace(px.imshow(imageData).data[0], row = 1, col=2)
imageAnnotationFigureWidget = go.FigureWidget(imageAnnotationSubplots)
imageAnnotationFigureWidget.show()

vbox = widgets.VBox([button, imageAnnotationFigureWidget])
display(vbox)
</code>```

Body:
I am doing a project where I need to display two images, followed by interactively drawing a bounding box on the displayed image. Before getting that far, I am unable to get the images displayed correctly inside jupyterlab together with ipywidgets. The problem is illustrated with 2 widgets inside a hbox. The button should be placed above the images, but when rendered the button is placed below the images.

To reproduce this problem, you can use any test images.

import ipywidgets as widgets
from IPython.display import display, clear_output
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
from PIL import Image

#Create two widgets to illustrate the problem

button = widgets.Button(description = 'test')

imageData = Image.open('sampleImage.jpg')
imageAnnotationSubplots = make_subplots(rows = 1, cols = 2)
imageAnnotationSubplots.add_trace(px.imshow(imageData).data[0], row = 1, col=1)
imageAnnotationSubplots.add_trace(px.imshow(imageData).data[0], row = 1, col=2)
imageAnnotationFigureWidget = go.FigureWidget(imageAnnotationSubplots)
imageAnnotationFigureWidget.show()

vbox = widgets.VBox([button, imageAnnotationFigureWidget])
display(vbox)


问:
The object retrieved from the cache (Redis) has different ClassLoader and throws ClassCastException on casting
I have a Spring Boot app with Redis cache. I faced the an issue - when I put an object of class A to cache and then retrieve it back the object can't be casted to the class A.

```<code>Person person = new Person();
getCache().put("person", person);

Person p = getCache().get("person", Person.class); // throws java.lang.IllegalStateException: Cached value is not of required type [com.dummy.domain.Person]: Person(name=null)

Object p = getCache().get("person").get();
(Person) p  // Cannot cast 'com.dummy.domain.Person' to 'com.dummy.domain.Person'

</code>```

If I do getClass on the object I receive the same fully qualified name of the of A-class, but I noticed that they have different ClassLoaders. getClass().getClassLoader() gives:
Initial object:

name = null

nameAndId = org.springframework.boot.devtools.restart.classloader.RestartClassLoader

parent = AppClassLoader

The object from the cache:

name = app

nameAndId = app

parent = PlatformClassLoader

What could be the reason changed ClassLoaders? I guess it is the source of the casting issue

Body:
I have a Spring Boot app with Redis cache. I faced the an issue - when I put an object of class A to cache and then retrieve it back the object can't be casted to the class A.

Person person = new Person();
getCache().put("person", person);

Person p = getCache().get("person", Person.class); // throws java.lang.IllegalStateException: Cached value is not of required type [com.dummy.domain.Person]: Person(name=null)

Object p = getCache().get("person").get();
(Person) p  // Cannot cast 'com.dummy.domain.Person' to 'com.dummy.domain.Person'

If I do getClass on the object I receive the same fully qualified name of the of A-class, but I noticed that they have different ClassLoaders. getClass().getClassLoader() gives:
Initial object:

name = null

nameAndId = org.springframework.boot.devtools.restart.classloader.RestartClassLoader

parent = AppClassLoader

The object from the cache:

name = app

nameAndId = app

parent = PlatformClassLoader

What could be the reason changed ClassLoaders? I guess it is the source of the casting issue


问:
Block category listing in mediawiki for guests
I know I can simply hide the page output for gests using css with

```<code>$wgHooks['BeforePageDisplay'][] = 'wfHideVariousTabsFromAnonymous';
function wfHideVariousTabsFromAnonymous( OutputPage $out, Skin $skin ) {
  if ( !$out->getUser()->isLoggedIn() ) {
    // addInineStyle is deprecated
    $out->addInlineStyle( '.mw-category-generated { display: none; }' );
  }
  return true;
}
</code>```

But I want to either fully block access to those pages for guests or simply not have any category listing, not even on page source.

Body:
I know I can simply hide the page output for gests using css with

$wgHooks['BeforePageDisplay'][] = 'wfHideVariousTabsFromAnonymous';
function wfHideVariousTabsFromAnonymous( OutputPage $out, Skin $skin ) {
  if ( !$out->getUser()->isLoggedIn() ) {
    // addInineStyle is deprecated
    $out->addInlineStyle( '.mw-category-generated { display: none; }' );
  }
  return true;
}

But I want to either fully block access to those pages for guests or simply not have any category listing, not even on page source.


问:
Maven dependency jar file corrupted "error in opening zip file"
I have the following issue on a Maven project (with Maven 3.8.1):

```<code>Compilation failure
error: error reading ${user.home}\my-repository\path\to\the\artifact\version\dependency-version.jar; error in opening zip file
</code>```

I have found a lot of posts on the matter (such as Maven : error in opening zip file when running maven) but none with a reliable solution.
The only workaround that helps is to manual download the JAR file from a browser and save it at the location mentioned in the error.

In my case, I would like to know if the fact that the repository is over HTTPS and using an internal Certificate Authority could be the cause since:

while investigating the issue, I saw warnings as follow:

```<code>[WARNING] Checksum validation failed, expected <!DOCTYPE but is 963eb274a2ab77544a448a617489e097a3797b81 from my-maven-repo for https://<host>:<port>/repository/my-maven-repo/path/to/the/artifact/version/dependency-version.pom
[WARNING] Could not validate integrity of download from https://<host>:<port>/repository/my-maven-repo/path/to/the/artifact/version/dependency-version.pom
org.eclipse.aether.transfer.ChecksumFailureException: Checksum validation failed, expected <!DOCTYPE but is 1bc04ac588e7b7f3a35851e63e9ff5f507579567
    at org.eclipse.aether.connector.basic.ChecksumValidator.validateExternalChecksums (ChecksumValidator.java:174)
    ...
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at org.codehaus.classworlds.Launcher.main (Launcher.java:47)
[WARNING] Checksum validation failed, expected <!DOCTYPE but is 1bc04ac588e7b7f3a35851e63e9ff5f507579567 from my-maven-repo for https://<host>:<port>/repository/my-maven-repo/path/to/the/artifact/version/dependency-version.pom
Downloaded from my-maven-repo: https://<host>:<port>/repository/my-maven-repo/path/to/the/artifact/version/dependency-version.pom (19 kB at 7.4 kB/s)
[WARNING] The POM for path.to.the:artifact:jar:version is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
</code>```

then, when opening https://host:port/repository/my-maven-repo/path/to/the/artifact/version/dependency-version.pom into a browser, it returns an error as :
NET::ERR_CERT_AUTHORITY_INVALID

If so, how can I solved it?

NOTE:

${user.home} is the placeholder set in the setting.xml in the
localRepository element, which refers to the .m2 directory under the
current user directory.

the setting.xml is set at project-level into
the .mvn directory, along with a maven.config file, and holds all repositories configurations.

The pom.xml  section:

```<code><build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <excludes>
          <exclude>**/*.conf</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.3.2</version>
          <configuration>
            <source>${jdk.version}</source>
            <target>${jdk.version}</target>
          </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <systemProperties>
                    <property>
                        <name>java.util.logging.config.file</name>
                        <value>${project.basedir}/src/main/resources/test/logging.properties</value>
                    </property>
                    <property>
                        <name>some_prop</name>
                        <value>some_value</value>
                    </property>
                </systemProperties>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.1.1</version>
            <configuration>
                <webappDirectory>${basedir}/target/tmp</webappDirectory>
                <packagingIncludes>WEB-INF/lib/*.jar,
                **/*.xml,**/*.idmap,**/*.info,
                **/*.properties,**/*.class,**/*.png,**/*.css,**/*.js,**/*.jsp,**/MANIFEST.MF
                </packagingIncludes>

                <webxml>src/main/webapp/WEB-INF/web.xml</webxml>
                <webResources>
                <resource>
                    <directory>src/main/resources</directory>
                    <exclude>*.properties</exclude>
                </resource>
                </webResources>
            </configuration>
            <executions>
                <execution>
                    <id>make-war</id>
                    <phase>package</phase>
                    <goals>
                        <goal>war</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

Body:
I have the following issue on a Maven project (with Maven 3.8.1):

Compilation failure
error: error reading ${user.home}\my-repository\path\to\the\artifact\version\dependency-version.jar; error in opening zip file

I have found a lot of posts on the matter (such as Maven : error in opening zip file when running maven) but none with a reliable solution.
The only workaround that helps is to manual download the JAR file from a browser and save it at the location mentioned in the error.

In my case, I would like to know if the fact that the repository is over HTTPS and using an internal Certificate Authority could be the cause since:

while investigating the issue, I saw warnings as follow:

[WARNING] Checksum validation failed, expected <!DOCTYPE but is 963eb274a2ab77544a448a617489e097a3797b81 from my-maven-repo for https://<host>:<port>/repository/my-maven-repo/path/to/the/artifact/version/dependency-version.pom
[WARNING] Could not validate integrity of download from https://<host>:<port>/repository/my-maven-repo/path/to/the/artifact/version/dependency-version.pom
org.eclipse.aether.transfer.ChecksumFailureException: Checksum validation failed, expected <!DOCTYPE but is 1bc04ac588e7b7f3a35851e63e9ff5f507579567
    at org.eclipse.aether.connector.basic.ChecksumValidator.validateExternalChecksums (ChecksumValidator.java:174)
    ...
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347)
    at org.codehaus.classworlds.Launcher.main (Launcher.java:47)
[WARNING] Checksum validation failed, expected <!DOCTYPE but is 1bc04ac588e7b7f3a35851e63e9ff5f507579567 from my-maven-repo for https://<host>:<port>/repository/my-maven-repo/path/to/the/artifact/version/dependency-version.pom
Downloaded from my-maven-repo: https://<host>:<port>/repository/my-maven-repo/path/to/the/artifact/version/dependency-version.pom (19 kB at 7.4 kB/s)
[WARNING] The POM for path.to.the:artifact:jar:version is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details

then, when opening https://host:port/repository/my-maven-repo/path/to/the/artifact/version/dependency-version.pom into a browser, it returns an error as :
NET::ERR_CERT_AUTHORITY_INVALID

If so, how can I solved it?

NOTE:

${user.home} is the placeholder set in the setting.xml in the
localRepository element, which refers to the .m2 directory under the
current user directory.

the setting.xml is set at project-level into
the .mvn directory, along with a maven.config file, and holds all repositories configurations.

The pom.xml  section:

<build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <excludes>
          <exclude>**/*.conf</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.3.2</version>
          <configuration>
            <source>${jdk.version}</source>
            <target>${jdk.version}</target>
          </configuration>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                <systemProperties>
                    <property>
                        <name>java.util.logging.config.file</name>
                        <value>${project.basedir}/src/main/resources/test/logging.properties</value>
                    </property>
                    <property>
                        <name>some_prop</name>
                        <value>some_value</value>
                    </property>
                </systemProperties>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.1.1</version>
            <configuration>
                <webappDirectory>${basedir}/target/tmp</webappDirectory>
                <packagingIncludes>WEB-INF/lib/*.jar,
                **/*.xml,**/*.idmap,**/*.info,
                **/*.properties,**/*.class,**/*.png,**/*.css,**/*.js,**/*.jsp,**/MANIFEST.MF
                </packagingIncludes>

                <webxml>src/main/webapp/WEB-INF/web.xml</webxml>
                <webResources>
                <resource>
                    <directory>src/main/resources</directory>
                    <exclude>*.properties</exclude>
                </resource>
                </webResources>
            </configuration>
            <executions>
                <execution>
                    <id>make-war</id>
                    <phase>package</phase>
                    <goals>
                        <goal>war</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>


问:
CCS @media print
I am working on a print template and through the Google Chrome browser and wanted to know if there is any parameter that can be sent from HTML or css to tell the browser to default to not place any header or footer.

since by default it takes the user's configuration thus placing the date and time as header and the url as footer.

```<code>@media print {
        @page { margin: 1.4cm; }
        /* body { margin: 1.6cm; } */
    }
</code>```

I would expect some parameter similar to @page to indicate whether it renders it or not.

Title: CCS @media print

Body:
I am working on a print template and through the Google Chrome browser and wanted to know if there is any parameter that can be sent from HTML or css to tell the browser to default to not place any header or footer.

since by default it takes the user's configuration thus placing the date and time as header and the url as footer.

@media print {
        @page { margin: 1.4cm; }
        /* body { margin: 1.6cm; } */
    }

I would expect some parameter similar to @page to indicate whether it renders it or not.


问:
spinxsql combine match and filter
I use Manticore Search. Fork of Spinx.
I'am trying to use Full text search. But problem in json fields. So I fond solutions via ANY()

```<code>ANY(client_user.login = "test" FOR client_user IN client_users)
</code>```

It works great. But when I try to use it with common full text search - it's not work

PHP code like this

```<code>$client = new \Manticoresearch\Client($config);
$search = new \Manticoresearch\Search($client);
$search->setIndex('clients');
$search->expression('cond1', 'ANY(client_user.login = "'.$query.'" FOR client_user IN client_users)');
$bool = new \Manticoresearch\Query\BoolQuery();
$bool->should(new \Manticoresearch\Query\Equals('cond1', 1));
$bool->should(new \Manticoresearch\Query\QueryString($query.'*'));
$search->search($bool);
$results = $search->get();

print '```'.print_r($search->getBody(), true).'```';
</code>```

Like query array:

```<code>Array
(
    [index] => clients
    [script_fields] => Array
        (
            [cond1] => Array
                (
                    [script] => Array
                        (
                            [inline] => ANY(client_user.login = "test" FOR client_user IN client_users)
                        )

                )

        )

    [query] => Array
        (
            [bool] => Array
                (
                    [should] => Array
                        (
                            [0] => Array
                                (
                                    [equals] => Array
                                        (
                                            [cond1] => 1
                                        )

                                )

                            [1] => Array
                                (
                                    [query_string] => test*
                                )

                        )

                )

        )

)

</code>```

Response is empty.

If I use sql:

```<code>select login, name, ANY(client_user.login = 'test' FOR client_user IN client_users) as cond1 from clients where cond1 = 1 OR match('test*');

</code>```

I have an error

ERROR 1064 (42000): sphinxql: syntax error, unexpected '(' near '('test*')'

Title: spinxsql combine match and filter

Body:
I use Manticore Search. Fork of Spinx.
I'am trying to use Full text search. But problem in json fields. So I fond solutions via ANY()

ANY(client_user.login = "test" FOR client_user IN client_users)

It works great. But when I try to use it with common full text search - it's not work

PHP code like this

$client = new \Manticoresearch\Client($config);
$search = new \Manticoresearch\Search($client);
$search->setIndex('clients');
$search->expression('cond1', 'ANY(client_user.login = "'.$query.'" FOR client_user IN client_users)');
$bool = new \Manticoresearch\Query\BoolQuery();
$bool->should(new \Manticoresearch\Query\Equals('cond1', 1));
$bool->should(new \Manticoresearch\Query\QueryString($query.'*'));
$search->search($bool);
$results = $search->get();

print '
'.print_r($search->getBody(), true).'
';

Like query array:

Array
(
    [index] => clients
    [script_fields] => Array
        (
            [cond1] => Array
                (
                    [script] => Array
                        (
                            [inline] => ANY(client_user.login = "test" FOR client_user IN client_users)
                        )

                )

        )

    [query] => Array
        (
            [bool] => Array
                (
                    [should] => Array
                        (
                            [0] => Array
                                (
                                    [equals] => Array
                                        (
                                            [cond1] => 1
                                        )

                                )

                            [1] => Array
                                (
                                    [query_string] => test*
                                )

                        )

                )

        )

)

Response is empty.

If I use sql:

select login, name, ANY(client_user.login = 'test' FOR client_user IN client_users) as cond1 from clients where cond1 = 1 OR match('test*');

I have an error

ERROR 1064 (42000): sphinxql: syntax error, unexpected '(' near '('test*')'


问:
Error attempting to create a multiomic object with the MOFA2 package in R
I am using the MOFA2 package based on a vignette outlined here and have merged three layers of omic data (metabolome, inflammatory factors, and microbiome) in a long format dataframe in the columns required (i.e., 'sample', 'feature', 'value', and 'view'.

```<code>> head(multiomic)
   sample              feature      value       view
1 SM01_01 X2_Aminobutyric.acid 0.05117221 metabolome
2 SM01_02 X2_Aminobutyric.acid 0.03615312 metabolome
3 SM01_03 X2_Aminobutyric.acid 0.15299858 metabolome
4 SM02_01 X2_Aminobutyric.acid 0.13094635 metabolome
5 SM02_02 X2_Aminobutyric.acid 0.63106917 metabolome
6 SM02_03 X2_Aminobutyric.acid 0.70794188 metabolome

> str(multiomic)
'data.frame':   26208 obs. of  4 variables:
 $ sample : chr  "SM01_01" "SM01_02" "SM01_03" "SM02_01" ...
 $ feature: Factor w/ 222 levels "X2_Aminobutyric.acid",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value  : num  0.0512 0.0362 0.153 0.1309 0.6311 ...
 $ view   : chr  "metabolome" "metabolome" "metabolome" "metabolome" ...
</code>```

When attempting to run the command to create a MOFA object I get this error message:

```<code>> create_mofa_from_df(multiomic)
Aggregation function missing: defaulting to length
Error in vapply(indices, fun, .default) : values must be type 'logical',
 but FUN(X[[1]]) result is type 'integer'
</code>```

I tried with just the metabolome and inflammation merged data, and it worked. I believe there is an issue with the microbiome data, but not sure where the issue is arising. I have formatted exactly as in the vigette mentioned above. Looking at the data structure for the microbiome data (i.e., 'data') vs. the combined metabolomic and inflammation data (i.e., 'mulit_long') yields the following:

```<code>> str(data)
'data.frame':   8424 obs. of  4 variables:
 $ sample : chr  "SM01_01" "SM26_01" "SM30_03" "SM02_01" ...
 $ feature: chr  "Bifidobacterium" "Blautia" "Bacteroides" "Blautia" ...
 $ value  : num  7.97 7.85 7.77 7.77 7.73 ...
 $ view   : chr  "microbiome" "microbiome" "microbiome" "microbiome" ...

> str(multi_long)
'data.frame':   17784 obs. of  4 variables:
 $ sample : chr  "SM01_01" "SM01_02" "SM01_03" "SM02_01" ...
 $ feature: Factor w/ 152 levels "X2_Aminobutyric.acid",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value  : num  0.0512 0.0362 0.153 0.1309 0.6311 ...
 $ view   : chr  "metabolome" "metabolome" "metabolome" "metabolome" ...
</code>```

I'm guessing this is a structural issue and I'm just missing the obvious solution... Appreciate any guidance!

Thank you

Body:
I am using the MOFA2 package based on a vignette outlined here and have merged three layers of omic data (metabolome, inflammatory factors, and microbiome) in a long format dataframe in the columns required (i.e., 'sample', 'feature', 'value', and 'view'.

> head(multiomic)
   sample              feature      value       view
1 SM01_01 X2_Aminobutyric.acid 0.05117221 metabolome
2 SM01_02 X2_Aminobutyric.acid 0.03615312 metabolome
3 SM01_03 X2_Aminobutyric.acid 0.15299858 metabolome
4 SM02_01 X2_Aminobutyric.acid 0.13094635 metabolome
5 SM02_02 X2_Aminobutyric.acid 0.63106917 metabolome
6 SM02_03 X2_Aminobutyric.acid 0.70794188 metabolome

> str(multiomic)
'data.frame':   26208 obs. of  4 variables:
 $ sample : chr  "SM01_01" "SM01_02" "SM01_03" "SM02_01" ...
 $ feature: Factor w/ 222 levels "X2_Aminobutyric.acid",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value  : num  0.0512 0.0362 0.153 0.1309 0.6311 ...
 $ view   : chr  "metabolome" "metabolome" "metabolome" "metabolome" ...

When attempting to run the command to create a MOFA object I get this error message:

> create_mofa_from_df(multiomic)
Aggregation function missing: defaulting to length
Error in vapply(indices, fun, .default) : values must be type 'logical',
 but FUN(X[[1]]) result is type 'integer'

I tried with just the metabolome and inflammation merged data, and it worked. I believe there is an issue with the microbiome data, but not sure where the issue is arising. I have formatted exactly as in the vigette mentioned above. Looking at the data structure for the microbiome data (i.e., 'data') vs. the combined metabolomic and inflammation data (i.e., 'mulit_long') yields the following:

> str(data)
'data.frame':   8424 obs. of  4 variables:
 $ sample : chr  "SM01_01" "SM26_01" "SM30_03" "SM02_01" ...
 $ feature: chr  "Bifidobacterium" "Blautia" "Bacteroides" "Blautia" ...
 $ value  : num  7.97 7.85 7.77 7.77 7.73 ...
 $ view   : chr  "microbiome" "microbiome" "microbiome" "microbiome" ...

> str(multi_long)
'data.frame':   17784 obs. of  4 variables:
 $ sample : chr  "SM01_01" "SM01_02" "SM01_03" "SM02_01" ...
 $ feature: Factor w/ 152 levels "X2_Aminobutyric.acid",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ value  : num  0.0512 0.0362 0.153 0.1309 0.6311 ...
 $ view   : chr  "metabolome" "metabolome" "metabolome" "metabolome" ...

I'm guessing this is a structural issue and I'm just missing the obvious solution... Appreciate any guidance!

Thank you


问:
ValueError: Failed to find data adapter that can handle input error while i am using CNN to water mark image
any help will be appreciated,  my code is to watermark image into other image using CNN, the error

```<code>ValueError: Failed to find data adapter that can handle input: (<class 'list'> containing values of types {"<class 'numpy.ndarray'>"}), (<class 'list'> containing values of types {"<class 'int'>"})
</code>```

keep showing even if i convert my data to nparray, my code as the following :

```<code>import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from keras.models import load_model
import PIL

watermark_image = tf.keras.preprocessing.image.load_img('watermark.jpg')
original_image = tf.keras.preprocessing.image.load_img('target.jpg')

watermark_image = watermark_image.resize((224, 224))
watermark_image = img_to_array(watermark_image)
watermark_image = watermark_image.reshape( -1,224, 224,3)

original_image = original_image.resize((224, 224))
original_image = img_to_array(original_image)
original_image = original_image.reshape( -1,224, 224,3)

model = tf.keras.Sequential([
    tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)),
    tf.keras.layers.MaxPooling2D((2, 2)),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D((2, 2)),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

model.fit(x=[watermark_image, original_image], y=[1, 0], epochs=10)

watermarked_array = model.predict(original_image)

watermarked_image = tf.keras.preprocessing.image.array_to_img(watermark_image)

watermarked_image.save('watermarked.jpg')
</code>```

Body:
any help will be appreciated,  my code is to watermark image into other image using CNN, the error

ValueError: Failed to find data adapter that can handle input: (<class 'list'> containing values of types {"<class 'numpy.ndarray'>"}), (<class 'list'> containing values of types {"<class 'int'>"})

keep showing even if i convert my data to nparray, my code as the following :

import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from keras.models import load_model
import PIL

watermark_image = tf.keras.preprocessing.image.load_img('watermark.jpg')
original_image = tf.keras.preprocessing.image.load_img('target.jpg')

watermark_image = watermark_image.resize((224, 224))
watermark_image = img_to_array(watermark_image)
watermark_image = watermark_image.reshape( -1,224, 224,3)

original_image = original_image.resize((224, 224))
original_image = img_to_array(original_image)
original_image = original_image.reshape( -1,224, 224,3)

model = tf.keras.Sequential([
    tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)),
    tf.keras.layers.MaxPooling2D((2, 2)),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D((2, 2)),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

model.fit(x=[watermark_image, original_image], y=[1, 0], epochs=10)

watermarked_array = model.predict(original_image)

watermarked_image = tf.keras.preprocessing.image.array_to_img(watermark_image)

watermarked_image.save('watermarked.jpg')


问:
How to persist real time data efficiently on a socket.io and express web application without making many calls to Postgres database?
I'm a newbie currently working on a portfolio project which is trying to implement a real-time comment section component using web sockets. I am wondering how to persist the data most efficiently, i.e., how do I persist the new comments that are posted in real-time without making expensive calls to the database every single time a new comment is made?

From my understanding, you could obviously just save each new entry into the database every single time a comment is posted, but I was thinking that this would be very expensive at high volumes because you would be making a call to the database every single time. I was wondering if what you could do is save the new comments to a global cache first, and then periodically update the database from the cache once X amount of new information has been cached or X amount of time has passed? Was just an idea. Would love to know what the best practice is and how to go about it!


问:
Cant get background script to execute content script
Background:
I am trying to create a firefox extension where I when I click the extension button, a pop up appears with a "count" button displayed. When I click the "count" button I want it to go through all my open tabs that match a url and count how many comments there are. With that being said, I havent gotten that far into the code, but I cant seem to get the background script to communicate with the content-script. In this program I am just using a simple console.log statement to make sure they are connected. New to javascript and extensions in general so any help would be appreciated.

manifest.json

```<code>{

  "manifest_version": 2,
  "name": "Ticket Audit",
  "version": "1.0",
  "description": "Gets information about the tickets regarding comments",

  "icons": {"48":"./image.png"},

  "content_scripts": [
    {
        "matches": ["https://testsite.com/*"],
        "js": ["content-script.js"]
    }
],

  "background":{
    "scripts":["count.js"]
  },

"browser_specific_settings": {
  "gecko": {
    "id": "test@gmail.com"
  }
},

  "permissions":[
    "https://testsite.com/*/",
    "activeTab",
    "tabs"
  ],

  "browser_action": {
    "default_icon": "ts.png",
    "default_title": "TicketAudit",
    "default_popup": "ticketaudit.html"
  }
}
</code>```

count.js

```<code>function getTabs(){
    browser.tabs.query({url:"https://testsite.com/*"})
    .then(sendMessageToTabs)
}

function sendMessageToTabs(tabs){
    for (const tab of tabs){
        browser.tabs.executeScript(tab.id,{file: "/content-script.js"})
    }
}
</code>```

content-script.js

```<code>console.log("test")
</code>```

ticketaudit.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div class="popup-body">
        <button onclick="getTabs()">Count</button>
    </div>
    <script src="count.js"></script>
</body>
</html>
</code>```

Body:
Background:
I am trying to create a firefox extension where I when I click the extension button, a pop up appears with a "count" button displayed. When I click the "count" button I want it to go through all my open tabs that match a url and count how many comments there are. With that being said, I havent gotten that far into the code, but I cant seem to get the background script to communicate with the content-script. In this program I am just using a simple console.log statement to make sure they are connected. New to javascript and extensions in general so any help would be appreciated.

manifest.json

{

  "manifest_version": 2,
  "name": "Ticket Audit",
  "version": "1.0",
  "description": "Gets information about the tickets regarding comments",

  "icons": {"48":"./image.png"},

  "content_scripts": [
    {
        "matches": ["https://testsite.com/*"],
        "js": ["content-script.js"]
    }
],

  "background":{
    "scripts":["count.js"]
  },

"browser_specific_settings": {
  "gecko": {
    "id": "test@gmail.com"
  }
},

  "permissions":[
    "https://testsite.com/*/",
    "activeTab",
    "tabs"
  ],

  "browser_action": {
    "default_icon": "ts.png",
    "default_title": "TicketAudit",
    "default_popup": "ticketaudit.html"
  }
}

count.js

function getTabs(){
    browser.tabs.query({url:"https://testsite.com/*"})
    .then(sendMessageToTabs)
}

function sendMessageToTabs(tabs){
    for (const tab of tabs){
        browser.tabs.executeScript(tab.id,{file: "/content-script.js"})
    }
}

content-script.js

console.log("test")

ticketaudit.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <button onclick="getTabs()">Count</button>


问:
Wrong label at the chart
The line on the Label is not what I want, because one is a show box and one is a show line

```<code>plt.figure(figsize=(7,5), dpi=100)
sns.histplot(x='hour_created', data=training1_data, hue='bot', alpha=.25,
             kde=True, stat='density', common_bins=True, element='step', legend=True)

plt.legend(title='Account Type', loc='best', labels=['Bot', 'Human'])
plt.title("Time of Day Account was Created", fontsize=12)
plt.xlabel('Time of Day (24h)', fontsize=10)
plt.ylabel('Density', fontsize=10)
plt.xlim(0, 24)
plt.ylim(0, 0.05)
sns.despine();
#plt.savefig('imgs/hour_created.png');
</code>```

enter image description here

What I want is for bot and human show to be line and different colors

Title: Wrong label at the chart

Body:
The line on the Label is not what I want, because one is a show box and one is a show line

plt.figure(figsize=(7,5), dpi=100)
sns.histplot(x='hour_created', data=training1_data, hue='bot', alpha=.25,
             kde=True, stat='density', common_bins=True, element='step', legend=True)

plt.legend(title='Account Type', loc='best', labels=['Bot', 'Human'])
plt.title("Time of Day Account was Created", fontsize=12)
plt.xlabel('Time of Day (24h)', fontsize=10)
plt.ylabel('Density', fontsize=10)
plt.xlim(0, 24)
plt.ylim(0, 0.05)
sns.despine();
#plt.savefig('imgs/hour_created.png');

enter image description here

What I want is for bot and human show to be line and different colors


问:
Sql query with dynamic questions outerjoined to a table (need to filter data)
I have three tables. A [customer] table, [dynamicquestions] table, and [dynamicanswers] table.
The customer table contains customer submitted data.
The dynamicquestions table contains the dynamic questions the customer needs to answer.
And the dynamicanswers table are the answers the customer submitted. (these answers are keyed to the dynamicquestions table and keyed to the customer table.

What I am doing is dynamically creating unique column names for these dynamic questions. And then pivoting the dynamic answers into the dynamically created column names.

This all works. My problem, is I want to filter and a customer that has submitted an answer to two dynamic questions.

for example: if there are dynamic questions "how old are you" and "what state do you live in". I want to get everyone that answered "30" and "Texas".

Below is an example query with an "OR statement But I need it to be some sort of "Get both if the customer answered "30" and "Texas".

DECLARE @docDates VARCHAR(MAX)
SELECT @docDates = STUFF((
SELECT DISTINCT ', ' + QUOTENAME(CONVERT(varchar, REPLACE(QAPanelName,'QA_','')) + CONVERT(varchar, LEN(Orderbynumber)) + CONVERT(varchar, Orderbynumber) + CONVERT(varchar, ControlID) + '_' + QuestionColumnName)
FROM DynamicAnswers RIGHT OUTER JOIN DynamicQuestions ON DynamicAnswers.FK_Answers_ControlID = DynamicQuestions.ControlID
WHERE FK_DynamicQuestions_Topic = 56
ORDER BY ', '  + QUOTENAME(CONVERT(varchar, REPLACE(QAPanelName,'QA_','')) + CONVERT(varchar, LEN(Orderbynumber)) + CONVERT(varchar, Orderbynumber) + CONVERT(varchar, ControlID) + '_' + QuestionColumnName)
FOR XML PATH('')
)
, 1, 1, '')

--------------------------------------------

DECLARE @sql NVARCHAR(MAX)

SET @sql = 'SELECT DISTINCT * FROM (SELECT  Country,eMail,ShortTalk,InvoiceNum, CONVERT(varchar, REPLACE(QAPanelName,''QA_'','''')) + CONVERT(varchar, LEN(Orderbynumber)) + CONVERT(varchar, Orderbynumber) + CONVERT(varchar, ControlID) + ''_'' + QuestionColumnName AS FK_Answers_ControlID, DynamicAnswers.Answer
FROM             customer LEFT OUTER JOIN DynamicQuestions INNER JOIN DynamicAnswers ON DynamicQuestions.ControlID = DynamicAnswers.FK_Answers_ControlID
                 ON DynamicAnswers.FK_Answers_customer = customer.InvoiceNum
WHERE( DynamicQuestions.FK_DynamicQuestions_Topic = 56  AND  (Deleted = 0 AND customer.SubmissionConfirmed = 1  AND FK_customer_Topic = 56  AND (Cancelled = 0)  AND ( (DynamicQuestions.ControlID = 42 AND DynamicAnswers.Answer = ''30'')  OR (DynamicQuestions.ControlID = 43 AND DynamicAnswers.Answer = ''Texas'') ) AND FK_DynamicQuestions_Topic = 56 ) )) AS[SubTable]
PIVOT
(
MAX(Answer)
FOR[FK_Answers_ControlID] IN(' + @docDates + ')
) AS[Pivot]; '
EXEC sp_executesql @sql
```


问:
How to load a PDF file from server and print it using Javascript?
I have an ajax function that gets a PDF file from the server.

```<code>$("button").click(function(){
  $.ajax({'/send/myfile', success: function(result){
    var myPDF = result;
    console.log(typeof(myPDF);
    myPDF.print()
  }});
});
</code>```

My backend is done in Flask

```<code>
@app.route('/send/myfile', methods=['GET', 'POST'])
def send_myfile():
    return send_file("myFolder/myfile.pdf",
                         mimetype='application/pdf',
                         attachment_filename=f"document.pdf",
                         as_attachment=True,
                         cache_timeout=-1)
</code>```

So when I send this pdf file from the server the output I get in my variable is a string and not an actual PDF object. What I am trying to achieve here is to directly print that PDF file sent from server using javascript. How can I achieve this?

Body:
I have an ajax function that gets a PDF file from the server.

$("button").click(function(){
  $.ajax({'/send/myfile', success: function(result){
    var myPDF = result;
    console.log(typeof(myPDF);
    myPDF.print()
  }});
});

My backend is done in Flask

@app.route('/send/myfile', methods=['GET', 'POST'])
def send_myfile():
    return send_file("myFolder/myfile.pdf",
                         mimetype='application/pdf',
                         attachment_filename=f"document.pdf",
                         as_attachment=True,
                         cache_timeout=-1)

So when I send this pdf file from the server the output I get in my variable is a string and not an actual PDF object. What I am trying to achieve here is to directly print that PDF file sent from server using javascript. How can I achieve this?


问:
Storing CSV file when running PowerShell with Intune
What are some options to save the CSV file when running the PowerShell script (imports the CSV) with Microsoft Endpoint with Intune?

Ways to save the CSV file outside of the cloud world


问:
Reading the video stream from another system (OpenCV, Python)
Good day dear community,

I have a system that is running a Nvidia NX system with an IntelSense 3D camera. The goal is to capture the video stream with Python and OpenCV on another computer that is connected over WiFi with the system.

On my computer I can access the videostream in my browser with XXX.XXX.XX.X:8080 over mjpg-streamer.  The correct http-address is: http://XXX.XXX.XX.X:8080/stream.html

Unfortunately I had zero success with different approaches. First I tried to fetch the stream directly with OpenCV:

```<code>import cv2

stream = cv2.VideoCapture('http://192.168.12.1:8080/stream.html')

while True:

    ret, frame = stream.read()
    cv2.imshow('Video Stream Monitor', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
stream.release()
cv2.destroyAllWindows()
</code>```

This didn't work. Too easy to be true.

Next I stumbled accross this thread and thought this may be more promising because in my first example I did nothing to convert the data. I updated my code:

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

# stream = cv2.VideoCapture('http://192.168.12.1:8080/stream.html')
stream = urllib.request.urlopen('http://localhost:8080/frame.mjpg')
bytes = ''

while True:
    bytes += stream.read(1024)
    a = bytes.find('\xff\xd8')
    b = bytes.find('\xff\xd9')
    if a != -1 and b != -1:
        jpg = bytes[a:b+2]
        bytes = bytes[b+2:]
        i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_COLOR)
        cv2.imshow('i', i)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
stream.release()
cv2.destroyAllWindows()
</code>```

And the result was an Error:

```<code>URLError: <urlopen error [WinError 10061] Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte>
</code>```

Target computer denies the connection. And this is where I'm still stuck (I run Windows and it may be due to that, I will try switching to a Linux system). Although I think, that with the connection established, there will still be problems because I capture data from .html link and the code is requesting with a .mjpg ending.

Anyways, is there somebody that knows how I can get the stream from my system to my computer?

I also thought about connection the computer with a socket to the system ip and port to retrieve the data. Would that be even possible without setting up a server-client architecture on both systems? But that would be not my very first option because I already have latency because of the WiFi connection. Implementing a socket with server and client will make latency issues worse, so I'd like to retrieve the stream preferably directly.

Any help appreciated.

Everything I tried is stated with my code examples. Thus, this line is obligatory information.

Body:
Good day dear community,

I have a system that is running a Nvidia NX system with an IntelSense 3D camera. The goal is to capture the video stream with Python and OpenCV on another computer that is connected over WiFi with the system.

On my computer I can access the videostream in my browser with XXX.XXX.XX.X:8080 over mjpg-streamer.  The correct http-address is: http://XXX.XXX.XX.X:8080/stream.html

Unfortunately I had zero success with different approaches. First I tried to fetch the stream directly with OpenCV:

import cv2

stream = cv2.VideoCapture('http://192.168.12.1:8080/stream.html')

while True:

    ret, frame = stream.read()
    cv2.imshow('Video Stream Monitor', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
stream.release()
cv2.destroyAllWindows()

This didn't work. Too easy to be true.

Next I stumbled accross this thread and thought this may be more promising because in my first example I did nothing to convert the data. I updated my code:

import cv2
import urllib
import numpy as np

# stream = cv2.VideoCapture('http://192.168.12.1:8080/stream.html')
stream = urllib.request.urlopen('http://localhost:8080/frame.mjpg')
bytes = ''

while True:
    bytes += stream.read(1024)
    a = bytes.find('\xff\xd8')
    b = bytes.find('\xff\xd9')
    if a != -1 and b != -1:
        jpg = bytes[a:b+2]
        bytes = bytes[b+2:]
        i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_COLOR)
        cv2.imshow('i', i)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
stream.release()
cv2.destroyAllWindows()

And the result was an Error:

URLError: <urlopen error [WinError 10061] Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte>

Target computer denies the connection. And this is where I'm still stuck (I run Windows and it may be due to that, I will try switching to a Linux system). Although I think, that with the connection established, there will still be problems because I capture data from .html link and the code is requesting with a .mjpg ending.

Anyways, is there somebody that knows how I can get the stream from my system to my computer?

I also thought about connection the computer with a socket to the system ip and port to retrieve the data. Would that be even possible without setting up a server-client architecture on both systems? But that would be not my very first option because I already have latency because of the WiFi connection. Implementing a socket with server and client will make latency issues worse, so I'd like to retrieve the stream preferably directly.

Any help appreciated.

Everything I tried is stated with my code examples. Thus, this line is obligatory information.


问:
Number of replacements performed by str.replace
I'd have expected to find at least a question on this subject, instead... nothing.

I am writing a script for the smart patching of a project, so I have a dictionary where keys are file paths and values are lists of tuples, and each tuple is an original/replacement pair. I loop on files, slurp each file, apply changes to the contents, rename the original, and write the changed contents to the original name. Pretty standard stuff.

The changes I have to apply were for a two month old version of the project, so I decided I did not want to use diff and patch: the sections I am changing now may have moved by many lines, but they shouldn't be changed – mostly.

This means I have to check that each diff is correctly applied – but it seems there is no way to obtain the number of replacements from str.replace().

Of course I can compare the string before and after the replacement, but this seems inefficient, and does not allow to check the number of replacements performed.

Annoyingly, regexps have a subn() method that does exactly this, but my patterns may contain lots of special characters, so using regexps would be a pain. And apparently there is no equivalent method for strings.

I'm going to write a function to do a search/replace in a loop for each replacement – but it seems a sort of an overkill... Does anybody have a better idea?

EDIT: oh, here's a similar question, but the replacement pattern is a regex, so re.subn() is an acceptable solution...


问:
dontwarn !com.my.package causes syntax error
I get a syntax error for this line:

```<code>-dontwarn !com.my.package.**,**
</code>```

The error is:

```<code><class name> expected, got '!'
</code>```

It builds without problems, and I don't get any warnings (which was the point of adding it).

I still get a red mark around it though, indicating that this is illegal syntax.

Body:
I get a syntax error for this line:

-dontwarn !com.my.package.**,**

The error is:

<class name> expected, got '!'

It builds without problems, and I don't get any warnings (which was the point of adding it).

I still get a red mark around it though, indicating that this is illegal syntax.


问:
Issues with images showing on PC but not on mobile
The CSS is not working. The text on certain images shows on PC but not on the mobile version of the site.

The site is www.greencitylandscapes.co.uk and the home page has 3 images with text visible on the PC version, but these are not visible in the mobile version.

The images appear but without text.
How can I fix this problem?

```<code>/**
 *  Master Slider
 *  Default Skin
 */

.ms-skin-default .ms-slide .ms-slide-vpbtn,
.ms-skin-default .ms-video-btn{
    width: 50px;
    height: 51px;
    background: url(light-skin-1.png) no-repeat -14px -150px;
    top: 50%;
    left: 50%;
    margin: -25px 0 0 -25px;
}

.ms-skin-default .ms-slide .ms-slide-vcbtn {
    width: 30px;
    height: 30px;
    background: url(light-skin-1.png) no-repeat -24px -28px;
    top: 18px;
    right: 30px;
}

/* controls */

.ms-skin-default .ms-nav-next,
.ms-skin-default .ms-nav-prev {
    width: 30px;
    background: url(light-skin-1.png);
    background-position: -89px -26px;
    height: 40px;
    cursor: pointer;
    top: 50%;
    left: 30px;
    margin-top: -20px;
    position: absolute;
    z-index: 110;
}
.ms-skin-default .ms-nav-next {
    right: 30px;
    left: auto;
    background-position: -89px -103px;
}

.ms-skin-default .ms-bullet {
    width: 10px;
    height: 10px;
    background: url(light-skin-1.png) no-repeat;
    margin: 4px;
    background-position: -34px -117px;
}

.ms-skin-default .ms-bullet-selected {
    background-position: -34px -84px;
}

.ms-skin-default .ms-time-bar {
    height: 3px;
    background: #FFFFFF;
    border-top: solid 1px rgba(0, 0, 0, 0.41);
}

.ms-skin-default .ms-tooltip{
    position: absolute;
    z-index: 210;
    cursor: auto;
}

.ms-skin-default .ms-tooltip-top .ms-tooltip-arrow,
.ms-skin-default .ms-tooltip-bottom .ms-tooltip-arrow{
    border-left: solid 10px transparent;
    border-right: solid 10px transparent;
    position: absolute;
    left: 50%;
    margin-left: -10px;
}

.ms-skin-default .ms-tooltip-top .ms-tooltip-arrow{
    border-top: solid 10px;
    border-top-color: silver;
    border-top-color: rgba(240, 240, 240, 0.88);
    bottom: -10px;
}

.ms-skin-default .ms-tooltip-bottom .ms-tooltip-arrow {
    border-bottom: solid 10px;
    border-bottom-color: silver;
    border-bottom-color: rgba(240, 240, 240, 0.88);
    top: -10px;
}

.ms-skin-default .ms-tooltip-right .ms-tooltip-arrow,
.ms-skin-default .ms-tooltip-left .ms-tooltip-arrow{
    border-top: solid 10px transparent;
    border-bottom: solid 10px transparent;
    position: absolute;
    top: 50%;
    margin-top: -10px;
}

.ms-skin-default .ms-tooltip-right .ms-tooltip-arrow{
    border-right: solid 10px;
    border-right-color: silver;
    border-right-color: rgba(240, 240, 240, 0.88);
    left: -10px;
}

.ms-skin-default .ms-tooltip-left .ms-tooltip-arrow {
    border-left: solid 10px;
    border-left-color: silver;
    border-left-color: rgba(240, 240, 240, 0.88);
    right: -10px;
}

.ms-skin-default .ms-tooltip-point {cursor: pointer;}
.ms-skin-default .ms-tooltip-point .ms-point-center {
    width: 12px;
    height: 12px;
    border-radius: 15px;
    border: solid 2px #BBB;
    background: white;
    margin: -8px 0 0 -8px;
    position: absolute;
    z-index: 105;
}

.ms-skin-default .ms-tooltip-point .ms-point-border {
    width: 22px;
    height: 22px;
    background: black;
    background:rgba(0, 0, 0, 0.36);
    margin: -11px 0 0 -11px;
    position: absolute;
    border-radius: 15px;

    animation: point-anim 1.5s infinite ;
    -moz-animation: point-anim 1.5s infinite;
    -webkit-animation: point-anim 1.5s infinite;
    -o-animation: point-anim 1.5s infinite;
}

.ms-skin-default .ms-tooltip {
    max-width:200px;
}

.ms-skin-default .ms-tooltip-cont {
    padding: 10px;
    background: silver;
    background: rgba(240, 240, 240, 0.88);
    text-shadow: 0 1px 0px white;
    margin-left: -1px;
}

/* retina */
@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (   min--moz-device-pixel-ratio: 2),
only screen and (     -o-min-device-pixel-ratio: 2/1),
only screen and (        min-device-pixel-ratio: 2),
only screen and (                min-resolution: 192dpi),
only screen and (                min-resolution: 2dppx) {

    .ms-skin-default .ms-slide .ms-slide-vpbtn,
    .ms-skin-default .ms-video-btn,
    .ms-skin-default .ms-slide .ms-slide-vcbtn,
    .ms-skin-default .ms-nav-next,
    .ms-skin-default .ms-nav-prev,
    .ms-skin-default .ms-bullet{
        background-image:url(light-skin-1-retina.png);
        background-size: 152px 225px;
    }

}
</code>```

Body:
The CSS is not working. The text on certain images shows on PC but not on the mobile version of the site.

The site is www.greencitylandscapes.co.uk and the home page has 3 images with text visible on the PC version, but these are not visible in the mobile version.

The images appear but without text.
How can I fix this problem?

/**
 *  Master Slider
 *  Default Skin
 */

.ms-skin-default .ms-slide .ms-slide-vpbtn,
.ms-skin-default .ms-video-btn{
    width: 50px;
    height: 51px;
    background: url(light-skin-1.png) no-repeat -14px -150px;
    top: 50%;
    left: 50%;
    margin: -25px 0 0 -25px;
}

.ms-skin-default .ms-slide .ms-slide-vcbtn {
    width: 30px;
    height: 30px;
    background: url(light-skin-1.png) no-repeat -24px -28px;
    top: 18px;
    right: 30px;
}

/* controls */

.ms-skin-default .ms-nav-next,
.ms-skin-default .ms-nav-prev {
    width: 30px;
    background: url(light-skin-1.png);
    background-position: -89px -26px;
    height: 40px;
    cursor: pointer;
    top: 50%;
    left: 30px;
    margin-top: -20px;
    position: absolute;
    z-index: 110;
}
.ms-skin-default .ms-nav-next {
    right: 30px;
    left: auto;
    background-position: -89px -103px;
}

.ms-skin-default .ms-bullet {
    width: 10px;
    height: 10px;
    background: url(light-skin-1.png) no-repeat;
    margin: 4px;
    background-position: -34px -117px;
}

.ms-skin-default .ms-bullet-selected {
    background-position: -34px -84px;
}

.ms-skin-default .ms-time-bar {
    height: 3px;
    background: #FFFFFF;
    border-top: solid 1px rgba(0, 0, 0, 0.41);
}

.ms-skin-default .ms-tooltip{
    position: absolute;
    z-index: 210;
    cursor: auto;
}

.ms-skin-default .ms-tooltip-top .ms-tooltip-arrow,
.ms-skin-default .ms-tooltip-bottom .ms-tooltip-arrow{
    border-left: solid 10px transparent;
    border-right: solid 10px transparent;
    position: absolute;
    left: 50%;
    margin-left: -10px;
}

.ms-skin-default .ms-tooltip-top .ms-tooltip-arrow{
    border-top: solid 10px;
    border-top-color: silver;
    border-top-color: rgba(240, 240, 240, 0.88);
    bottom: -10px;
}

.ms-skin-default .ms-tooltip-bottom .ms-tooltip-arrow {
    border-bottom: solid 10px;
    border-bottom-color: silver;
    border-bottom-color: rgba(240, 240, 240, 0.88);
    top: -10px;
}

.ms-skin-default .ms-tooltip-right .ms-tooltip-arrow,
.ms-skin-default .ms-tooltip-left .ms-tooltip-arrow{
    border-top: solid 10px transparent;
    border-bottom: solid 10px transparent;
    position: absolute;
    top: 50%;
    margin-top: -10px;
}

.ms-skin-default .ms-tooltip-right .ms-tooltip-arrow{
    border-right: solid 10px;
    border-right-color: silver;
    border-right-color: rgba(240, 240, 240, 0.88);
    left: -10px;
}

.ms-skin-default .ms-tooltip-left .ms-tooltip-arrow {
    border-left: solid 10px;
    border-left-color: silver;
    border-left-color: rgba(240, 240, 240, 0.88);
    right: -10px;
}

.ms-skin-default .ms-tooltip-point {cursor: pointer;}
.ms-skin-default .ms-tooltip-point .ms-point-center {
    width: 12px;
    height: 12px;
    border-radius: 15px;
    border: solid 2px #BBB;
    background: white;
    margin: -8px 0 0 -8px;
    position: absolute;
    z-index: 105;
}

.ms-skin-default .ms-tooltip-point .ms-point-border {
    width: 22px;
    height: 22px;
    background: black;
    background:rgba(0, 0, 0, 0.36);
    margin: -11px 0 0 -11px;
    position: absolute;
    border-radius: 15px;

    animation: point-anim 1.5s infinite ;
    -moz-animation: point-anim 1.5s infinite;
    -webkit-animation: point-anim 1.5s infinite;
    -o-animation: point-anim 1.5s infinite;
}

.ms-skin-default .ms-tooltip {
    max-width:200px;
}

.ms-skin-default .ms-tooltip-cont {
    padding: 10px;
    background: silver;
    background: rgba(240, 240, 240, 0.88);
    text-shadow: 0 1px 0px white;
    margin-left: -1px;
}

/* retina */
@media
only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (   min--moz-device-pixel-ratio: 2),
only screen and (     -o-min-device-pixel-ratio: 2/1),
only screen and (        min-device-pixel-ratio: 2),
only screen and (                min-resolution: 192dpi),
only screen and (                min-resolution: 2dppx) {

    .ms-skin-default .ms-slide .ms-slide-vpbtn,
    .ms-skin-default .ms-video-btn,
    .ms-skin-default .ms-slide .ms-slide-vcbtn,
    .ms-skin-default .ms-nav-next,
    .ms-skin-default .ms-nav-prev,
    .ms-skin-default .ms-bullet{
        background-image:url(light-skin-1-retina.png);
        background-size: 152px 225px;
    }

}


问:
Real time notification without reloading
I am building some reminders on my system. A user can create reminders that will show an alert when is time to remind something to the user.

I'd like to know how to display an alert without reloading. I want to show this alert when remindTime = now.

Migration:

 Schema::create('reminders', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->string('description', 255);
    $table->dateTime('remindTime');
    $table->timestamps();
});
```
<p>Function from where I fetch only reminders who will be comming after 3 hours from now:</p>
<pre class="lang-php prettyprint-override"><code>$latestReminder = Reminder::where('remindTime', '<=', Carbon::now()->addHours(3)->toDateTimeString())
    ->where('remindTime', '>=', Carbon::now()->toDateTimeString())
    ->latest()
    ->take(3)
    ->get()
;
</code>```

How I fetch on vue:

```<code>getReminders() {
  axios.get('/reminders/get-reminders')
    .then(response => {
      this.reminders = response.data.data
    })
  },
}
</code>```

Body:
I am building some reminders on my system. A user can create reminders that will show an alert when is time to remind something to the user.

I'd like to know how to display an alert without reloading. I want to show this alert when remindTime = now.

Migration:

 Schema::create('reminders', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->string('description', 255);
    $table->dateTime('remindTime');
    $table->timestamps();
});

Function from where I fetch only reminders who will be comming after 3 hours from now:

$latestReminder = Reminder::where('remindTime', '<=', Carbon::now()->addHours(3)->toDateTimeString())
    ->where('remindTime', '>=', Carbon::now()->toDateTimeString())
    ->latest()
    ->take(3)
    ->get()
;

How I fetch on vue:

getReminders() {
  axios.get('/reminders/get-reminders')
    .then(response => {
      this.reminders = response.data.data
    })
  },
}


问:
How to show GenericRelation object field value in list_display?

models.py

```<code>class ModelA(models.Model):
  name = models.CharField(max_length=40)

class ModelB(models.Model):
  name = models.CharField(max_length=100)
  model_c = GenericRelation("modelc")

class ModelC(models.Model):
  model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE)
  content_type = models.ForeignKey(ContentType,
    limit_choices_to={"model__in":["modelb", "modelx", "modely"]},
    on_delete=models.CASCADE)
  object_id = models.PositiveIntegerField()
  details = GenericForeignKey("content_type","object_id")
</code>```

admin.py

```<code>class AdminModelB(admin.ModelAdmin):
  list_display = ("name", "model_a")

  @staticmethod
  def model_a(obj):
    return obj.model_c.model_a  # 'GenericRelatedObjectManager' object has no attribute 'model_a'
</code>```

I have ModelB having GenericRelation in field model_c where ModelC contain ContentType as ForeignKey. Now I want to display ModelA.name in list_display of ModelB. I have tried like other foreignkey fields but it gives me an error 'GenericRelatedObjectManager' object has no attribute 'model_a'.

Body:
models.py

class ModelA(models.Model):
  name = models.CharField(max_length=40)

class ModelB(models.Model):
  name = models.CharField(max_length=100)
  model_c = GenericRelation("modelc")

class ModelC(models.Model):
  model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE)
  content_type = models.ForeignKey(ContentType,
    limit_choices_to={"model__in":["modelb", "modelx", "modely"]},
    on_delete=models.CASCADE)
  object_id = models.PositiveIntegerField()
  details = GenericForeignKey("content_type","object_id")

admin.py

class AdminModelB(admin.ModelAdmin):
  list_display = ("name", "model_a")

  @staticmethod
  def model_a(obj):
    return obj.model_c.model_a  # 'GenericRelatedObjectManager' object has no attribute 'model_a'

I have ModelB having GenericRelation in field model_c where ModelC contain ContentType as ForeignKey. Now I want to display ModelA.name in list_display of ModelB. I have tried like other foreignkey fields but it gives me an error 'GenericRelatedObjectManager' object has no attribute 'model_a'.


问:
How to hide implementation of Nuget package?
I've created a Nuget package. After adding that nuget package to a test project, I'm able to navigate to the definition and see the implementation. I've packed the nuget using release configuration only. So, any help how to disable this definition navigation of my nuget package normally and even while debugging?</p>


问:
Claims being blown away after 5 minutes
Very simple setup in a new project.  If you do this, all your claims will be blown away after 5 minutes.  aud, id, name.  Everything gone after five minutes.  I think it has something to do with the first line.  I'd bet it's overriding all the claims after some sort of timeout.  You can test this, too. Just create a Startup class in a new .Net Framework MVC project and add this code.  Couldn't be simpler.  I have a feeling this is expected behaviour but I don't know why.

```<code>app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" });

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
    SaveTokens = true,
    ClientId = "mvc",
    Authority = "https://localhost:5001",
    RedirectUri = "https://localhost:44323/home",
    PostLogoutRedirectUri = "https://localhost:44323/home",
    UsePkce = true,
    RedeemCode = true,
    ClientSecret = "###",
    ResponseType = OpenIdConnectResponseType.CodeIdToken,
    Scope = "openid profile",
    SignInAsAuthenticationType = "Cookies",
});
</code>```

Wait 5 minutes.  Reload a page.  All the claims will be gone.  Within that 5 minutes they're all there.

Title: Claims being blown away after 5 minutes

Body:
Very simple setup in a new project.  If you do this, all your claims will be blown away after 5 minutes.  aud, id, name.  Everything gone after five minutes.  I think it has something to do with the first line.  I'd bet it's overriding all the claims after some sort of timeout.  You can test this, too. Just create a Startup class in a new .Net Framework MVC project and add this code.  Couldn't be simpler.  I have a feeling this is expected behaviour but I don't know why.

app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies" });

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
    SaveTokens = true,
    ClientId = "mvc",
    Authority = "https://localhost:5001",
    RedirectUri = "https://localhost:44323/home",
    PostLogoutRedirectUri = "https://localhost:44323/home",
    UsePkce = true,
    RedeemCode = true,
    ClientSecret = "###",
    ResponseType = OpenIdConnectResponseType.CodeIdToken,
    Scope = "openid profile",
    SignInAsAuthenticationType = "Cookies",
});

Wait 5 minutes.  Reload a page.  All the claims will be gone.  Within that 5 minutes they're all there.


问:
Front slash and special characters in rest service url
Restful web services : GetMapping url has a variable which should be passed as a path variable but that variable contains front slash and special characters in it. Any suggestions on how to handle that in springboot

```<code>@GetMapping(value = “/test/{id}”)
Public TestClass getData(@PathVariable(“id”)){
return testService.getDataService(id);
}
</code>```

Here the Path variable “id” value is “00/01*1”

Body:
Restful web services : GetMapping url has a variable which should be passed as a path variable but that variable contains front slash and special characters in it. Any suggestions on how to handle that in springboot

@GetMapping(value = “/test/{id}”)
Public TestClass getData(@PathVariable(“id”)){
return testService.getDataService(id);
}

Here the Path variable “id” value is “00/01*1”


问:
JavaFX application freezes when using Robot mouse move
I am trying to write an application which allow me to turn on and off mouse moving on button click.
However, when mouse starting to move whole application freezes and I have to kill it from IDE.

I have tried to put mouse mover to different thread but I have an error:

```<code>Exception in thread "Thread-4" java.lang.IllegalStateException: This operation is permitted on the event thread only; currentThread = Thread-4
    at javafx.graphics/com.sun.glass.ui.Application.checkEventThread(Application.java:447)
    at javafx.graphics/com.sun.glass.ui.mac.MacRobot.mouseMove(MacRobot.java:78)
    at javafx.graphics/javafx.scene.robot.Robot.mouseMove(Robot.java:168)
    at com.example.testfx/com.example.testfx.HelloController.lambda$new$0(HelloController.java:32)
    at java.base/java.lang.Thread.run(Thread.java:833)
</code>```

Code snippet:

```<code>import java.util.Random;

import javafx.fxml.FXML;
import javafx.scene.control.ToggleButton;
import javafx.scene.paint.Paint;
import javafx.scene.robot.Robot;
import javafx.scene.shape.Circle;
import lombok.SneakyThrows;

public class HelloController {

    private static final String red = "#da203f";
    private static final String green = "#2fb21e";
    public static final int FIVE_SECONDS = 5000;

    @FXML
    private Circle circle1;
    @FXML
    private ToggleButton toggleClick;
    public Thread t;

    public HelloController() {
        t = new Thread(() -> {

            while (true) {
                try {
                    Robot robot = new Robot();
                    Random random = new Random();
                    robot.mouseMove(random.nextInt(400), random.nextInt(400));
                    Thread.sleep(FIVE_SECONDS);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    @FXML
    @SneakyThrows
    protected void onToggleClicked() {
        if (toggleClick.isSelected()) {
            circle1.setFill(Paint.valueOf(red));
            t.interrupt();
        } else {
            circle1.setFill(Paint.valueOf(green));
            t.start();
        }
    }
</code>```

If if put the while loop in onToggleClicked() method without new thread, mouse is moving but application freezes.
I have tried also Platform.runLater but the effect is the same - app freezes.

Body:
I am trying to write an application which allow me to turn on and off mouse moving on button click.
However, when mouse starting to move whole application freezes and I have to kill it from IDE.

I have tried to put mouse mover to different thread but I have an error:

Exception in thread "Thread-4" java.lang.IllegalStateException: This operation is permitted on the event thread only; currentThread = Thread-4
    at javafx.graphics/com.sun.glass.ui.Application.checkEventThread(Application.java:447)
    at javafx.graphics/com.sun.glass.ui.mac.MacRobot.mouseMove(MacRobot.java:78)
    at javafx.graphics/javafx.scene.robot.Robot.mouseMove(Robot.java:168)
    at com.example.testfx/com.example.testfx.HelloController.lambda$new$0(HelloController.java:32)
    at java.base/java.lang.Thread.run(Thread.java:833)

Code snippet:

import java.util.Random;

import javafx.fxml.FXML;
import javafx.scene.control.ToggleButton;
import javafx.scene.paint.Paint;
import javafx.scene.robot.Robot;
import javafx.scene.shape.Circle;
import lombok.SneakyThrows;

public class HelloController {

    private static final String red = "#da203f";
    private static final String green = "#2fb21e";
    public static final int FIVE_SECONDS = 5000;

    @FXML
    private Circle circle1;
    @FXML
    private ToggleButton toggleClick;
    public Thread t;

    public HelloController() {
        t = new Thread(() -> {

            while (true) {
                try {
                    Robot robot = new Robot();
                    Random random = new Random();
                    robot.mouseMove(random.nextInt(400), random.nextInt(400));
                    Thread.sleep(FIVE_SECONDS);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    @FXML
    @SneakyThrows
    protected void onToggleClicked() {
        if (toggleClick.isSelected()) {
            circle1.setFill(Paint.valueOf(red));
            t.interrupt();
        } else {
            circle1.setFill(Paint.valueOf(green));
            t.start();
        }
    }

If if put the while loop in onToggleClicked() method without new thread, mouse is moving but application freezes.
I have tried also Platform.runLater but the effect is the same - app freezes.


问:
Error in lmSupport (package): 'lmSupport_2.9.11.tar.gz’ had non-zero exit status >
I want to find the effect size and power for the glm with gamma family. To do that I tried to install lmSupport package in R but it seems there is no package called "lmSupport".
I tried to install it manually by downloading the last version of it in R but got this error. Any one has any suggestion to solve it?

Here is the error that I get:

```<code>Warning in install.packages :
  installation of package ‘/var/folders/56/2d426wt94fs99vp9ysntwmb00000gn/T//RtmpF7zWtl/downloaded_packages/lmSupport_2.9.11.tar.gz’ had non-zero exit status.
</code>```

Body:
I want to find the effect size and power for the glm with gamma family. To do that I tried to install lmSupport package in R but it seems there is no package called "lmSupport".
I tried to install it manually by downloading the last version of it in R but got this error. Any one has any suggestion to solve it?

Here is the error that I get:

Warning in install.packages :
  installation of package ‘/var/folders/56/2d426wt94fs99vp9ysntwmb00000gn/T//RtmpF7zWtl/downloaded_packages/lmSupport_2.9.11.tar.gz’ had non-zero exit status.


问:
How can I load some specific files in advance on cache before actually using it?
I set up the NAS on ubunut servers, and mount it with nfs and cachefilesd.
So I want to use NAS with local cache.

The question I have is that before first access, if I want to load some files in advance to the local cache, what is the easiest way to do it.

I can think of that execute cat for all files, but is there a better way to do this?

Thanks!

I have tried to execute cat for all files, but I wonder if there exists a better way to do this.


问:
I have an issue with search of special characters in Elasticsearch wildcard
So, i have the following search in Elasticsearch

```<code>{
  "query": {
    "bool": {
      "should": [
        {
          "wildcard": {
            "projectName_search": {
              "value": "*Örli*",
              "case_insensitive": true
            }
          }
        }
        ...
      ]
    }
  }
}
</code>```

and this works fine. But if my query string is 'örli' (just a lowercase ö) I get no results. If i try to search with 'Zürich' and 'zürich' I get same results which meens that lowercase works in this case.

I expect go get same results for lowercase and uppercase letters. For Zürich it works but if first letter is lovercase ö I get no results

Body:
So, i have the following search in Elasticsearch

{
  "query": {
    "bool": {
      "should": [
        {
          "wildcard": {
            "projectName_search": {
              "value": "*Örli*",
              "case_insensitive": true
            }
          }
        }
        ...
      ]
    }
  }
}

and this works fine. But if my query string is 'örli' (just a lowercase ö) I get no results. If i try to search with 'Zürich' and 'zürich' I get same results which meens that lowercase works in this case.

I expect go get same results for lowercase and uppercase letters. For Zürich it works but if first letter is lovercase ö I get no results


问:
Flutter render downloaded html
I have an elearning APP in Flutter, which can render html files stored online. Now I want to download these files to assets, so they may be accessed offline. For this, I will download a zipped file with the entire html's folder and unzip it.

The problem is the html has many subfolders with it's own assets, which I would have to declare in the pubsp.yaml in order to access, but these downloadable htmls are constantly being added (every new course has new files).

I see a few ways to solve the problem:

Somehow declare access to subfolders in the pubsp.yaml.
As far as I know, this cannot be done.

Update the folder access for the installed APP dynamically.
As far as I know, this cannot be done.

Read the html file without unziping it.
I don't know if this is doable (I'm using webview_flutter_plus to render) and weather it would allow access to files in folders inside the zip without declaring them in the .yaml.

Pre-load empty folders inside assets that would mimic the html folder structure, declare them in the .yaml and then unzip and read the htmls from these folders. I would create some 100 of them in order to accomodate a large number of course downloads.
I believe this method would work, but it seems very cumbersome and inelegant.

So my questions are:

Would any of methods 1-3 work and if so how?

Would method 4 work?

Is it possible to reference folders in the .yaml file without them existing? It would make method 4 far easier.

Is there any other way to accomplish this? I cannot change the language, since the APP is months along, but plugins are fair game.

Thanks in advance!

Title: Flutter render downloaded html


问:
Remove warning when navigating away from changed form in PDF.js viewer
I have set up a PDF viewer in my web application using the PDF.js project. If the PDF contains a form, and the user has edited the form, but navigates back, he gets a popup asking if he wants to navigate away, and that changes might not have been saved.

How do I remove the popup warning my users?

I have tried removing the beforeunload event that is triggering this popup with all of these lines alone, but none of them work:

// None of these work:
window.beforeunload = null;
window.beforeunload = function(event) { };
window.beforeunload = undefined;
```

I know this event is added by the PDF.js project because of this issue stating it.

I am using PDF.js version 3.0.279.

Body:
I have set up a PDF viewer in my web application using the PDF.js project. If the PDF contains a form, and the user has edited the form, but navigates back, he gets a popup asking if he wants to navigate away, and that changes might not have been saved.

How do I remove the popup warning my users?

I have tried removing the beforeunload event that is triggering this popup with all of these lines alone, but none of them work:

// None of these work:
window.beforeunload = null;
window.beforeunload = function(event) { };
window.beforeunload = undefined;

I know this event is added by the PDF.js project because of this issue stating it.

I am using PDF.js version 3.0.279.


问:
Ata interrupts fires constantly on real hardware
I have been writing some ata stuff recently. On real hardware the ata controller uses IRQ_11. To get the driver to work I had to mask IRQ_11 because it would constantly fire after issuing the identify command. Down here is some simplified code which will cause the problem.

```<code>  mov si, 45056 ;Real hardware port

  mov dx, si
  add dx, 6
  mov al, 0xA0
  out dx, al ;Select drive (master in this test)

  push 10 ;Give controller a bit more time
  call wait_milliseconds

  ;These things should be set to 0

  mov dx, si
  add dx, 3
  mov al, 0
  out dx, al ;Set to 0

  mov dx, si
  add dx, 4
  mov al, 0
  out dx, al ;Set to 0

  mov dx, si
  add dx, 5
  mov al, 0
  out dx, al ;Set to 0

  ;Send identify command
  mov dx, si
  add dx, 7
  mov al, 0xEC
  out dx, al
</code>```

I have made sure my handler sends a EOI. I am also sure that my Pic is remapped. I have also tried reading the status port after, as well as in the handler. I really have no idea why this thing will constantly fire and filling the screen with the message I put in my handler.

Body:
I have been writing some ata stuff recently. On real hardware the ata controller uses IRQ_11. To get the driver to work I had to mask IRQ_11 because it would constantly fire after issuing the identify command. Down here is some simplified code which will cause the problem.

  mov si, 45056 ;Real hardware port

  mov dx, si
  add dx, 6
  mov al, 0xA0
  out dx, al ;Select drive (master in this test)

  push 10 ;Give controller a bit more time
  call wait_milliseconds

  ;These things should be set to 0

  mov dx, si
  add dx, 3
  mov al, 0
  out dx, al ;Set to 0

  mov dx, si
  add dx, 4
  mov al, 0
  out dx, al ;Set to 0

  mov dx, si
  add dx, 5
  mov al, 0
  out dx, al ;Set to 0

  ;Send identify command
  mov dx, si
  add dx, 7
  mov al, 0xEC
  out dx, al

I have made sure my handler sends a EOI. I am also sure that my Pic is remapped. I have also tried reading the status port after, as well as in the handler. I really have no idea why this thing will constantly fire and filling the screen with the message I put in my handler.


问:
Which way to perform AST transformation in webpack is fastest currently?
I need to replace some JS constructions on build phase.
Rules are simple, usually I need just special named symbols to replace with another construction. Like mySymbol -> mySymbolReplaced().
I'm using webpack 5.
Could you suggest the fastest way to perform such action?

I've tried babel loader, but it was very slow, maybe I was cooking it wrong.
Now I'm using string-replace-loader plugin and just replace strings. It's faster, but still slow because there are multiple rules and it isn't flexible enough. So I'd prefer AST -> AST transformation.


问:
"ReferenceError: Worker is not defined when running tests in Jest"
I am using Jest to run tests for a React app, and I am seeing the following error when running the tests:

```<code>ReferenceError: Worker is not defined
</code>```

This error is occurring even though the component that is being tested is not using the heic2any library. The error is causing the tests to stop running.

Here is the code for the component that is being tested:

```<code>import { Button } from '@material-ui/core';
import { ReactElement } from 'react';
import useBreakpoint from 'src/hooks/useBreakpoint';

interface ActionButtonProps {
  isMobileOnly?: boolean;
  icon?: ReactElement;
  onClick?: () => void;
  ['data-testid']?: string
}

const ActionButton = ({ isMobileOnly = false, icon, onClick, ...rest }: ActionButtonProps) => {
  const { isMobile } = useBreakpoint();
  const text = isMobile ? 'Add' : 'Add Photo Description Set';

  if ((!isMobile && isMobileOnly) || (isMobile && !isMobileOnly)) {
    return null;
  }

  return (
    <Button
      data-testid={rest['data-testid']}
      startIcon={icon}
      variant="outlined"
      onClick={onClick}
    >
      {text}
    </Button>
  );
};

export default ActionButton;
</code>```

This is the code of the component where heic2any was imported (which is another file)

```<code>import React from 'react';
import { SxProps } from '@material-ui/system';
import { PencilAlt } from 'src/icons';
import heic2any from 'heic2any';

interface FileImageDropzoneProps extends DropzoneOptions {
  cardMediaSx?: SxProps;
}

const FileImageDropzone: React.FC<FileImageDropzoneProps> = (props) => {
  // component code goes here...
};

export default FileImageDropzone;
</code>```

Here's my unit test:

```<code>import ActionButton from '../ActionButton';
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
import useBreakpoint, { BreakpointHook } from 'src/hooks/useBreakpoint';
import '@testing-library/jest-dom';

afterEach(cleanup)
jest.mock('src/hooks/useBreakpoint');

const mockUseBreakpoint: jest.Mock<BreakpointHook> = useBreakpoint as jest.Mock<BreakpointHook>;

describe('ActionButton', () => {
  it('should render the compnent', () => {

    render(<ActionButton data-testid='action-button' />);
    mockUseBreakpoint.mockReturnValue({
      isMobile: true,
      isDesktop: false,
    })

    const { getByTestId } = screen

    expect(getByTestId('action-button')).toBeInTheDocument()
  });
});
</code>```

Here's my jest config :

```<code>module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  transform: {
    '^.+\\.tsx?$': [
      'ts-jest',
      {
        isolatedModules: true,
      },
    ],
  },
  testMatch: ['**/src/**/__tests__/**/*.test.ts?(x)'],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  collectCoverage: true,
  coveragePathIgnorePatterns: [
    '/node_modules/',
    '/__tests__/',
    '/dist/',
    '/coverage/',
  ],
  setupFilesAfterEnv: [
    '@testing-library/jest-dom/extend-expect',
    'jest-canvas-mock',
    '<rootDir>/jest.setup.ts',
  ],
  moduleNameMapper: {
    '^components/(.*)$': '<rootDir>/src/components/$1',
  },
  testPathIgnorePatterns: ['node_modules'],
  moduleNameMapper: {
    '^src/(.*)$': '<rootDir>/src',
  },
  moduleDirectories: ['node_modules'],
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
};
</code>```

I am not sure why this error is occurring or how to fix it. Can anyone help me understand what is causing this issue and how to resolve it? The error even shows even if i commented out the it()

Body:
I am using Jest to run tests for a React app, and I am seeing the following error when running the tests:

ReferenceError: Worker is not defined

This error is occurring even though the component that is being tested is not using the heic2any library. The error is causing the tests to stop running.

Here is the code for the component that is being tested:

import { Button } from '@material-ui/core';
import { ReactElement } from 'react';
import useBreakpoint from 'src/hooks/useBreakpoint';

interface ActionButtonProps {
  isMobileOnly?: boolean;
  icon?: ReactElement;
  onClick?: () => void;
  ['data-testid']?: string
}

const ActionButton = ({ isMobileOnly = false, icon, onClick, ...rest }: ActionButtonProps) => {
  const { isMobile } = useBreakpoint();
  const text = isMobile ? 'Add' : 'Add Photo Description Set';

  if ((!isMobile && isMobileOnly) || (isMobile && !isMobileOnly)) {
    return null;
  }

  return (
    <Button
      data-testid={rest['data-testid']}
      startIcon={icon}
      variant="outlined"
      onClick={onClick}
    >
      {text}
    </Button>
  );
};

export default ActionButton;

This is the code of the component where heic2any was imported (which is another file)

import React from 'react';
import { SxProps } from '@material-ui/system';
import { PencilAlt } from 'src/icons';
import heic2any from 'heic2any';

interface FileImageDropzoneProps extends DropzoneOptions {
  cardMediaSx?: SxProps;
}

const FileImageDropzone: React.FC<FileImageDropzoneProps> = (props) => {
  // component code goes here...
};

export default FileImageDropzone;

Here's my unit test:

import ActionButton from '../ActionButton';
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
import useBreakpoint, { BreakpointHook } from 'src/hooks/useBreakpoint';
import '@testing-library/jest-dom';

afterEach(cleanup)
jest.mock('src/hooks/useBreakpoint');

const mockUseBreakpoint: jest.Mock<BreakpointHook> = useBreakpoint as jest.Mock<BreakpointHook>;

describe('ActionButton', () => {
  it('should render the compnent', () => {

    render(<ActionButton data-testid='action-button' />);
    mockUseBreakpoint.mockReturnValue({
      isMobile: true,
      isDesktop: false,
    })

    const { getByTestId } = screen

    expect(getByTestId('action-button')).toBeInTheDocument()
  });
});

Here's my jest config :

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom',
  transform: {
    '^.+\\.tsx?$': [
      'ts-jest',
      {
        isolatedModules: true,
      },
    ],
  },
  testMatch: ['**/src/**/__tests__/**/*.test.ts?(x)'],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  collectCoverage: true,
  coveragePathIgnorePatterns: [
    '/node_modules/',
    '/__tests__/',
    '/dist/',
    '/coverage/',
  ],
  setupFilesAfterEnv: [
    '@testing-library/jest-dom/extend-expect',
    'jest-canvas-mock',
    '<rootDir>/jest.setup.ts',
  ],
  moduleNameMapper: {
    '^components/(.*)$': '<rootDir>/src/components/$1',
  },
  testPathIgnorePatterns: ['node_modules'],
  moduleNameMapper: {
    '^src/(.*)$': '<rootDir>/src',
  },
  moduleDirectories: ['node_modules'],
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
};

I am not sure why this error is occurring or how to fix it. Can anyone help me understand what is causing this issue and how to resolve it? The error even shows even if i commented out the it()


问:
How to update the dynamic island view after a certain interval of time in App kill state.?
I want to start the dynamic island live activity for count down timer with event title.

Like christmas in 05 days.

I am trying to update it with the help of timer in extension, but not able to update the view.

```<code> Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { [self] time in

                 if minute < 1 {
                     updateActivity(dynamicIslandType: dynamicIslandType, minute: 0)
                     time.invalidate()
                }
</code>```

I have tried this code in widget extension to update the view, but not able to get any update of the view.

Body:
I want to start the dynamic island live activity for count down timer with event title.

Like christmas in 05 days.

I am trying to update it with the help of timer in extension, but not able to update the view.

 Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { [self] time in

                 if minute < 1 {
                     updateActivity(dynamicIslandType: dynamicIslandType, minute: 0)
                     time.invalidate()
                }

I have tried this code in widget extension to update the view, but not able to get any update of the view.