问:
SQL: Advantages of an ENUM vs. a one-to-many relationship?
I very rarely see ENUM datatypes used in the wild; a developer almost always just uses a secondary table that looks like this:

```<code>CREATE TABLE officer_ranks (
id int PRIMARY KEY
,title varchar NOT NULL UNIQUE);
INSERT INTO officer_ranks VALUES (1,'2LT'),(2,'1LT'),(3,'CPT'),(4,'MAJ'),(5,'LTC'),(6,'COL'),(7,'BG'),(8,'MG'),(9,'LTG'),(10,'GEN');

CREATE TABLE officers (
solider_name varchar NOT NULL
,rank int NOT NULL REFERENCES officer_ranks(id) ON DELETE RESTRICT
,serial_num varchar PRIMARY KEY);
</code>```

But the same thing can also be shown using a user-defined type / ENUM:

```<code>CREATE TYPE officer_rank AS ENUM ('2LT', '1LT','CPT','MAJ','LTC','COL','BG','MG','LTG','GEN');

CREATE TABLE officers (
solider_name varchar NOT NULL
,rank officer_rank NOT NULL
,serial_num varchar PRIMARY KEY);
</code>```

(Example shown using PostgreSQL, but other RDBMS's have similar syntax)

The biggest disadvantage I see to using an ENUM is that it's more difficult to update from within an application.  And it might also confuse an inexperienced developer who's used to using a SQL DB simply as a bit bucket.

Assuming that the information is mostly static (weekday names, month names, US Army ranks, etc) is there any advantage to using a ENUM?

答: Another benefit of enums over a lookup table is that when you write SQL functions you get type checking.</p>

Body:
I very rarely see ENUM datatypes used in the wild; a developer almost always just uses a secondary table that looks like this:

CREATE TABLE officer_ranks (
id int PRIMARY KEY
,title varchar NOT NULL UNIQUE);
INSERT INTO officer_ranks VALUES (1,'2LT'),(2,'1LT'),(3,'CPT'),(4,'MAJ'),(5,'LTC'),(6,'COL'),(7,'BG'),(8,'MG'),(9,'LTG'),(10,'GEN');

CREATE TABLE officers (
solider_name varchar NOT NULL
,rank int NOT NULL REFERENCES officer_ranks(id) ON DELETE RESTRICT
,serial_num varchar PRIMARY KEY);

But the same thing can also be shown using a user-defined type / ENUM:

CREATE TYPE officer_rank AS ENUM ('2LT', '1LT','CPT','MAJ','LTC','COL','BG','MG','LTG','GEN');

CREATE TABLE officers (
solider_name varchar NOT NULL
,rank officer_rank NOT NULL
,serial_num varchar PRIMARY KEY);

(Example shown using PostgreSQL, but other RDBMS's have similar syntax)

The biggest disadvantage I see to using an ENUM is that it's more difficult to update from within an application.  And it might also confuse an inexperienced developer who's used to using a SQL DB simply as a bit bucket.

Assuming that the information is mostly static (weekday names, month names, US Army ranks, etc) is there any advantage to using a ENUM?


来源: stackexchange

问:
How does global variable work in Angular, Ionic
Perhaps this is a dumb question to ask but I am new to front-end development and come from a backend background. Doing things as so in a java class is not threadsafe if the object created is a singleton that is shared across all threads

```<code>class{
  String username;
}
</code>```

In Angular what happens if we have

```<code>export class RegistrationPage implements OnInit {

  firstname: string = "";

}
</code>```

Are components in Angular singletons?

答:
Generally components are not singleton. And if you declare a public variable in a component, it can only be accessed from the files of the same module(for example html file).
But services are singleton. You can access public variables declared in the services globally.

Is that the answer you are looking for?

ContentLicense: CC BY-SA 4.0

Body:
Perhaps this is a dumb question to ask but I am new to front-end development and come from a backend background. Doing things as so in a java class is not threadsafe if the object created is a singleton that is shared across all threads

class{
  String username;
}

In Angular what happens if we have

export class RegistrationPage implements OnInit {

  firstname: string = "";

}

Are components in Angular singletons?


问:
Scrape data from dynamic table using Python & Selenium
I'm trying to scrape data from this URL : https://qmjhldraft.rinknet.com/results.htm?year=2018, but I can't seem to be even able to scrape one single name from the dynamic table.

Here's the code that I currently have :

```<code>from selenium import webdriver
PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
driver.get('https://qmjhldraft.rinknet.com/results.htm?year=2018')
element = driver.find_element_by_xpath('//*[@id="ht-results-table"]/tbody[1]/tr[2]/td[4]').text
print(element)
</code>```

The code gives me this error :

```<code>NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="ht-results-table"]/tbody[1]/tr[2]/td[4]"}
</code>```

There's obviously something wrong with my XPath, but I can't figure out what.

Thanks a lot for the help!

答:
the first problem is as if the website is loading dynamically you need to give some time to load the page fully. to solve it you can use this

```<code>time.sleep(2)
// change the number according to your need.
element = driver.find_element_by_xpath('//*[@id="ht-results-table"]/tbody[1]/tr[2]/td[4]').text
</code>```

the best way is using Explicit Waits. this will wait for the element to load then execute the next step.

2nd problem is you shouldn't just copy the XPath from the chrome dev tools

to get all the names you can do this

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
driver.get('https://qmjhldraft.rinknet.com/results.htm?year=2018')

try:
    elements = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//tr[@rnid]/td[3]"))
    )
finally:
    names = driver.find_elements_by_xpath('//tr[@rnid]/td[3]')

for name in names:
    nm = name.text
    print(nm)

driver.quit()
</code>```

Body:
I'm trying to scrape data from this URL : https://qmjhldraft.rinknet.com/results.htm?year=2018, but I can't seem to be even able to scrape one single name from the dynamic table.

Here's the code that I currently have :

from selenium import webdriver
PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
driver.get('https://qmjhldraft.rinknet.com/results.htm?year=2018')
element = driver.find_element_by_xpath('//*[@id="ht-results-table"]/tbody[1]/tr[2]/td[4]').text
print(element)

The code gives me this error :

NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="ht-results-table"]/tbody[1]/tr[2]/td[4]"}

There's obviously something wrong with my XPath, but I can't figure out what.

Thanks a lot for the help!

Body:
the first problem is as if the website is loading dynamically you need to give some time to load the page fully. to solve it you can use this

time.sleep(2)
// change the number according to your need.
element = driver.find_element_by_xpath('//*[@id="ht-results-table"]/tbody[1]/tr[2]/td[4]').text

the best way is using Explicit Waits. this will wait for the element to load then execute the next step.

2nd problem is you shouldn't just copy the XPath from the chrome dev tools

to get all the names you can do this

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
driver.get('https://qmjhldraft.rinknet.com/results.htm?year=2018')

try:
    elements = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, "//tr[@rnid]/td[3]"))
    )
finally:
    names = driver.find_elements_by_xpath('//tr[@rnid]/td[3]')

for name in names:
    nm = name.text
    print(nm)

driver.quit()


问:
Data label on each entry in xy scatter
I have an x-y scatter plot in MATLAB and want to put a data label on each point.  I can't seem to find this in the documentation.  Is it possible?</p>

答:
Example:

```<code>p = rand(10,2);
scatter(p(:,1), p(:,2), 'filled')
axis([0 1 0 1])

labels = num2str((1:size(p,1))','%d');    %'
text(p(:,1), p(:,2), labels, 'horizontal','left', 'vertical','bottom')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Data label on each entry in xy scatter

Body:
Example:

p = rand(10,2);
scatter(p(:,1), p(:,2), 'filled')
axis([0 1 0 1])

labels = num2str((1:size(p,1))','%d');    %'
text(p(:,1), p(:,2), labels, 'horizontal','left', 'vertical','bottom')


问:
method in class cannot be applied to given types
I'm creating a program that generates 100 random integers between 0 and 9 and displays the count for each number. I'm using an array of ten integers, counts, to store the number of 0s, 1s, ..., 9s.)

When I compile the program I get the error:

RandomNumbers.java:9: error: method generateNumbers in class RandomNumbers cannot be applied to given types;

                generateNumbers();

required: int[]

found:generateNumbers();

reason: actual and formal argument lists differ in length

I get this error for the lines of code that I call the methods generateNumbers() and displayCounts() in the main method.

```<code>    public class RandomNumbers {

       public static void main(String[] args) {

            //declares array for random numbers
        int[] numbers = new int [99];

        //calls the generateNumbers method
        generateNumbers();

        //calls the displayCounts method
        displayCounts();
    }

    //*****************************************************************

    private static int generateNumbers(int[] numbers){

        for(int i = 0; i < 100; i++){
            int randomNumber;
            randomNumber = (int)(Math.random() *10);
            numbers[i] = randomNumber;
        return randomNumber;
        }

    }

    //*****************************************************************

    private static void displayCounts(int[] numbers){
        int[] frequency = new int[10];

        for(int i = 0, size = numbers.length; i < size; i++ ){
            System.out.println((i) + " counts = " + frequency[i]);
        }

    }//end of displayCounts

    }//end of class
</code>```

答: If you get this error with Dagger Android dependency injection, first just try and clean and rebuild project. If that doesn't work, maybe delete the project .gradle cache. Sometimes Dagger just fails to generate the needed factory classes on changes.</p>

Body:
I'm creating a program that generates 100 random integers between 0 and 9 and displays the count for each number. I'm using an array of ten integers, counts, to store the number of 0s, 1s, ..., 9s.)

When I compile the program I get the error:

RandomNumbers.java:9: error: method generateNumbers in class RandomNumbers cannot be applied to given types;

                generateNumbers();

required: int[]

found:generateNumbers();

reason: actual and formal argument lists differ in length

I get this error for the lines of code that I call the methods generateNumbers() and displayCounts() in the main method.

    public class RandomNumbers {

       public static void main(String[] args) {

            //declares array for random numbers
        int[] numbers = new int [99];

        //calls the generateNumbers method
        generateNumbers();

        //calls the displayCounts method
        displayCounts();
    }

    //*****************************************************************

    private static int generateNumbers(int[] numbers){

        for(int i = 0; i < 100; i++){
            int randomNumber;
            randomNumber = (int)(Math.random() *10);
            numbers[i] = randomNumber;
        return randomNumber;
        }

    }

    //*****************************************************************

    private static void displayCounts(int[] numbers){
        int[] frequency = new int[10];

        for(int i = 0, size = numbers.length; i < size; i++ ){
            System.out.println((i) + " counts = " + frequency[i]);
        }

    }//end of displayCounts

    }//end of class


问:
How to set MVC binding correctly
There is a controller:

```<code>[Route("Socket")]
public class SocketController : Controller
{
    [Route("New")]
    public ActionResult NewSocketForm()
    {
        ViewBag.ChargeTypes = new List<SelectListItem>()
        {
            new SelectListItem("bla", "0"),
            new SelectListItem("bla2", "1")
        };
        var model = new Model();
        return View(model);
    }
}
</code>```

There is a View:

```<code>@model blabla.Model

<div class="soket-item">
    <div class="form-group">
        <label asp-for="ChargeType" class="control-label"></label>
        <select asp-for="ChargeType" class="form-control" asp-items="ViewBag.ChargeTypes" />
        <span asp-validation-for="ChargeType" class="text-danger"></span>
    </div>
</div>
</code>```

and there is a Model:

```<code>public class Model
{
    [Required]
    [Range(0, 5)]
    [Display(Name = "Charge Type")]
    public int ChargeType { get; set; }
}
</code>```

I have 2 problems :

asp-items does not load the list from the ViewBag

label does not load Display Name from Model
Why?

答:
First time in model define a property for asp-items:

```<code>  public class Model
    {
        public List<SelectListItem> ListChargeType{ get; set; }
    }
</code>```

then fill this property in controller:

```<code> [Route("New")]
    public ActionResult NewSocketForm()
    {

        var model = new Model();
        List<SelectListItem> lstChargeTypes= new  List<SelectListItem>();
        lstChargeTypes.Add( new SelectListItem {Value= "0", Text = "bla" });
        lstChargeTypes.Add( new SelectListItem {Value= "1", Text = "bla2" });

        var model = new Model();
        model.ListChargeType= lstChargeTypes;
        return View(model);
    }
</code>```

then in view :

```<code>@model blabla.Model

<div class="soket-item">
    <div class="form-group">
        <label asp-for="ChargeType" class="control-label">@ChargeType</label>
        <select asp-for="ChargeType" class="form-control" asp-items="ListChargeType" />
        <span asp-validation-for="ChargeType" class="text-danger"></span>
    </div>
</div>
</code>```

Title: How to set MVC binding correctly

Body:
There is a controller:

[Route("Socket")]
public class SocketController : Controller
{
    [Route("New")]
    public ActionResult NewSocketForm()
    {
        ViewBag.ChargeTypes = new List<SelectListItem>()
        {
            new SelectListItem("bla", "0"),
            new SelectListItem("bla2", "1")
        };
        var model = new Model();
        return View(model);
    }
}

There is a View:

@model blabla.Model

        <select asp-for="ChargeType" class="form-control" asp-items="ViewBag.ChargeTypes" />

and there is a Model:

public class Model
{
    [Required]
    [Range(0, 5)]
    [Display(Name = "Charge Type")]
    public int ChargeType { get; set; }
}

I have 2 problems :

asp-items does not load the list from the ViewBag

label does not load Display Name from Model
Why?

Body:
First time in model define a property for asp-items:

  public class Model
    {
        public List<SelectListItem> ListChargeType{ get; set; }
    }

then fill this property in controller:

 [Route("New")]
    public ActionResult NewSocketForm()
    {

        var model = new Model();
        List<SelectListItem> lstChargeTypes= new  List<SelectListItem>();
        lstChargeTypes.Add( new SelectListItem {Value= "0", Text = "bla" });
        lstChargeTypes.Add( new SelectListItem {Value= "1", Text = "bla2" });

        var model = new Model();
        model.ListChargeType= lstChargeTypes;
        return View(model);
    }

then in view :

@model blabla.Model

<div class="soket-item">
    <div class="form-group">
        <label asp-for="ChargeType" class="control-label">@ChargeType</label>
        <select asp-for="ChargeType" class="form-control" asp-items="ListChargeType" />
        <span asp-validation-for="ChargeType" class="text-danger"></span>
    </div>
</div>


问:
MS Access: How to query a second table when value is not found in the first
I have a simple query to find values in a related table. In some cases, the value is null.  In this case, I would like to query a second table.  I looked at the NZ function but it won't allow for another query operation.  I assume I am looking at a nested query or an operation like SQL COALASCE.

I want to first search tbl_bi_item_mstr

```<code>SELECT tbl_cust_fcst_demd.cust_item_nr, tbl_bi_item_mstr.bi_item_nr
FROM tbl_cust_fcst_demd LEFT JOIN tbl_bi_item_mstr ON tbl_cust_fcst_demd.cust_item_nr = tbl_bi_item_mstr.bi_item_nr;
</code>```

For the null values, I would want to find them in tbl_cust_xref

```<code>SELECT tbl_cust_fcst_demd.cust_item_nr, tbl_cust_xref.bi_item_nr
FROM tbl_cust_fcst_demd INNER JOIN tbl_cust_xref ON tbl_cust_fcst_demd.cust_item_nr = tbl_cust_xref.cust_item_nr;
</code>```

答:
The conditional query might be tricky, you could do it in a macro or vba etc, but that would need to be done outside the sql statement.  If you wish to keep it simple, I'd suggest unioning 2 tables with a differentiating column.

Example code for the union below:

```<code>SELECT
tbl_cust_fcst_demd.cust_item_nr
, tbl_bi_item_mstr.bi_item_nr
, 1 as "src_priority"
FROM tbl_cust_fcst_demd LEFT JOIN tbl_bi_item_mstr ON tbl_cust_fcst_demd.cust_item_nr = tbl_bi_item_mstr.bi_item_nr

Union

SELECT tbl_cust_fcst_demd.cust_item_nr
, tbl_cust_xref.bi_item_nr
, 2 as "src_priority"
FROM tbl_cust_fcst_demd INNER JOIN tbl_cust_xref ON tbl_cust_fcst_demd.cust_item_nr

Order by src_priority

</code>```

You may still work on the consumption requirement, I'd recommend keeping the union as a query/view and create another select for the  consumption query (subject to your requirements and performance), where you can aggregate or partition etc.

Body:
I have a simple query to find values in a related table. In some cases, the value is null.  In this case, I would like to query a second table.  I looked at the NZ function but it won't allow for another query operation.  I assume I am looking at a nested query or an operation like SQL COALASCE.

I want to first search tbl_bi_item_mstr

SELECT tbl_cust_fcst_demd.cust_item_nr, tbl_bi_item_mstr.bi_item_nr
FROM tbl_cust_fcst_demd LEFT JOIN tbl_bi_item_mstr ON tbl_cust_fcst_demd.cust_item_nr = tbl_bi_item_mstr.bi_item_nr;

For the null values, I would want to find them in tbl_cust_xref

SELECT tbl_cust_fcst_demd.cust_item_nr, tbl_cust_xref.bi_item_nr
FROM tbl_cust_fcst_demd INNER JOIN tbl_cust_xref ON tbl_cust_fcst_demd.cust_item_nr = tbl_cust_xref.cust_item_nr;

Body:
The conditional query might be tricky, you could do it in a macro or vba etc, but that would need to be done outside the sql statement.  If you wish to keep it simple, I'd suggest unioning 2 tables with a differentiating column.

Example code for the union below:

SELECT
tbl_cust_fcst_demd.cust_item_nr
, tbl_bi_item_mstr.bi_item_nr
, 1 as "src_priority"
FROM tbl_cust_fcst_demd LEFT JOIN tbl_bi_item_mstr ON tbl_cust_fcst_demd.cust_item_nr = tbl_bi_item_mstr.bi_item_nr

Union

SELECT tbl_cust_fcst_demd.cust_item_nr
, tbl_cust_xref.bi_item_nr
, 2 as "src_priority"
FROM tbl_cust_fcst_demd INNER JOIN tbl_cust_xref ON tbl_cust_fcst_demd.cust_item_nr

Order by src_priority

You may still work on the consumption requirement, I'd recommend keeping the union as a query/view and create another select for the  consumption query (subject to your requirements and performance), where you can aggregate or partition etc.


问:
How do I find the previous URL for login using pure JavaScript? document.referrer is not working for me
I am using express with pug templates and pure JavaScript,for the log in system I want to save the URL someone came to the login page with so I can move them back to it after they finish to log in, however I can't find it.

I tried using document.referrer and put it inside an hidden input to store it inside the pug template,it responded with an error message saying document is not defined, type error, when I rendered the login page.do I need to define something or download some module for me to use document properties? if I simply cant do it that way how can I do it?

here is my get route handler in the my router:

```<code>router.get('/login', function(req,res,next) {
  res.render('login', {backUrl: document.referrer});
});
</code>```

Thanks!

答:
You can get the referrer in Express.js:

```<code>req.get('Referrer')
</code>```

If you want to redirect after login, you can add query string to your login URL and you can redirect the page after login.

You can add the current page at the end of the URL.

Let's say user browsing "/view-documents" page. After user click login button add the current path to login URL like this:

/login?redirect=/view-documents

and you can redirect like this:

```<code>router.get('/login', function(req,res,next) {
  res.redirect(req.query.redirect);
});
</code>```

Query strings tutorial

Body:
I am using express with pug templates and pure JavaScript,for the log in system I want to save the URL someone came to the login page with so I can move them back to it after they finish to log in, however I can't find it.

I tried using document.referrer and put it inside an hidden input to store it inside the pug template,it responded with an error message saying document is not defined, type error, when I rendered the login page.do I need to define something or download some module for me to use document properties? if I simply cant do it that way how can I do it?

here is my get route handler in the my router:

router.get('/login', function(req,res,next) {
  res.render('login', {backUrl: document.referrer});
});

Thanks!

Body:
You can get the referrer in Express.js:

req.get('Referrer')

If you want to redirect after login, you can add query string to your login URL and you can redirect the page after login.

You can add the current page at the end of the URL.

Let's say user browsing "/view-documents" page. After user click login button add the current path to login URL like this:

/login?redirect=/view-documents

and you can redirect like this:

router.get('/login', function(req,res,next) {
  res.redirect(req.query.redirect);
});

Query strings tutorial


问:
Flutter background service in custome time fireing function
I should implement feature which should fires function in every 10 seconds in the the background and I had tried out work manager but it minimal time is 15 min but I want 10 seconds and I cant find any packages or good example for it ,</p>

答: you can use background_fetch, it a good lib for this propose.</p>


问:
nginx error when server responds too soon (I think)
Using ingress-nginx in a kubernetes cluster in front of a Node.js server running express.

Getting this error:
upstream prematurely closed connection while reading response header from upstream

In this scenario:

The server is processing a small-ish file (60kb) upload, as a node stream (i.e. in express terms it's pipelineing the req (Request) that's passed in as the first argument of the route handler).

While processing the file, an error is thrown near the beginning (maybe 4-5k in), and a 400 response is sent on the spot.

The nginx ingress proxy gives a 502 to the client and the logs show the error above.

The reason I believe the error may be due to the server sending back a response before the entire request is read:

When I cut down the input file to end right after the place that causes the error, the nginx error goes away and the client gets the 400 from the server as I'd expect.

The same error-handling code works fine in other cases in which the request is fully read i.e. when using req.body and not streaming the request body.

When the file is corrected and doesn't throw errors, everything is great and 200 is returned, so it's not a timeout (like a lot of the results when searching for this nginx error) or something along those lines.

I'd like to find a way to fix the error without ugly workarounds in the code, but I'm open to anything. My thoughts were some ingress-nginx annotation that makes it handle the "premature response end" properly, or a way on the node side to consume the stream (even though I don't really want to and don't feel I should have to) before sending back the error, to make nginx happy. Or open to other ideas.

答:
As I waited hopefully for an answer here, the days passed and my hope grew dim. I spent a while playing with it some more and came up with an "ugly workaround in the code" as I mentioned in my question.

In case this might help someone in the future:

I wrapped the input stream by reading it into a buffer/string and then re-streaming it, and this fixed the problem. This will obviously only be a solution if you can afford to read the entire input into memory - I could so it's all good, but if you can't, I don't know what you can do to avoid this error.

```<code>async (input) => {
    const chunks = [];
    await new Promise((resolve, reject) => {
        input.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
        input.on('error', (err) => reject(err));
        input.on('end', () => resolve());
    });
    return Readable.from([Buffer.concat(chunks).toString('utf-8')]);
}
</code>```

Body:
As I waited hopefully for an answer here, the days passed and my hope grew dim. I spent a while playing with it some more and came up with an "ugly workaround in the code" as I mentioned in my question.

In case this might help someone in the future:

I wrapped the input stream by reading it into a buffer/string and then re-streaming it, and this fixed the problem. This will obviously only be a solution if you can afford to read the entire input into memory - I could so it's all good, but if you can't, I don't know what you can do to avoid this error.

async (input) => {
    const chunks = [];
    await new Promise((resolve, reject) => {
        input.on('data', (chunk) => chunks.push(Buffer.from(chunk)));
        input.on('error', (err) => reject(err));
        input.on('end', () => resolve());
    });
    return Readable.from([Buffer.concat(chunks).toString('utf-8')]);
}


问:
How do you handle ajax requests when user is not authenticated?
How do you handle ajax requests when user is not authenticated?

Someone enters the page, leaves room for an hour, returns, adds comment on the page that goes throuh ajax using jQuery ($.post). Since he is not authenticated, method return RedirectToRoute result (redirects to login page). What do you do with it? How do you handle it on client side and how do you handle it in controller?

答:
Here's a solution I use. It is dead simple, if a bit brute-force. I like it because I'm lazy and I don't want to think about special attributes on action methods and I don't want to write  ajax error handlers if I don't have to (although there's no reason client script couldn't detect the 403 status code and do something user friendly).

Putting this in Global.axax detects any unauthenticated ajax request and simply returns 403, with no content. This prevents unauthenticated ajax calls getting redirected to the login form when forms authentication is in use.

```<code> protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        // Prevent Ajax requests from being returned the login form when not authenticated
        // (eg. after authentication timeout).
        if ((Request.Headers["X-Requested-With"] != null && Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            ||
            (Request["X-Requested-With"] != null && Request["X-Requested-With"] == "XMLHttpRequest"))
        {
            if (!Request.IsAuthenticated)
            {
                Response.Clear();
                Response.StatusCode = 403;
                Response.Flush();
                Response.End();
            }
        }
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Here's a solution I use. It is dead simple, if a bit brute-force. I like it because I'm lazy and I don't want to think about special attributes on action methods and I don't want to write  ajax error handlers if I don't have to (although there's no reason client script couldn't detect the 403 status code and do something user friendly).

Putting this in Global.axax detects any unauthenticated ajax request and simply returns 403, with no content. This prevents unauthenticated ajax calls getting redirected to the login form when forms authentication is in use.

 protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        // Prevent Ajax requests from being returned the login form when not authenticated
        // (eg. after authentication timeout).
        if ((Request.Headers["X-Requested-With"] != null && Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            ||
            (Request["X-Requested-With"] != null && Request["X-Requested-With"] == "XMLHttpRequest"))
        {
            if (!Request.IsAuthenticated)
            {
                Response.Clear();
                Response.StatusCode = 403;
                Response.Flush();
                Response.End();
            }
        }
    }


问:
How to append np.array?
I have an np.array d1 of (3,6), and an np.array a4 of (6,).

How can I combine the two np.arrays to form an np.array d2 of (4,6)?

My code is as follows:

```<code>import numpy as np
a1=np.array(range(6))
a2=a1+2
a3=a2+3
a4=a3+4
d1=np.array([a1,a2,a3])
d1.shape
</code>```
```<code>Out[44]: (3, 6)
</code>```
```<code>d2=np.array([a1,a2,a3,a4])
d2.shape
d2
</code>```
```<code>Out[45]: (4, 6)
Out[46]:
array([[ 0,  1,  2,  3,  4,  5],
       [ 2,  3,  4,  5,  6,  7],
       [ 5,  6,  7,  8,  9, 10],
       [ 9, 10, 11, 12, 13, 14]])
</code>```

How to get d2 from d1 and a4?

I tried np.insert and np.append, but maybe my usage is wrong and I didn't get the correct result.

答:
I believe https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html concatenate is the command you are looking for.</p>
```<code>foo = np.array([[1,2,3],
                [4,5,6]])
bar = np.array([7,8,9])

# axis 0 will combine rows, axis 1 will combine columns
foobar = numpy.concatenate(foo,bar,axis = 0)

array([[1,2,3],
       [4,5,6],
       [7,8,9]])
</code>```

Title: How to append np.array?

Body:
I have an np.array d1 of (3,6), and an np.array a4 of (6,).

How can I combine the two np.arrays to form an np.array d2 of (4,6)?

My code is as follows:

import numpy as np
a1=np.array(range(6))
a2=a1+2
a3=a2+3
a4=a3+4
d1=np.array([a1,a2,a3])
d1.shape

Out[44]: (3, 6)

d2=np.array([a1,a2,a3,a4])
d2.shape
d2

Out[45]: (4, 6)
Out[46]:
array([[ 0,  1,  2,  3,  4,  5],
       [ 2,  3,  4,  5,  6,  7],
       [ 5,  6,  7,  8,  9, 10],
       [ 9, 10, 11, 12, 13, 14]])

How to get d2 from d1 and a4?

I tried np.insert and np.append, but maybe my usage is wrong and I didn't get the correct result.

Body:
I believe https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html concatenate is the command you are looking for.

foo = np.array([[1,2,3],
                [4,5,6]])
bar = np.array([7,8,9])

# axis 0 will combine rows, axis 1 will combine columns
foobar = numpy.concatenate(foo,bar,axis = 0)

array([[1,2,3],
       [4,5,6],
       [7,8,9]])


问:
Listening of bloc getting called multiple times
I have this code for listening to bloc on my screen.

```<code>late MyBloc myBloc;

@override
  void initState() {
    print('inside init state');
    super.initState();
    myBloc = BlocProvider.of<MyBloc>(context);
    myBloc.stream.listen((state) {
      if (state is MyAddCompletedState) {
        print('listening to bloc');
      }
    }
}
</code>```

If I add an event, it will print listening to bloc once. If I go to another screen and return to this same screen, it will print listening to bloc twice. It seems like the first listen I did was still active. Next, I tried to close the bloc on my dispose thinking that it would stop the first listen. So that when I come back to the screen it will have a fresh listen but it will have an error: Bad state: Cannot add new events after calling close. I tried to research about this and some mention to dispose the bloc but it doesn't have that syntax anymore. Please help on how to properly close or stop it from listening once I have change screen. Thanks!

```<code>//this is found on my screen
late MyBloc myBloc;

@override
  void initState() {
    print('inside init state');
    super.initState();
    myBloc = BlocProvider.of<MyBloc>(context);
    myBloc.stream.listen((state) {
      if (state is MyAddCompletedState) {
        print('listening to bloc');
      }
    }
}

  @override
  void dispose() {
    myBloc.close();
    // myBloc.dispose(); --> I saw some tutorial to use this but it doesn't work
    super.dispose();
  }
</code>```

This is on my main.dart:

```<code>    return FutureBuilder(
        future: InitFirst.instance.initialize(),
        builder: (context, AsyncSnapshot snapshot) {
          return MultiBlocProvider(
            providers: [
              BlocProvider<MyBloc>(
                create: (context) => MyBloc(
                  authenticationRepository: authenticationRepository,
                  userDataRepository: userDataRepository,
                ),
              ),
            ...
</code>```

This is the part where I trigger the event. After this event run, the stream.listen will get triggered. But it will be triggered multiple times every time I visit the my screen.

```<code>    myBloc.add(MyAddEvent(
        selectedName,
        selectedCount);
</code>```

Additional note: this event is triggering an update in Firebase which I need to check if it got completed that is why I do the stream.listen.

答:
There are several ways to solve this issue depending on the context. I try to avoid using BLoC instantiation with StatefulWidgets. And, I like to use Cubits in connection with Observers, depending on the event entering my stream. I have added most of them in the following code, which isn't all used but for you to look at as a reference. My code example eliminates the issues that you describe. I would be happy to help further if you could provide a minimum viable code.

The following code is an example that I have put together to demonstrate a possible strategy. The BLoC package website heavily inspires the code. It has the standard counter app that we are all familiar with and navigation functionality.

Please see the following code to see if it helps at all:

Please be sure to add
flutter_bloc: ^8.0.1 to your pubspec.yaml file.

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

void main() {
  BlocOverrides.runZoned(
    () => runApp(const MaterialApp(home: CounterPage())),
    blocObserver: CounterObserver(),
  );
}

class CounterObserver extends BlocObserver {
  @override
  void onChange(BlocBase bloc, Change change) {
    super.onChange(bloc, change);
    print('${bloc.runtimeType} $change');
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    print('onTransition -- bloc: ${bloc.runtimeType}, transition: $transition');
  }

  @override
  void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
    print('onError -- bloc: ${bloc.runtimeType}, error: $error');
    super.onError(bloc, error, stackTrace);
  }

  @override
  void onClose(BlocBase bloc) {
    super.onClose(bloc);
    print('onClose -- bloc: ${bloc.runtimeType}');
  }
}

class CounterCubit extends Cubit<int> {
  CounterCubit() : super(0);
  void increment() => emit(state + 1);
  void decrement() => emit(state - 1);
}

class ScoreCubit extends Cubit<int> {
  ScoreCubit() : super(0);
  void increment() => emit(state + 1);
  void decrement() => emit(state - 1);
}

class CounterPage extends StatelessWidget {
  const CounterPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider<CounterCubit>(create: (context) => CounterCubit()),
        BlocProvider<ScoreCubit>(create: (context) => ScoreCubit()),
      ],
      child: const CounterView(),
    );
  }
}

class CounterView extends StatelessWidget {
  const CounterView({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Counter')),
      body: Column(
        children: [
          Center(
            child: BlocBuilder<ScoreCubit, int>(
              builder: (context, score) => Text('Score: $score'),
            ),
          ),
          Center(
            child: BlocBuilder<CounterCubit, int>(
              builder: (context, state) {
                return Text('$state',
                    style: Theme.of(context).textTheme.headline2);
              },
            ),
          ),
        ],
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          FloatingActionButton(
              heroTag: 'FAB1',
              child: const Icon(Icons.add),
              onPressed: () {
                // format from
                context.read<CounterCubit>().increment();
                context.read<ScoreCubit>().increment();
              }),
          const SizedBox(height: 8),
          FloatingActionButton(
            heroTag: 'FAB2',
            child: const Icon(Icons.remove),
            onPressed: () {
              context.read<CounterCubit>().decrement();
            },
          ),
          const SizedBox(height: 8),
          FloatingActionButton(
            heroTag: 'FAB3',
            child: const Icon(Icons.arrow_forward),
            onPressed: () {
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (context) => Scaffold(
                    appBar: AppBar(title: const Text('Next Page')),
                    body: const Center(
                      child: Text('This is the next page'),
                    ),
                  ),
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}
</code>```

Like all things in Flutter, this, of course, is only one strategy of many.

Body:
I have this code for listening to bloc on my screen.

late MyBloc myBloc;

@override
  void initState() {
    print('inside init state');
    super.initState();
    myBloc = BlocProvider.of<MyBloc>(context);
    myBloc.stream.listen((state) {
      if (state is MyAddCompletedState) {
        print('listening to bloc');
      }
    }
}

If I add an event, it will print listening to bloc once. If I go to another screen and return to this same screen, it will print listening to bloc twice. It seems like the first listen I did was still active. Next, I tried to close the bloc on my dispose thinking that it would stop the first listen. So that when I come back to the screen it will have a fresh listen but it will have an error: Bad state: Cannot add new events after calling close. I tried to research about this and some mention to dispose the bloc but it doesn't have that syntax anymore. Please help on how to properly close or stop it from listening once I have change screen. Thanks!

//this is found on my screen
late MyBloc myBloc;

@override
  void initState() {
    print('inside init state');
    super.initState();
    myBloc = BlocProvider.of<MyBloc>(context);
    myBloc.stream.listen((state) {
      if (state is MyAddCompletedState) {
        print('listening to bloc');
      }
    }
}

  @override
  void dispose() {
    myBloc.close();
    // myBloc.dispose(); --> I saw some tutorial to use this but it doesn't work
    super.dispose();
  }

This is on my main.dart:

    return FutureBuilder(
        future: InitFirst.instance.initialize(),
        builder: (context, AsyncSnapshot snapshot) {
          return MultiBlocProvider(
            providers: [
              BlocProvider<MyBloc>(
                create: (context) => MyBloc(
                  authenticationRepository: authenticationRepository,
                  userDataRepository: userDataRepository,
                ),
              ),
            ...

This is the part where I trigger the event. After this event run, the stream.listen will get triggered. But it will be triggered multiple times every time I visit the my screen.

    myBloc.add(MyAddEvent(
        selectedName,
        selectedCount);

Additional note: this event is triggering an update in Firebase which I need to check if it got completed that is why I do the stream.listen.

Body:
There are several ways to solve this issue depending on the context. I try to avoid using BLoC instantiation with StatefulWidgets. And, I like to use Cubits in connection with Observers, depending on the event entering my stream. I have added most of them in the following code, which isn't all used but for you to look at as a reference. My code example eliminates the issues that you describe. I would be happy to help further if you could provide a minimum viable code.

The following code is an example that I have put together to demonstrate a possible strategy. The BLoC package website heavily inspires the code. It has the standard counter app that we are all familiar with and navigation functionality.

Please see the following code to see if it helps at all:

Please be sure to add
flutter_bloc: ^8.0.1 to your pubspec.yaml file.

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

void main() {
  BlocOverrides.runZoned(
    () => runApp(const MaterialApp(home: CounterPage())),
    blocObserver: CounterObserver(),
  );
}

class CounterObserver extends BlocObserver {
  @override
  void onChange(BlocBase bloc, Change change) {
    super.onChange(bloc, change);
    print('${bloc.runtimeType} $change');
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    super.onTransition(bloc, transition);
    print('onTransition -- bloc: ${bloc.runtimeType}, transition: $transition');
  }

  @override
  void onError(BlocBase bloc, Object error, StackTrace stackTrace) {
    print('onError -- bloc: ${bloc.runtimeType}, error: $error');
    super.onError(bloc, error, stackTrace);
  }

  @override
  void onClose(BlocBase bloc) {
    super.onClose(bloc);
    print('onClose -- bloc: ${bloc.runtimeType}');
  }
}

class CounterCubit extends Cubit<int> {
  CounterCubit() : super(0);
  void increment() => emit(state + 1);
  void decrement() => emit(state - 1);
}

class ScoreCubit extends Cubit<int> {
  ScoreCubit() : super(0);
  void increment() => emit(state + 1);
  void decrement() => emit(state - 1);
}

class CounterPage extends StatelessWidget {
  const CounterPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider<CounterCubit>(create: (context) => CounterCubit()),
        BlocProvider<ScoreCubit>(create: (context) => ScoreCubit()),
      ],
      child: const CounterView(),
    );
  }
}

class CounterView extends StatelessWidget {
  const CounterView({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Counter')),
      body: Column(
        children: [
          Center(
            child: BlocBuilder<ScoreCubit, int>(
              builder: (context, score) => Text('Score: $score'),
            ),
          ),
          Center(
            child: BlocBuilder<CounterCubit, int>(
              builder: (context, state) {
                return Text('$state',
                    style: Theme.of(context).textTheme.headline2);
              },
            ),
          ),
        ],
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          FloatingActionButton(
              heroTag: 'FAB1',
              child: const Icon(Icons.add),
              onPressed: () {
                // format from
                context.read<CounterCubit>().increment();
                context.read<ScoreCubit>().increment();
              }),
          const SizedBox(height: 8),
          FloatingActionButton(
            heroTag: 'FAB2',
            child: const Icon(Icons.remove),
            onPressed: () {
              context.read<CounterCubit>().decrement();
            },
          ),
          const SizedBox(height: 8),
          FloatingActionButton(
            heroTag: 'FAB3',
            child: const Icon(Icons.arrow_forward),
            onPressed: () {
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (context) => Scaffold(
                    appBar: AppBar(title: const Text('Next Page')),
                    body: const Center(
                      child: Text('This is the next page'),
                    ),
                  ),
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}

Like all things in Flutter, this, of course, is only one strategy of many.


问:
How to pass struct array arguments to a function the right way?
Source Code:

```<code>#include <iostream>

using namespace std;

struct Employee {

   string name;
   int age;
   float salary;

};

void displayData(Employee);

int main() {

   Employee employee[3];
   int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);

   for(int i = 0; i < sizeOfEmployee; i++) {
       cout << "Enter name for employee " << i + 1 << ": ";
       cin >> employee->name;
       cout << "Enter age for employee " << i + 1 << ": ";
       cin >> employee->age;
       cout << "Enter salary for employee " << i + 1 << ": ";
       cin >> employee->salary;
}

   for(int i = 0; i < sizeOfEmployee; i++) {
       displayData(employee[i]);
}

}

void displayData(Employee employee) {

   cout << "DISPLAYING INFORMATION" << endl;
   cout << "Name: " << employee.name << endl;
   cout << "Age: " << employee.age << endl;
   cout << "Salary: " << employee.salary << endl;

}
</code>```

My code doesn't display all the data i've stored into the array, it only reads and display the last data i've inputted.

CODE OUTPUT:

In what way could i possibly get all the data i've stored into the array and display it?

答:
```<code>int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);
</code>```

Don't do this. Use std::size(employee) if you want to get the length of the array.

```<code>for(int i = 0; i < sizeOfEmployee; i++) {
</code>```

Don't do this. Instead, use a range-for to loop over all elements of a range:

```<code>for (auto&& e : employee)
</code>```

Which incidentally will fix the bug that you had. The bug is that you always write to the first element of the array. Each iteration over-writes the previous ones and the other elements remain uninitialised.

The range-for will correctly iterate all elements with less chance of messing things up.

Body:
Source Code:

#include <iostream>

using namespace std;

struct Employee {

   string name;
   int age;
   float salary;

};

void displayData(Employee);

int main() {

   Employee employee[3];
   int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);

   for(int i = 0; i < sizeOfEmployee; i++) {
       cout << "Enter name for employee " << i + 1 << ": ";
       cin >> employee->name;
       cout << "Enter age for employee " << i + 1 << ": ";
       cin >> employee->age;
       cout << "Enter salary for employee " << i + 1 << ": ";
       cin >> employee->salary;
}

   for(int i = 0; i < sizeOfEmployee; i++) {
       displayData(employee[i]);
}

}

void displayData(Employee employee) {

   cout << "DISPLAYING INFORMATION" << endl;
   cout << "Name: " << employee.name << endl;
   cout << "Age: " << employee.age << endl;
   cout << "Salary: " << employee.salary << endl;

}

My code doesn't display all the data i've stored into the array, it only reads and display the last data i've inputted.

CODE OUTPUT:

In what way could i possibly get all the data i've stored into the array and display it?

Body:
int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);

Don't do this. Use std::size(employee) if you want to get the length of the array.

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

Don't do this. Instead, use a range-for to loop over all elements of a range:

for (auto&& e : employee)

Which incidentally will fix the bug that you had. The bug is that you always write to the first element of the array. Each iteration over-writes the previous ones and the other elements remain uninitialised.

The range-for will correctly iterate all elements with less chance of messing things up.


问:
How to copy Youtube text by using pyautogui?
```<code>import pyautogui

pyautogui.moveTo(x=100,y=100,duration=10)

keyDown = ('cntrl')

pyautogui.press('c')
</code>```

step 1 :#importing pyautogui module.
step 2:#moving mouse to the youtube text i want to copy
step 3:#pressing control to copy the text
step 4:#pressing c to copy the text.
In simple words I dont want to do my work of copying youtube title to text file,I wanna automate it,cause its work from free intership.

答:
Use pyperclip for the pasting, it's simpler. Also, use the locateOnScreen function, (from here) since it's more reliable than moving the mouse. Here's some pseudocode for you:

```<code>from pyautogui import locateOnScreen, moveTo, hotkey, ImageNotFoundException
from pyperclip import paste
try:
    # Move to top left of bar, then move into bar
    moveTo(locateOnScreen('image_of_search_bar_top_left_only.png'))
    moveRel(7, -7)
    hotkey('ctrl', 'c')
    with open('log.txt', 'a') as fyl:
        fyl.write(str(paste()), '\n')
except ImageNotFoundException:
    print("Unable to find search bar!")
</code>```

Would this work for your purposes?

Body:
import pyautogui

pyautogui.moveTo(x=100,y=100,duration=10)

keyDown = ('cntrl')

pyautogui.press('c')

step 1 :#importing pyautogui module.
step 2:#moving mouse to the youtube text i want to copy
step 3:#pressing control to copy the text
step 4:#pressing c to copy the text.
In simple words I dont want to do my work of copying youtube title to text file,I wanna automate it,cause its work from free intership.

Body:
Use pyperclip for the pasting, it's simpler. Also, use the locateOnScreen function, (from here) since it's more reliable than moving the mouse. Here's some pseudocode for you:

from pyautogui import locateOnScreen, moveTo, hotkey, ImageNotFoundException
from pyperclip import paste
try:
    # Move to top left of bar, then move into bar
    moveTo(locateOnScreen('image_of_search_bar_top_left_only.png'))
    moveRel(7, -7)
    hotkey('ctrl', 'c')
    with open('log.txt', 'a') as fyl:
        fyl.write(str(paste()), '\n')
except ImageNotFoundException:
    print("Unable to find search bar!")

Would this work for your purposes?


问:
TIMEVALUE setting off a script
I'm trying to have TIMEVALUE set off a script. I have column P which is a Timer column that is subtracting a time from NOW to get a time value and then I am converting that to a TIMEVALUE in column O. When that value is either below or above certain values I want column N to then have a value so it would trigger my checkboxes script. But for some reason I can't get the TIMEVALUE to trigger. I tried to put it in another column and have the values CopyAndPasted Values Only into a column with that run on a time trigger of every minute, but apparently that doesn't count as an Edit or it's not reading the DisplayValue.

```<code>function onEdit(e) {
  timeValue(e);
  checkboxes(e);
  rangerTime(e);
}

function rangerTime(e){
  var editRow = e.range.getRow();
  var editColumn = e.range.getColumn();
  if (editColumn === 13 && e.value == "TRUE") {
    const sh = e.range.getSheet();
    sh.getRange(editRow, 25).setValue(sh.getRange(editRow, 25).getValue()+1);
    sh.getRange(editRow, 13).setValue(" ")
  }
}

function timeValue(e) {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getActiveSheet();
  var editRow = e.range.getRow();
  var editColumn = e.range.getColumn();
  if(editRow > 3) {
    var rowRange = sheet.getRange("O" + editRow);
    var kCell = sheet.getRange("K" + editRow);
    var kValue = kCell.getValue();
    var nCell = sheet.getRange("N" + editRow);
    var kHasValue = kValue != "";
    if(editColumn > 10) {
      if(rowRange.getDisplayValue()<0.02 && !kHasValue){
        nCell.setValue(1);
      }
      if (rowRange.getDisplayValue()>0.5 && !kHasValue){
        nCell.setValue(1);
      }
      if(kHasValue) {
        nCell.setValue(" ");
        }
      }
    }
      }

function checkboxes(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ui = SpreadsheetApp.getUi();

  var names = ss.getRange("N4:N");
  var namesValues = names.getValues();
  var checkboxes = ss.getRange("M4:M");
  var cbRows = checkboxes.getHeight();
  var cbValues = checkboxes.getValues();
  var newCBValues = new Array(cbRows);

  for (var row = 0; row < cbRows; row++) {
    newCBValues[row] = new Array(0);
    if (namesValues[row] == "" || namesValues[row] == " ") {
      newCBValues[row][0] = " ";
    }else{
      if (cbValues[row][0] === true) {
        newCBValues[row][0] = true;
      }else{
        newCBValues[row][0] = false;

      }
    }
  }
  checkboxes.setValues(newCBValues);
}
</code>```

This part is run on the every minute Time Trigger:

```<code>function CopyandPaste() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('AA4').activate();
  var currentCell = spreadsheet.getCurrentCell();
  spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate();
  currentCell.activateAsCurrentCell();
  spreadsheet.getRange('O4').activate();
  currentCell = spreadsheet.getCurrentCell();
  spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate();
  currentCell.activateAsCurrentCell();
  spreadsheet.getRange('AA4:AA202').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
};
</code>```

Column AA = TIMEVALUE(Column P)

答:
From the question

I tried to put it in another column and have the values CopyAndPasted Values Only into a column with that run on a time trigger of every minute, but apparently that doesn't count as an Edit or it's not reading the DisplayValue.

You are right, only actions done by a user directly through the Google Sheets user interface will cause the edit trigger to be triggered.

One option is to make that your time-driven trigger besides changing the checkboxes also call the timeValue function but you have to refactor it or to mock the edit event object to pass it as the timeValue parameter.

Reference

https://developers.google.com/apps-script/guides/triggers

Title: TIMEVALUE setting off a script

Body:
I'm trying to have TIMEVALUE set off a script. I have column P which is a Timer column that is subtracting a time from NOW to get a time value and then I am converting that to a TIMEVALUE in column O. When that value is either below or above certain values I want column N to then have a value so it would trigger my checkboxes script. But for some reason I can't get the TIMEVALUE to trigger. I tried to put it in another column and have the values CopyAndPasted Values Only into a column with that run on a time trigger of every minute, but apparently that doesn't count as an Edit or it's not reading the DisplayValue.

function onEdit(e) {
  timeValue(e);
  checkboxes(e);
  rangerTime(e);
}

function rangerTime(e){
  var editRow = e.range.getRow();
  var editColumn = e.range.getColumn();
  if (editColumn === 13 && e.value == "TRUE") {
    const sh = e.range.getSheet();
    sh.getRange(editRow, 25).setValue(sh.getRange(editRow, 25).getValue()+1);
    sh.getRange(editRow, 13).setValue(" ")
  }
}

function timeValue(e) {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getActiveSheet();
  var editRow = e.range.getRow();
  var editColumn = e.range.getColumn();
  if(editRow > 3) {
    var rowRange = sheet.getRange("O" + editRow);
    var kCell = sheet.getRange("K" + editRow);
    var kValue = kCell.getValue();
    var nCell = sheet.getRange("N" + editRow);
    var kHasValue = kValue != "";
    if(editColumn > 10) {
      if(rowRange.getDisplayValue()<0.02 && !kHasValue){
        nCell.setValue(1);
      }
      if (rowRange.getDisplayValue()>0.5 && !kHasValue){
        nCell.setValue(1);
      }
      if(kHasValue) {
        nCell.setValue(" ");
        }
      }
    }
      }

function checkboxes(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ui = SpreadsheetApp.getUi();

  var names = ss.getRange("N4:N");
  var namesValues = names.getValues();
  var checkboxes = ss.getRange("M4:M");
  var cbRows = checkboxes.getHeight();
  var cbValues = checkboxes.getValues();
  var newCBValues = new Array(cbRows);

  for (var row = 0; row < cbRows; row++) {
    newCBValues[row] = new Array(0);
    if (namesValues[row] == "" || namesValues[row] == " ") {
      newCBValues[row][0] = " ";
    }else{
      if (cbValues[row][0] === true) {
        newCBValues[row][0] = true;
      }else{
        newCBValues[row][0] = false;

      }
    }
  }
  checkboxes.setValues(newCBValues);
}

This part is run on the every minute Time Trigger:

function CopyandPaste() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('AA4').activate();
  var currentCell = spreadsheet.getCurrentCell();
  spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate();
  currentCell.activateAsCurrentCell();
  spreadsheet.getRange('O4').activate();
  currentCell = spreadsheet.getCurrentCell();
  spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate();
  currentCell.activateAsCurrentCell();
  spreadsheet.getRange('AA4:AA202').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
};

Column AA = TIMEVALUE(Column P)


问:
Multiple local strategy not working in PassportStrategy
I am working with NestJS framework. I have a LocalStrategy to authenticate users. Now I want another LocalStrategy named MylocalStrategy. For this I add two files: mylocal.strategy.ts and mylocal-auth.guard.ts

Here is my mylocal-auth.guard.ts content:

```<code>import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class MylocalAuthGuard extends AuthGuard('mylocal') {}
</code>```

But when I use @UseGuards(MylocalAuthGuard) I get the error: 'Unknown authentication strategy "mylocal"'.

What could be the problem?

答:
You have to name your strategies and register in provider. For me, it works with following setup

```<code>import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class LocalAuthGuard extends AuthGuard('UsernamePasswordStrategy') {}

@Injectable()
export class OTPAuthGuard extends AuthGuard('OTPStrategy') {}
</code>```

UserName And Password Strategy

```<code>import { Strategy } from 'passport-local';

@Injectable()
export class LocalStrategy extends PassportStrategy(
  Strategy,
  'UsernamePasswordStrategy',
) {
  constructor(
    @Inject(IAuthService)
    private readonly authService: IAuthService,
  ) {
    super({
      usernameField: 'user_name',
      passwordField: 'password',
    });
  }

  async validate(user_name: string, password: string): Promise<any> {
    const loginDto = new LoginDto();
    loginDto.userName = user_name;
    loginDto.password = password;
    const user: UserDto = await this.authService.validateUser(loginDto);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}
</code>```

OTP strategy

```<code>import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { IAuthService } from '../services';
import { OtpLoginDto } from '../dto';
import { UserDto } from 'src/modules/user/dto';
import { plainToClass } from 'class-transformer';

@Injectable()
export class OTPStrategy extends PassportStrategy(Strategy, 'OTPStrategy') {
  constructor(
    @Inject(IAuthService)
    private readonly authService: IAuthService,
  ) {
    super({
      usernameField: 'phone',
      passwordField: 'otp',
    });
  }

  async validate(phone: string, otp: string): Promise<any> {
    const loginDto = plainToClass(OtpLoginDto, {
      phone: phone,
      otp: otp,
    });
    const user: UserDto = await this.authService.verifyOtp(loginDto);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}
</code>```

Body:
I am working with NestJS framework. I have a LocalStrategy to authenticate users. Now I want another LocalStrategy named MylocalStrategy. For this I add two files: mylocal.strategy.ts and mylocal-auth.guard.ts

Here is my mylocal-auth.guard.ts content:

import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class MylocalAuthGuard extends AuthGuard('mylocal') {}

But when I use @UseGuards(MylocalAuthGuard) I get the error: 'Unknown authentication strategy "mylocal"'.

What could be the problem?

Body:
You have to name your strategies and register in provider. For me, it works with following setup

import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class LocalAuthGuard extends AuthGuard('UsernamePasswordStrategy') {}

@Injectable()
export class OTPAuthGuard extends AuthGuard('OTPStrategy') {}

UserName And Password Strategy

import { Strategy } from 'passport-local';

@Injectable()
export class LocalStrategy extends PassportStrategy(
  Strategy,
  'UsernamePasswordStrategy',
) {
  constructor(
    @Inject(IAuthService)
    private readonly authService: IAuthService,
  ) {
    super({
      usernameField: 'user_name',
      passwordField: 'password',
    });
  }

  async validate(user_name: string, password: string): Promise<any> {
    const loginDto = new LoginDto();
    loginDto.userName = user_name;
    loginDto.password = password;
    const user: UserDto = await this.authService.validateUser(loginDto);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}

OTP strategy

import { Strategy } from 'passport-local';
import { PassportStrategy } from '@nestjs/passport';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { IAuthService } from '../services';
import { OtpLoginDto } from '../dto';
import { UserDto } from 'src/modules/user/dto';
import { plainToClass } from 'class-transformer';

@Injectable()
export class OTPStrategy extends PassportStrategy(Strategy, 'OTPStrategy') {
  constructor(
    @Inject(IAuthService)
    private readonly authService: IAuthService,
  ) {
    super({
      usernameField: 'phone',
      passwordField: 'otp',
    });
  }

  async validate(phone: string, otp: string): Promise<any> {
    const loginDto = plainToClass(OtpLoginDto, {
      phone: phone,
      otp: otp,
    });
    const user: UserDto = await this.authService.verifyOtp(loginDto);
    if (!user) {
      throw new UnauthorizedException();
    }
    return user;
  }
}


问:
Not getting data from nodejs server for the first time in React
I'm trying to get the images from the Nodejs server. Whenever I refresh the page or open it for the first time the data is not getting stored in the React state variable and hence the state value is giving null due to which I can't display the images on the client-side.

This is my React code:

```<code>const Images = ()=>{
    const [images,setImages] = useState([]);
    var res=[];
    useEffect(()=>{
        function fetchData(){
            instance.get('/Index/getphoto')
            .then(res=>{
                console.log(res);
                setImages(res.data);
                console.log(images);
            })

        }
        fetchData();
    },[])
    return(
        <>
            {
                images.map((item)=>{
                    return(
                        <div key={item.id}>
                        <img src={`http://localhost:3000/${item.img}`} alt="anything" />
                        </div>
                    )
                })

            }
        </>
    );
}

</code>```

In the above fetchData function  I'm getting all the data from an endpoint but when I try to store that data in images state variable using setImages(res.data), it is not getting stored there and I'm getting the below result in my console:

答:
Setting state in React is asynchronous so you will not be able to see your images immediately on the next line after setting the state.

```<code>useEffect(() => {
   function fetchData(){
       instance.get('/Index/getphoto')
       .then(res=>{
           console.log(res);
           setImages(res.data);
       })
    }
    fetchData();
}, [])
// Moved this log outside useEffect
console.log(images);
</code>```

And about the warning you are getting is related to unique keys is because you are using map over images so you need to assign unique keys to each element inside map.

In your case, you are using item.id so just make sure the id is unique for all images otherwise it will not behave as expected.

```<code> <div key={item.id}>
</code>```

References -

ReactJS : What is the best way to give keys in array element

Why calling react setState method doesn't mutate the state immediately?

Correct path for img on React.js

React won't load local images

Body:
I'm trying to get the images from the Nodejs server. Whenever I refresh the page or open it for the first time the data is not getting stored in the React state variable and hence the state value is giving null due to which I can't display the images on the client-side.

This is my React code:

const Images = ()=>{
    const [images,setImages] = useState([]);
    var res=[];
    useEffect(()=>{
        function fetchData(){
            instance.get('/Index/getphoto')
            .then(res=>{
                console.log(res);
                setImages(res.data);
                console.log(images);
            })

        }
        fetchData();
    },[])
    return(
        <>
            {
                images.map((item)=>{
                    return(

                        <img src={`http://localhost:3000/${item.img}`} alt="anything" />

                    )
                })

            }
        </>
    );
}

In the above fetchData function  I'm getting all the data from an endpoint but when I try to store that data in images state variable using setImages(res.data), it is not getting stored there and I'm getting the below result in my console:

Body:
Setting state in React is asynchronous so you will not be able to see your images immediately on the next line after setting the state.

useEffect(() => {
   function fetchData(){
       instance.get('/Index/getphoto')
       .then(res=>{
           console.log(res);
           setImages(res.data);
       })
    }
    fetchData();
}, [])
// Moved this log outside useEffect
console.log(images);

And about the warning you are getting is related to unique keys is because you are using map over images so you need to assign unique keys to each element inside map.

In your case, you are using item.id so just make sure the id is unique for all images otherwise it will not behave as expected.

 <div key={item.id}>

References -

ReactJS : What is the best way to give keys in array element

Why calling react setState method doesn't mutate the state immediately?

Correct path for img on React.js

React won't load local images


问:
Replace the extreme value with percentile with DolphinDB update statement?
I want to replace the value in the perform column that is less than the 5th percentile with 5th percentile. Can I use the following to achieve?

```<code>update ljdata set perform=percentile(perform, 5) where perform<percentile(perform, 5)>
</code>```

I have sample data percentile(perform, 5)=-15.77, but after executing this sentence, all the original values less than -15.77 are replaced by -61.38. How can I correct it? Thank you in advance for any help!

答:
You can try the following code:

```<code>p5=exec percentile(perform, 5) from ljdata
update ljdata set perform=p5 where perform <p5
</code>```

The problem is that where statement is executed before update. When the percentile is calculated, it is not the original data, but the remaining data involved in calculation.

Body:
I want to replace the value in the perform column that is less than the 5th percentile with 5th percentile. Can I use the following to achieve?

update ljdata set perform=percentile(perform, 5) where perform<percentile(perform, 5)>

I have sample data percentile(perform, 5)=-15.77, but after executing this sentence, all the original values less than -15.77 are replaced by -61.38. How can I correct it? Thank you in advance for any help!

Body:
You can try the following code:

p5=exec percentile(perform, 5) from ljdata
update ljdata set perform=p5 where perform <p5

The problem is that where statement is executed before update. When the percentile is calculated, it is not the original data, but the remaining data involved in calculation.


问:
Flutter: How to make dropdownbutton resize according to what was selected
I'm trying to make a dropdown button resize its width according to either what item was selected in the dropdown or the width of the "hint" text. How can I do this I'm totally lost. The dropdown button is being placed inside of a ListView that is horizontally scrollable.</p>
```<code>class FilterDropdown extends StatelessWidget {
  final Text? hint;
  final String? value;
  final List<DropdownMenuItem<String>>? items;
  final Function(String?)? onChanged;
  final Key? key;
  final IconData? iconData;

  FilterDropdown(
      {this.key,
      this.hint,
      this.value,
      this.items,
      this.onChanged,
      this.iconData});

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
          border: Border.all(color: Colors.white),
          borderRadius: BorderRadius.circular(8.0),
          color: const Color(0xff161F25),
        ),
        child: Padding(
          padding: const EdgeInsets.fromLTRB(21, 0, 21, 0),
          child: DropdownButtonHideUnderline(
              child: DropdownButton<String>(
            selectedItemBuilder: (BuildContext context) {
              return items!.map<Widget>((DropdownMenuItem<String> item) {
                Text innerWidget = item.child as Text;
                return Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      innerWidget.data!,
                      style: TextStyle(color: Colors.white),
                    )
                    // style: const TextStyle(color: Colors.white)),
                    );
              }).toList();
            },
            style: const TextStyle(
              color: Colors.black,
              fontSize: 16,
            ),
            key: key,
            hint: Align(
              alignment: Alignment.centerLeft,
              child: hint,
            ),
            value: value,
            icon: const Icon(Icons.arrow_drop_down),
            items: items,
            onChanged: onChanged,
          )),
        ));
  }
}
</code>```

答:
you can do like this:</p>
```<code>Container(
          width: MediaQuery.of(context).size.width,
          margin: EdgeInsets.only(left: 8, right: 3, top: 0, bottom: 0),
          child: DropdownButtonHideUnderline(
            child: DropdownButton(
              icon: widget.icon,
              isExpanded: true,
              onChanged: (value) {},
              value: 0,
              items:
                    new DropdownMenuItem(child: new Text("1")),
                    new DropdownMenuItem(child: new Text("2")),
            ),
          ),
        )
</code>```

Body:
I'm trying to make a dropdown button resize its width according to either what item was selected in the dropdown or the width of the "hint" text. How can I do this I'm totally lost. The dropdown button is being placed inside of a ListView that is horizontally scrollable.

class FilterDropdown extends StatelessWidget {
  final Text? hint;
  final String? value;
  final List<DropdownMenuItem<String>>? items;
  final Function(String?)? onChanged;
  final Key? key;
  final IconData? iconData;

  FilterDropdown(
      {this.key,
      this.hint,
      this.value,
      this.items,
      this.onChanged,
      this.iconData});

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
          border: Border.all(color: Colors.white),
          borderRadius: BorderRadius.circular(8.0),
          color: const Color(0xff161F25),
        ),
        child: Padding(
          padding: const EdgeInsets.fromLTRB(21, 0, 21, 0),
          child: DropdownButtonHideUnderline(
              child: DropdownButton<String>(
            selectedItemBuilder: (BuildContext context) {
              return items!.map<Widget>((DropdownMenuItem<String> item) {
                Text innerWidget = item.child as Text;
                return Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      innerWidget.data!,
                      style: TextStyle(color: Colors.white),
                    )
                    // style: const TextStyle(color: Colors.white)),
                    );
              }).toList();
            },
            style: const TextStyle(
              color: Colors.black,
              fontSize: 16,
            ),
            key: key,
            hint: Align(
              alignment: Alignment.centerLeft,
              child: hint,
            ),
            value: value,
            icon: const Icon(Icons.arrow_drop_down),
            items: items,
            onChanged: onChanged,
          )),
        ));
  }
}

Body:
you can do like this:

Container(
          width: MediaQuery.of(context).size.width,
          margin: EdgeInsets.only(left: 8, right: 3, top: 0, bottom: 0),
          child: DropdownButtonHideUnderline(
            child: DropdownButton(
              icon: widget.icon,
              isExpanded: true,
              onChanged: (value) {},
              value: 0,
              items:
                    new DropdownMenuItem(child: new Text("1")),
                    new DropdownMenuItem(child: new Text("2")),
            ),
          ),
        )


问:
python regex to select everything before and after a particular string
I am trying to apply regex on one of the columns in pandas dataframe, this column has text data in it, I am trying to extract a specific block. This is a sample of how my data will look like,

```<code>Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

INDICATION:
Fall some time ago with ataxia since. Recent admission with
tachybrady syndrome.
</code>```

I am trying to extract text from the beginning of the given string up to the first blank line following the first line containing 'Patient Referred from'., the entities may or may not appear in same order except the "Patient Referred from" which will always be the first entity, but there wont be any empty line until that entire block is finished. I have tried this below one,

```<code>import re
def extract_patient_details(s):

    match = re.search('(?s)Patient Referred(.*?)(?:(?:\r*\n){2})', s)
    return match.group(0)

extract_patient_details(s)
</code>```

The above snippet works fine and gives me this output:

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head
```
<p>But what I want is:</p>
<pre class="lang-none prettyprint-override"><code>Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head
</code>```

答:
To match the part of string s that is of interest, write:

```<code>rgx = r'[\s\S]*\bPatient Referred from\b.*\r?\n(?:.+\r?\n)*'
</code>```

```<code>re.search(rgx, s)
</code>```

Regex demo

To obtain the part of the string that is not matched (including one or more leading empty lines), write:

```<code>re.sub(rgx, '', s)
</code>```

Regex demo

This regular expression can be broken down as follows.

```<code>[\s\S]*                # match zero or more characters
\b                     # word boundary
Patient Referred from  # match literal
\b                     # word boundary
.*\r?\n                # match rest of line
(?:                    # begin non-capture group
  [^\r\n]+             # match one or non-line terminator chars
  \r?\n                # match a line terminator
)*                     # end non-capture group and execute
                       # it zero or more times
</code>```

[\s\S] matches all whitespace characters and all non-whitespace error, so it is a way to match all characters, including, but unlike ., line terminators. [\w\W] does the same thing. \r? is needed for files created by Windows.

Body:
I am trying to apply regex on one of the columns in pandas dataframe, this column has text data in it, I am trying to extract a specific block. This is a sample of how my data will look like,

Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

INDICATION:
Fall some time ago with ataxia since. Recent admission with
tachybrady syndrome.

I am trying to extract text from the beginning of the given string up to the first blank line following the first line containing 'Patient Referred from'., the entities may or may not appear in same order except the "Patient Referred from" which will always be the first entity, but there wont be any empty line until that entire block is finished. I have tried this below one,

import re
def extract_patient_details(s):

    match = re.search('(?s)Patient Referred(.*?)(?:(?:\r*\n){2})', s)
    return match.group(0)

extract_patient_details(s)

The above snippet works fine and gives me this output:

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

But what I want is:

Patient Name :
NHI:  ABC2134
DOB:  10/03/1737

Patient Referred from: WTH ABC
Exam performed at:  XYZ Hospital Radiology
Reference:   ABCADAFAD
Date of exam:   12/11/2019
Examination(s) included in this report:
 CT Head

Body:
To match the part of string s that is of interest, write:

rgx = r'[\s\S]*\bPatient Referred from\b.*\r?\n(?:.+\r?\n)*'

re.search(rgx, s)

Regex demo

To obtain the part of the string that is not matched (including one or more leading empty lines), write:

re.sub(rgx, '', s)

Regex demo

This regular expression can be broken down as follows.

[\s\S]*                # match zero or more characters
\b                     # word boundary
Patient Referred from  # match literal
\b                     # word boundary
.*\r?\n                # match rest of line
(?:                    # begin non-capture group
  [^\r\n]+             # match one or non-line terminator chars
  \r?\n                # match a line terminator
)*                     # end non-capture group and execute
                       # it zero or more times

[\s\S] matches all whitespace characters and all non-whitespace error, so it is a way to match all characters, including, but unlike ., line terminators. [\w\W] does the same thing. \r? is needed for files created by Windows.


问:
How to extract dates based on months using regex
```<code>import re

pattern = ['[\d]{1,2} [ADFJMNOS]\w* [\d]{2,4}','\d{1,2}/\d{1,2}/\d{2,4}']

text = "He welcomed me on 12 Jan 2014 and there by 15 OF 16 cakes for the party. Next morning on 16/05/2022 he waked up. He attended on 16 Feb 1966"

for i in pattern:
    temp_list = re.findall(i,text)
    print(temp_list)

Required output:
['12 Jan 2014','16 Feb 1966']
['16/05/2022']
</code>```

The output is coming with 15 OF 16. Is there any solution to get only the dates with months

答:
Reverse the order of findall arguments and ensure correct escaping. (?:) avoids capturing the group.

```<code>patterns = [
    r"\d{1,2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,4}",
    r"\d{1,2}/\d{1,2}/\d{2,4}",
]

for pattern in patterns:
    matches = re.findall(pattern, text)
    print(matches)
</code>```

Output:

```<code>['12 Jan 2014', '16 Feb 1966']
['16/05/2022']
</code>```

Body:
import re

pattern = ['[\d]{1,2} [ADFJMNOS]\w* [\d]{2,4}','\d{1,2}/\d{1,2}/\d{2,4}']

text = "He welcomed me on 12 Jan 2014 and there by 15 OF 16 cakes for the party. Next morning on 16/05/2022 he waked up. He attended on 16 Feb 1966"

for i in pattern:
    temp_list = re.findall(i,text)
    print(temp_list)

Required output:
['12 Jan 2014','16 Feb 1966']
['16/05/2022']

The output is coming with 15 OF 16. Is there any solution to get only the dates with months

Body:
Reverse the order of findall arguments and ensure correct escaping. (?:) avoids capturing the group.

patterns = [
    r"\d{1,2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,4}",
    r"\d{1,2}/\d{1,2}/\d{2,4}",
]

for pattern in patterns:
    matches = re.findall(pattern, text)
    print(matches)

Output:

['12 Jan 2014', '16 Feb 1966']
['16/05/2022']


问:
Is there a way to allocate a Bitmap in JNI and use it in Java to avoid OOM error
I have a drawing-board App and there's an "export image" function. I hope the exported image size can be as large as users want. The exporting steps are:

create a bitmap;

applying some transformation matrices;

create a canvas on that bitmap and draw something on it.

compress the bitmap and save to file

When using Java Bitmap.createBitmap, if the created bitmap is so large and the required memory reaches Android VM heap size limit, an OutOfMemoryError encountered.

To avoid the OOM error I'm considering to create a bitmap with native-allocated pixel data in JNI, and used the bitmap as a reference in Java. But so far I have no idea about how to achieve this at all even after I searched a lot.

Or if I can't do this, is there another way to draw canvas to a probably very large bitmap without OOM errors?

Thanks for any help!

答:
If the end result is a file, you don't need to use Bitmap at all.  Use a C or C++ image library and do everything natively.  It'll also be MUCH faster (in fact Android decodes bitmap in C already, it's too slow in Java and pointers make it easier).

How big is the bitmap anyway?  Remember that a bmp requires 4*width*height bytes in memory.  There's a limit to how big of one you can create even in C based memory.


问:
How do I create a consistent file path for shipping on multiple computers
I am a novice programmer that knows a bit but not a lot about c#, regardless I want to use what I knew to make this little console text game as a joke to send to my friends. It has a failure sound effect that uses System.Media.SoundPlayer and from what I know, SoundPlayer needs a path in order to grab a file and play it. It works fine on my computer under the file path "C:\Users\lambk\source\repos\Retarded Game 2022\scare_effectHipitch.wav" (sorry about the project title to anyone offended) but obviously this file path doesn't work for my friends who will download it to their downloads folder and will not be using a user called "lambk". Is there a sort of file path framework that would solve this issue for me? If not then how do people typically circumvent this problem?

Script for reference:

```<code>class Program
{
    static void Main(string[] args)
    {
        System.Media.SoundPlayer failureSound = new System.Media.SoundPlayer(@"C:\Users\lambk\source\repos\Retarded Game 2022\scare_effectHipitch.wav");
        Console.WriteLine("Guard: Hello Strange Traveler.\n State Your Business In The Motherland.");
        Console.WriteLine("\nA) I have come to inaugurate a new king with this dagger!\nB) Seeking Trade Amongst The People, For I Am A Merchant From The B Lands");
        string answer = Console.ReadLine();
        if (answer == "Seeking Trade Amongst The People, For I Am A Merchant From The B Lands" || answer == "b" || answer == "B")
        {
            Console.WriteLine("Swell, the motherland may always welcome additional merchendise. \n (you enter the motherland and are greeted with vast stretches of merchendise, selling souvineirs for all the visitors to snag before they leave. You accept this competition wholeheartedly, as you've come to sell not trivial materialistic items, but rather weaponry in the form of bows, arrows, swords, and shields, perhaps also as a souvinier though visitors aren't your core consumers.)\n(you make your way to your new shop)\n");
            Console.Read();
        }
        else
        {
            failure();
        }
        //-------VOID CLASSIFICATION-------//
        void failure()
        {
            int counter = 0;
            failureSound.PlayLooping();
            while (counter < 350)
            {
                Console.Write("FAILURE_FAILURE_FAILURE_FAILURE_FAILURE_FAILURE_FAILURE_FAILURE_");
                Thread.Sleep(1);
                counter++;
                if (counter == 350)
                {
                    failureSound.Stop();
                    Console.WriteLine("\nPress Enter To Restart");
                    Console.Read();
                    Application.Restart();
                }
            }
        }
        //-------VOID CLASSIFICATION-------//
    }

}
</code>```

}

答:
Assuming that the sound file is located in the Downloads folder, you can reference that folder using:

```<code> // using Microsoft.Win32;
string GetDownloadFolderPath()
{
    return Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", "{374DE290-123F-4565-9164-39C4925E467B}", String.Empty).ToString();
}
</code>```

Body:
I am a novice programmer that knows a bit but not a lot about c#, regardless I want to use what I knew to make this little console text game as a joke to send to my friends. It has a failure sound effect that uses System.Media.SoundPlayer and from what I know, SoundPlayer needs a path in order to grab a file and play it. It works fine on my computer under the file path "C:\Users\lambk\source\repos\Retarded Game 2022\scare_effectHipitch.wav" (sorry about the project title to anyone offended) but obviously this file path doesn't work for my friends who will download it to their downloads folder and will not be using a user called "lambk". Is there a sort of file path framework that would solve this issue for me? If not then how do people typically circumvent this problem?

Script for reference:

class Program
{
    static void Main(string[] args)
    {
        System.Media.SoundPlayer failureSound = new System.Media.SoundPlayer(@"C:\Users\lambk\source\repos\Retarded Game 2022\scare_effectHipitch.wav");
        Console.WriteLine("Guard: Hello Strange Traveler.\n State Your Business In The Motherland.");
        Console.WriteLine("\nA) I have come to inaugurate a new king with this dagger!\nB) Seeking Trade Amongst The People, For I Am A Merchant From The B Lands");
        string answer = Console.ReadLine();
        if (answer == "Seeking Trade Amongst The People, For I Am A Merchant From The B Lands" || answer == "b" || answer == "B")
        {
            Console.WriteLine("Swell, the motherland may always welcome additional merchendise. \n (you enter the motherland and are greeted with vast stretches of merchendise, selling souvineirs for all the visitors to snag before they leave. You accept this competition wholeheartedly, as you've come to sell not trivial materialistic items, but rather weaponry in the form of bows, arrows, swords, and shields, perhaps also as a souvinier though visitors aren't your core consumers.)\n(you make your way to your new shop)\n");
            Console.Read();
        }
        else
        {
            failure();
        }
        //-------VOID CLASSIFICATION-------//
        void failure()
        {
            int counter = 0;
            failureSound.PlayLooping();
            while (counter < 350)
            {
                Console.Write("FAILURE_FAILURE_FAILURE_FAILURE_FAILURE_FAILURE_FAILURE_FAILURE_");
                Thread.Sleep(1);
                counter++;
                if (counter == 350)
                {
                    failureSound.Stop();
                    Console.WriteLine("\nPress Enter To Restart");
                    Console.Read();
                    Application.Restart();
                }
            }
        }
        //-------VOID CLASSIFICATION-------//
    }

}

}

Body:
Assuming that the sound file is located in the Downloads folder, you can reference that folder using:

 // using Microsoft.Win32;
string GetDownloadFolderPath()
{
    return Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", "{374DE290-123F-4565-9164-39C4925E467B}", String.Empty).ToString();
}


问:
What does `openssl x509 -hash` calculate the hash of?
In the following command, openssl x509 -in example.crt -hash -noout outputs 8927dc31.

openssl req -out example.crt -keyout example.key -newkey rsa:2048 -nodes -x509 -subj '/C=US/CN=example.com' -days 3650
openssl x509 -in example.crt -hash -noout  # 8927dc31
```
<p>openssl-x509(1) just says it's the "hash" of the subject name.</p>
```       -subject_hash
           Outputs the "hash" of the certificate subject name. This is used in OpenSSL to form an index to allow certificates in a
           directory to be looked up by subject name.

       -issuer_hash
           Outputs the "hash" of the certificate issuer name.

       -hash
           Synonym for "-subject_hash" for backward compatibility reasons.
```

What is the "hash" function? (sha1? md5?)

What exactly is "the subject name"? (Subject: C = US, CN = example.com in openssl x509 -in example.crt -text?)

Can I reproduce the same hash value with the command line?

答:
The first 4 bytes (8 hex-letters) of the sha1 hash of the ASN.1-encoded subject value (issuer value for -issuer_hash).

You can reproduce the hash with the following command:

echo '
  310b30 09060355
04060c02 75733114
30120603 5504030c
0b657861 6d706c65
2e636f6d
' | xxd -r -p | sha1sum
# => 31dc2789c1e1182fbfbb64ee0a0c9a6e11276f97  -
```
<p>The first 4 bytes is <code>31dc2789</code>. If the CPU on which <code>openssl</code> runs is little-endian (including x86_64),
openssl inverts the bytes [1] (<code>31 dc 27 89</code> → <code>89 27 dc 31</code>) then prints <code>8927dc31</code></p>
<p>The ASN.1-encoded subject value <code>310b30...</code> is found by <code>wireshark example.crt</code>.</p>
<p><img src="https://i.stack.imgur.com/Xd4Sm.png" alt="Finding out the ASN.1-encoded subject value with Wireshark" /></p>
<p>If the subject is empty (<code>-subj '/'</code>), the hash is the sha1 of empty data.</p>
<pre class="lang-sh prettyprint-override"><code>openssl req -out example.crt -keyout example.key -newkey rsa:2048 -nodes -x509 -subj '/' -days 3650
openssl x509 -in example.crt -hash -noout  # eea339da
sha1sum </dev/null
# => da39a3ee5e6b4b0d3255bfef95601890afd80709  -
# da 39 a3 ee ... -> flip bytes: ee a3 39 da: eea339da
</code>```

[1]: This looks unnatural to me. I consider this should have been ntohl()ed.

Body:
In the following command, openssl x509 -in example.crt -hash -noout outputs 8927dc31.

openssl req -out example.crt -keyout example.key -newkey rsa:2048 -nodes -x509 -subj '/C=US/CN=example.com' -days 3650
openssl x509 -in example.crt -hash -noout  # 8927dc31

openssl-x509(1) just says it's the "hash" of the subject name.

       -subject_hash
           Outputs the "hash" of the certificate subject name. This is used in OpenSSL to form an index to allow certificates in a
           directory to be looked up by subject name.

       -issuer_hash
           Outputs the "hash" of the certificate issuer name.

       -hash
           Synonym for "-subject_hash" for backward compatibility reasons.

What is the "hash" function? (sha1? md5?)

What exactly is "the subject name"? (Subject: C = US, CN = example.com in openssl x509 -in example.crt -text?)

Can I reproduce the same hash value with the command line?

Body:
The first 4 bytes (8 hex-letters) of the sha1 hash of the ASN.1-encoded subject value (issuer value for -issuer_hash).

You can reproduce the hash with the following command:

echo '
  310b30 09060355
04060c02 75733114
30120603 5504030c
0b657861 6d706c65
2e636f6d
' | xxd -r -p | sha1sum
# => 31dc2789c1e1182fbfbb64ee0a0c9a6e11276f97  -

The first 4 bytes is 31dc2789. If the CPU on which openssl runs is little-endian (including x86_64),
openssl inverts the bytes [1] (31 dc 27 89 → 89 27 dc 31) then prints 8927dc31

The ASN.1-encoded subject value 310b30... is found by wireshark example.crt.

If the subject is empty (-subj '/'), the hash is the sha1 of empty data.

openssl req -out example.crt -keyout example.key -newkey rsa:2048 -nodes -x509 -subj '/' -days 3650
openssl x509 -in example.crt -hash -noout  # eea339da
sha1sum </dev/null
# => da39a3ee5e6b4b0d3255bfef95601890afd80709  -
# da 39 a3 ee ... -> flip bytes: ee a3 39 da: eea339da

[1]: This looks unnatural to me. I consider this should have been ntohl()ed.


问:
Are there any benefits of using subcollections in firestore?
I have a subcollection for each doc in the users collection of my app. This subcollection stores docs that are related to the user, however they could just as well be saved to a master collection, each doc with an associated userId.

I chose this structure as it seemed the most obvious at the time but I can imagine it will make things harder down the road if I need to do database maintenance. E.g. If I wanted to clean up those docs, I would have to query each user and then each users docs, whereas if I had a master collection I could just query all docs.

That lead me to question what is the point of subcollections at all, if you can just associate those docs with an ID. Is it solely there so that you can expand if your doc becomes close to the 1MB limit?

答: Subcollections are also helpful in setting up security rules. Suppose you are building a chat app and have a user collection with a replies subcollection. You want other users to be able to add to the replies collection but want to give the user full rights to the user collection. If you have replies as an array of maps/objects in user collection, it severely limits the rules you can write against the user collection for the collection owner and other users to be able to add to the collection. Whereas, having it as its own subcollection makes writing security rules waaaaay easier.