问:
How to search for multiple terms in Wikidata API using 'srsearch' (e.g. from Python)?
I am trying to search multiple terms on Wikidata and then parse the results locally using Python.

I am currently looping through a list of terms and running the following piece of code:

```<code>import requests

term_list = ["term a", "term b"]

for search_term in term_list:
    base_url = "https://www.wikidata.org/w/api.php"
    payload = {
        "action": "query",
        "list": "search",
        "srsearch": search_term,
        "language": "en",
        "format": "json",
        "origin": "*",
    }
    res = requests.get(base_url, params=payload)
</code>```

This takes a lot of time, as each iteration makes new requests.

Is there a way I could send a batch of terms simultaneously to the Wikidata API, thereby saving me time and saving resources to the API?

edit

By digging deeper in Phabricator, it seems that I can't actually do it (https://phabricator.wikimedia.org/T194016). If anyone has more information on it, it would be very useful.

Body:
I am trying to search multiple terms on Wikidata and then parse the results locally using Python.

I am currently looping through a list of terms and running the following piece of code:

import requests

term_list = ["term a", "term b"]

for search_term in term_list:
    base_url = "https://www.wikidata.org/w/api.php"
    payload = {
        "action": "query",
        "list": "search",
        "srsearch": search_term,
        "language": "en",
        "format": "json",
        "origin": "*",
    }
    res = requests.get(base_url, params=payload)

This takes a lot of time, as each iteration makes new requests.

Is there a way I could send a batch of terms simultaneously to the Wikidata API, thereby saving me time and saving resources to the API?

edit

By digging deeper in Phabricator, it seems that I can't actually do it (https://phabricator.wikimedia.org/T194016). If anyone has more information on it, it would be very useful.


来源: stackexchange

问:
Error encoding UTF-8 in netbeans-13 with jdk 1.8
How can I fix this problem with netbeans13 in window10? I'm using JDK 1.8 also JRE I am learning web applications with java. The problem start is when I type ư (Vietnamese character) into the editor, it starts to convert in to ?. How can I fix this?

I tried to add  -J-Dfile.encoding=UTF-8 to netbeans.conf, restart Netbeans, install again and again, but it seem not working.

```<code><<script language = "JavaScript">
var Ten, Tuoi;      // Khai bao 2 bien de luu ten va tuoi
Ten  = prompt("Bạn hãy nhập vào tên ", "");
Tuoi = prompt("Bạn hãy nhập vào Tuổi : ", 20);
document.write("Chào bạn : <B> " + Ten + "</B>");
document.write("<BR>");  // Xuống dòng
document.write("Tuổi của bạn là : <U> " + Tuoi + "</U>");
    //i can paste "Tuổi của bạn là :" but cant type tu?i c?a b?n là
</code>```

enter image description here

ContentLicense: CC BY-SA 4.0

Body:
How can I fix this problem with netbeans13 in window10? I'm using JDK 1.8 also JRE I am learning web applications with java. The problem start is when I type ư (Vietnamese character) into the editor, it starts to convert in to ?. How can I fix this?

I tried to add  -J-Dfile.encoding=UTF-8 to netbeans.conf, restart Netbeans, install again and again, but it seem not working.

<


问:
No source available for xx_func() at 0xyy_address
I have been trying to develop and run core-mark benchmark on the EVB. I have added bunch of different source files provided by EEMBC and a static library too. All in accordance to the guidelines provided. Compilation is fine.
However, when I try to run the actual benchmark command - mcoremark-(#iterations), I am getting a hard fault.
I am not really sure why that is happening - but when I check the thread - it says "No source available for xx_func() at yy_address"

IDE that I am using - Eclipse

Could you please help me understand what might be happening here?

If you need more details, please let me know.

Thank you.

I am not really sure where to start in terms of debugging. I did check the symbol path of the library file provided and that seems to be in order.


问:
Camera calibration focal length twice as large as expected
I used the CameraCalibration node in Meshroom 2021.1.0 using a checkerboard grid to do a camera calibration. From what I understand, Meshroom is using OpenCV, so this question indirectly relates to the calibration process in OpenCV as well.

The lens I'm using is advertised as an 8mm lens, so I was expecting a focal length of something between 7 and 9 mm, but the fx value was 2541.273 and fy value was 2641.111 and I know the sensor pixel size is 6 microns, so when converting from pixels to mm, I'm getting focal lengths of 15.247 mm and 15.847 mm respectively which is right around double what I would expect.

The checkerboard I'm using has 50 mm squares, and I specified the size of the square in the camera calibration, and I double checked the printed dimensions with calipers. I also verified that the size of my images were full resolution compared to the expected size based on sensor specifications, so it wasn't a case where the resolution was half or double the original sensor size or something like that.

Curious if there is anything obvious I may have missed that would cause the focal length in the calibration to come out double what is expected.

I went through a similar calibration process with my smartphone and the camera I was testing with advertised a focal length of 7 mm and the camera calibration returned in that case an fx of 7.21 mm and an fy of 7.20 mm. The only difference was the grid I was using in that test was using 30 mm squares and was 7 x 5 instead of 4 x 3, but the process to get those values was essentially the same.

Update:

I reran a camera calibration with a different set of images, and this time I got an fx of 23.07 mm and fy of 23.23 mm, so it would seem that the previous run that was off by a factor of 2 may have been a coincidence that it was off by 2. Given how inconsistent the focal length values are from one run to the next and how far off they are from expected values, I'm guessing that the errors that I'm seeing are due to poor calibration images being used in the process? The camera is fixed, so I'm moving the checkerboard on a surface, so mostly in a single plane. To get a good calibration do I just need a better variety of orientations that the checkerboard is captured in like different distances and different angles?

Is the size of the grid just too small for the field of view to get good calibration values from it? I calibrated with 80 calibration shots similar to the two above moving the board from one edge to the other.

I got a larger calibration target using the ChAruco pattern, and it looks like the values are more stable now, but every now and then if I repeat the calibration, I can get very far out numbers. Should the board below be large enough to get stable calibration values?


问:
I want to save dataframe styler as image
```<code>df.style.background_gradient(cmap='coolwarm').set_precision(1)
</code>```

I want to save the output of the code as an image

Body:
df.style.background_gradient(cmap='coolwarm').set_precision(1)

I want to save the output of the code as an image


问:
Can't compile with Clang on MacOS, only builds
I'm attemping to follow this article to be able to code in c++ on MacOS, but my code isn't running? Or the output isn't going into the terminal.

I've gotten to the "Run helloworld.cpp" step in the article and have chosen "C/C++: clang++ build and debug active file." When I run the code, it brings me to the debug console and says main is asking for permission to access files in my Desktop folder.

Here is my tasks.json:

```<code>{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: clang++ build active file",
            "command": "/usr/bin/clang++",
            "args": [
                "-fdiagnostics-color=always",
                "-std=c++17",
                "-stdlib=libc++",
                "-g",
                "-pedantic-errors",
                "-Wall",
                "-Weffc++",
                "-Wextra",
                "-Wsign-conversion",
                "-Werror",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}
</code>```

Build finished successfully.

Body:
I'm attemping to follow this article to be able to code in c++ on MacOS, but my code isn't running? Or the output isn't going into the terminal.

I've gotten to the "Run helloworld.cpp" step in the article and have chosen "C/C++: clang++ build and debug active file." When I run the code, it brings me to the debug console and says main is asking for permission to access files in my Desktop folder.

Here is my tasks.json:

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: clang++ build active file",
            "command": "/usr/bin/clang++",
            "args": [
                "-fdiagnostics-color=always",
                "-std=c++17",
                "-stdlib=libc++",
                "-g",
                "-pedantic-errors",
                "-Wall",
                "-Weffc++",
                "-Wextra",
                "-Wsign-conversion",
                "-Werror",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}

Build finished successfully.


问:
How to reset D3 zoom transform when data from props (React) changes?
I've got a d3 viz that I need to reset every time data changes. As an examples I setup a small fiddle.

click on the red box and move mouse to the right. Release mouse.

the transform X value will be displayed.

select another color from the drop down

repeat steps 1 and 2.

The transform does not start from 0 but from where we left it at the first time.

We have a requirement to reset the transform values.

This is our d3 code for the rectangle and zoom logic:

```<code> useEffect(() => {
    const svg = d3.select(svgRef.current);

    svg.append("g").attr("class", "group");

    const g = d3.select(".group");

    g.append("rect")
      .attr("class", "red-rect")
      .attr("x", 0)
      .attr("y", 0)
      .attr("width", 50)
      .attr("height", 50)
      .attr("fill", `${color}`);

    const zoomed = (e) => {
      console.log("transform", e.transform.x);
    };

    const zoom = d3
      .zoom()
      .on("zoom", zoomed)
      .on("end", (e) => setTransfomX(e.transform.x));

    svg.call(zoom);
  }, [svgRef, color]);
</code>```

I've tried to add a reset logic to the svg transform but without success

```<code>  useEffect(() => {
    const svg = d3.select(svgRef.current);
    const redRect = d3.select(".red-rect");

    const zoom = d3.zoom();
    const onZoom = (e) => redRect.attr("transform", e.transform);

    zoom.on("zoom", onZoom);

    svg.call(zoomTransform, zoomIdentity);
  }, [color]);
</code>```

This logic would reset d3 zoom every time the 'color' prop changes.

I feel I'm very close but something's missing.

EDIT 09/01/23 - Fiddle link

Body:
I've got a d3 viz that I need to reset every time data changes. As an examples I setup a small fiddle.

click on the red box and move mouse to the right. Release mouse.

the transform X value will be displayed.

select another color from the drop down

repeat steps 1 and 2.

The transform does not start from 0 but from where we left it at the first time.

We have a requirement to reset the transform values.

This is our d3 code for the rectangle and zoom logic:

 useEffect(() => {
    const svg = d3.select(svgRef.current);

    svg.append("g").attr("class", "group");

    const g = d3.select(".group");

    g.append("rect")
      .attr("class", "red-rect")
      .attr("x", 0)
      .attr("y", 0)
      .attr("width", 50)
      .attr("height", 50)
      .attr("fill", `${color}`);

    const zoomed = (e) => {
      console.log("transform", e.transform.x);
    };

    const zoom = d3
      .zoom()
      .on("zoom", zoomed)
      .on("end", (e) => setTransfomX(e.transform.x));

    svg.call(zoom);
  }, [svgRef, color]);

I've tried to add a reset logic to the svg transform but without success

  useEffect(() => {
    const svg = d3.select(svgRef.current);
    const redRect = d3.select(".red-rect");

    const zoom = d3.zoom();
    const onZoom = (e) => redRect.attr("transform", e.transform);

    zoom.on("zoom", onZoom);

    svg.call(zoomTransform, zoomIdentity);
  }, [color]);

This logic would reset d3 zoom every time the 'color' prop changes.

I feel I'm very close but something's missing.

EDIT 09/01/23 - Fiddle link


问:
VS Code Flask temporary hosting with an actual url?
This is my current app.py file on my local machine. I would like to recieve webhooks from shopify when an order is sent to my shop which will be handled inside the order_api blueprint.

```<code>from flask import Flask, request
from routes.new_shopify_order import order_api

app = Flask(__name__)
app.register_blueprint(order_api)
app.config['DEBUG'] = True

@app.route('/')
def hello_world():
    return 'Hello from Flask!'

if __name__ == "__main__":
    app.run()

</code>```

Shopify requires an actual url to send these webhooks and I would like to know if there is any Extenstion I can use with VS Code for me to host my flask app from my local machine with an actual url (even if it's a temporary one) just so I don't have to use a webhosting client.

Body:
This is my current app.py file on my local machine. I would like to recieve webhooks from shopify when an order is sent to my shop which will be handled inside the order_api blueprint.

from flask import Flask, request
from routes.new_shopify_order import order_api

app = Flask(__name__)
app.register_blueprint(order_api)
app.config['DEBUG'] = True

@app.route('/')
def hello_world():
    return 'Hello from Flask!'

if __name__ == "__main__":
    app.run()

Shopify requires an actual url to send these webhooks and I would like to know if there is any Extenstion I can use with VS Code for me to host my flask app from my local machine with an actual url (even if it's a temporary one) just so I don't have to use a webhosting client.


问:
I want to create a messagebox when the sqlite3.IntegrityError: appears but its not working
I want to create a messagebox when the sqlite3.IntegrityError appears but it's  not working

I try with try except an if else

```<code>def data_b(*args):
    import sqlite3

    conection = sqlite3.Connection('annuaire_telephobque.db')
    cursorr = conection.cursor()
    cursorr.execute("CREATE TABLE IF NOT EXISTS a_t_users(row_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,user_f_name TEXT NOT NULL UNIQUE, user_l_name TEXT  NOT NULL UNIQUE ,use_number TEXT NOT NULL UNIQUE)")

    f_get=str(nam0.get())
    l_get=str(l_nam0.get())
    n_get=str(numero0.get())
    try:
        cursorr = conection.cursor()
        cursorr.execute("INSERT INTO a_t_users (user_f_name, user_l_name ,use_number) VALUES (?,?,?)",(f_get,l_get,n_get))
        conection.commit()

    except sqlite3.IntegrityError:
        cursorr.close()
        conection.commit()
        conection.close()
        print('karim')
        messagebox.showerror(title='error',message='les information existes deja')
</code>```

Body:
I want to create a messagebox when the sqlite3.IntegrityError appears but it's  not working

I try with try except an if else

def data_b(*args):
    import sqlite3

    conection = sqlite3.Connection('annuaire_telephobque.db')
    cursorr = conection.cursor()
    cursorr.execute("CREATE TABLE IF NOT EXISTS a_t_users(row_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,user_f_name TEXT NOT NULL UNIQUE, user_l_name TEXT  NOT NULL UNIQUE ,use_number TEXT NOT NULL UNIQUE)")

    f_get=str(nam0.get())
    l_get=str(l_nam0.get())
    n_get=str(numero0.get())
    try:
        cursorr = conection.cursor()
        cursorr.execute("INSERT INTO a_t_users (user_f_name, user_l_name ,use_number) VALUES (?,?,?)",(f_get,l_get,n_get))
        conection.commit()

    except sqlite3.IntegrityError:
        cursorr.close()
        conection.commit()
        conection.close()
        print('karim')
        messagebox.showerror(title='error',message='les information existes deja')


问:
How to convert multiple 19 Digit Snapchat.jpg files to datetime
I have a list of strings that have various 19digits (& 10 digits) in a row that MAY signify a meaningful datetime. I am unable to convert this into a useable datetime.

Does anyone know if the snapchat file saved format (i.e. snapchat-1234567890123456789.jpg) have any rhyme or reason to it?

The file-format comes from old saved personal snapchat photos titles that I'm trying to organize; unfortunately there is no associated EXIF data - just the title.

18/19 Digit examples include:

Snapchat-3201324732883372891 - which equates to Jan 17th, 2016.

Snapchat-2026690704509960542 - which equates to Nov 8th, 2016.

Snapchat-8887179640815077729 - which equates to ~Oct 31st, 2016.

But then on newer dates, I have 10 digit file formats:

Snapchat-915670844 - which equates to ~Jan 2022

Snapchat-363015577 - which equates to ~Dec 2022

I've scoured the internet and snapchat API page. No luck.  Open to any suggestions.

If anyone has experience processing Snapchat photos, please feel free to add any commentary.

One of the many links that I tried to establish some sort of linear relationship which I do not see: 19 Digit Timestamp Conversion


问:
Why are all of my symbols not showing up on Latex editor?
I am trying to create a symbols list. I have been provided a LaTex template from the university to write my thesis on. I am not well versed in LaTex, and need some help to determine why my list of symbols are not showing up in the compiled document.

I have a "List of Symbols Glosseries.tex" page that contains a bunch of sample symbols. I have added one test symbol at the bottom labeled "ET." However, in the compiled document, I only see 7 symbols, when in the "List of Symbols.tex" document there are 10.

This is the symbols code:

```<code>% This uses the glossaries package. With this package, you can include multiple types of lists, track page numbers if desired, and define new lists. More information can be found at the following sites: https://mirrors.mit.edu/CTAN/macros/latex/contrib/glossaries/glossariesbegin.pdf and https://mirrors.rit.edu/CTAN/macros/latex/contrib/glossaries/glossaries-user.pdf https://www.overleaf.com/learn/latex/Glossaries

%*****************************************
%Define your list of glossary items below. Remember that the entries that you enter in this file will not automatically appear in the List of Symbols. You also have to reference the symbol in the body of your thesis by using the \gls command.

%symbols
\newglossaryentry{deg}{name=$^\circ$, description={Degree}}
\newglossaryentry{grav}{name={1D}, description={Normal gravity environment}}
\newglossaryentry{wf}{name={\textit{f}}, description={Wear factor}}
\newglossaryentry{alp}{name={$\alpha$},description={Alpha}}
\newglossaryentry{theta}{name={$r_O$}, description={ecosystem respiration at reference temperature $T_a=0{^\circ}$C}}
\newglossaryentry{te}{name={$\tau_e$}, description={precision of the normal distribution of the likelihood}}
\newglossaryentry{q10}{name={$Q_{10}$}, description={multiplication factor to respiration with 10$^\circ$C increases in $T_a$}}
\newglossaryentry{phi}{name={$\phi$}, description={vapour pressure deficit response function}}
\newglossaryentry{del}{name=$\delta$, description={Transition coefficient constant for the design of linear-phase FIR filters which are used to take up space when testing the list of symbols}}

%this is the new symbol I am testing
\newglossaryentry{ET}{name=$\lambda$\text{E}, description={Latent Heat of Vaporization supplied to the atmosphere in watts per meter squared}}

</code>```

Here is the code referenced in the "main.tex" which calls the list of symbols and generates a page with each symbol and description under the "list of symbols" title:

```<code>%**************************
%List of Symbols Section
%**************************
\singlespacing
\renewcommand*{\arraystretch}{2}
\printglossary[title=\centering List of Symbols, title=List of Symbols,style=mystyle,nonumberlist]
</code>```

Here is the portion of the .pdf generated that is missing symbols:

Why is this happening? I appreciate any information provided.

Body:
I am trying to create a symbols list. I have been provided a LaTex template from the university to write my thesis on. I am not well versed in LaTex, and need some help to determine why my list of symbols are not showing up in the compiled document.

I have a "List of Symbols Glosseries.tex" page that contains a bunch of sample symbols. I have added one test symbol at the bottom labeled "ET." However, in the compiled document, I only see 7 symbols, when in the "List of Symbols.tex" document there are 10.

This is the symbols code:

% This uses the glossaries package. With this package, you can include multiple types of lists, track page numbers if desired, and define new lists. More information can be found at the following sites: https://mirrors.mit.edu/CTAN/macros/latex/contrib/glossaries/glossariesbegin.pdf and https://mirrors.rit.edu/CTAN/macros/latex/contrib/glossaries/glossaries-user.pdf https://www.overleaf.com/learn/latex/Glossaries

%*****************************************
%Define your list of glossary items below. Remember that the entries that you enter in this file will not automatically appear in the List of Symbols. You also have to reference the symbol in the body of your thesis by using the \gls command.

%symbols
\newglossaryentry{deg}{name=$^\circ$, description={Degree}}
\newglossaryentry{grav}{name={1D}, description={Normal gravity environment}}
\newglossaryentry{wf}{name={\textit{f}}, description={Wear factor}}
\newglossaryentry{alp}{name={$\alpha$},description={Alpha}}
\newglossaryentry{theta}{name={$r_O$}, description={ecosystem respiration at reference temperature $T_a=0{^\circ}$C}}
\newglossaryentry{te}{name={$\tau_e$}, description={precision of the normal distribution of the likelihood}}
\newglossaryentry{q10}{name={$Q_{10}$}, description={multiplication factor to respiration with 10$^\circ$C increases in $T_a$}}
\newglossaryentry{phi}{name={$\phi$}, description={vapour pressure deficit response function}}
\newglossaryentry{del}{name=$\delta$, description={Transition coefficient constant for the design of linear-phase FIR filters which are used to take up space when testing the list of symbols}}

%this is the new symbol I am testing
\newglossaryentry{ET}{name=$\lambda$\text{E}, description={Latent Heat of Vaporization supplied to the atmosphere in watts per meter squared}}

Here is the code referenced in the "main.tex" which calls the list of symbols and generates a page with each symbol and description under the "list of symbols" title:

%**************************
%List of Symbols Section
%**************************
\singlespacing
\renewcommand*{\arraystretch}{2}
\printglossary[title=\centering List of Symbols, title=List of Symbols,style=mystyle,nonumberlist]

Here is the portion of the .pdf generated that is missing symbols:

Why is this happening? I appreciate any information provided.


问:
jar with embedded tomcat, when using another spring project, is not working with just yml - it's needing a blank application.properties file as well
Been searching for others that have run into this issue, and not finding much out there, so it can't be that common.

I have a spring-boot project that I want to convert into a jar project, running with embedded tomcat. It's using yml files (application.yml and then the profile versions - eg appplication-dev.yml.)  It ran fine as war with the yml files, however, when I convert it to a jar, and kick off the jar, the embedded tomcat never starts UNLESSS I add an empty application.properties file as well. (No errors just no Tomcat startup unless the empty application.properties file is added.)

I believe it's somehow related to one of our internal jar dependencies (also spring), since if I remove that dependency from the pom (and any of the code referencing it) I can get the jar to startup the embedded tomcat just fine (without providing the empty application.properties file.)

I could also, of course, forgo using yml files and just use .properties files, but I'd like to use yml files if possible. Why adding an empty applcation.properties file causes things to work has me stumped.

If it helps, the config in the dependency project that causes the issue we're seeing is set up as:

```<code>@Configuration
@EnableConfigurationProperties(OracleDataSourceProperties.class)
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.foo.data.services","com.foo.data.domain", "com.foo.utility", "com.foo.cipher.utility"})
@MapperScan(value = {"com.foo.data.services.mapper","com.foo.data.services.batchmapper"})
public class DataServicesPersistenceConfig { ... }
</code>```

and the OracleDataSourceProperties class:

```<code>@ConfigurationProperties(prefix="oradb", ignoreUnknownFields = true)
public class OracleDataSourceProperties extends BaseVO implements InitializingBean{
</code>```

Body:
Been searching for others that have run into this issue, and not finding much out there, so it can't be that common.

I have a spring-boot project that I want to convert into a jar project, running with embedded tomcat. It's using yml files (application.yml and then the profile versions - eg appplication-dev.yml.)  It ran fine as war with the yml files, however, when I convert it to a jar, and kick off the jar, the embedded tomcat never starts UNLESSS I add an empty application.properties file as well. (No errors just no Tomcat startup unless the empty application.properties file is added.)

I believe it's somehow related to one of our internal jar dependencies (also spring), since if I remove that dependency from the pom (and any of the code referencing it) I can get the jar to startup the embedded tomcat just fine (without providing the empty application.properties file.)

I could also, of course, forgo using yml files and just use .properties files, but I'd like to use yml files if possible. Why adding an empty applcation.properties file causes things to work has me stumped.

If it helps, the config in the dependency project that causes the issue we're seeing is set up as:

@Configuration
@EnableConfigurationProperties(OracleDataSourceProperties.class)
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.foo.data.services","com.foo.data.domain", "com.foo.utility", "com.foo.cipher.utility"})
@MapperScan(value = {"com.foo.data.services.mapper","com.foo.data.services.batchmapper"})
public class DataServicesPersistenceConfig { ... }

and the OracleDataSourceProperties class:

@ConfigurationProperties(prefix="oradb", ignoreUnknownFields = true)
public class OracleDataSourceProperties extends BaseVO implements InitializingBean{


问:
Loading Google resources (recaptcha, fonts) occasionally failing with status code 0 for some users
Using logrocket, I have identified a small segment of users that is sometimes unable to load any resources from google. We discovered this because it causes an invisible recaptcha to fail which results in a "dead click" and stuck users, but I can see that all requests to google fail in these instances, like analytics and fonts.

I am using an older React app. The static index.html file has link tags that are loading the failing fonts.googleapis.com URLs:

   <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700" rel="stylesheet">
```
<p>Googla analytics is loaded with <code>react-ga</code>:</p>
<pre class="lang-js prettyprint-override"><code>  import ReactGA from 'react-ga';

ReactGA.initialize('my-tracker', {
  debug: !process.env.NODE_ENV || process.env.NODE_ENV === 'development',
});
</code>```

And the recpatcha script is loaded with little-loader on demand using a provider:

import React from 'react';
import load from 'little-loader';
import * as PropTypes from 'prop-types';

export const ReCaptchaContext = React.createContext({
  isReady: false,
});

const RE_CAPTCHA_SRC = 'https://www.google.com/recaptcha/api.js';

const ReCaptchaProvider = ({ children }) => {
  const existingContext = React.useContext(ReCaptchaContext);
  const [context, setContext] = React.useState({ ...existingContext });

  React.useEffect(() => {
    if (!existingContext.isReady) {
      load(RE_CAPTCHA_SRC, () => {
        setContext({ isReady: true });
      });
    }
  }, [existingContext.isReady]);

  return (
    <ReCaptchaContext.Provider value={context}>
      {children}
    </ReCaptchaContext.Provider>
  );
};

ReCaptchaProvider.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
  ]).isRequired,
};

export default ReCaptchaProvider;
```

I have dozens if not hundreds of successful loads for every failing one. I am also using google tag manager which loads successfully in these cases, also setup in the static index file.

All the users are on mobile, and the majority on iOS.

According to logrocket, the error code on the requests is 0 and take ~10s to fail.

Am I getting caught up in some kind of privacy related blocking? I obviously don't need analytics or fonts for our app to work correctly but recaptcha is vital. Should I rehost it? I worry that would still fail as the loaded script attempts to communicate with google's servers.

Body:
Using logrocket, I have identified a small segment of users that is sometimes unable to load any resources from google. We discovered this because it causes an invisible recaptcha to fail which results in a "dead click" and stuck users, but I can see that all requests to google fail in these instances, like analytics and fonts.

I am using an older React app. The static index.html file has link tags that are loading the failing fonts.googleapis.com URLs:

   <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,700" rel="stylesheet">

Googla analytics is loaded with react-ga:

  import ReactGA from 'react-ga';

ReactGA.initialize('my-tracker', {
  debug: !process.env.NODE_ENV || process.env.NODE_ENV === 'development',
});

And the recpatcha script is loaded with little-loader on demand using a provider:

import React from 'react';
import load from 'little-loader';
import * as PropTypes from 'prop-types';

export const ReCaptchaContext = React.createContext({
  isReady: false,
});

const RE_CAPTCHA_SRC = 'https://www.google.com/recaptcha/api.js';

const ReCaptchaProvider = ({ children }) => {
  const existingContext = React.useContext(ReCaptchaContext);
  const [context, setContext] = React.useState({ ...existingContext });

  React.useEffect(() => {
    if (!existingContext.isReady) {
      load(RE_CAPTCHA_SRC, () => {
        setContext({ isReady: true });
      });
    }
  }, [existingContext.isReady]);

  return (
    <ReCaptchaContext.Provider value={context}>
      {children}
    </ReCaptchaContext.Provider>
  );
};

ReCaptchaProvider.propTypes = {
  children: PropTypes.oneOfType([
    PropTypes.arrayOf(PropTypes.node),
    PropTypes.node,
  ]).isRequired,
};

export default ReCaptchaProvider;

I have dozens if not hundreds of successful loads for every failing one. I am also using google tag manager which loads successfully in these cases, also setup in the static index file.

All the users are on mobile, and the majority on iOS.

According to logrocket, the error code on the requests is 0 and take ~10s to fail.

Am I getting caught up in some kind of privacy related blocking? I obviously don't need analytics or fonts for our app to work correctly but recaptcha is vital. Should I rehost it? I worry that would still fail as the loaded script attempts to communicate with google's servers.


问:
Minikube mount hostpath
I'm trying to mount a local folder onto minikube for persisting jenkins data but its failing with below error.
idea is to run jenkins on minikube cluster with persistent data for its workspace.
minikube version and kubernetes version is mentioned below along with error logs.

```<code>'$ minikube mount "/home/sourabh/jenkins_data:/jenkins_data"
  Mounting host path /home/sourabh/jenkins_data into VM as /jenkins_data ...
    ▪ Mount type:
    ▪ User ID:      docker
    ▪ Group ID:     docker
    ▪ Version:      9p2000.L
    ▪ Message Size: 262144
    ▪ Options:      map[]
    ▪ Bind Address: 172.19.196.135:38837
  Userspace file server: ufs starting

❌  Exiting due to GUEST_MOUNT_COULD_NOT_CONNECT: /bin/bash -c "sudo mount -t 9p -o dfltgid=$(grep ^docker: /etc/group | cut -d: -f3),dfltuid=$(id -u docker),msize=262144,port=38837,trans=tcp,version=9p2000.L 172.19.196.135 /jenkins_data": Process exited with status 32
stdout:

stderr:
mount: /jenkins_data: mount(2) system call failed: Connection timed out.

  Suggestion:

    If the host has a firewall:

    1. Allow a port through the firewall
    2. Specify "--port=<port_number>" for "minikube mount"

╭───────────────────────────────────────────────────────────────────────────────────────────╮
│                                                                                │
│      If the above advice does not help, please let us know:                             │
│      https://github.com/kubernetes/minikube/issues/new/choose                           │
│                                                                                │
│    Please run `minikube logs --file=logs.txt` and attach logs.txt to the GitHub issue.    │
│    Please also attach the following file to the GitHub issue:                             │
│    - /tmp/minikube_mount_a057c2cb7d52cb75588bb40c4af93fe409b78381_0.log                   │
│                                                                                │
╰───────────────────────────────────────────────────────────────────────────────────────────╯

Logfile generate shown here

Binary: Built with gc go1.19.2 for linux/amd64
Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg
I0109 16:36:07.842613    2616 out.go:296] Setting OutFile to fd 1 ...
I0109 16:36:07.842751    2616 out.go:348] isatty.IsTerminal(1) = true
I0109 16:36:07.842754    2616 out.go:309] Setting ErrFile to fd 2...
I0109 16:36:07.842757    2616 out.go:348] isatty.IsTerminal(2) = true
I0109 16:36:07.842890    2616 root.go:334] Updating PATH: /home/sourabh/.minikube/bin
W0109 16:36:07.842980    2616 root.go:311] Error reading config file at /home/sourabh/.minikube/config/config.json: open /home/sourabh/.minikube/config/config.json: no such file or directory
I0109 16:36:07.843091    2616 mustload.go:65] Loading cluster: minikube
I0109 16:36:07.843369    2616 config.go:180] Loaded profile config "minikube": Driver=docker, ContainerRuntime=docker, KubernetesVersion=v1.25.3
I0109 16:36:07.843676    2616 cli_runner.go:164] Run: docker container inspect minikube --format={{.State.Status}}
I0109 16:36:07.914497    2616 host.go:66] Checking if "minikube" exists ...
I0109 16:36:07.914672    2616 cli_runner.go:164] Run: docker container inspect -f "'{{(index (index .NetworkSettings.Ports "8443/tcp") 0).HostPort}}'" minikube
I0109 16:36:07.978854    2616 mount.go:141] Selecting IP for WSL. This may be incorrect...
I0109 16:36:07.983207    2616 out.go:177]   Mounting host path /home/sourabh/jenkins_data into VM as /jenkins_data ...
I0109 16:36:07.987688    2616 out.go:177]     ▪ Mount type:
I0109 16:36:07.992029    2616 out.go:177]     ▪ User ID:      docker
I0109 16:36:07.996174    2616 out.go:177]     ▪ Group ID:     docker
I0109 16:36:08.000666    2616 out.go:177]     ▪ Version:      9p2000.L
I0109 16:36:08.005048    2616 out.go:177]     ▪ Message Size: 262144
I0109 16:36:08.009032    2616 out.go:177]     ▪ Options:      map[]
I0109 16:36:08.012980    2616 out.go:177]     ▪ Bind Address: 172.19.196.135:46487
I0109 16:36:08.017007    2616 out.go:177]   Userspace file server:
I0109 16:36:08.016686    2616 ssh_runner.go:195] Run: /bin/bash -c "[ "x$(findmnt -T /jenkins_data | grep /jenkins_data)" != "x" ] && sudo umount -f /jenkins_data || echo "
I0109 16:36:08.017091    2616 cli_runner.go:164] Run: docker container inspect -f "'{{(index (index .NetworkSettings.Ports "22/tcp") 0).HostPort}}'" minikube
I0109 16:36:08.087038    2616 sshutil.go:53] new ssh client: &{IP:127.0.0.1 Port:61875 SSHKeyPath:/home/sourabh/.minikube/machines/minikube/id_rsa Username:docker}
I0109 16:36:08.127492    2616 mount.go:168] unmount for /jenkins_data ran successfully
I0109 16:36:08.127507    2616 ssh_runner.go:195] Run: /bin/bash -c "sudo mkdir -p /jenkins_data"
I0109 16:36:08.135776    2616 ssh_runner.go:195] Run: /bin/bash -c "sudo mount -t 9p -o dfltgid=$(grep ^docker: /etc/group | cut -d: -f3),dfltuid=$(id -u docker),msize=262144,port=46487,trans=tcp,version=9p2000.L 172.19.196.135 /jenkins_data"
I0109 16:37:31.315966    2616 out.go:177]   Unmounting /jenkins_data ...
I0109 16:37:31.322056    2616 ssh_runner.go:195] Run: /bin/bash -c "[ "x$(findmnt -T /jenkins_data | grep /jenkins_data)" != "x" ] && sudo umount -f /jenkins_data || echo "
Log file created at: 2023/01/09 16:38:06
Running on machine: Sourabh_PC
Binary: Built with gc go1.19.2 for linux/amd64
Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg
I0109 16:38:06.875663    2694 out.go:296] Setting OutFile to fd 1 ...
I0109 16:38:06.875853    2694 out.go:348] isatty.IsTerminal(1) = true

OS
NAME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04.1 LTS (Jammy Jellyfish)"

running minikube version 1.28
kuberneter 1.23.0`
</code>```

Tried looking for other possible options but nothing is availble online related to this issue.

Title: Minikube mount hostpath

Body:
I'm trying to mount a local folder onto minikube for persisting jenkins data but its failing with below error.
idea is to run jenkins on minikube cluster with persistent data for its workspace.
minikube version and kubernetes version is mentioned below along with error logs.

'$ minikube mount "/home/sourabh/jenkins_data:/jenkins_data"
  Mounting host path /home/sourabh/jenkins_data into VM as /jenkins_data ...
    ▪ Mount type:
    ▪ User ID:      docker
    ▪ Group ID:     docker
    ▪ Version:      9p2000.L
    ▪ Message Size: 262144
    ▪ Options:      map[]
    ▪ Bind Address: 172.19.196.135:38837
  Userspace file server: ufs starting

❌  Exiting due to GUEST_MOUNT_COULD_NOT_CONNECT: /bin/bash -c "sudo mount -t 9p -o dfltgid=$(grep ^docker: /etc/group | cut -d: -f3),dfltuid=$(id -u docker),msize=262144,port=38837,trans=tcp,version=9p2000.L 172.19.196.135 /jenkins_data": Process exited with status 32
stdout:

stderr:
mount: /jenkins_data: mount(2) system call failed: Connection timed out.

  Suggestion:

    If the host has a firewall:

    1. Allow a port through the firewall
    2. Specify "--port=<port_number>" for "minikube mount"

╭───────────────────────────────────────────────────────────────────────────────────────────╮
│                                                                                │
│      If the above advice does not help, please let us know:                             │
│      https://github.com/kubernetes/minikube/issues/new/choose                           │
│                                                                                │
│    Please run `minikube logs --file=logs.txt` and attach logs.txt to the GitHub issue.    │
│    Please also attach the following file to the GitHub issue:                             │
│    - /tmp/minikube_mount_a057c2cb7d52cb75588bb40c4af93fe409b78381_0.log                   │
│                                                                                │
╰───────────────────────────────────────────────────────────────────────────────────────────╯

Logfile generate shown here

Binary: Built with gc go1.19.2 for linux/amd64
Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg
I0109 16:36:07.842613    2616 out.go:296] Setting OutFile to fd 1 ...
I0109 16:36:07.842751    2616 out.go:348] isatty.IsTerminal(1) = true
I0109 16:36:07.842754    2616 out.go:309] Setting ErrFile to fd 2...
I0109 16:36:07.842757    2616 out.go:348] isatty.IsTerminal(2) = true
I0109 16:36:07.842890    2616 root.go:334] Updating PATH: /home/sourabh/.minikube/bin
W0109 16:36:07.842980    2616 root.go:311] Error reading config file at /home/sourabh/.minikube/config/config.json: open /home/sourabh/.minikube/config/config.json: no such file or directory
I0109 16:36:07.843091    2616 mustload.go:65] Loading cluster: minikube
I0109 16:36:07.843369    2616 config.go:180] Loaded profile config "minikube": Driver=docker, ContainerRuntime=docker, KubernetesVersion=v1.25.3
I0109 16:36:07.843676    2616 cli_runner.go:164] Run: docker container inspect minikube --format={{.State.Status}}
I0109 16:36:07.914497    2616 host.go:66] Checking if "minikube" exists ...
I0109 16:36:07.914672    2616 cli_runner.go:164] Run: docker container inspect -f "'{{(index (index .NetworkSettings.Ports "8443/tcp") 0).HostPort}}'" minikube
I0109 16:36:07.978854    2616 mount.go:141] Selecting IP for WSL. This may be incorrect...
I0109 16:36:07.983207    2616 out.go:177]   Mounting host path /home/sourabh/jenkins_data into VM as /jenkins_data ...
I0109 16:36:07.987688    2616 out.go:177]     ▪ Mount type:
I0109 16:36:07.992029    2616 out.go:177]     ▪ User ID:      docker
I0109 16:36:07.996174    2616 out.go:177]     ▪ Group ID:     docker
I0109 16:36:08.000666    2616 out.go:177]     ▪ Version:      9p2000.L
I0109 16:36:08.005048    2616 out.go:177]     ▪ Message Size: 262144
I0109 16:36:08.009032    2616 out.go:177]     ▪ Options:      map[]
I0109 16:36:08.012980    2616 out.go:177]     ▪ Bind Address: 172.19.196.135:46487
I0109 16:36:08.017007    2616 out.go:177]   Userspace file server:
I0109 16:36:08.016686    2616 ssh_runner.go:195] Run: /bin/bash -c "[ "x$(findmnt -T /jenkins_data | grep /jenkins_data)" != "x" ] && sudo umount -f /jenkins_data || echo "
I0109 16:36:08.017091    2616 cli_runner.go:164] Run: docker container inspect -f "'{{(index (index .NetworkSettings.Ports "22/tcp") 0).HostPort}}'" minikube
I0109 16:36:08.087038    2616 sshutil.go:53] new ssh client: &{IP:127.0.0.1 Port:61875 SSHKeyPath:/home/sourabh/.minikube/machines/minikube/id_rsa Username:docker}
I0109 16:36:08.127492    2616 mount.go:168] unmount for /jenkins_data ran successfully
I0109 16:36:08.127507    2616 ssh_runner.go:195] Run: /bin/bash -c "sudo mkdir -p /jenkins_data"
I0109 16:36:08.135776    2616 ssh_runner.go:195] Run: /bin/bash -c "sudo mount -t 9p -o dfltgid=$(grep ^docker: /etc/group | cut -d: -f3),dfltuid=$(id -u docker),msize=262144,port=46487,trans=tcp,version=9p2000.L 172.19.196.135 /jenkins_data"
I0109 16:37:31.315966    2616 out.go:177]   Unmounting /jenkins_data ...
I0109 16:37:31.322056    2616 ssh_runner.go:195] Run: /bin/bash -c "[ "x$(findmnt -T /jenkins_data | grep /jenkins_data)" != "x" ] && sudo umount -f /jenkins_data || echo "
Log file created at: 2023/01/09 16:38:06
Running on machine: Sourabh_PC
Binary: Built with gc go1.19.2 for linux/amd64
Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg
I0109 16:38:06.875663    2694 out.go:296] Setting OutFile to fd 1 ...
I0109 16:38:06.875853    2694 out.go:348] isatty.IsTerminal(1) = true

OS
NAME="Ubuntu"
VERSION_ID="22.04"
VERSION="22.04.1 LTS (Jammy Jellyfish)"

running minikube version 1.28
kuberneter 1.23.0`

Tried looking for other possible options but nothing is availble online related to this issue.


问:
Minecraft 1.19.3 modding fabric .createExplosion with user as entity and explosion deals player still damage
I am currently learning how to program minecraft mods using fabric. I want to create an Item, which, when used on a creeper, let the player explode, which will also be shown in the deathmessage, that the player was the cause of the death(like when you kill yourself with TNT).

```<code>package net.lurchfresser.tutorialmod.item.custom;

import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.mob.CreeperEntity;
import net.minecraft.entity.mob.ZombieEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.world.World;
import org.w3c.dom.Text;

public class ConsumerItem extends Item {
    public ConsumerItem(Settings settings){
        super(settings);
    }

    @Override
    public ActionResult useOnEntity(ItemStack stack, PlayerEntity user, LivingEntity entity, Hand hand) {
        double x = user.getX();
        double y = user.getY();
        double z = user.getZ();

        if(!user.world.isClient) {
            if (entity instanceof ZombieEntity) {
                entity.kill();
                user.addStatusEffect(new StatusEffectInstance(StatusEffect.byRawId(19), 100));
            } else if (entity instanceof CreeperEntity) {
                entity.kill();
                user.world.createExplosion(user, null,null, x + 0.5D, y + 0.5d, z + 0.5d,3F,false,World.ExplosionSourceType.MOB);
            }
        }
        return super.useOnEntity(stack, user, entity, hand);
    }

}
</code>```

If I put the creeper in the first param of the createExplosion method. The Creeper will be the cause of the death. Also trying pass user.getName.toString in the second param(damageSource) didn't work out.

Body:
I am currently learning how to program minecraft mods using fabric. I want to create an Item, which, when used on a creeper, let the player explode, which will also be shown in the deathmessage, that the player was the cause of the death(like when you kill yourself with TNT).

package net.lurchfresser.tutorialmod.item.custom;

import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.entity.mob.CreeperEntity;
import net.minecraft.entity.mob.ZombieEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Hand;
import net.minecraft.world.World;
import org.w3c.dom.Text;

public class ConsumerItem extends Item {
    public ConsumerItem(Settings settings){
        super(settings);
    }

    @Override
    public ActionResult useOnEntity(ItemStack stack, PlayerEntity user, LivingEntity entity, Hand hand) {
        double x = user.getX();
        double y = user.getY();
        double z = user.getZ();

        if(!user.world.isClient) {
            if (entity instanceof ZombieEntity) {
                entity.kill();
                user.addStatusEffect(new StatusEffectInstance(StatusEffect.byRawId(19), 100));
            } else if (entity instanceof CreeperEntity) {
                entity.kill();
                user.world.createExplosion(user, null,null, x + 0.5D, y + 0.5d, z + 0.5d,3F,false,World.ExplosionSourceType.MOB);
            }
        }
        return super.useOnEntity(stack, user, entity, hand);
    }

}

If I put the creeper in the first param of the createExplosion method. The Creeper will be the cause of the death. Also trying pass user.getName.toString in the second param(damageSource) didn't work out.


问:
Microcontroller input state counter problem
I am doing a major embedded project of making a GM counter. As a main microcontroller I am using a PIC32MK1024MCM064. I wont bore you with details, but I need to implement following algorithm:

When MCU turns on, 13 seconds delay has to pass

MCU waits for a button press, which triggers an interrupt

Button interrupt starts 60 seconds timer

During that 60 seconds, MCU input pin counts the impulses (Idle voltage state is high (3.3V) and low voltage state counts as an impulse (50-130 us duration))

After the timer has expired, MCU outputs the impulse number via 16x2 LCD screen

Project has many files included in it, but I have already verified all the peripheral code is written right:

I have already made sure, that my button interrupt and the timer interrupt work absolutely fine (used the oscilloscope, real timer and all the other stuff.)

I also verified that my I2C driver for the LCD screen works great as well.

I made sure I am indeed getting the low state impulses as defined (50-130 us duration.)

```<code> #include <xc.h>
#include "configurations_bits.h"

#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include "stdio.h"
#include <sys/attribs.h>

#include "delay.h"
#include "inter_integrated_circuit_protocol.h"
#include "liquid_crystal_display.h"
#include "pulse_width_modulation.h"
#include "timer.h"
#include "state_change_interrupts.h"

static int  Particle_count = 0;                                //Variable for counting events

 char Value[10]={0};                                           //Particle value string

    int main(void) {

        __builtin_disable_interrupts();                        //Global interrupt disable

        ANSELA = 0x00000000;                                   //Enable PORT A digital inputs
        ANSELG = 0x00000000;                                   //Enable PORT G digital inputs

        TRISEbits.TRISE12 = 0;                                 //Output gpio of a led
        TRISDbits.TRISD8 = 0;                                  //Output gpio of a led
        TRISGbits.TRISG9 = 0;                                  //Output GPIO of GM ENABLE

        LATGbits.LATG9 = 1;                                    //Enable GM right away
        TRISAbits.TRISA1 = 1;                                  //Input for counting particles
        TRISCbits.TRISC7 = 1;                                  //Input for control button

        Inter_Integrated_Circuit_Setup ();                     //I2C configuration
        Inter_Integrated_Circuit_Enable ();                    //I2C enable
        Liquid_Crystal_Display_initialization();               //LCD configuration

        Liquid_Crystal_Display_Set_Cursor(1, 1);
        Liquid_Crystal_Display_Write_String("Preparing for");
        Liquid_Crystal_Display_Set_Cursor(2, 1);
        Liquid_Crystal_Display_Write_String("Measurement");

        Pulse_Width_Modulation_Setup();                        //PWM setup
        Pulse_Width_Modulation_Enable();                       //Turn on high voltage generation

        for(int i=0; i<13; i++){
        delay_ms(1000);}                                       //Waiting until the high voltage rail rises up to 400V (starting GM tube voltage)

        Liquid_Crystal_Display_Clear();                        //Clearing LCD

        Liquid_Crystal_Display_Set_Cursor(1, 1);
        Liquid_Crystal_Display_Write_String("Ready for");
        Liquid_Crystal_Display_Set_Cursor(2, 1);
        Liquid_Crystal_Display_Write_String("Measurement");

        State_Change_Interrupts_Setup ();                      //Button interrupt setup
        Timer2_Setup ();                                       //Timer interrupt setup

        __builtin_enable_interrupts();                         //Global interrupt enable

            while (1){

                 if(T2CONbits.ON){                             //Condition, that the timer is on

                    Liquid_Crystal_Display_Clear();            //Clearing LCD

                    Liquid_Crystal_Display_Set_Cursor(1, 1);
                    Liquid_Crystal_Display_Write_String(" Measurement Is ");
                    Liquid_Crystal_Display_Set_Cursor(2, 1);
                    Liquid_Crystal_Display_Write_String("  In Progress   ");

                    while(T2CONbits.ON){                         //Execute this while cycle until the timer shuts off
                        if(PORTAbits.RA1==0){
                        Particle_count = Particle_count+1;
                        delay_us(100);}                         //GM tube dead time compensation
                    }

                    Liquid_Crystal_Display_Clear();            //Clearing LCD

                    sprintf(Value,"%05d CPM",Particle_count);

                    Particle_count=0;                          //Resetting the CPM value

                    Liquid_Crystal_Display_Set_Cursor(1, 1);
                    Liquid_Crystal_Display_Write_String(Value);//Printing radiation level in CPM notation
                    delay_ms(5000);

                    Liquid_Crystal_Display_Clear();            //Clearing LCD
                 }
            }

        return (EXIT_FAILURE);

    }
</code>```

When I press the button, my LCD outputs "Measurement Is In Progress" for a fraction of a second, then it immediately outputs "00000 CPM" which means it had counted zero impulses (In my application, I know for sure that I must capture at least 5 impulses per minute.) Looks like the while cycle has only one or few iterations (it should last for a minute). So my code problem is not a missing semicolon somewhere, but I feel like the whole architecture is not right. Have you got any observations or suggestions, how could I implement the mentioned algorithm? Want to thank you in advance.

(P.S I am running a 8 MHz internal FRC as the main clock)

Body:
I am doing a major embedded project of making a GM counter. As a main microcontroller I am using a PIC32MK1024MCM064. I wont bore you with details, but I need to implement following algorithm:

When MCU turns on, 13 seconds delay has to pass

MCU waits for a button press, which triggers an interrupt

Button interrupt starts 60 seconds timer

During that 60 seconds, MCU input pin counts the impulses (Idle voltage state is high (3.3V) and low voltage state counts as an impulse (50-130 us duration))

After the timer has expired, MCU outputs the impulse number via 16x2 LCD screen

Project has many files included in it, but I have already verified all the peripheral code is written right:

I have already made sure, that my button interrupt and the timer interrupt work absolutely fine (used the oscilloscope, real timer and all the other stuff.)

I also verified that my I2C driver for the LCD screen works great as well.

I made sure I am indeed getting the low state impulses as defined (50-130 us duration.)

 #include <xc.h>
#include "configurations_bits.h"

#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>
#include "stdio.h"
#include <sys/attribs.h>

#include "delay.h"
#include "inter_integrated_circuit_protocol.h"
#include "liquid_crystal_display.h"
#include "pulse_width_modulation.h"
#include "timer.h"
#include "state_change_interrupts.h"

static int  Particle_count = 0;                                //Variable for counting events

 char Value[10]={0};                                           //Particle value string

    int main(void) {

        __builtin_disable_interrupts();                        //Global interrupt disable

        ANSELA = 0x00000000;                                   //Enable PORT A digital inputs
        ANSELG = 0x00000000;                                   //Enable PORT G digital inputs

        TRISEbits.TRISE12 = 0;                                 //Output gpio of a led
        TRISDbits.TRISD8 = 0;                                  //Output gpio of a led
        TRISGbits.TRISG9 = 0;                                  //Output GPIO of GM ENABLE

        LATGbits.LATG9 = 1;                                    //Enable GM right away
        TRISAbits.TRISA1 = 1;                                  //Input for counting particles
        TRISCbits.TRISC7 = 1;                                  //Input for control button

        Inter_Integrated_Circuit_Setup ();                     //I2C configuration
        Inter_Integrated_Circuit_Enable ();                    //I2C enable
        Liquid_Crystal_Display_initialization();               //LCD configuration

        Liquid_Crystal_Display_Set_Cursor(1, 1);
        Liquid_Crystal_Display_Write_String("Preparing for");
        Liquid_Crystal_Display_Set_Cursor(2, 1);
        Liquid_Crystal_Display_Write_String("Measurement");

        Pulse_Width_Modulation_Setup();                        //PWM setup
        Pulse_Width_Modulation_Enable();                       //Turn on high voltage generation

        for(int i=0; i<13; i++){
        delay_ms(1000);}                                       //Waiting until the high voltage rail rises up to 400V (starting GM tube voltage)

        Liquid_Crystal_Display_Clear();                        //Clearing LCD

        Liquid_Crystal_Display_Set_Cursor(1, 1);
        Liquid_Crystal_Display_Write_String("Ready for");
        Liquid_Crystal_Display_Set_Cursor(2, 1);
        Liquid_Crystal_Display_Write_String("Measurement");

        State_Change_Interrupts_Setup ();                      //Button interrupt setup
        Timer2_Setup ();                                       //Timer interrupt setup

        __builtin_enable_interrupts();                         //Global interrupt enable

            while (1){

                 if(T2CONbits.ON){                             //Condition, that the timer is on

                    Liquid_Crystal_Display_Clear();            //Clearing LCD

                    Liquid_Crystal_Display_Set_Cursor(1, 1);
                    Liquid_Crystal_Display_Write_String(" Measurement Is ");
                    Liquid_Crystal_Display_Set_Cursor(2, 1);
                    Liquid_Crystal_Display_Write_String("  In Progress   ");

                    while(T2CONbits.ON){                         //Execute this while cycle until the timer shuts off
                        if(PORTAbits.RA1==0){
                        Particle_count = Particle_count+1;
                        delay_us(100);}                         //GM tube dead time compensation
                    }

                    Liquid_Crystal_Display_Clear();            //Clearing LCD

                    sprintf(Value,"%05d CPM",Particle_count);

                    Particle_count=0;                          //Resetting the CPM value

                    Liquid_Crystal_Display_Set_Cursor(1, 1);
                    Liquid_Crystal_Display_Write_String(Value);//Printing radiation level in CPM notation
                    delay_ms(5000);

                    Liquid_Crystal_Display_Clear();            //Clearing LCD
                 }
            }

        return (EXIT_FAILURE);

    }

When I press the button, my LCD outputs "Measurement Is In Progress" for a fraction of a second, then it immediately outputs "00000 CPM" which means it had counted zero impulses (In my application, I know for sure that I must capture at least 5 impulses per minute.) Looks like the while cycle has only one or few iterations (it should last for a minute). So my code problem is not a missing semicolon somewhere, but I feel like the whole architecture is not right. Have you got any observations or suggestions, how could I implement the mentioned algorithm? Want to thank you in advance.

(P.S I am running a 8 MHz internal FRC as the main clock)


问:
How can I speed up Elasticsearch term_statistics queries?

Term statistics Setting term_statistics to true (default is false)
will return

total term frequency (how often a term occurs in all documents)

document frequency (the number of documents containing the current term)

By default these values are not returned since term statistics can
have a serious performance impact.

https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-termvectors.html#docs-termvectors-api-term-stats

Is the performance bad because it re-counts total term frequency and/or document frequency every time, or does it keep that number on hand and run slowly just when there are a lot of terms to fetch stats for?

If it's the first, I can use a stale export of frequencies to avoid recounts, but if it's the second, I'm going to have to get stats for truncated documents, which probably also calls for exporting frequencies.


问:
Nuxt load data from localstorage into vuex on startup
I have the following problem in Nuxt. I want to load account data from localstorage to Vuex store on initial page load. I first tried to do this in the default layout. However, it seems like the child components are rendered first, and then the layout.

So I rewrote it as a plugin and as middleware. The code looks like this "plugins/account-loader.js":

```<code>export default ({ store }) => {
    if (process.client) {
        try {

            let user = JSON.parse(localStorage.user);
            store.commit("auth/setUser", user);

        } catch (error) {
            console.log(error)
        }
    }
}
</code>```

nuxt.config.js:

```<code>  plugins: [
    { src: '~/plugins/account-loader', mode: 'client' },
  ],
</code>```

However, I get the following error message:

```<code>[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. Bailing hydration and performing full client-side render.
</code>```

The problem has already been described here. However, the answer described there does not work for me. The same error message appears here.

Would be happy if you can help. I think I have not yet understood something basic about Nuxt (it is an existing vue SPA app migrated to Nuxt).

Body:
I have the following problem in Nuxt. I want to load account data from localstorage to Vuex store on initial page load. I first tried to do this in the default layout. However, it seems like the child components are rendered first, and then the layout.

So I rewrote it as a plugin and as middleware. The code looks like this "plugins/account-loader.js":

export default ({ store }) => {
    if (process.client) {
        try {

            let user = JSON.parse(localStorage.user);
            store.commit("auth/setUser", user);

        } catch (error) {
            console.log(error)
        }
    }
}

nuxt.config.js:

  plugins: [
    { src: '~/plugins/account-loader', mode: 'client' },
  ],

However, I get the following error message:

[Vue warn]: The client-side rendered virtual DOM tree is not matching server-rendered content. This is likely caused by incorrect HTML markup, for example nesting block-level elements inside
, or missing
. Bailing hydration and performing full client-side render.

The problem has already been described here. However, the answer described there does not work for me. The same error message appears here.

Would be happy if you can help. I think I have not yet understood something basic about Nuxt (it is an existing vue SPA app migrated to Nuxt).


问:
How to know when exactly does the device get locked in Android?
I'm trying to implement a system level lock screen from a third-party/device-owner MDM app in Android.

I tried looking up on the internet for ways for third-party apps to implement system level lock-screen but from the information that I was able to gather there doesn't seem to be a standard way to implement the same.

The approach we are currently using for the same is to use the (system) overlay permission and showing up the overlay when the boot completes (BOOT_COMPLETED system broadcast intent) and when the device gets locked.

To know when the device gets locked, there were two approaches that we mainly found for the same.

Use a background service, add an invisible overlay, listen to key events until we find a key event related to the power button

Use a background service, register a receiver for SCREEN_OFF event there, and wait for the same.

In both the approaches, we need to use a background service which could potentially drain out battery... By any chance, is there any event/broadcast intent that we could listen to, to make this more efficient overall for the given use case?


问:
How to read image tag value of kubernetes cronjob with python kubernetes client?
What is python code for kubernetes client same as:

'kubectl get cronjob -o yaml'

I tried with https://github.com/kubernetes-client/python/blob/master/examples/cronjob_crud.py

get_cronjob_body(namespace,name,command) which return body but this doesn't work.


问:
Decoding Target values as "NEGATIVE" and "POSITIVE"
trying to decode the target variables 0:Negative, 2:Neutral and 4:Positive

```<code>df.target.values
Output:array(['NEGATIVE', 'NEGATIVE', 'NEGATIVE', ..., 'POSITIVE', 'POSITIVE',
       'POSITIVE'], dtype=object)
</code>```

So, I tried doing

```<code>decode_map = {0: 'NEGATIVE', 2: 'NEUTRAL', 4: 'POSITIVE'}
def decode_sentiment(label):
    return decode_map[int(label)]
</code>```
```<code>df.target = df.target.apply(lambda x: decode_sentiment(x))

</code>```

But it is giving me the Error of

```<code>ValueError: invalid literal for int() with base 10: 'NEGATIVE'

</code>```

Body:
trying to decode the target variables 0:Negative, 2:Neutral and 4:Positive

df.target.values
Output:array(['NEGATIVE', 'NEGATIVE', 'NEGATIVE', ..., 'POSITIVE', 'POSITIVE',
       'POSITIVE'], dtype=object)

So, I tried doing

decode_map = {0: 'NEGATIVE', 2: 'NEUTRAL', 4: 'POSITIVE'}
def decode_sentiment(label):
    return decode_map[int(label)]

df.target = df.target.apply(lambda x: decode_sentiment(x))

But it is giving me the Error of

ValueError: invalid literal for int() with base 10: 'NEGATIVE'


问:
Line and text don't align in matplotlib
I'm trying to draw a line with text written on it using the following code:

```<code>def angle_line(A, B):
    x = B[0] - A[0]
    y = B[1] - A[1]
    angle = math.atan2(y, x )
    return angle*180/np.pi

fig, ax = plt.subplots()
xy_init = (0,0)
xy_end = (1, 0.5)

#PLOT LINE
ax.plot((xy_init[0], xy_end[0]), (xy_init[1], xy_end[1]), color='black', linewidth=0.5, linestyle='--')

center = (xy_init[0]+xy_end[0])/2, (xy_init[1]+xy_end[1])/2
angle = angle_line(xy_init, xy_end)

#PLOT TEXT
ax.text(*center, 'TEST', horizontalalignment='center', rotation = angle,
        verticalalignment='center',fontdict={'fontsize': 20}, color='red')
</code>```

Basically, I draw the line using the two points, and then for the text, I calculate the angle and rotate the text accordingly. But, for some reason I cannot comprehend, they are misaligned, as shown in the picture below:

Do I understand something wrong about the parameters of the matplotlib functions, or is there any problem with the code above?

Title: Line and text don't align in matplotlib

Body:
I'm trying to draw a line with text written on it using the following code:

def angle_line(A, B):
    x = B[0] - A[0]
    y = B[1] - A[1]
    angle = math.atan2(y, x )
    return angle*180/np.pi

fig, ax = plt.subplots()
xy_init = (0,0)
xy_end = (1, 0.5)

#PLOT LINE
ax.plot((xy_init[0], xy_end[0]), (xy_init[1], xy_end[1]), color='black', linewidth=0.5, linestyle='--')

center = (xy_init[0]+xy_end[0])/2, (xy_init[1]+xy_end[1])/2
angle = angle_line(xy_init, xy_end)

#PLOT TEXT
ax.text(*center, 'TEST', horizontalalignment='center', rotation = angle,
        verticalalignment='center',fontdict={'fontsize': 20}, color='red')

Basically, I draw the line using the two points, and then for the text, I calculate the angle and rotate the text accordingly. But, for some reason I cannot comprehend, they are misaligned, as shown in the picture below:

Do I understand something wrong about the parameters of the matplotlib functions, or is there any problem with the code above?


问:
How to see column constraints in h2-database
I'm trying to view my database information in h2-database. For example, if I want to see what column constraints I have (if the column is unique, not-null, etc...) I tried using

```<code>ELECT COMMENT, PARENT_ID,
       is_nullable
from information_schema.columns
</code>```

but I get

Column "COMMENT" not found; SQL statement: SELECT COMMENT, PARENT_ID,
is_nullable from information_schema.columns [42122-214] 42S22/42122 (Help)

I tried running the CHECK_CONSTRAINTS in INFORMATION_SCHEMA

My h2-database looks like this

and I would like to see info like in MYSQL ALTER TABLE. Like this:

Also is there any way I can connect to h2 using other 3rd party service instead of localhost:8080/h2-console

Body:
I'm trying to view my database information in h2-database. For example, if I want to see what column constraints I have (if the column is unique, not-null, etc...) I tried using

ELECT COMMENT, PARENT_ID,
       is_nullable
from information_schema.columns

but I get

Column "COMMENT" not found; SQL statement: SELECT COMMENT, PARENT_ID,
is_nullable from information_schema.columns [42122-214] 42S22/42122 (Help)

I tried running the CHECK_CONSTRAINTS in INFORMATION_SCHEMA

My h2-database looks like this

and I would like to see info like in MYSQL ALTER TABLE. Like this:

Also is there any way I can connect to h2 using other 3rd party service instead of localhost:8080/h2-console


问:
POX - Modifying a packet's destination in POX Controller
I am trying to create a honeypot using Mininet and POX Controller. Here, what I want to achieve is that whenever a particular host pings a specific network, instead of redirecting it to the actual host, the switch should modify its destination as the ip address of our host behaving as honeypot.

I'm quite confused about the implementation of this using ofp_flow_mod() method and which switch should actually implement it. Any code examples to give me a direction would be really helpful.

I've included the topology diagram below to illustrate a clear understanding:
Mininet Topology

I've created a Mininet Topology using the following code:

```<code>from mininet.net import Mininet
from mininet.node import RemoteController
from mininet.cli import CLI
from mininet.log import setLogLevel, info

setLogLevel( 'info' )

info('\n*** Initialize Mininet\n')
net = Mininet()

info( '*** Adding controller\n' )
net.addController(name='c0', controller=RemoteController, ip='192.168.56.101', port=6633 )

info( '*** Adding hosts\n' )
h1 = net.addHost( 'h1', ip='10.0.1.1', )
h2 = net.addHost( 'h2', ip='10.0.1.2', )
h3 = net.addHost( 'h3', ip='10.0.2.1', )
h4 = net.addHost( 'h4', ip='10.0.2.2', )
h5 = net.addHost( 'h5', ip='10.0.2.3', )
h6 = net.addHost( 'h6', ip='10.0.2.4', )
h7 = net.addHost( 'h7', ip='10.0.3.1', )
h8 = net.addHost( 'h8', ip='10.0.3.2', )

info( '*** Adding switches\n' )
s1 = net.addSwitch( 's1' )
s2 = net.addSwitch( 's2' )
s3 = net.addSwitch( 's3' )

info( '*** Creating links\n' )
net.addLink(s1, s2)
net.addLink(s2, s3)
net.addLink( s1, h1 )
net.addLink( s1, h2 )
net.addLink( s2, h3 )
net.addLink( s2, h4 )
net.addLink( s2, h5 )
net.addLink( s2, h6 )
net.addLink( s3, h7 )
net.addLink( s3, h8 )

info( '*** Starting network\n')
net.start()

info( '*** Running CLI\n' )
CLI( net )

info( '*** Stopping network' )
net.stop()

</code>```

This topology is successfully connected with POX.

The goal here is that whenever h1 (10.0.1.1) or h2 (10.0.1.2) pings any hosts connected to switch2, the packets should be redirected from switch 2 directly to switch 3 with a modified IP address and vice-versa.

I've tried to implement the following code in POX but it doesn't seem to give me a direction at all.

```<code>from pox.core import core
from pox.lib.addresses import IPAddr
import pox.openflow.libopenflow_01 as of
from pox.lib.revent import *
from pox.lib.util import dpid_to_str
from pox.lib.packet.ethernet import ethernet
from pox.lib.packet.ipv4 import ipv4
from pox.lib.addresses import IPAddr, EthAddr

log = core.getLogger()

# creating an event which triggers when a request from switch 1 device sent to switch 2 device
class SDNHoneyPot(EventMixin):

    def __init__ (self):
        self.listenTo(core.openflow)

    def _handle_PacketIn (self, event):
        """
        Handles packet in messages from the switch.
        """
        packet = event.parsed # This is the parsed packet data.
        if not packet.parsed:
            log.warning("Ignoring incomplete packet")
            return

        packet_in = event.ofp # The actual ofp_packet_in message.

        msg = of.ofp_flow_mod()

        if (event.dpid == 2 and
            (isinstance(packet.next, ipv4) and
                (packet.next.srcip == "10.0.1.1" and packet.next.dstip == "10.0.2.1") or ((packet.next.srcip == "10.0.2.1" and packet.next.dstip == "10.0.1.1"))))

            msg.priority = 10
            msg.match.dl_type = 0x0800
            msg.match.nw_proto = 1 # ICMP
            msg.match.nw_src = "10.0.1.1" # from untrusted host
            msg.match.nw_dst = "10.0.2.1" # to our datacenter
            event.connection.send(msg)

            msg = of.ofp_flow_mod()
            msg.priority = 10
            msg.match.dl_type = 0x0800
            msg.match.nw_proto = 1 # ICMP
            msg.match.nw_src = "10.0.2.1" # from untrusted host
            msg.match.nw_dst = "10.0.1.1" # to our datacenter
            event.connection.send(msg)
        else:
            msg.data = packet_in
            msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))
            event.connection.send(msg)

    def _handle_ConnectionUp (self, event):

        # Log whenever a switch is registered in Mininet Topology.
        log.debug("Switch %s has come up.", dpid_to_str(event.dpid))

# registering the event to the core component
def launch ():
    core.registerNew(SDNHoneyPot)

</code>```

Since I have no idea about how to redirect these packets, I'm currently trying to block these packets from forwarding by providing no actions, but that does not seem to work as well.

Body:
I am trying to create a honeypot using Mininet and POX Controller. Here, what I want to achieve is that whenever a particular host pings a specific network, instead of redirecting it to the actual host, the switch should modify its destination as the ip address of our host behaving as honeypot.

I'm quite confused about the implementation of this using ofp_flow_mod() method and which switch should actually implement it. Any code examples to give me a direction would be really helpful.

I've included the topology diagram below to illustrate a clear understanding:
Mininet Topology

I've created a Mininet Topology using the following code:

from mininet.net import Mininet
from mininet.node import RemoteController
from mininet.cli import CLI
from mininet.log import setLogLevel, info

setLogLevel( 'info' )

info('\n*** Initialize Mininet\n')
net = Mininet()

info( '*** Adding controller\n' )
net.addController(name='c0', controller=RemoteController, ip='192.168.56.101', port=6633 )

info( '*** Adding hosts\n' )
h1 = net.addHost( 'h1', ip='10.0.1.1', )
h2 = net.addHost( 'h2', ip='10.0.1.2', )
h3 = net.addHost( 'h3', ip='10.0.2.1', )
h4 = net.addHost( 'h4', ip='10.0.2.2', )
h5 = net.addHost( 'h5', ip='10.0.2.3', )
h6 = net.addHost( 'h6', ip='10.0.2.4', )
h7 = net.addHost( 'h7', ip='10.0.3.1', )
h8 = net.addHost( 'h8', ip='10.0.3.2', )

info( '*** Adding switches\n' )
s1 = net.addSwitch( 's1' )
s2 = net.addSwitch( 's2' )
s3 = net.addSwitch( 's3' )

info( '*** Creating links\n' )
net.addLink(s1, s2)
net.addLink(s2, s3)
net.addLink( s1, h1 )
net.addLink( s1, h2 )
net.addLink( s2, h3 )
net.addLink( s2, h4 )
net.addLink( s2, h5 )
net.addLink( s2, h6 )
net.addLink( s3, h7 )
net.addLink( s3, h8 )

info( '*** Starting network\n')
net.start()

info( '*** Running CLI\n' )
CLI( net )

info( '*** Stopping network' )
net.stop()

This topology is successfully connected with POX.

The goal here is that whenever h1 (10.0.1.1) or h2 (10.0.1.2) pings any hosts connected to switch2, the packets should be redirected from switch 2 directly to switch 3 with a modified IP address and vice-versa.

I've tried to implement the following code in POX but it doesn't seem to give me a direction at all.

from pox.core import core
from pox.lib.addresses import IPAddr
import pox.openflow.libopenflow_01 as of
from pox.lib.revent import *
from pox.lib.util import dpid_to_str
from pox.lib.packet.ethernet import ethernet
from pox.lib.packet.ipv4 import ipv4
from pox.lib.addresses import IPAddr, EthAddr

log = core.getLogger()

# creating an event which triggers when a request from switch 1 device sent to switch 2 device
class SDNHoneyPot(EventMixin):

    def __init__ (self):
        self.listenTo(core.openflow)

    def _handle_PacketIn (self, event):
        """
        Handles packet in messages from the switch.
        """
        packet = event.parsed # This is the parsed packet data.
        if not packet.parsed:
            log.warning("Ignoring incomplete packet")
            return

        packet_in = event.ofp # The actual ofp_packet_in message.

        msg = of.ofp_flow_mod()

        if (event.dpid == 2 and
            (isinstance(packet.next, ipv4) and
                (packet.next.srcip == "10.0.1.1" and packet.next.dstip == "10.0.2.1") or ((packet.next.srcip == "10.0.2.1" and packet.next.dstip == "10.0.1.1"))))

            msg.priority = 10
            msg.match.dl_type = 0x0800
            msg.match.nw_proto = 1 # ICMP
            msg.match.nw_src = "10.0.1.1" # from untrusted host
            msg.match.nw_dst = "10.0.2.1" # to our datacenter
            event.connection.send(msg)

            msg = of.ofp_flow_mod()
            msg.priority = 10
            msg.match.dl_type = 0x0800
            msg.match.nw_proto = 1 # ICMP
            msg.match.nw_src = "10.0.2.1" # from untrusted host
            msg.match.nw_dst = "10.0.1.1" # to our datacenter
            event.connection.send(msg)
        else:
            msg.data = packet_in
            msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))
            event.connection.send(msg)

    def _handle_ConnectionUp (self, event):

        # Log whenever a switch is registered in Mininet Topology.
        log.debug("Switch %s has come up.", dpid_to_str(event.dpid))

# registering the event to the core component
def launch ():
    core.registerNew(SDNHoneyPot)

Since I have no idea about how to redirect these packets, I'm currently trying to block these packets from forwarding by providing no actions, but that does not seem to work as well.


问:
getting error status 422 in calling axios api with postman in react native
```<code> const getAllSurvey = async () => {
    const api = `http://112.196.108.244:9002/api/survey/by-filter`;
    const fetchApiUsingAxios = await axios.post(
        api,
        {
          id: '68213656',
          isMandatory: 'false',
        },
        {
          headers: {
            'content-Type': 'application/json',
            Authorization: `Bearer token-key`,
          },
        },
      )

      .then(response => {
        console.log('response', response.data);
        setItem(response.data);
      })
      .catch(error => {
        console.log('error', error.response);
      });
  };

</code>```

My error in console :

Array(2)
0: {field: 'paginationFilter', message: 'must not be null'}
1: {field: 'filterInput', message: 'must not be null'}

message: "Validation error. Check 'errors' field for details."
status: 422

Body:
 const getAllSurvey = async () => {
    const api = `http://112.196.108.244:9002/api/survey/by-filter`;
    const fetchApiUsingAxios = await axios.post(
        api,
        {
          id: '68213656',
          isMandatory: 'false',
        },
        {
          headers: {
            'content-Type': 'application/json',
            Authorization: `Bearer token-key`,
          },
        },
      )

      .then(response => {
        console.log('response', response.data);
        setItem(response.data);
      })
      .catch(error => {
        console.log('error', error.response);
      });
  };

My error in console :

Array(2)
0: {field: 'paginationFilter', message: 'must not be null'}
1: {field: 'filterInput', message: 'must not be null'}

message: "Validation error. Check 'errors' field for details."
status: 422


问:
How to create Grafana alert for when backup failed?
We have 3 PostgreSQL databases in GCP's CloudSQL, all three of them are backed-up daily. I need to use Grafana to monitor those back-ups and alert when they've failed.

Unfortunately I'm not finding many resources to help me with this task. Is there a way to create this kind of alerting rule?


问:
.NET7 Json serialization: cannot handle circular references
I have these tables in my db:

```<code>- Turns
- Jobs
- Turns_Jobs (a turn may have multiple jobs, a single job may span across multiple turns)
- Managers (each job has a manager)
</code>```

These are the corresponding classes:

```<code>- Turn
   - int TurnID
   - ...
   - virtual ICollection<Turn_Job> TurnJobs

- Job
   - int JobID
   - ...
   - int ManagerID
   - virtual Manager Manager
   - ...
   - virtual ICollection<Turn_Job> JobTurns

- Turn_Job
   - int TurnID
   - ...
   - virtual Turn Turn
   - int JobID
   - virtual Job Job

- Manager
   - ManagerID
   - Name
</code>```

I'm trying to serialize the following query:

```<code>var q = await _db.Turns
    .Include(x => x.TurnJobs).ThenInclude(x => x.Job).ThenInclude(x => x.Manager)
    .Where(x => true; /* real application has some conditions here */ )
    .Select(x => x)
    .ToListAsync();
</code>```

Usually I would do:

```<code>var json = JsonSerializer.Serialize(q, new JsonSerializerOptions(JsonSerializerDefaults.Web) { ReferenceHandler = ReferenceHandler.Preserve });
</code>```

but this throws the following exception:

```<code>System.Text.Json.JsonException: The object or value could not be serialized. Path: $.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.
 ---> System.InvalidOperationException: CurrentDepth (64) is equal to or larger than the maximum allowed depth of 64. Cannot write the next JSON object or array.
</code>```

It seems that circular reference is not detected and/or correctly handled.

If I ignore references:

```<code>var json = JsonSerializer.Serialize(r, new JsonSerializerOptions(JsonSerializerDefaults.Web) { ReferenceHandler = ReferenceHandler.IgnoreCycles });
</code>```

the exception becomes:

```<code>System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 64. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. Path: $.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.TurnID.
</code>```

Body:
I have these tables in my db:

- Turns
- Jobs
- Turns_Jobs (a turn may have multiple jobs, a single job may span across multiple turns)
- Managers (each job has a manager)

These are the corresponding classes:

- Turn
   - int TurnID
   - ...
   - virtual ICollection<Turn_Job> TurnJobs

- Job
   - int JobID
   - ...
   - int ManagerID
   - virtual Manager Manager
   - ...
   - virtual ICollection<Turn_Job> JobTurns

- Turn_Job
   - int TurnID
   - ...
   - virtual Turn Turn
   - int JobID
   - virtual Job Job

- Manager
   - ManagerID
   - Name

I'm trying to serialize the following query:

var q = await _db.Turns
    .Include(x => x.TurnJobs).ThenInclude(x => x.Job).ThenInclude(x => x.Manager)
    .Where(x => true; /* real application has some conditions here */ )
    .Select(x => x)
    .ToListAsync();

Usually I would do:

var json = JsonSerializer.Serialize(q, new JsonSerializerOptions(JsonSerializerDefaults.Web) { ReferenceHandler = ReferenceHandler.Preserve });

but this throws the following exception:

System.Text.Json.JsonException: The object or value could not be serialized. Path: $.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.
 ---> System.InvalidOperationException: CurrentDepth (64) is equal to or larger than the maximum allowed depth of 64. Cannot write the next JSON object or array.

It seems that circular reference is not detected and/or correctly handled.

If I ignore references:

var json = JsonSerializer.Serialize(r, new JsonSerializerOptions(JsonSerializerDefaults.Web) { ReferenceHandler = ReferenceHandler.IgnoreCycles });

the exception becomes:

System.Text.Json.JsonException: A possible object cycle was detected. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 64. Consider using ReferenceHandler.Preserve on JsonSerializerOptions to support cycles. Path: $.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.Job.JobTurns.Turn.TurnJobs.TurnID.


问:
How to get mod_auth_openidc_session id using python?
I am a complete beginner for requests library and web scraping. When I want to scrape a website, it scraped data as expected. But, it is not scraping data when session id ends. I used chrome cookies to scrape the data from that website.

What I need is, if it is possible to get the mod_auth_openidc_session id, I can use it whenever a session ends. If it is possible, please give me the python code to get it.

Please let me know if any further clarification needed. Thanks in advance.

I need the python code to get the mod_auth_openidc_session of a website.


问:
Return true or false based on a mysql query
So bare with me, I'm trying to create a function that checks if a user exists in a mysql database, and if it exists it would return true, else return false. However, I've run into a problem due to the fact that I'm using ANOTHER function to get the result of the mysql query to which the return is using that function instead of the main function that I need. So heres a snippet of the function that I am currently using.

```<code>let connection = mysql.createConnection(db_config);
connection.connect()
let query = connection.query('SELECT * FROM users WHERE usid = "' + token + '"', function (err, result, fields) {
 if (Object.keys(result).length != 0){
    return true
     } else {
          return false;
     }
})
connection.end();

}
</code>```

So is there some way that I could get the return value from that inner function and then return that same value to where I am originally calling the function or would I need to completely rewrite how I am currently doing this?

The way I am calling it is just putting it as a variable and determining the values and what to do with each of them.

let usercheck = checkClient(userid);

Body:
So bare with me, I'm trying to create a function that checks if a user exists in a mysql database, and if it exists it would return true, else return false. However, I've run into a problem due to the fact that I'm using ANOTHER function to get the result of the mysql query to which the return is using that function instead of the main function that I need. So heres a snippet of the function that I am currently using.

let connection = mysql.createConnection(db_config);
connection.connect()
let query = connection.query('SELECT * FROM users WHERE usid = "' + token + '"', function (err, result, fields) {
 if (Object.keys(result).length != 0){
    return true
     } else {
          return false;
     }
})
connection.end();

}

So is there some way that I could get the return value from that inner function and then return that same value to where I am originally calling the function or would I need to completely rewrite how I am currently doing this?

The way I am calling it is just putting it as a variable and determining the values and what to do with each of them.

let usercheck = checkClient(userid);


问:
How to do a django multi-multi-selection form field
I have a django form where in a choice field the users can not only select more values but also select more combinations of values , for example:

option1

option 2 and option 3

option 2 and option 4

here we have three combinations, the first one of one value (option1), the others of two values.
How can I do that?

Maybe I can use a M2M field with a through table where to associate at each option the combinations in which appear like this:

```<code>option1: combination 1
option2: combination 2 and combination 3
option3: combination 2
option4: combination 3
</code>```

I'm not sure the through table can have an undetermined number of combinations. Maybe there's a better way.

Also any help on how to actually realize it will be appreciated because the widget allows only one combination.

Body:
I have a django form where in a choice field the users can not only select more values but also select more combinations of values , for example:

option1

option 2 and option 3

option 2 and option 4

here we have three combinations, the first one of one value (option1), the others of two values.
How can I do that?

Maybe I can use a M2M field with a through table where to associate at each option the combinations in which appear like this:

option1: combination 1
option2: combination 2 and combination 3
option3: combination 2
option4: combination 3

I'm not sure the through table can have an undetermined number of combinations. Maybe there's a better way.

Also any help on how to actually realize it will be appreciated because the widget allows only one combination.


问:
How to pass a list as parameter in soap requests in python?
I am new in python, i want to pass a list as parameters in soap request using for loop , but there are two lists that i need to pass on. one list is passing rightly but if i want to try to pass both list for different variables then it cannot return desired output.

```<code>id = sql_query_fetch_data(q_id)
approve_id = sql_query_fetch_data(q_approve_id)
id_fetch = ('\n'.join(''.join(elems) for elems in id)).split('\n')
for t in id_fetch:
    print('id_fetch : ', t)

approve_id_fetch = ('\n'.join(''.join(elems) for elems in approve_id)).split('\n')
for q in id_fetch:
    print('approve_id_fetch : ', q)

# This code returns :
id_fetch :  9150048917_50
id_fetch :  2144152002_92
and
approve_id_fetch :  10048917
approve_id_fetch :  24152002

</code>```

I am sending approve_id list and id list in soap request xml

```<code>

 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                    xmlns:per="http://*************************************/">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <per:setOperationStatus>
                         <Id>{t}</Id>
                         <operationResult>
                            <result>
                               <decission>YES</decission>
                               <approveId>{q}</approve_Id>
                            </result>
                         </operationResult>
                      </per:setOperationStatus>
                   </soapenv:Body>
                </soapenv:Envelope>"""

</code>```

How to pass both list t & q in this request, i tried to pass this form inside for loop in approve_id(q) and id(t).please help me.

Body:
I am new in python, i want to pass a list as parameters in soap request using for loop , but there are two lists that i need to pass on. one list is passing rightly but if i want to try to pass both list for different variables then it cannot return desired output.

id = sql_query_fetch_data(q_id)
approve_id = sql_query_fetch_data(q_approve_id)
id_fetch = ('\n'.join(''.join(elems) for elems in id)).split('\n')
for t in id_fetch:
    print('id_fetch : ', t)

approve_id_fetch = ('\n'.join(''.join(elems) for elems in approve_id)).split('\n')
for q in id_fetch:
    print('approve_id_fetch : ', q)

# This code returns :
id_fetch :  9150048917_50
id_fetch :  2144152002_92
and
approve_id_fetch :  10048917
approve_id_fetch :  24152002

I am sending approve_id list and id list in soap request xml

 <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                    xmlns:per="http://*************************************/">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <per:setOperationStatus>
                         <Id>{t}</Id>
                         <operationResult>
                            <result>
                               <decission>YES</decission>
                               <approveId>{q}</approve_Id>
                            </result>
                         </operationResult>
                      </per:setOperationStatus>
                   </soapenv:Body>
                </soapenv:Envelope>"""

How to pass both list t & q in this request, i tried to pass this form inside for loop in approve_id(q) and id(t).please help me.