问:
Commands not working, and trying to add a queue/ability to add playlists
I'm trying to make a music bot for discord, everything appears to be working. It's turning on and detects the prefix, but when I do "?join" so it joins the Voice Channel it tells me "discord.ext.commands.errors.CommandNotFound: Command "join" is not found. Below is the code that I've used for the bot

```<code>import discord
from discord.ext import commands
import youtube_dl

class music(commands.Cog):

    def __init__(self, client):
        self.client = client

    @commands.command()
    async def join(self,ctx):
        if ctx.author.voice is None:
            await ctx.send("You're not in a voice channel!")
        voice_channel = ctx.author.voice.channel
        if ctx.voice_client is None:
            await voice_channel.connect()
        else:
            await ctx.voice_client.move_to(voice_channel)

    @commands.command()
    async def disconnect(self,ctx):
        await ctx.voice_client.disconnect()

    @commands.command()
    async def play(self,ctx,url):
        ctx.voice_client.stop()
        FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
        YDL_OPTIONS = {'format':"bestaudio"}
        vc = ctx.voice_client

        with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url, download=False)
            url2 = info['formats'][0]['url']
            source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
            vc.play(source)

    @commands.command()
    async def pause(self,ctx):
        await ctx.voice_client.pause()
        await ctx.channel.send("Paused")

    @commands.command()
    async def resume(self,ctx):
        await ctx.voice_client.resume()
        await ctx.channel.send("Resume")

def setup(client):

    client.add_cog(music(client))
</code>```

I'm unsure of what to do to fix this, I've tried looking up solutions but I either don't understand the code or it's not in the same "style" as the code that I have.

If someone could also help me integrate the ability to play playlists & queues into the bot, I'm once again lost on this since I have little to no experience with this, so any help would also be greatly appreciated. I figured I'd ask on the same post since all the code that I think is necessary to figure it out would already be here.

Body:
I'm trying to make a music bot for discord, everything appears to be working. It's turning on and detects the prefix, but when I do "?join" so it joins the Voice Channel it tells me "discord.ext.commands.errors.CommandNotFound: Command "join" is not found. Below is the code that I've used for the bot

import discord
from discord.ext import commands
import youtube_dl

class music(commands.Cog):

    def __init__(self, client):
        self.client = client

    @commands.command()
    async def join(self,ctx):
        if ctx.author.voice is None:
            await ctx.send("You're not in a voice channel!")
        voice_channel = ctx.author.voice.channel
        if ctx.voice_client is None:
            await voice_channel.connect()
        else:
            await ctx.voice_client.move_to(voice_channel)

    @commands.command()
    async def disconnect(self,ctx):
        await ctx.voice_client.disconnect()

    @commands.command()
    async def play(self,ctx,url):
        ctx.voice_client.stop()
        FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
        YDL_OPTIONS = {'format':"bestaudio"}
        vc = ctx.voice_client

        with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
            info = ydl.extract_info(url, download=False)
            url2 = info['formats'][0]['url']
            source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
            vc.play(source)

    @commands.command()
    async def pause(self,ctx):
        await ctx.voice_client.pause()
        await ctx.channel.send("Paused")

    @commands.command()
    async def resume(self,ctx):
        await ctx.voice_client.resume()
        await ctx.channel.send("Resume")

def setup(client):

    client.add_cog(music(client))

I'm unsure of what to do to fix this, I've tried looking up solutions but I either don't understand the code or it's not in the same "style" as the code that I have.

If someone could also help me integrate the ability to play playlists & queues into the bot, I'm once again lost on this since I have little to no experience with this, so any help would also be greatly appreciated. I figured I'd ask on the same post since all the code that I think is necessary to figure it out would already be here.


来源: stackexchange

问:
Flutter html: how to get the document of a new tab
I am trying to open telegram in a new tab using flutter. Once telegram is open, I want it to search in the chats using a given input e.g. look for the chats containing cats. When using window.open, it returns a WindowBase instance, which has no document attribute. I need that attribute in order to execute querySelector.

How can I get the document of the new tab?

ContentLicense: CC BY-SA 4.0


问:
How to draw an histogram with float values and a specific step?
I am trying stuff out with plotter-rs and I wanted to create an histogram with float values ranging from 0.0f64 to 1.0f64 and have like 50 segments.

Following is what I have been trying. .build_cartesion_2d() is the part that creates bars with a define range on the x and y axis.

```<code>use plotters::prelude::*;
use tch::{kind,Tensor};

let path = path.unwrap_or("plots/0.png");
let root = BitMapBackend::new(path, (1280, 720)).into_drawing_area();
root.fill(&WHITE)?;
let mut chart = ChartBuilder::on(&root)
    .set_label_area_size(LabelAreaPosition::Left, 40)
    .set_label_area_size(LabelAreaPosition::Bottom, 40)
    .caption("Histogram", ("sans-serif", 40))
    .build_cartesian_2d((0i64..10).into_segmented(), 0i64..100)
    .unwrap();

chart.configure_mesh().draw().unwrap();
let t = Tensor::rand(&[100], kind::FLOAT_CPU);
t.print();
let data: ndarray::ArrayD<f64> = (&t).try_into().unwrap();

root.draw_series(
     Histogram::vertical(&chart)
     .style(BLUE.filled())
     .margin(10)
     .data(data.map(|x| (((x*100.).round()/100.) as i64, 1))),
).unwrap();
</code>```

Cargo.toml :

```<code>[package]
name = "test-rs"
version = "0.1.0"
edition = "2021"

[dependencies]
ndarray = "0.15.6"
plotters = "0.3.4"
tch = "0.10.1"```
```

Body:
I am trying stuff out with plotter-rs and I wanted to create an histogram with float values ranging from 0.0f64 to 1.0f64 and have like 50 segments.

Following is what I have been trying. .build_cartesion_2d() is the part that creates bars with a define range on the x and y axis.

use plotters::prelude::*;
use tch::{kind,Tensor};

let path = path.unwrap_or("plots/0.png");
let root = BitMapBackend::new(path, (1280, 720)).into_drawing_area();
root.fill(&WHITE)?;
let mut chart = ChartBuilder::on(&root)
    .set_label_area_size(LabelAreaPosition::Left, 40)
    .set_label_area_size(LabelAreaPosition::Bottom, 40)
    .caption("Histogram", ("sans-serif", 40))
    .build_cartesian_2d((0i64..10).into_segmented(), 0i64..100)
    .unwrap();

chart.configure_mesh().draw().unwrap();
let t = Tensor::rand(&[100], kind::FLOAT_CPU);
t.print();
let data: ndarray::ArrayD<f64> = (&t).try_into().unwrap();

root.draw_series(
     Histogram::vertical(&chart)
     .style(BLUE.filled())
     .margin(10)
     .data(data.map(|x| (((x*100.).round()/100.) as i64, 1))),
).unwrap();

Cargo.toml :

[package]
name = "test-rs"
version = "0.1.0"
edition = "2021"

[dependencies]
ndarray = "0.15.6"
plotters = "0.3.4"
tch = "0.10.1"```


问:
Moving Zeros To The End(in python) - my code doesn't work
The question is simply 'Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.'

Here is the code I wrote:

```<code>def move_zeros(lst):
    num_zeros = 0
    for num in lst:
        if num == 0:
            lst.remove(num)
            num_zeros+=1
    i = 1
    while i<=num_zeros:
        lst.append(0)
        i+=1
    return lst
</code>```

Input: [9, 0, 0, 9, 1, 2, 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9]

Output: [9, 9, 1, 2, 1, 1, 3, 1, 9, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0]

Expected: [9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

Body:
The question is simply 'Write an algorithm that takes an array and moves all of the zeros to the end, preserving the order of the other elements.'

Here is the code I wrote:

def move_zeros(lst):
    num_zeros = 0
    for num in lst:
        if num == 0:
            lst.remove(num)
            num_zeros+=1
    i = 1
    while i<=num_zeros:
        lst.append(0)
        i+=1
    return lst

Input: [9, 0, 0, 9, 1, 2, 0, 1, 0, 1, 0, 3, 0, 1, 9, 0, 0, 0, 0, 9]

Output: [9, 9, 1, 2, 1, 1, 3, 1, 9, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0]

Expected: [9, 9, 1, 2, 1, 1, 3, 1, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]


问:
Updating jquery version in rails
I'm running rails3 and was going to play around with jquery mobile, but it requires jQuery 1.5, and my install is currently using 1.4

When I run

```
rails g jquery:install
```

I get a jQuery UJS error, but it might not matter because it says 'downloading jQuery 1.4.4', which is the same version I already have.

When I request jQuery v 1.6.1 from with the javascript_include_tag, rails says that the version of jQuery isn't compatible with rails.

Should I just turn off the error?? If so, how?
Or should I somehow update something else in rails?

How can I update the version of jQuery?

ContentLicense: CC BY-SA 3.0

Title: Updating jquery version in rails

Body:
I'm running rails3 and was going to play around with jquery mobile, but it requires jQuery 1.5, and my install is currently using 1.4

When I run

rails g jquery:install

I get a jQuery UJS error, but it might not matter because it says 'downloading jQuery 1.4.4', which is the same version I already have.

When I request jQuery v 1.6.1 from with the javascript_include_tag, rails says that the version of jQuery isn't compatible with rails.

Should I just turn off the error?? If so, how?
Or should I somehow update something else in rails?

How can I update the version of jQuery?


问:
JavaFX Accelerator using Numeric keys (Ctrl+1) not cross plateform?
I have a JavaFX project that has a menu bar, and keyboard shortcuts assigned to the menu buttons. These shortcuts works fine, until I try to use the numeric keys (1234567890). I'm trying to assign shortcuts to tabs, so that Ctrl+1 selects the first tab, Ctrl+2 the second, and so on. Theses work fine on Windows, but the Ctrl+1 and Ctrl+0 shorcuts don't work on macOS, and not a single one works on Linux (Mint 21.1).

All the keyboards are french (Azerty).

I tried to override the fxml accelerator in the window controller initalizer, using KeyCode.SOFTKEY_1, DIGIT1 and AMPERSAND, but none of them work (see HelloControler.java)

In a new JavaFX project:

hello-view.fxml

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.Menu?>

<VBox xmlns:fx="http://javafx.com/fxml" fx:controller="com.example.minrepex.HelloController">
    <MenuBar fx:id="mainMenuBar">
        <Menu text="Vue">
            <MenuItem text="Manatee" accelerator="Ctrl+1" fx:id="button1"/>
            <MenuItem text="Manatee" accelerator="Ctrl+2" fx:id="button2"/>
            <MenuItem text="Manatee" accelerator="Ctrl+3" fx:id="button3"/>
            <MenuItem text="Manatee" accelerator="Ctrl+4" fx:id="button4"/>
            <MenuItem text="Manatee" accelerator="Ctrl+5" fx:id="button5"/>
            <MenuItem text="Manatee" accelerator="Ctrl+6" fx:id="button6"/>
            <MenuItem text="Manatee" accelerator="Ctrl+7" fx:id="button7"/>
            <MenuItem text="Manatee" accelerator="Ctrl+8" fx:id="button8"/>
            <MenuItem text="Manatee" accelerator="Ctrl+9" fx:id="button9"/>
            <MenuItem text="Manatee" accelerator="Ctrl+0" fx:id="button0"/>
        </Menu>
    </MenuBar>
</VBox>

</code>```

HelloController.java:

package com.example.minrepex;

import javafx.fxml.FXML;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;

public class HelloController {
    private final boolean isMacos;

    @FXML private MenuBar mainMenuBar;
    @FXML private MenuItem button1;
    @FXML private MenuItem button2;
    @FXML private MenuItem button3;
    @FXML private MenuItem button4;
    @FXML private MenuItem button5;
    @FXML private MenuItem button6;
    @FXML private MenuItem button7;
    @FXML private MenuItem button8;
    @FXML private MenuItem button9;
    @FXML private MenuItem button0;

    public HelloController() {
        final String os = System.getProperty("os.name");
        this.isMacos = (os != null && os.startsWith("Mac"));
    }

    @FXML
    public void initialize() {

        if (isMacos){
            // Use macOS menu bar
            mainMenuBar.setUseSystemMenuBar(true);
        }

        button1.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button1.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button2.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button3.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button4.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button5.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button6.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button7.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button8.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button9.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button0.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
    }
}
```
<p>HelloApplication.java (app)</p>
<pre class="lang-java prettyprint-override"><code>package com.example.minrepex;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class HelloApplication extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
        Scene scene = new Scene(fxmlLoader.load(), 320, 240);
        stage.setTitle("Hello!");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}
</code>```

Main.java

package com.example.minrepex;

public class Main {

    public static void main(String[] args) {
        HelloApplication.main(args);
    }

}
```

What is going on ?

Body:
I have a JavaFX project that has a menu bar, and keyboard shortcuts assigned to the menu buttons. These shortcuts works fine, until I try to use the numeric keys (1234567890). I'm trying to assign shortcuts to tabs, so that Ctrl+1 selects the first tab, Ctrl+2 the second, and so on. Theses work fine on Windows, but the Ctrl+1 and Ctrl+0 shorcuts don't work on macOS, and not a single one works on Linux (Mint 21.1).

All the keyboards are french (Azerty).

I tried to override the fxml accelerator in the window controller initalizer, using KeyCode.SOFTKEY_1, DIGIT1 and AMPERSAND, but none of them work (see HelloControler.java)

In a new JavaFX project:

hello-view.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.layout.VBox?>
<?import javafx.scene.control.MenuItem?>
<?import javafx.scene.control.MenuBar?>
<?import javafx.scene.control.Menu?>

<VBox xmlns:fx="http://javafx.com/fxml" fx:controller="com.example.minrepex.HelloController">
    <MenuBar fx:id="mainMenuBar">
        <Menu text="Vue">
            <MenuItem text="Manatee" accelerator="Ctrl+1" fx:id="button1"/>
            <MenuItem text="Manatee" accelerator="Ctrl+2" fx:id="button2"/>
            <MenuItem text="Manatee" accelerator="Ctrl+3" fx:id="button3"/>
            <MenuItem text="Manatee" accelerator="Ctrl+4" fx:id="button4"/>
            <MenuItem text="Manatee" accelerator="Ctrl+5" fx:id="button5"/>
            <MenuItem text="Manatee" accelerator="Ctrl+6" fx:id="button6"/>
            <MenuItem text="Manatee" accelerator="Ctrl+7" fx:id="button7"/>
            <MenuItem text="Manatee" accelerator="Ctrl+8" fx:id="button8"/>
            <MenuItem text="Manatee" accelerator="Ctrl+9" fx:id="button9"/>
            <MenuItem text="Manatee" accelerator="Ctrl+0" fx:id="button0"/>
        </Menu>
    </MenuBar>
</VBox>

HelloController.java:

package com.example.minrepex;

import javafx.fxml.FXML;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;

public class HelloController {
    private final boolean isMacos;

    @FXML private MenuBar mainMenuBar;
    @FXML private MenuItem button1;
    @FXML private MenuItem button2;
    @FXML private MenuItem button3;
    @FXML private MenuItem button4;
    @FXML private MenuItem button5;
    @FXML private MenuItem button6;
    @FXML private MenuItem button7;
    @FXML private MenuItem button8;
    @FXML private MenuItem button9;
    @FXML private MenuItem button0;

    public HelloController() {
        final String os = System.getProperty("os.name");
        this.isMacos = (os != null && os.startsWith("Mac"));
    }

    @FXML
    public void initialize() {

        if (isMacos){
            // Use macOS menu bar
            mainMenuBar.setUseSystemMenuBar(true);
        }

        button1.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button1.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button2.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button3.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button4.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button5.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button6.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button7.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button8.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button9.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
//      button0.setAccelerator(new KeyCodeCombination(KeyCode.AMPERSAND, KeyCombination.CONTROL_DOWN));
    }
}

HelloApplication.java (app)

package com.example.minrepex;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

public class HelloApplication extends Application {
    @Override
    public void start(Stage stage) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
        Scene scene = new Scene(fxmlLoader.load(), 320, 240);
        stage.setTitle("Hello!");
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

Main.java

package com.example.minrepex;

public class Main {

    public static void main(String[] args) {
        HelloApplication.main(args);
    }

}

What is going on ?


问:
Ingesting Scrapy data to Elasticsearch?
I'm trying to load my scrapy data to elasticsearch so that I can do such search, I've actually succeeded in loading the data to an sql database, but with ElasticSearch I think I am missing something in my code:

in pipeline.py

```<code>def ingestForES(title: str, author: str,rank: int,description):
    es_url = es(hosts=[{'host': 'http://X.X.X.X', 'port': 9200}])
    es = es(es_url,basic_auth=("elastic", "Datascience"), verify_certs=False)
    data = {'title': title,
            'author':  author,
            'rank':rank,
            'description': description,
            }
    resp = es.create(index='myindex', doc_type='mytype', body=data)
    print(resp)
</code>```

I think I should add something inside settings.py, because with sqllite I have uncommented the following rule

```<code>ITEM_PIPELINES = {
    'amazon.pipelines.AmazonPipeline': 300,
}
</code>```

I did a search and I found that I should also add in  settings.py:

```<code> ITEM_PIPELINES = {
  'scrapyelasticsearch.scrapyelasticsearch.ElasticSearchPipeline': 500
}

ELASTICSEARCH_SERVERS = ['http://X.X.X.X:9200']
ELASTICSEARCH_INDEX = 'myindex'
ELASTICSEARCH_TYPE = 'items'
ELASTICSEARCH_UNIQ_KEY = 'url'
</code>```

It's a little bit confusing to me, I am not that good with Scrapy but I am doing my best. So,please could anyone help me out with this and I will be gratefull. Thanks in advance.
Note: If you need extra information about the code I can share it.

Title: Ingesting Scrapy data to Elasticsearch?

Body:
I'm trying to load my scrapy data to elasticsearch so that I can do such search, I've actually succeeded in loading the data to an sql database, but with ElasticSearch I think I am missing something in my code:

in pipeline.py

def ingestForES(title: str, author: str,rank: int,description):
    es_url = es(hosts=[{'host': 'http://X.X.X.X', 'port': 9200}])
    es = es(es_url,basic_auth=("elastic", "Datascience"), verify_certs=False)
    data = {'title': title,
            'author':  author,
            'rank':rank,
            'description': description,
            }
    resp = es.create(index='myindex', doc_type='mytype', body=data)
    print(resp)

I think I should add something inside settings.py, because with sqllite I have uncommented the following rule

ITEM_PIPELINES = {
    'amazon.pipelines.AmazonPipeline': 300,
}

I did a search and I found that I should also add in  settings.py:

 ITEM_PIPELINES = {
  'scrapyelasticsearch.scrapyelasticsearch.ElasticSearchPipeline': 500
}

ELASTICSEARCH_SERVERS = ['http://X.X.X.X:9200']
ELASTICSEARCH_INDEX = 'myindex'
ELASTICSEARCH_TYPE = 'items'
ELASTICSEARCH_UNIQ_KEY = 'url'

It's a little bit confusing to me, I am not that good with Scrapy but I am doing my best. So,please could anyone help me out with this and I will be gratefull. Thanks in advance.
Note: If you need extra information about the code I can share it.


问:
Why does compiling with "mvn --update-snapshots install" fail, but immediately following with "mvn install" succeeds?
I've got a project with a bunch of modules that I'm trying to compile and run, and there's one module giving me trouble. The problem is the same in IntelliJ as on the command line ("error: cannot access SomeClass. class file for SomeClass not found"). This file exists in a dependency for the module I am trying to compile.

If I compile this one module with mvn --update-snapshots -Dmaven.test.skip install, the build fails. Then I immediately follow this up with mvn -Dmaven.test.skip install and it works fine.

Why is this? From what I understand about -U, if anything, the second build without the flag should also fail since it'd be referencing the newly pulled down snapshots.


问:
Ansible Python - Get vars including group vars and host vars
I'm trying to get vars of specified host including his host/group vars but I can't get the vars inside group var file

For example:

```<code>from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.vars.manager import Host

class AnsibleConnector:
    def __init__(self):
        self.ansible_inventory_file_path = "inventory.yml"
        self.loader = DataLoader()
        self.inventory = InventoryManager(self.loader, sources=self.ansible_inventory_file_path)
        self.variable_manager = VariableManager(loader=self.loader, inventory=self.inventory)

    def get_host_vars(self, host, include_group_vars=False, groups=None):
        if groups is None:
            groups = []
        group_vars = {}
        if include_group_vars:
            for group in groups:
                group_vars.update(self.get_group_vars(group))
        if isinstance(host, str):
            host = Host(name=host)
        # combine 3 dict in 1 with priority of host_vars (as ansible does)
        host_vars = {**group_vars, **self.variable_manager.get_vars(host=host, include_hostvars=True), **self.inventory.get_host(host.name).vars}
        return host_vars

    def get_group_vars(self, group):
        return self.inventory.groups[group].get_vars()

if __name__ == "__main__":
    ansible_connector = AnsibleConnector()
    ansible_connector.get_host_vars('hpserver01', True, ['hp-servers'])
</code>```

The code above gives me the host var of hpserver01 and gives me the group vars that are only inside my inventory.ini file but I can't get vars that are in groups_vars/hp-servers.yml

How can I get those vars?
I've searched in many threads, but I couldn't find any reference for how to get the group vars file.

I tried using get_group_vars from ansible.helpers but it didn't help...

Body:
I'm trying to get vars of specified host including his host/group vars but I can't get the vars inside group var file

For example:

from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.vars.manager import Host

class AnsibleConnector:
    def __init__(self):
        self.ansible_inventory_file_path = "inventory.yml"
        self.loader = DataLoader()
        self.inventory = InventoryManager(self.loader, sources=self.ansible_inventory_file_path)
        self.variable_manager = VariableManager(loader=self.loader, inventory=self.inventory)

    def get_host_vars(self, host, include_group_vars=False, groups=None):
        if groups is None:
            groups = []
        group_vars = {}
        if include_group_vars:
            for group in groups:
                group_vars.update(self.get_group_vars(group))
        if isinstance(host, str):
            host = Host(name=host)
        # combine 3 dict in 1 with priority of host_vars (as ansible does)
        host_vars = {**group_vars, **self.variable_manager.get_vars(host=host, include_hostvars=True), **self.inventory.get_host(host.name).vars}
        return host_vars

    def get_group_vars(self, group):
        return self.inventory.groups[group].get_vars()

if __name__ == "__main__":
    ansible_connector = AnsibleConnector()
    ansible_connector.get_host_vars('hpserver01', True, ['hp-servers'])

The code above gives me the host var of hpserver01 and gives me the group vars that are only inside my inventory.ini file but I can't get vars that are in groups_vars/hp-servers.yml

How can I get those vars?
I've searched in many threads, but I couldn't find any reference for how to get the group vars file.

I tried using get_group_vars from ansible.helpers but it didn't help...


问:
AddressSanitizer memcpy-param-overlap errors with std::string with visual studio 2019
I'm using address sanitizer (ASAN) with visual studio 2019 (version 16.9.2) on windows.

ASAN is reporting lots of errors and  almost all of them are memcpy-param-overlap.

They are related usage of std::string.

```<code>==13388==ERROR: AddressSanitizer: memcpy-param-overlap: memory ranges [0x2141a3ba,0x2141a3cb) and [0x2141a3b0, 0x2141a3c1) overlap
    #1 0x16d3e32 in std::basic_string<char,std::char_traits<char>,std::allocator<char> >::insert C:\VS2019\VC\Tools\MSVC\14.25.28610\include\xstring:3006
    #2 0x16ae413 in std::operator+<char,std::char_traits<char>,std::allocator<char> > C:\VS2019\VC\Tools\MSVC\14.25.28610\include\xstring:4346
</code>```

Here is another instance

```<code>==13388==ERROR: AddressSanitizer: memcpy-param-overlap: memory ranges [0x214239ba,0x214239cb) and [0x214239b0, 0x214239c1) overlap
    #1 0x16d3e32 in std::basic_string<char,std::char_traits<char>,std::allocator<char> >::insert C:\VS2019\VC\Tools\MSVC\14.25.28610\include\xstring:3006
    #2 0x16ae413 in std::operator+<char,std::char_traits<char>,std::allocator<char> > C:\VS2019\VC\Tools\MSVC\14.25.28610\include\xstring:4346
</code>```

There are lots of these and all the errors are similar to above.

I don't know what I'm missing here. Is this related to std libraries.

Any hints/direction would be helpful.

Body:
I'm using address sanitizer (ASAN) with visual studio 2019 (version 16.9.2) on windows.

ASAN is reporting lots of errors and  almost all of them are memcpy-param-overlap.

They are related usage of std::string.

==13388==ERROR: AddressSanitizer: memcpy-param-overlap: memory ranges [0x2141a3ba,0x2141a3cb) and [0x2141a3b0, 0x2141a3c1) overlap
    #1 0x16d3e32 in std::basic_string<char,std::char_traits<char>,std::allocator<char> >::insert C:\VS2019\VC\Tools\MSVC\14.25.28610\include\xstring:3006
    #2 0x16ae413 in std::operator+<char,std::char_traits<char>,std::allocator<char> > C:\VS2019\VC\Tools\MSVC\14.25.28610\include\xstring:4346

Here is another instance

==13388==ERROR: AddressSanitizer: memcpy-param-overlap: memory ranges [0x214239ba,0x214239cb) and [0x214239b0, 0x214239c1) overlap
    #1 0x16d3e32 in std::basic_string<char,std::char_traits<char>,std::allocator<char> >::insert C:\VS2019\VC\Tools\MSVC\14.25.28610\include\xstring:3006
    #2 0x16ae413 in std::operator+<char,std::char_traits<char>,std::allocator<char> > C:\VS2019\VC\Tools\MSVC\14.25.28610\include\xstring:4346

There are lots of these and all the errors are similar to above.

I don't know what I'm missing here. Is this related to std libraries.

Any hints/direction would be helpful.


问:
deallocate method is not correctly merging the free blocks after deallocating them
After deallocating two contiguous blocks I don't know why they are not merging this function is only merging deallocated blocks with free memory I have no idea what is wrong with this code this is what I tried how can I fix it?

public void deallocate(MemoryBlock block) {
block.allocated = false;

```<code>// Find the previous and next blocks in the list
int index = blocks.indexOf(block);
MemoryBlock prevBlock = index > 0 ? blocks.get(index - 1) : null;
MemoryBlock nextBlock = index < blocks.size() - 1 ? blocks.get(index + 1) : null;

// Try to merge the current block with the previous and next blocks, if they are free
if (prevBlock != null && !prevBlock.allocated) {
  prevBlock.size += block.size;
  blocks.remove(block);
  block = prevBlock;
  if (nextBlock != null && !nextBlock.allocated) {
    block.size += nextBlock.size;
    blocks.remove(nextBlock);
  }
} else if (nextBlock != null && !nextBlock.allocated) {
  block.size += nextBlock.size;
  blocks.remove(nextBlock);
}
</code>```

}

Body:
After deallocating two contiguous blocks I don't know why they are not merging this function is only merging deallocated blocks with free memory I have no idea what is wrong with this code this is what I tried how can I fix it?

public void deallocate(MemoryBlock block) {
block.allocated = false;

// Find the previous and next blocks in the list
int index = blocks.indexOf(block);
MemoryBlock prevBlock = index > 0 ? blocks.get(index - 1) : null;
MemoryBlock nextBlock = index < blocks.size() - 1 ? blocks.get(index + 1) : null;

// Try to merge the current block with the previous and next blocks, if they are free
if (prevBlock != null && !prevBlock.allocated) {
  prevBlock.size += block.size;
  blocks.remove(block);
  block = prevBlock;
  if (nextBlock != null && !nextBlock.allocated) {
    block.size += nextBlock.size;
    blocks.remove(nextBlock);
  }
} else if (nextBlock != null && !nextBlock.allocated) {
  block.size += nextBlock.size;
  blocks.remove(nextBlock);
}

}


问:
Bar chart not rendering in react using the nivo library
I can't seem to get nivo's bar charts to show up even though I'm following the docs. The doc is here: https://nivo.rocks/bar/

Below is the code, essentially the same as the docs except I added the parent div tag to add the height as mentioned by React js: Nivo Pie chart not showing up:

```<code>// install (please make sure versions match peerDependencies)
// yarn add @nivo/core @nivo/bar
import React from 'react'
import { render } from "react-dom";
import { ResponsiveBar } from '@nivo/bar'

// make sure parent container have a defined height when using
// responsive component, otherwise height will be 0 and
// no chart will be rendered.
// website examples showcase many properties,
// you'll often use just a few of them.
const BarChart = ({ data /* see data tab */ }) => {
  console.log(data)
  return (
    <div style={{ height: 400 }}>
    <ResponsiveBar
        data={data}
        keys={[
            'hot dog',
            'burger',
            'sandwich',
            'kebab',
            'fries',
            'donut'
        ]}
        indexBy="country"
        margin={{ top: 50, right: 130, bottom: 50, left: 60 }}
        padding={0.3}
        valueScale={{ type: 'linear' }}
        indexScale={{ type: 'band', round: true }}
        colors={{ scheme: 'nivo' }}
        defs={[
            {
                id: 'dots',
                type: 'patternDots',
                background: 'inherit',
                color: '#38bcb2',
                size: 4,
                padding: 1,
                stagger: true
            },
            {
                id: 'lines',
                type: 'patternLines',
                background: 'inherit',
                color: '#eed312',
                rotation: -45,
                lineWidth: 6,
                spacing: 10
            }
        ]}
        fill={[
            {
                match: {
                    id: 'fries'
                },
                id: 'dots'
            },
            {
                match: {
                    id: 'sandwich'
                },
                id: 'lines'
            }
        ]}
        borderColor={{
            from: 'color',
            modifiers: [
                [
                    'darker',
                    1.6
                ]
            ]
        }}
        axisTop={null}
        axisRight={null}
        axisBottom={{
            tickSize: 5,
            tickPadding: 5,
            tickRotation: 0,
            legend: 'country',
            legendPosition: 'middle',
            legendOffset: 32
        }}
        axisLeft={{
            tickSize: 5,
            tickPadding: 5,
            tickRotation: 0,
            legend: 'food',
            legendPosition: 'middle',
            legendOffset: -40
        }}
        labelSkipWidth={12}
        labelSkipHeight={12}
        labelTextColor={{
            from: 'color',
            modifiers: [
                [
                    'darker',
                    1.6
                ]
            ]
        }}
        legends={[
            {
                dataFrom: 'keys',
                anchor: 'bottom-right',
                direction: 'column',
                justify: false,
                translateX: 120,
                translateY: 0,
                itemsSpacing: 2,
                itemWidth: 100,
                itemHeight: 20,
                itemDirection: 'left-to-right',
                itemOpacity: 0.85,
                symbolSize: 20,
                effects: [
                    {
                        on: 'hover',
                        style: {
                            itemOpacity: 1
                        }
                    }
                ]
            }
        ]}
        role="application"
        ariaLabel="Nivo bar chart demo"
        barAriaLabel={function(e){return e.id+": "+e.formattedValue+" in country: "+e.indexValue}}
    />
    </div>
  )
}

export default BarChart
</code>```

Without specifying the height, nothing renders but by specifying the height, from the browser console I get the error:

```<code>nivo-bar.es.js:477 Uncaught TypeError: Object(...) is not a function
    at e (nivo-bar.es.js:477:1)
    at pe (nivo-bar.es.js:615:1)
    at ye (nivo-bar.es.js:748:1)
    at ke (nivo-bar.es.js:917:1)
    at renderWithHooks (react-dom.development.js:16317:1)
    at mountIndeterminateComponent (react-dom.development.js:19987:1)
    at beginWork (react-dom.development.js:21457:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4113:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4162:1)
    at invokeGuardedCallback (react-dom.development.js:4224:1)
    at beginWork$1 (react-dom.development.js:27244:1)
    at performUnitOfWork (react-dom.development.js:26380:1)
    at workLoopSync (react-dom.development.js:26290:1)
    at renderRootSync (react-dom.development.js:26259:1)
    at performConcurrentWorkOnRoot (react-dom.development.js:25556:1)
    at workLoop (scheduler.development.js:260:1)
    at flushWork (scheduler.development.js:234:1)
    at performWorkUntilDeadline (scheduler.development.js:518:1)
    at run (setImmediate.js:48:1)
    at runIfPresent (setImmediate.js:83:1)
    at onGlobalMessage (setImmediate.js:125:1)
</code>```

What am I missing? I should also mention I have used the line chart and pie chart from nivo and they render. Below is a list of my dependencies form package.json

```<code>"dependencies": {
    "@nivo/bar": "^0.80.0",
    "@nivo/core": "^0.80.0",
    "@nivo/line": "^0.80.0",
    "@nivo/pie": "^0.80.0",
    "@nivo/radar": "^0.80.0",
    "@reduxjs/toolkit": "^1.9.0",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.1.3",
    "bootstrap": "^5.2.2",
    "react": "^18.2.0",
    "react-bootstrap": "^2.5.0",
    "react-dom": "^18.2.0",
    "react-redux": "^8.0.5",
    "react-scripts": "^2.1.3",
    "react-select": "^5.7.0",
    "redux": "^4.2.0",
    "web-vitals": "^2.1.4"
  },
</code>```

Body:
I can't seem to get nivo's bar charts to show up even though I'm following the docs. The doc is here: https://nivo.rocks/bar/

Below is the code, essentially the same as the docs except I added the parent div tag to add the height as mentioned by React js: Nivo Pie chart not showing up:

// install (please make sure versions match peerDependencies)
// yarn add @nivo/core @nivo/bar
import React from 'react'
import { render } from "react-dom";
import { ResponsiveBar } from '@nivo/bar'

// make sure parent container have a defined height when using
// responsive component, otherwise height will be 0 and
// no chart will be rendered.
// website examples showcase many properties,
// you'll often use just a few of them.
const BarChart = ({ data /* see data tab */ }) => {
  console.log(data)
  return (

    <ResponsiveBar
        data={data}
        keys={[
            'hot dog',
            'burger',
            'sandwich',
            'kebab',
            'fries',
            'donut'
        ]}
        indexBy="country"
        margin={{ top: 50, right: 130, bottom: 50, left: 60 }}
        padding={0.3}
        valueScale={{ type: 'linear' }}
        indexScale={{ type: 'band', round: true }}
        colors={{ scheme: 'nivo' }}
        defs={[
            {
                id: 'dots',
                type: 'patternDots',
                background: 'inherit',
                color: '#38bcb2',
                size: 4,
                padding: 1,
                stagger: true
            },
            {
                id: 'lines',
                type: 'patternLines',
                background: 'inherit',
                color: '#eed312',
                rotation: -45,
                lineWidth: 6,
                spacing: 10
            }
        ]}
        fill={[
            {
                match: {
                    id: 'fries'
                },
                id: 'dots'
            },
            {
                match: {
                    id: 'sandwich'
                },
                id: 'lines'
            }
        ]}
        borderColor={{
            from: 'color',
            modifiers: [
                [
                    'darker',
                    1.6
                ]
            ]
        }}
        axisTop={null}
        axisRight={null}
        axisBottom={{
            tickSize: 5,
            tickPadding: 5,
            tickRotation: 0,
            legend: 'country',
            legendPosition: 'middle',
            legendOffset: 32
        }}
        axisLeft={{
            tickSize: 5,
            tickPadding: 5,
            tickRotation: 0,
            legend: 'food',
            legendPosition: 'middle',
            legendOffset: -40
        }}
        labelSkipWidth={12}
        labelSkipHeight={12}
        labelTextColor={{
            from: 'color',
            modifiers: [
                [
                    'darker',
                    1.6
                ]
            ]
        }}
        legends={[
            {
                dataFrom: 'keys',
                anchor: 'bottom-right',
                direction: 'column',
                justify: false,
                translateX: 120,
                translateY: 0,
                itemsSpacing: 2,
                itemWidth: 100,
                itemHeight: 20,
                itemDirection: 'left-to-right',
                itemOpacity: 0.85,
                symbolSize: 20,
                effects: [
                    {
                        on: 'hover',
                        style: {
                            itemOpacity: 1
                        }
                    }
                ]
            }
        ]}
        role="application"
        ariaLabel="Nivo bar chart demo"
        barAriaLabel={function(e){return e.id+": "+e.formattedValue+" in country: "+e.indexValue}}
    />

  )
}

export default BarChart

Without specifying the height, nothing renders but by specifying the height, from the browser console I get the error:

nivo-bar.es.js:477 Uncaught TypeError: Object(...) is not a function
    at e (nivo-bar.es.js:477:1)
    at pe (nivo-bar.es.js:615:1)
    at ye (nivo-bar.es.js:748:1)
    at ke (nivo-bar.es.js:917:1)
    at renderWithHooks (react-dom.development.js:16317:1)
    at mountIndeterminateComponent (react-dom.development.js:19987:1)
    at beginWork (react-dom.development.js:21457:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4113:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4162:1)
    at invokeGuardedCallback (react-dom.development.js:4224:1)
    at beginWork$1 (react-dom.development.js:27244:1)
    at performUnitOfWork (react-dom.development.js:26380:1)
    at workLoopSync (react-dom.development.js:26290:1)
    at renderRootSync (react-dom.development.js:26259:1)
    at performConcurrentWorkOnRoot (react-dom.development.js:25556:1)
    at workLoop (scheduler.development.js:260:1)
    at flushWork (scheduler.development.js:234:1)
    at performWorkUntilDeadline (scheduler.development.js:518:1)
    at run (setImmediate.js:48:1)
    at runIfPresent (setImmediate.js:83:1)
    at onGlobalMessage (setImmediate.js:125:1)

What am I missing? I should also mention I have used the line chart and pie chart from nivo and they render. Below is a list of my dependencies form package.json

"dependencies": {
    "@nivo/bar": "^0.80.0",
    "@nivo/core": "^0.80.0",
    "@nivo/line": "^0.80.0",
    "@nivo/pie": "^0.80.0",
    "@nivo/radar": "^0.80.0",
    "@reduxjs/toolkit": "^1.9.0",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.1.3",
    "bootstrap": "^5.2.2",
    "react": "^18.2.0",
    "react-bootstrap": "^2.5.0",
    "react-dom": "^18.2.0",
    "react-redux": "^8.0.5",
    "react-scripts": "^2.1.3",
    "react-select": "^5.7.0",
    "redux": "^4.2.0",
    "web-vitals": "^2.1.4"
  },


问:
OnClick function using Vite+Blade Laravel
I have a new laravel application, where I am using Vite

I have already included my js files in vite.config and also in the head of my html

```<code>@vite(['resources/js/services/live.js'])
</code>```

however, when I try to use a button with the onclick function, it does not find any of my functions.

For example, let's say this is my js file "resources/js/services/live.js"

var Print = function () { alert('Test'); };
```
<p>Now in my html, where I have already included my js using vite, I want to do the following</p>
<pre class="lang-html prettyprint-override"><code><input type="button" onclick="Print()"
</code>```

But when I click the button, js debugger says "Print is undefined"

I have already tried with function Print(), export function, but the same result.

Is there something that I am missing using vite?

I have tried exporting the function, creating a variable to access, creating a class, but none looks to work

Body:
I have a new laravel application, where I am using Vite

I have already included my js files in vite.config and also in the head of my html

@vite(['resources/js/services/live.js'])

however, when I try to use a button with the onclick function, it does not find any of my functions.

For example, let's say this is my js file "resources/js/services/live.js"

var Print = function () { alert('Test'); };

Now in my html, where I have already included my js using vite, I want to do the following

<input type="button" onclick="Print()"

But when I click the button, js debugger says "Print is undefined"

I have already tried with function Print(), export function, but the same result.

Is there something that I am missing using vite?

I have tried exporting the function, creating a variable to access, creating a class, but none looks to work


问:
How do I use itertools for these nested for loops
I have a dataframe I want to iterate through using a function, but can't seem to use itertools correctly. The below nested for loop works fine!

```<code>columns = len(df_test.columns)
rows = len(df_test.index)
list = []
list2 = []

def inRange(df, min, max):
    for i in range(rows):
        x = 0
        for j in range(columns):
            if df_test.iloc[i, j] >= min and df_test.iloc[i, j] <= max:
                x = x + 1
            else:
                x = x + 0
                list2.append((i, j))
    if x == columns:
        list.insert(i, "True")
        # print("True")
    else:
        # print("False")
        list.insert(i, "False")
</code>```

When I use itertools, it does not. It gives only 1 False value added into the list, when it should be [False, True, True, False].

```<code>def inRange(df, min, max):
    x = 0
    # i = index, j = columns
    for i, j in itertools.product(range(rows), range(columns)):
        if df_test.iloc[i, j] >= min and df_test.iloc[i, j] <= max:
            x = x + 1
        else:
            x = x + 0
            list2.append((i, j))
    if x == columns:
        list.insert(i, "True")
        # print("True")
    else:
        # print("False")
        list.insert(i, "False")
</code>```

Expected:
list = [False, True, True, False]

list2 = [(0, 0), (0, 1), (0, 3), (3, 2), (3, 3)]

list 2 works fine and gives the correct result.

Body:
I have a dataframe I want to iterate through using a function, but can't seem to use itertools correctly. The below nested for loop works fine!

columns = len(df_test.columns)
rows = len(df_test.index)
list = []
list2 = []

def inRange(df, min, max):
    for i in range(rows):
        x = 0
        for j in range(columns):
            if df_test.iloc[i, j] >= min and df_test.iloc[i, j] <= max:
                x = x + 1
            else:
                x = x + 0
                list2.append((i, j))
    if x == columns:
        list.insert(i, "True")
        # print("True")
    else:
        # print("False")
        list.insert(i, "False")

When I use itertools, it does not. It gives only 1 False value added into the list, when it should be [False, True, True, False].

def inRange(df, min, max):
    x = 0
    # i = index, j = columns
    for i, j in itertools.product(range(rows), range(columns)):
        if df_test.iloc[i, j] >= min and df_test.iloc[i, j] <= max:
            x = x + 1
        else:
            x = x + 0
            list2.append((i, j))
    if x == columns:
        list.insert(i, "True")
        # print("True")
    else:
        # print("False")
        list.insert(i, "False")

Expected:
list = [False, True, True, False]

list2 = [(0, 0), (0, 1), (0, 3), (3, 2), (3, 3)]

list 2 works fine and gives the correct result.


问:
Need support, Initially Django Search page is displaying all data, while i want to have only search text boxes and display data after user input
Views.py

```<code>def advance_filter(request):
user_list = SarnarLogs.objects.all()
user_filter = UserFilter(request.GET)
return render(request, 'advance_filter.html', {'filter': user_filter})
</code>```

Template: Advance_filter.html

```<code><form method="get">
            <div class="well">
              <h4 style="margin-top: 0">Filter</h4>
              <div class="row">
                <div class="form-group col-sm-4 col-md-3">
                  {{ filter.form.source.label_tag }}
                  {% render_field filter.form.source class="searchfield" %}
                </div>
                <div class="form-group col-sm-4 col-md-3">
                  {{ filter.form.destination.label_tag }}
                  {% render_field filter.form.destination class="searchfield" %}
                </div>
                <div class="form-group col-sm-4 col-md-3">
                  {{ filter.form.port.label_tag }}
                  {% render_field filter.form.port class="searchfield" %}
                </div>
                <div class="form-group col-sm-4 col-md-3">
                  {{ filter.form.request_no.label_tag }}
                  {% render_field filter.form.request_no class="searchfield" %}
                </div>

              </div>
              <button type="submit" class="btn btn-primary"  placeholder="Search" aria-label="Search" name="q" value='{{ request.GET.q }}'>
                <span class="glyphicon glyphicon-search"></span> Search
              </button>

            </div>

          </form><br>

           <div class="col-12">
              <div class="card my-4">
                 <div class="card-header p-0 position-relative mt-n4 mx-3 z-index-2">
                    <div class="bg-gradient-primary shadow-primary border-radius-lg pt-4 pb-3">
                       <h6 class="text-white text-capitalize ps-3">HUB Requests</h6>
                    </div>
                 </div>
                 <div class="card-body px-0 pb-2">
                    <div class="table-responsive p-0">
                       <table class="table align-items-center mb-0">
                          <thead>
                             <tr>
                                <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">ID</th>
                                <th class="text-uppercase text-secondary text-xxs font-weight-bolder opacity-7 ps-2">SOURCE</th>
                                <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">DESTINATION</th>
                                <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">PORT</th>
                                <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">REQUEST TYPE</th>
                                <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">REQUEST_NO</th>
                                <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">REQUESTER</th>
                                <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">START DATE</th>
                                <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">EXPIRY DATE</th>
                                <th class="text-center text-uppercase text-secondary text-xxs font-weight-bolder opacity-7">Days Left</th>
                                <th class="text-secondary opacity-7"></th>
                             </tr>
                          </thead>
                          <tbody>
                             {% for user in filter.qs %}
                             <tr>
                                <td>
                                   <div class="d-flex px-2 py-1">
                                      <div class="d-flex flex-column justify-content-center">
                                         <h6 class="mb-0 text-sm">{{user.id}}</h6>
                                      </div>
                                   </div>
                                </td>
                                <td>
                                   <p class="text-xs font-weight-bold mb-0">{{user.source}}</p>
                                </td>
                                <td class="align-middle text-center text-sm">
                                   <p class="text-xs font-weight-bold mb-0">{{user.destination}}</p>
                                </td>
                                <td class="align-middle text-center text-sm">
                                   <p class="text-xs font-weight-bold mb-0">{{user.port}}</p>
                                </td>
                                <td class="align-middle text-center text-sm">
                                   <p class="text-xs font-weight-bold mb-0">{{user.request_type}}</p>
                                </td>
                                <td class="align-middle text-center text-sm">
                                   <p class="text-xs font-weight-bold mb-0">{{user.request_no}}</p>
                                </td>
                                <td class="align-middle text-center text-sm">
                                   <p class="text-xs font-weight-bold mb-0">{{user.requester}}</p>
                                </td>
                                <td class="align-middle text-center">
                                   <span class="text-secondary text-xs font-weight-bold">{{user.start_date|date:'d-m-Y'}}</span>
                                </td>
                                <td class="align-middle text-center">
                                   <span class="text-secondary text-xs font-weight-bold">{{user.expiry_date|date:'d-m-Y'}}</span>
                                </td>
                                <td class="align-middle text-center">
                                  <span class="text-secondary text-xs font-weight-bold">{{ user.expiry_date|timeuntil:user.start_date }}</span>
                               </td>
                             </tr>
                             {% empty %}
                              <tr>
                                <td colspan="5">No data</td>
                              </tr>
                             {% endfor %}
                          </tbody>
</code>```

Any solution to load the page with search boxes and later when user provide inputs and hits the seach to display the data. Problem is that there are millions of records and page is consuming time to load up.
Appriciate if someone can provide insight in resolving it.

Body:
Views.py

def advance_filter(request):
user_list = SarnarLogs.objects.all()
user_filter = UserFilter(request.GET)
return render(request, 'advance_filter.html', {'filter': user_filter})

Template: Advance_filter.html

<form method="get">

Filter

                  {{ filter.form.source.label_tag }}
                  {% render_field filter.form.source class="searchfield" %}

                  {{ filter.form.destination.label_tag }}
                  {% render_field filter.form.destination class="searchfield" %}

                  {{ filter.form.port.label_tag }}
                  {% render_field filter.form.port class="searchfield" %}

                  {{ filter.form.request_no.label_tag }}
                  {% render_field filter.form.request_no class="searchfield" %}

              <button type="submit" class="btn btn-primary"  placeholder="Search" aria-label="Search" name="q" value='{{ request.GET.q }}'>
                 Search
              </button>

          </form>

HUB Requests

                                ID
                                SOURCE
                                DESTINATION
                                PORT
                                REQUEST TYPE
                                REQUEST_NO
                                REQUESTER
                                START DATE
                                EXPIRY DATE
                                Days Left

                             {% for user in filter.qs %}

{{user.id}}

{{user.source}}

{{user.destination}}

{{user.port}}

{{user.request_type}}

{{user.request_no}}

{{user.requester}}

                                   {{user.start_date|date:'d-m-Y'}}

                                   {{user.expiry_date|date:'d-m-Y'}}

                                  {{ user.expiry_date|timeuntil:user.start_date }}

                             {% empty %}

                                No data

                             {% endfor %}

Any solution to load the page with search boxes and later when user provide inputs and hits the seach to display the data. Problem is that there are millions of records and page is consuming time to load up.
Appriciate if someone can provide insight in resolving it.


问:
What do “io.Systemd.DynamicUser” and “io.Systemd.Machine” use to?
When I run "ssh user@localhost" to make ssh connection, use strace and grep connect syscalls.

```<code>54290 connect(3<UNIX-STREAM:[216286]>, {sa_family=AF_UNIX, sun_path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
54290 connect(3<UNIX-STREAM:[216286]>, {sa_family=AF_UNIX, sun_path="/run/systemd/userdb/io.Systemd.Machine"}, 110) = 0
54290 connect(3<UNIX-STREAM:[216286]>, {sa_family=AF_UNIX, sun_path="/run/systemd/userdb/io.Systemd.DynamicUser"}, 110) = 0
</code>```

There are three socket files I am confused. I don't know why need to "connect" to those socket files. What does they use to?

Body:
When I run "ssh user@localhost" to make ssh connection, use strace and grep connect syscalls.

54290 connect(3<UNIX-STREAM:[216286]>, {sa_family=AF_UNIX, sun_path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
54290 connect(3<UNIX-STREAM:[216286]>, {sa_family=AF_UNIX, sun_path="/run/systemd/userdb/io.Systemd.Machine"}, 110) = 0
54290 connect(3<UNIX-STREAM:[216286]>, {sa_family=AF_UNIX, sun_path="/run/systemd/userdb/io.Systemd.DynamicUser"}, 110) = 0

There are three socket files I am confused. I don't know why need to "connect" to those socket files. What does they use to?


问:
Automatically Determine Best Filter Values for Feature Matching
I am using SIFT to match features between two videos. I would like my HSV/CannyEdge filter trackbar GUI to automatically adjust parameters based on what will result in optimal feature-matching results. Because the feature matching is happening on a frame-by-frame basis, the parameter values (for what is optimal) might differ as I feature-match throughout the video.

Trackbar GUI. Applies adjustable image processing filters

Because there are so many possible parameter value variations, I am wondering what is the best way to automatically find the best combination. I would apply this technique to both images for the feature matching

Doing this manually is too time-consuming and I need an automatic way of maybe with brute-forcing every parameter value combination to find the best feature-matching result between the two images.


问:
How to play .ts files (video/MP2T media type) in blogger?
I need to play .ts streaming video file in blogger site through a web page link, kindly provide me any example of it. I have file ts video source tag with type application/x-mpegURL but it is not working. Can we call the .ts video file in a HTML5 video tag?


问:
How to use original Type of Custom App in Next.js
I want to use App type (original Next.js type) as MyApp type but I got an error related to declaration of MyApp Component:

```<code>Property 'origGetInitialProps' is missing in type '{ ({ Component, pageProps }: AppProps): JSX.Element; getInitialProps(ctx: AppContext): Promise<AppProps<any>>; }' but required in type 'typeof App'.ts(2741)

_app.d.ts(14, 12): 'origGetInitialProps' is declared here.
</code>```

My code:

/pages/_app.ts

import type { AppProps, AppContext } from 'next/app.js'

type App = typeof import('next/app.js').default

const MyApp: App = ({ Component, pageProps }: AppProps) => {
  return <Component {...pageProps} />
}

MyApp.getInitialProps = async (ctx: AppContext): Promise<AppProps> => {
  ...
  return {}
}
```
<ul>
<li><em>next/app.d.ts</em> (same of <em>next/app.js</em>)</li>
</ul>
<pre class="lang-js prettyprint-override"><code>import App from './dist/pages/_app'
export * from './dist/pages/_app'
export default App
</code>```

next/dist/pages/_app.d.ts (same of default export of next/app.js)

import React from 'react';
import type { AppContextType, AppInitialProps, AppPropsType, NextWebVitalsMetric, AppType } from '../shared/lib/utils';
import type { Router } from '../client/router';
export { AppInitialProps, AppType };
export { NextWebVitalsMetric };
export declare type AppContext = AppContextType<Router>;
export declare type AppProps
 = AppPropsType<Router, P>;
/**
 * `App` component is used for initialize of pages. It allows for overwriting and full control of the `page` initialization.
 * This allows for keeping state between navigation, custom error handling, injecting additional data.
 */
declare function appGetInitialProps({ Component, ctx, }: AppContext): Promise<AppInitialProps>;
export default class App
 extends React.Component<P & AppProps<CP>, S> {
    static origGetInitialProps: typeof appGetInitialProps;
    static getInitialProps: typeof appGetInitialProps;
    render(): JSX.Element;
}
```

Other related/similar question

Body:
I want to use App type (original Next.js type) as MyApp type but I got an error related to declaration of MyApp Component:

Property 'origGetInitialProps' is missing in type '{ ({ Component, pageProps }: AppProps): JSX.Element; getInitialProps(ctx: AppContext): Promise<AppProps<any>>; }' but required in type 'typeof App'.ts(2741)

_app.d.ts(14, 12): 'origGetInitialProps' is declared here.

My code:

/pages/_app.ts

import type { AppProps, AppContext } from 'next/app.js'

type App = typeof import('next/app.js').default

const MyApp: App = ({ Component, pageProps }: AppProps) => {
  return <Component {...pageProps} />
}

MyApp.getInitialProps = async (ctx: AppContext): Promise<AppProps> => {
  ...
  return {}
}

next/app.d.ts (same of next/app.js)

import App from './dist/pages/_app'
export * from './dist/pages/_app'
export default App

next/dist/pages/_app.d.ts (same of default export of next/app.js)

import React from 'react';
import type { AppContextType, AppInitialProps, AppPropsType, NextWebVitalsMetric, AppType } from '../shared/lib/utils';
import type { Router } from '../client/router';
export { AppInitialProps, AppType };
export { NextWebVitalsMetric };
export declare type AppContext = AppContextType<Router>;
export declare type AppProps
 = AppPropsType<Router, P>;
/**
 * `App` component is used for initialize of pages. It allows for overwriting and full control of the `page` initialization.
 * This allows for keeping state between navigation, custom error handling, injecting additional data.
 */
declare function appGetInitialProps({ Component, ctx, }: AppContext): Promise<AppInitialProps>;
export default class App
 extends React.Component<P & AppProps<CP>, S> {
    static origGetInitialProps: typeof appGetInitialProps;
    static getInitialProps: typeof appGetInitialProps;
    render(): JSX.Element;
}

Other related/similar question


问:
Trigger a function after the NFC session screen goes out of view
I am using NFCTagReaderSession().connect() to get the UID of a tag, once that is done, I want to fire a function, but only after the NFC popup has scrolled down out of view. Is that possible?

I have the following code:

```<code>class Scanner {

    func start(session: NFCTagReaderSession, tag: NFCTag, completion: @escaping (String) -> ()) {
        session.connect(to: tag) { error in
            if nil != error {
                session.invalidate(errorMessage: "Connection failed")
            }
            if case let .miFare(sTag) = tag {
                let uid = sTag.identifier.map{ String(format: "%.2hhx", $0)}.joined(separator: "").uppercased()
                session.alertMessage = "Please wait for authentication."
                session.invalidate()
                DispatchQueue.main.async {
                    completion(uid)
                }
            }
        }
    }

}
</code>```

But the function I fire after I get the id (using the completion), is firing WHILE this pesky popup is still in view and it takes like 2 seconds for it to go away. This means any view changes in the background is partially obstructed.

Thanks in advance.

Body:
I am using NFCTagReaderSession().connect() to get the UID of a tag, once that is done, I want to fire a function, but only after the NFC popup has scrolled down out of view. Is that possible?

I have the following code:

class Scanner {

    func start(session: NFCTagReaderSession, tag: NFCTag, completion: @escaping (String) -> ()) {
        session.connect(to: tag) { error in
            if nil != error {
                session.invalidate(errorMessage: "Connection failed")
            }
            if case let .miFare(sTag) = tag {
                let uid = sTag.identifier.map{ String(format: "%.2hhx", $0)}.joined(separator: "").uppercased()
                session.alertMessage = "Please wait for authentication."
                session.invalidate()
                DispatchQueue.main.async {
                    completion(uid)
                }
            }
        }
    }

}

But the function I fire after I get the id (using the completion), is firing WHILE this pesky popup is still in view and it takes like 2 seconds for it to go away. This means any view changes in the background is partially obstructed.

Thanks in advance.


问:
Multithread file reading and processing
I just came to multithreaded programming. Below is my attempt to do a large txt file reading and processing with 1 thread to read and multiple threads to process line by line. Right now, I put a trivial process function; the actual process function takes longer in my real application, then outputs the processed result to a new file.

Somehow, the code works intermittently; some race conditions may occur somewhere. I tried using gdb and extensively logging to debug, couldn't figure out where the bug was. So, please help. Any suggestion is appreciated.

```<code>#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <semaphore.h>
#include <string.h>
#include <zlib.h>

#define READER_SIZE 30

#define NUM_PROCESSORS 4

// shared data by the reader and processors
//------------------------------------------------
char reader_buffer[READER_SIZE][64];
int reader_in = 0;                      // next free position
int reader_out = 0;                     // first full position

sem_t reads_mutex; // semaphore to lock buffer
sem_t reads_full;  // counts the number of filled slots
sem_t reads_empty; // counts the number of empty slots
gzFile fileIn;
//------------------------------------------------

// shared data by the processors and writer
//------------------------------------------------
pthread_mutex_t writes_mutex; // mutex lock for writting
gzFile fileOut;
//------------------------------------------------

// Function reader
void *producer()
{
    while (!gzeof(fileIn))
    {
        printf("reader turn ");
        sem_wait(&reads_empty);
        sem_wait(&reads_mutex);

        gzgets(fileIn, reader_buffer[reader_in], 64);

        // printf("reader is working!\n");
        // printf("producer read in: %d, %s \n", reader_in, reader_buffer[reader_in]);
        int empty, full;
        sem_getvalue(&reads_empty, &empty);
        sem_getvalue(&reads_full, &full);

        reader_in = (reader_in + 1) % READER_SIZE;
        printf("reader_in: %d, empty is %d, full is %d\n", reader_in, empty, full + 1);

        sem_post(&reads_mutex);
        sem_post(&reads_full);
    }
}

void *consumer(void *id)
{
    int consumer_id = *((int *)id);
    while (!gzeof(fileIn))
    {
        printf("consumer %d turn ", consumer_id);
        sem_wait(&reads_full);
        sem_wait(&reads_mutex);

        // copy the data
        char processor_buffer[64];
        char cell_barcode[17];

        strcpy(processor_buffer, reader_buffer[reader_out]);
        reader_out = (reader_out + 1) % READER_SIZE;

        int empty, full;
        sem_getvalue(&reads_empty, &empty);
        sem_getvalue(&reads_full, &full);

        printf("reader_out: %d, empty is %d, full is %d \n", reader_out, empty + 1, full);

        sem_post(&reads_mutex);
        sem_post(&reads_empty);

        // processing, here I made trivial to take substring
        if(processor_buffer[0] == '@')
        {

        pthread_mutex_lock(&writes_mutex);

        gzputs(fileOut, processor_buffer);

        pthread_mutex_unlock(&writes_mutex);

        }

    }

}

int main()
{
    fileIn = gzopen("temp.gz", "rb");
    fileOut = gzopen("test.gz", "wb");

    int *proc_id = malloc(NUM_PROCESSORS * sizeof(int));

    pthread_t reader_thread;
    pthread_t processor_thread[NUM_PROCESSORS];

    // initialize semaphores
    sem_init(&reads_mutex, 0, 1);
    sem_init(&reads_full, 0, 0);
    sem_init(&reads_empty, 0, READER_SIZE);

    pthread_mutex_init(&writes_mutex, NULL);

    pthread_create(&reader_thread, NULL, producer, NULL);

    for (int i = 0; i < NUM_PROCESSORS; i++)
    {
        proc_id[i] = i;
        pthread_create(&processor_thread[i], NULL, consumer, &proc_id[i]);
    }

    // wait for the reader and processor threads to finish
    pthread_join(reader_thread, NULL);

    for (int i = 0; i < NUM_PROCESSORS; i++)
    {

        pthread_join(processor_thread[i], NULL);
    }

    sem_destroy(&reads_mutex);
    sem_destroy(&reads_full);
    sem_destroy(&reads_empty);

    gzclose(fileIn);

    gzclose(fileOut);

    return 0;
}
</code>```

Title: Multithread file reading and processing

Body:
I just came to multithreaded programming. Below is my attempt to do a large txt file reading and processing with 1 thread to read and multiple threads to process line by line. Right now, I put a trivial process function; the actual process function takes longer in my real application, then outputs the processed result to a new file.

Somehow, the code works intermittently; some race conditions may occur somewhere. I tried using gdb and extensively logging to debug, couldn't figure out where the bug was. So, please help. Any suggestion is appreciated.

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <semaphore.h>
#include <string.h>
#include <zlib.h>

#define READER_SIZE 30

#define NUM_PROCESSORS 4

// shared data by the reader and processors
//------------------------------------------------
char reader_buffer[READER_SIZE][64];
int reader_in = 0;                      // next free position
int reader_out = 0;                     // first full position

sem_t reads_mutex; // semaphore to lock buffer
sem_t reads_full;  // counts the number of filled slots
sem_t reads_empty; // counts the number of empty slots
gzFile fileIn;
//------------------------------------------------

// shared data by the processors and writer
//------------------------------------------------
pthread_mutex_t writes_mutex; // mutex lock for writting
gzFile fileOut;
//------------------------------------------------

// Function reader
void *producer()
{
    while (!gzeof(fileIn))
    {
        printf("reader turn ");
        sem_wait(&reads_empty);
        sem_wait(&reads_mutex);

        gzgets(fileIn, reader_buffer[reader_in], 64);

        // printf("reader is working!\n");
        // printf("producer read in: %d, %s \n", reader_in, reader_buffer[reader_in]);
        int empty, full;
        sem_getvalue(&reads_empty, &empty);
        sem_getvalue(&reads_full, &full);

        reader_in = (reader_in + 1) % READER_SIZE;
        printf("reader_in: %d, empty is %d, full is %d\n", reader_in, empty, full + 1);

        sem_post(&reads_mutex);
        sem_post(&reads_full);
    }
}

void *consumer(void *id)
{
    int consumer_id = *((int *)id);
    while (!gzeof(fileIn))
    {
        printf("consumer %d turn ", consumer_id);
        sem_wait(&reads_full);
        sem_wait(&reads_mutex);

        // copy the data
        char processor_buffer[64];
        char cell_barcode[17];

        strcpy(processor_buffer, reader_buffer[reader_out]);
        reader_out = (reader_out + 1) % READER_SIZE;

        int empty, full;
        sem_getvalue(&reads_empty, &empty);
        sem_getvalue(&reads_full, &full);

        printf("reader_out: %d, empty is %d, full is %d \n", reader_out, empty + 1, full);

        sem_post(&reads_mutex);
        sem_post(&reads_empty);

        // processing, here I made trivial to take substring
        if(processor_buffer[0] == '@')
        {

        pthread_mutex_lock(&writes_mutex);

        gzputs(fileOut, processor_buffer);

        pthread_mutex_unlock(&writes_mutex);

        }

    }

}

int main()
{
    fileIn = gzopen("temp.gz", "rb");
    fileOut = gzopen("test.gz", "wb");

    int *proc_id = malloc(NUM_PROCESSORS * sizeof(int));

    pthread_t reader_thread;
    pthread_t processor_thread[NUM_PROCESSORS];

    // initialize semaphores
    sem_init(&reads_mutex, 0, 1);
    sem_init(&reads_full, 0, 0);
    sem_init(&reads_empty, 0, READER_SIZE);

    pthread_mutex_init(&writes_mutex, NULL);

    pthread_create(&reader_thread, NULL, producer, NULL);

    for (int i = 0; i < NUM_PROCESSORS; i++)
    {
        proc_id[i] = i;
        pthread_create(&processor_thread[i], NULL, consumer, &proc_id[i]);
    }

    // wait for the reader and processor threads to finish
    pthread_join(reader_thread, NULL);

    for (int i = 0; i < NUM_PROCESSORS; i++)
    {

        pthread_join(processor_thread[i], NULL);
    }

    sem_destroy(&reads_mutex);
    sem_destroy(&reads_full);
    sem_destroy(&reads_empty);

    gzclose(fileIn);

    gzclose(fileOut);

    return 0;
}


问:
Uiautomation Findfirst Classname Fails when Client is using Endpoint Security
Vb.net app successfully using uiautomation.findfirst method returns nothing when used in windows 10 or 11 and any type of endpoint protection installed, will always work otherwise.

I first obtain a process object with Process.GetProcessesByName("appname"), this always works.
Then I get a Automationelement using _AutomationElement = AutomationElement.FromHandle(proc(0).MainWindowHandle) this always works.
Then I can get the parent window name using _AutomationElement.Current.Name, This always works.

Now here is where the problem surfaces, when I attempt to get automationelementfindfirst (No errors or exception) just nothing found.

```<code>         propCondition = New PropertyCondition(AutomationElement.ClassNameProperty, txtClassToFind.Text, PropertyConditionFlags.IgnoreCase)
         _MDIAutomationElement = _AutomationElement.FindFirst(TreeScope.Element Or TreeScope.Children, propCondition)
</code>```

This code has always worked until we started installing when clients are using Endpoint Protection, such as TrendMicro, Microsoft, Bitdefender, Eset and others.

If they temporarily uninstall the endpoint protection the app goes back to working again, and they can never find a logged entry, this is really weird and driving me crazy.

Body:
Vb.net app successfully using uiautomation.findfirst method returns nothing when used in windows 10 or 11 and any type of endpoint protection installed, will always work otherwise.

I first obtain a process object with Process.GetProcessesByName("appname"), this always works.
Then I get a Automationelement using _AutomationElement = AutomationElement.FromHandle(proc(0).MainWindowHandle) this always works.
Then I can get the parent window name using _AutomationElement.Current.Name, This always works.

Now here is where the problem surfaces, when I attempt to get automationelementfindfirst (No errors or exception) just nothing found.

         propCondition = New PropertyCondition(AutomationElement.ClassNameProperty, txtClassToFind.Text, PropertyConditionFlags.IgnoreCase)
         _MDIAutomationElement = _AutomationElement.FindFirst(TreeScope.Element Or TreeScope.Children, propCondition)

This code has always worked until we started installing when clients are using Endpoint Protection, such as TrendMicro, Microsoft, Bitdefender, Eset and others.

If they temporarily uninstall the endpoint protection the app goes back to working again, and they can never find a logged entry, this is really weird and driving me crazy.