问:
How to get adjacent array key in PHP if my keys are not in sequence?
Below is my array. Assuming I know the current array key (say 53), how do I get the adjacent/next array key which is not in sequence? I can't use current(), can I?

```<code>(
    [50] => Array
        (
            [product_id] => 50
            [unit] => 1
        )

    [53] => Array
        (
            [product_id] => 53
            [unit] => 1
        )

    [58] => Array
        (
            [product_id] => 58
            [unit] => 1
        )

)
</code>```

答:
You can get the keys and the values as an array with array_keys() and array_values() respectively. Now use array_search() to get the index of the key (53).

You can then increase the index by 1 which will be the index of the next key. Once you know the index of the next key, you can use it to get its corresponding value as well. Try this

```<code>$array = array(
    '50' => array(
            'product_id' => 50,
            'unit' => 1
        ),

    '53' => array(
            'product_id' => 53,
            'unit' => 1
        ),

    '58' => array(
            'product_id' => 58,
            'unit' => 1
        ),

);

$current_index = array_search('53', array_keys($array));
$next_array    = array_values($array)[$current_index + 1];
print_r($next_array);
</code>```

Body:
Below is my array. Assuming I know the current array key (say 53), how do I get the adjacent/next array key which is not in sequence? I can't use current(), can I?

(
    [50] => Array
        (
            [product_id] => 50
            [unit] => 1
        )

    [53] => Array
        (
            [product_id] => 53
            [unit] => 1
        )

    [58] => Array
        (
            [product_id] => 58
            [unit] => 1
        )

)

Body:
You can get the keys and the values as an array with array_keys() and array_values() respectively. Now use array_search() to get the index of the key (53).

You can then increase the index by 1 which will be the index of the next key. Once you know the index of the next key, you can use it to get its corresponding value as well. Try this

$array = array(
    '50' => array(
            'product_id' => 50,
            'unit' => 1
        ),

    '53' => array(
            'product_id' => 53,
            'unit' => 1
        ),

    '58' => array(
            'product_id' => 58,
            'unit' => 1
        ),

);

$current_index = array_search('53', array_keys($array));
$next_array    = array_values($array)[$current_index + 1];
print_r($next_array);


来源: stackexchange

问:
import error: no module named spectral
I have already installed all the SPy dependencies and trying to import the spectral module in ipython version3.0 and getting this error : no module named spectral. what could possibly be wrong?</p>

答:
you can use "pip install spectral"on terminal to install the spectral package.
you can refer to "https://pypi.org/project/spectral/".</p>

ContentLicense: CC BY-SA 3.0

Title: import error: no module named spectral

ContentLicense: CC BY-SA 4.0


问:
send html table data to google sheet via apps-script
trying to get the cell values from html table and send them to google sheet via apps script:

index.html:

```<code>     var values = [];
     $("td").each(function(){
       values.push($(this).text());
     });

alert(values);  // i can see the array in the alert.

      google.script.run.addRows(values);
    }
</code>```

code.gs:

```<code>function addRows(values) {

  var doc = SpreadsheetApp.openById("id");
  var sheet = doc.getSheetByName('newdata');
  var lastrow = sheet.getLastRow();
   sheet.getRange(lastrow+1, 1, values.length, values[0].length).setValues(values);
}
</code>```

i got an error in the console uncaught addRows, it seems that the array is not detected on the server side, can anyone help
thanks in advance

答:
```<code> var values = [];
 $("td").each(function(){
   values.push($(this).text());
 });
 var finalarray =  [[values]]
</code>```
<p>// this will be a 1 row to append</p>

Body:
trying to get the cell values from html table and send them to google sheet via apps script:

index.html:

     var values = [];
     $("td").each(function(){
       values.push($(this).text());
     });

alert(values);  // i can see the array in the alert.

      google.script.run.addRows(values);
    }

code.gs:

function addRows(values) {

  var doc = SpreadsheetApp.openById("id");
  var sheet = doc.getSheetByName('newdata');
  var lastrow = sheet.getLastRow();
   sheet.getRange(lastrow+1, 1, values.length, values[0].length).setValues(values);
}

i got an error in the console uncaught addRows, it seems that the array is not detected on the server side, can anyone help
thanks in advance

Body:
 var values = [];
 $("td").each(function(){
   values.push($(this).text());
 });
 var finalarray =  [[values]]

// this will be a 1 row to append


问:
There are some changes opening in the linux of a git repo. But the repo is latest in windows
My pc is a dual system with Linux Mint and Windows 11.
The git repo always has some changes in Linux.

Every time I need to git stash and git stash drop.
I don't know how to descript this situation with google.

Help pls. Thanks.

答:
The problem is that you have different line ending settings between Linux and Windows.  What you're seeing in Linux is that your files have carriage returns on the end of them, which is the Windows line ending.

The easiest way to solve this is to add this to .gitattributes:

```<code>* text=auto
</code>```

Then, on an otherwise empty working tree, add that file, run git add --renormalize ., and commit.  That will cause the files to be renormalized as having LF line endings in the index.

If you're going to be working across OSes, then you'd also do well to add eol=lf to the end of that line in .gitattributes so that files are always handled with LF endings.  You'll also need to configure your tools on Windows to emit LF endings instead of CRLF endings.  That will prevent line ending differences in the working tree across systems.

Body:
The problem is that you have different line ending settings between Linux and Windows.  What you're seeing in Linux is that your files have carriage returns on the end of them, which is the Windows line ending.

The easiest way to solve this is to add this to .gitattributes:

* text=auto

Then, on an otherwise empty working tree, add that file, run git add --renormalize ., and commit.  That will cause the files to be renormalized as having LF line endings in the index.

If you're going to be working across OSes, then you'd also do well to add eol=lf to the end of that line in .gitattributes so that files are always handled with LF endings.  You'll also need to configure your tools on Windows to emit LF endings instead of CRLF endings.  That will prevent line ending differences in the working tree across systems.


问:
Regex for matching strings between '=' and '/' or "=" and end of string
I am looking for regex which can help me replace strings like

source=abc/task=cde/env=it --> source='abc'/task='cde'/env='it'
```
<p>To be more precise, I want to replace a string which starts with <code>=</code> and ends with either <code>/</code> or end of the string with <code>''</code></p>
<p>Tried code like this</p>
```"source=abc/task=cde/env=it".replaceAll("=(.*?)/","'$1'")
```
<p>But that results in</p>
```source'abc'task'cde'env=it
```

答:
Try

```<code>String input = "source=abc/task=cde/env=it".replaceAll("=(.*?)(/|$)","='$1'/");
</code>```

The problems I found are that you are not replacing the =
and also the / is not there for the end of String, that also needs to be replaced when found.

output

```<code>source='abc'/task='cde'/env='it'/
</code>```

If you don't want the last '/', that is trivial to remove isn't it.

Body:
I am looking for regex which can help me replace strings like

source=abc/task=cde/env=it --> source='abc'/task='cde'/env='it'

To be more precise, I want to replace a string which starts with = and ends with either / or end of the string with ''

Tried code like this

"source=abc/task=cde/env=it".replaceAll("=(.*?)/","'$1'")

But that results in

source'abc'task'cde'env=it

Body:
Try

String input = "source=abc/task=cde/env=it".replaceAll("=(.*?)(/|$)","='$1'/");

The problems I found are that you are not replacing the =
and also the / is not there for the end of String, that also needs to be replaced when found.

output

source='abc'/task='cde'/env='it'/

If you don't want the last '/', that is trivial to remove isn't it.


问:
Why is a control not initializing? In one Form with two classes
I try to edit my text until it is compare able for others. Many tasks have
not lead to be recoginzeable. First of all i still work not more than with two classes. And my main language i use is not english.
Class one, Form1 holds :

```<code>Class Form1

Sub New()
    InitializeComponent()

End Sub

End Class
</code>```

Class two, can be named other than class Form1, named Second_Class holds :

```<code>Class Second_Class
'Dim MainForm As New Form1 'object
WithEvents Button1 As New Button
Public Sub New()
    Development()
End Sub

Sub Development()
    Button1 = New Button With {
        .Size = New Size(40, 40),
        .Location = New Point(30, 30),
        .Text = "Click me"
    }
    Form1.Controls.Add(Button1)
End Sub
End Class
</code>```

By pressing the start without debugger key, the solution can also be achieved with the ctrl + F5 key, a form is starting. But the form starts without a button.

答:
It is not easy to recognize the shortest way to write code that has to be maintained.
A tension like summaries are personal logs in relation to others. A cloud at night is not visible inside a building. Less reflections. The english word neat is also a consideration for some who have written the language VB dot Net. Building a heap starts with leaves and a tab in visual studio is not an other side of a leave. Also a second tab.
A Form1 Class Tab for using a second class control has

```<code>Public Class Form1
Dim FairWay As New MyLabel
Public Sub New()
    InitializeComponent()
    FairWay.Application(FairWay.Bunker)
    Controls.Add(FairWay.Bunker)
End Sub
End Class
</code>```

and a MyLabel Class Tab has

```<code>Public Class MyLabel
Inherits Label
Public WithEvents Bunker As New Label
Sub Application(MudSteel As Label)
    With MudSteel
        .Location = New Point(50, 50)
        .BackColor = Color.Gold
        .Size = New Size(250, 250)
    End With
End Sub
End Class
</code>```

Body:
I try to edit my text until it is compare able for others. Many tasks have
not lead to be recoginzeable. First of all i still work not more than with two classes. And my main language i use is not english.
Class one, Form1 holds :

Class Form1

Sub New()
    InitializeComponent()

End Sub

End Class

Class two, can be named other than class Form1, named Second_Class holds :

Class Second_Class
'Dim MainForm As New Form1 'object
WithEvents Button1 As New Button
Public Sub New()
    Development()
End Sub

Sub Development()
    Button1 = New Button With {
        .Size = New Size(40, 40),
        .Location = New Point(30, 30),
        .Text = "Click me"
    }
    Form1.Controls.Add(Button1)
End Sub
End Class

By pressing the start without debugger key, the solution can also be achieved with the ctrl + F5 key, a form is starting. But the form starts without a button.

Body:
It is not easy to recognize the shortest way to write code that has to be maintained.
A tension like summaries are personal logs in relation to others. A cloud at night is not visible inside a building. Less reflections. The english word neat is also a consideration for some who have written the language VB dot Net. Building a heap starts with leaves and a tab in visual studio is not an other side of a leave. Also a second tab.
A Form1 Class Tab for using a second class control has

Public Class Form1
Dim FairWay As New MyLabel
Public Sub New()
    InitializeComponent()
    FairWay.Application(FairWay.Bunker)
    Controls.Add(FairWay.Bunker)
End Sub
End Class

and a MyLabel Class Tab has

Public Class MyLabel
Inherits Label
Public WithEvents Bunker As New Label
Sub Application(MudSteel As Label)
    With MudSteel
        .Location = New Point(50, 50)
        .BackColor = Color.Gold
        .Size = New Size(250, 250)
    End With
End Sub
End Class


问:
Nestjs auth and user Module circular dependency
My issue is that I need an auth module and user module each containing a service (eg. auth and user service).

First I wanted to import the user module (whcih exports the user service) into the auth module. However now the user controller should return an jwt (created by auth service) instead of the user id etc. which was returned by the user service before.

This results in a circular dependency.
(I thought all interactions with the user table should be run through the user service)

Is there a best practise to handle this?

答:
TLDR: use forwardRef.

Here's an extract from their discord:


问:
How to change displayed project name in authentication with google,firebase
This is my default UI for authentication with Google.
I'm using IOS emulator and i don't know how to change project name.
Can you show me how to change project name? Thanks.

答:
From the documentation on renaming your project:

The project card displays the name of your project (visible only to project members) and the project's public-facing name.

The public-facing name is the name presented to users when they are shown any public instances of your project. For example, the public-facing name displays on emails that your users receive after creating an account with your app.

To edit either of your project's names:

Click the pencil icon next to the name for either Project name or Public-facing name.

Enter a new name.

Click Save.

Also see:

Firebase change app name which display on google sign in alert?

How to change the app name for firebase authentication (what the user sees)


问:
Spring-Boot behind a network proxy
I am currently implementing an OpenID authentication based on this example. Now I am developing behind a network proxy, therefore the server cannot connect to google. The java proxy settings seem to not have any effect. I also found this stackoverflow question, but I cannot figure out where to put the code. How can I configure the proxy for my spring boot container?

thanks

答:
I could able to solve the problem in two methods

Through JVM args (both http & https)

```<code>-Dhttp.proxyHost=your-http-proxy-host -Dhttp.proxyPort=8080
-Dhttps.proxyHost=your-https-proxy-host -Dhttps.proxyPort=8080
</code>```

Or Programatically

```<code>public static void setProxy() {
        System.setProperty("http.proxyHost", "your-http-proxy-host");
        System.setProperty("http.proxyPort", "8080");

        System.setProperty("https.proxyHost", "your-http-proxy-host");
        System.setProperty("https.proxyPort", "8080");
    }
</code>```

Title: Spring-Boot behind a network proxy

Body:
I could able to solve the problem in two methods

Through JVM args (both http & https)

-Dhttp.proxyHost=your-http-proxy-host -Dhttp.proxyPort=8080
-Dhttps.proxyHost=your-https-proxy-host -Dhttps.proxyPort=8080

Or Programatically

public static void setProxy() {
        System.setProperty("http.proxyHost", "your-http-proxy-host");
        System.setProperty("http.proxyPort", "8080");

        System.setProperty("https.proxyHost", "your-http-proxy-host");
        System.setProperty("https.proxyPort", "8080");
    }


问:
Default .NET APIs in Visual Studio
My question is relatively simple, however I cannot find an answer online.
Where can you find out which .NET APIs will be installed by default with visual studio, and which will need to be installed serperately?

e.g.

System.Threading.Tasks -> Available immediately after installing VS with .Net development options

System.IO.Ports -> Requires a seperate NuGet package installation to become available

Does this depend on the .Net versions installed or on some other factor?

答:
Using the package manager console you can check if it is included or not.

First find out if the package exists:

Find-Package <Your Package>

Doing it with the System package will give you something like:

```<code>    Id                                  Versions                                 Description
--                                  --------                                 -----------
System.Buffers                      {4.5.1}                                  Provides resource pooling of any type for performance-critical applications that allocate and deallocate objects frequently....
System.Memory                       {4.5.4}                                  Provides types for efficient representation and pooling of managed, stack, and native memory segments and sequences of such s...
System.Threading.Tasks.Extensions   {4.5.4}                                  Provides additional types that simplify the work of writing concurrent and asynchronous code....
...
</code>```

If you know the package is an actual package then you can skip the step above and type:

Get-Package <Your Package>

If it is included in .NET by default you will get the following message:

No packages installed.

Otherwise you will get something like:

```<code>Id                                  Versions                                 Description
--                                  --------                                 -----------
MathParser.org-mXparser             {4.4.2}                                  mXparser is a super easy, rich, fast and highly flexible math expression parser library (parser and evaluator of mathematical...
Time Elapsed: 00:00:01.0141148
</code>```

Title: Default .NET APIs in Visual Studio

Body:
Using the package manager console you can check if it is included or not.

First find out if the package exists:

Find-Package <Your Package>

Doing it with the System package will give you something like:

    Id                                  Versions                                 Description
--                                  --------                                 -----------
System.Buffers                      {4.5.1}                                  Provides resource pooling of any type for performance-critical applications that allocate and deallocate objects frequently....
System.Memory                       {4.5.4}                                  Provides types for efficient representation and pooling of managed, stack, and native memory segments and sequences of such s...
System.Threading.Tasks.Extensions   {4.5.4}                                  Provides additional types that simplify the work of writing concurrent and asynchronous code....
...

If you know the package is an actual package then you can skip the step above and type:

Get-Package <Your Package>

If it is included in .NET by default you will get the following message:

No packages installed.

Otherwise you will get something like:

Id                                  Versions                                 Description
--                                  --------                                 -----------
MathParser.org-mXparser             {4.4.2}                                  mXparser is a super easy, rich, fast and highly flexible math expression parser library (parser and evaluator of mathematical...
Time Elapsed: 00:00:01.0141148


问:
How to call Assembla REST apis from android program
I want to call assembla apis from my code in android.
I am able to connect to assembla using the code given below, I am getting output in HTMl form.
but not able to understand how to use this data.

Code fragment :

HttpURLConnection conn = null;
        try {

```<code>        String authentication = "username:password";
        String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
        URL url = new URL("https://www.assembla.com/spaces/my_spaces");
        //URL url = new URL("https://www.assembla.com/");
         conn = (HttpURLConnection) url.openConnection();
         conn.setRequestMethod("GET");
         conn.setRequestProperty("Authorization", "Basic " + encoding);
         conn.setDoOutput(true);
         conn.connect();

        System.out.println(conn.getResponseCode());
        System.out.println(conn.getResponseMessage());

        InputStreamReader isr =
            new InputStreamReader(conn.getInputStream());
        BufferedReader br = new BufferedReader(isr);

        String inputLine;

        while ((inputLine = br.readLine()) != null)
            System.out.println(inputLine);

        br.close();
</code>```

I am very new to android so no idea the approach i m using to call rest api is correct or not.
Please advice.

Thanks.

答:
This is how I mostly make my api requests.

```<code>        HttpClient c = new DefaultHttpClient();
        HttpPost post = new HttpPost("URL");

        post.addHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");
        List<NameValuePair> httpparams = new ArrayList<NameValuePair>();

        httpparams.add(new BasicNameValuePair("password", password));

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(httpparams);
        post.setEntity(entity);

        HttpResponse resp = c.execute(post);

        InputStream i = resp.getEntity().getContent();
        InputStreamReader ir = new InputStreamReader(i);
        BufferedReader br = new BufferedReader(ir);

        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        ir.close();
        br.close();

        JSONObject user = new JSONObject(sb.toString());
</code>```

You can add or remove parameters if you want.
And I asume you receive a JSON Object (sb.toString())

Edit: In this case it's a POST , you can easily change it to GET (HttpGet)

Body:
I want to call assembla apis from my code in android.
I am able to connect to assembla using the code given below, I am getting output in HTMl form.
but not able to understand how to use this data.

Code fragment :

HttpURLConnection conn = null;
        try {

        String authentication = "username:password";
        String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
        URL url = new URL("https://www.assembla.com/spaces/my_spaces");
        //URL url = new URL("https://www.assembla.com/");
         conn = (HttpURLConnection) url.openConnection();
         conn.setRequestMethod("GET");
         conn.setRequestProperty("Authorization", "Basic " + encoding);
         conn.setDoOutput(true);
         conn.connect();

        System.out.println(conn.getResponseCode());
        System.out.println(conn.getResponseMessage());

        InputStreamReader isr =
            new InputStreamReader(conn.getInputStream());
        BufferedReader br = new BufferedReader(isr);

        String inputLine;

        while ((inputLine = br.readLine()) != null)
            System.out.println(inputLine);

        br.close();

I am very new to android so no idea the approach i m using to call rest api is correct or not.
Please advice.

Thanks.

Body:
This is how I mostly make my api requests.

        HttpClient c = new DefaultHttpClient();
        HttpPost post = new HttpPost("URL");

        post.addHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");
        List<NameValuePair> httpparams = new ArrayList<NameValuePair>();

        httpparams.add(new BasicNameValuePair("password", password));

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(httpparams);
        post.setEntity(entity);

        HttpResponse resp = c.execute(post);

        InputStream i = resp.getEntity().getContent();
        InputStreamReader ir = new InputStreamReader(i);
        BufferedReader br = new BufferedReader(ir);

        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        ir.close();
        br.close();

        JSONObject user = new JSONObject(sb.toString());

You can add or remove parameters if you want.
And I asume you receive a JSON Object (sb.toString())

Edit: In this case it's a POST , you can easily change it to GET (HttpGet)


问:
Loop to list names of files with NAs
I have a folder called "Holder" with a list of files in it. I am trying to write a loop that will iterate through the list of files, and add to a vector (called "FileList") the names of files that contain NAs. When I check my statement "sum(is.na(Orig))>=1" on a file that I know has an NA, it returns "TRUE". However, when I source the script, my vector returns "logical(0)". What am I missing here?

```<code>setwd("/Users/.../Desktop/NAs")
fileNames <- Sys.glob("*.csv")
fileNumbers <- seq(fileNames)
FileList<-vector()

for (fileNumber in fileNumbers) {
  Orig <- read.csv(fileNames[fileNumber],
                       header = TRUE,
                       sep = ",")

  if (sum(is.na(Orig))>=1) {
    append(fileNames[fileNumber], FileList)
  }}
</code>```

Also tried the below, with same result:

```<code>  if (sum(is.na(Orig$D_postIAT))>=1) {
    append(fileNames[fileNumber], FileList)
  } else if (sum(is.na(Orig$D_preIAT))>=1) {
    append(fileNames[fileNumber], FileList)
  }
</code>```

答:
There are a few issues here.

You want seq_along(), not seq(). seq() expects numeric arguments.

```<code>fileNumbers <- seq_along(fileNames)
</code>```

vector() defaults to creating a logical vector, but you want a character vector.

```<code>FileList<-vector(mode = “character”)
</code>```

You need to assign the results of each append(). With very few exceptions (outside of R6 classes), objects in R aren’t modified in place.

Your arguments are backwards: append() takes the object to be
appended to, then the object to append.

Finally, you can simplify
your code by using any() instead of sum() >= 1, and by combining
the two if clauses into one with an or. So try:

```<code>if (any(is.na(Orig$D_postIAT)) || any(is.na(Orig$D_preIAT))) {
    FileList <- append(FileList , fileNames[fileNumber])
  }
</code>```

Title: Loop to list names of files with NAs

Body:
I have a folder called "Holder" with a list of files in it. I am trying to write a loop that will iterate through the list of files, and add to a vector (called "FileList") the names of files that contain NAs. When I check my statement "sum(is.na(Orig))>=1" on a file that I know has an NA, it returns "TRUE". However, when I source the script, my vector returns "logical(0)". What am I missing here?

setwd("/Users/.../Desktop/NAs")
fileNames <- Sys.glob("*.csv")
fileNumbers <- seq(fileNames)
FileList<-vector()

for (fileNumber in fileNumbers) {
  Orig <- read.csv(fileNames[fileNumber],
                       header = TRUE,
                       sep = ",")

  if (sum(is.na(Orig))>=1) {
    append(fileNames[fileNumber], FileList)
  }}

Also tried the below, with same result:

  if (sum(is.na(Orig$D_postIAT))>=1) {
    append(fileNames[fileNumber], FileList)
  } else if (sum(is.na(Orig$D_preIAT))>=1) {
    append(fileNames[fileNumber], FileList)
  }

Body:
There are a few issues here.

You want seq_along(), not seq(). seq() expects numeric arguments.

fileNumbers <- seq_along(fileNames)

vector() defaults to creating a logical vector, but you want a character vector.

FileList<-vector(mode = “character”)

You need to assign the results of each append(). With very few exceptions (outside of R6 classes), objects in R aren’t modified in place.

Your arguments are backwards: append() takes the object to be
appended to, then the object to append.

Finally, you can simplify
your code by using any() instead of sum() >= 1, and by combining
the two if clauses into one with an or. So try:

if (any(is.na(Orig$D_postIAT)) || any(is.na(Orig$D_preIAT))) {
    FileList <- append(FileList , fileNames[fileNumber])
  }


答:
Using lookahead and look behind:

```<code>(?<==)([^/]*)((?=/)|$)
</code>```

Lookbehind allows you to specify what comes before your match. In this case an equals: (?<==).

The main match in my regex looks for any non-slash character, zero or more times: ([^/]*)

Lookahead allows you to specify what comes after your match. In this case, a slash: (?=/).

The $ matches the end of the line, so that the last item in your test data becomes quoted. ((?=/)|$) combines with this with the lookahead, meaning "either a slash comes after the match or this is the end of the line".

Here it is in action in a test.

```<code>@Test
public void test_quote_items() {
    String regex = "(?<==)([^/]*)((?=/)|$)";
    String actual = "source=abc/task=cde/env=it".replaceAll(regex,"'$1'");
    String expected = "source='abc'/task='cde'/env='it'";
    assertEquals(expected, actual);
}
</code>```

Title: Regex for matching strings between '=' and '/' or "=" and end of string

Body:
Using lookahead and look behind:

(?<==)([^/]*)((?=/)|$)

Lookbehind allows you to specify what comes before your match. In this case an equals: (?<==).

The main match in my regex looks for any non-slash character, zero or more times: ([^/]*)

Lookahead allows you to specify what comes after your match. In this case, a slash: (?=/).

The $ matches the end of the line, so that the last item in your test data becomes quoted. ((?=/)|$) combines with this with the lookahead, meaning "either a slash comes after the match or this is the end of the line".

Here it is in action in a test.

@Test
public void test_quote_items() {
    String regex = "(?<==)([^/]*)((?=/)|$)";
    String actual = "source=abc/task=cde/env=it".replaceAll(regex,"'$1'");
    String expected = "source='abc'/task='cde'/env='it'";
    assertEquals(expected, actual);
}


问:
Where are you supposed to initialize your firebase web app?
So I am brand new to web applications and I don't understand where I am supposed to initialize the my firebase app using this code:

```<code>        // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
    import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-analytics.js";

    // Your web app's Firebase configuration
    const firebaseConfig = {
    // my firebase configuration would go here...
    };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
</code>```

Example:

I will have 2 different pages for my web app (a login page and a home page). I could initialize firebase in the login page and it would work fine for the first time the user logs into the website, but then what happens if the user returns to the website and they skip the login page and go straight to the home page because they are already logged in? Does firebase not get initialized in this case because it never ran the login page code? If so what am I supposed to do?

答:
Once it loads a new page, the browser clears its memory of anything that happened on the previous page. This means that you have to initialize Firebase every page that uses it.

So if you use Firebase both on your login page and on your home page, you will have to initialize it on both of those pages.

Body:
So I am brand new to web applications and I don't understand where I am supposed to initialize the my firebase app using this code:

        // Import the functions you need from the SDKs you need
    import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
    import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-analytics.js";

    // Your web app's Firebase configuration
    const firebaseConfig = {
    // my firebase configuration would go here...
    };

    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);

Example:

I will have 2 different pages for my web app (a login page and a home page). I could initialize firebase in the login page and it would work fine for the first time the user logs into the website, but then what happens if the user returns to the website and they skip the login page and go straight to the home page because they are already logged in? Does firebase not get initialized in this case because it never ran the login page code? If so what am I supposed to do?


问:
Rails - errors partial not rendering
I'm very new to Rails and full-stack development in general. I've just finished Michael Hartl's Ruby on Rails Tutorial 6th edition and am walking through it again to build my first project (i.e. an app that's different from the sample app built in the book, but draws on a lot of the same lessons). Catch is that new project is using Rails 7.

It was going well until I ran into issues around Chapter 7; my app will not render a partial with error messages for bad submissions to the new user form. The code in the partial executes (as verified with debugger, and later with a puts statement to output on console), but the HTML doesn't output (i.e. it cannot be found when inspecting the page in Chrome). There is a CSS issue related to newer version of bootstrap, but I even tried downgrading to the bootstrap version from the book (3.4.1) with no luck. (the offending CSS segment is commented out below)

I've banged my head on this for a few hours. Hoping it's just something dumb I'm missing. If it's a broader issue with Bootstrap vs Importmaps or something I'd also appreciate references on good places to learn these. I am extremely grateful for any ideas!

Edit This definitely isn't an issue with passing local variables into the partial; see code snippet and comment added at the end of this post.

app/views/users/new.html.erb:

```<code><% provide(:title, 'Create New User') %>
<h1>Create New User</h1>

<div class="row">
    <div class="col-md-6 col-md-offset-3">

        <%= form_with(model: @user, local: true) do |f| %>
            <%= render 'shared/error_messages' %>

            <%= f.label :email %>* <i>required</i>
            <%= f.email_field :email %>

            <%= f.label :first_name %>
            <%= f.text_field :first_name %>

            <%= f.label :last_name %>
            <%= f.text_field :last_name %>

            <%= f.label :phone_number %>
            <%= f.text_field :phone_number %>

            <% # f.label :admin, "Company Admin" %>
            <% # f.radio_button :admin, "True" %>
            <% # f.label :admin, "Regular User" %>
            <% # f.radio_button :admin, "False", :checked => true %>

            <%= f.submit "Create New User", class: "btn btn-primary" %>
        <% end %>
    </div>
</div>
</code>```

app/views/shared/_error_messages.html.erb:

```<code><% if @user.errors.any? %>
  <% puts "the error partial was called" %>
  <div id="error_explanation">
    <div class="alert alert-danger">
      The form contains <%= pluralize(@user.errors.count, "error") %>
    </div>
    <ul>
      <% @user.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
    </ul>
  </div>
<% end %>
</code>```

Example server output when submitting bad data that should generate an error (fail email validation):

```<code> Started POST "/users" for 24.85.170.222 at 2022-02-14 01:01:56 +0000
Cannot render console from 24.85.170.222! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by UsersController#create as TURBO_STREAM
  Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"email"=>"no123@good-email", "first_name"=>"Jeff", "last_name"=>"Lebowski", "phone_number"=>""}, "commit"=>"Create New User"}
   (0.1ms)  SELECT sqlite_version(*)
  ↳ app/controllers/users_controller.rb:13:in `create'
  TRANSACTION (0.1ms)  begin transaction
  ↳ app/controllers/users_controller.rb:13:in `create'
  User Exists? (0.2ms)  SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ?  [["email", "no123@good-email"], ["LIMIT", 1]]
  ↳ app/controllers/users_controller.rb:13:in `create'
  TRANSACTION (0.1ms)  rollback transaction
  ↳ app/controllers/users_controller.rb:13:in `create'
  Rendering layout layouts/application.html.erb
  Rendering users/new.html.erb within layouts/application
the error partial was called
  Rendered shared/_error_messages.html.erb (Duration: 1.8ms | Allocations: 701)
  Rendered users/new.html.erb within layouts/application (Duration: 6.2ms | Allocations: 2949)
  Rendered layouts/_rails_default.html.erb (Duration: 6.7ms | Allocations: 6277)
  Rendered layouts/_shim.html.erb (Duration: 0.5ms | Allocations: 153)
  Rendered layouts/_header.html.erb (Duration: 0.8ms | Allocations: 318)
  Rendered layouts/_footer.html.erb (Duration: 0.8ms | Allocations: 258)
  Rendered layout layouts/application.html.erb (Duration: 18.8ms | Allocations: 11238)
Completed 200 OK in 35ms (Views: 23.0ms | ActiveRecord: 0.8ms | Allocations: 16412)
</code>```

Gemfile:

```<code>source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby "3.0.3"

gem "rails", "~> 7.0.1"
gem "sprockets-rails"
gem "puma", "~> 5.0"
gem "importmap-rails"
gem "turbo-rails"           # Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev]
gem "stimulus-rails"        # Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
gem "jbuilder"              # Build JSON APIs with ease [https://github.com/rails/jbuilder]

gem "bootsnap", require: false
gem "sassc-rails"           # Use Sass to process CSS

gem 'image_processing'#,           '1.9.3'
gem 'mini_magick'#,                '4.9.5'
gem 'active_storage_validations'#, '0.8.9'
gem 'bcrypt'#,                     '3.1.13'
gem 'faker'#,                      '2.11.0'
gem 'will_paginate'#,              '3.3.0'
gem 'bootstrap-will_paginate'#,    '1.0.0'
gem 'bootstrap-sass'#,             '3.4.1'

group :development, :test do
  gem "sqlite3", "~> 1.4"
  gem "debug", platforms: %i[ mri mingw x64_mingw ]
end

group :development do
  gem "web-console"
  gem "rack-mini-profiler"
  gem "spring"
end

group :test do
  # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
  gem "capybara"
  gem "selenium-webdriver"
  gem "webdrivers"

  gem 'rails-controller-testing'#, '1.0.5'
  gem 'minitest'#,                 '5.11.3'
  gem 'minitest-reporters'#,       '1.3.8'
  gem 'guard'#,                    '2.16.2'
  gem 'guard-minitest'#,           '2.4.6'
end

group :production do
  gem "pg"
  gem 'aws-sdk-s3', require: false
end
</code>```

app/assets/stylesheets/custom.scss:

```<code>@import "bootstrap-sprockets";
@import "bootstrap";

/* mixins, variables, etc. */

$gray-medium-light: #eaeaea;

/* universal */

body {
  padding-top: 60px;
}

section {
  overflow: auto;
}

textarea {
  resize: vertical;
}

.center {
  text-align: center;
  h1 {
    margin-bottom: 10px;
  }
}

@mixin box_sizing {
  -moz-box-sizing:    border-box;
  -webkit-box-sizing: border-box;
  box-sizing:         border-box;
}

/* typography */

h1, h2, h3, h4, h5, h6 {
  line-height: 1;
}

h1 {
  font-size: 3em;
  letter-spacing: -2px;
  margin-bottom: 30px;
  text-align: center;
}

h2 {
  font-size: 1.2em;
  letter-spacing: -1px;
  margin-bottom: 30px;
  text-align: center;
  font-weight: normal;
  color: $gray-light;

}

p {
  font-size: 1.1em;
  line-height: 1.7em;
}

/* header */

#logo {
  float: left;
  margin-right: 10px;
  font-size: 1.7em;
  color: white;
  /* text-transform: uppercase; */
  letter-spacing: -1px;
  padding-top: 9px;
  font-weight: bold;
  &:hover {
    color: white;
    text-decoration: none;
  }
}

/* footer */

footer {
  margin-top: 45px;
  padding-top: 5px;
  border-top: 1px solid #eaeaea;
  color: $gray-light;
  a {
    color: $gray;
    &:hover {
      color: $gray-darker;
    }
  }
  small {
    float: left;
  }

}

footer ul {
  float: right;
  list-style: none;
}

footer ul li {
  float: left;
  margin-left: 15px;
}

/* Forms */

input, textarea, select, .uneditable-input {
  border: 1px solid #bbb;
  width: 100%;
  margin-bottom: 15px;
  @include box_sizing
}

input {
  height: auto !important;
}

#error_explanation {
  color: red;
  ul {
    color: red;
    margin: 0 0 30px 0;
  }
}

/*
.field_with_errors {
  @extend .has-error;    /*this is breaking
  /*potential solution? https://jasoncharnes.com/bootstrap-4-rails-fields-with-errors/
  .form_control {

    color: $state-danger-text;
  }
}
*/

/* Miscellaneous */

.debug_dump {
  clear:       both;
  float:       left;
  width:       100%;
  margin-top:  45px;
  @include box_sizing;
}
</code>```

app/controllers/users_controller.rb:

```<code>class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def show
    @user = User.find(params[:id])
  end

  def create
    @user = User.new(user_params)   #strong params required by Rails
    #debugger
    if @user.save
      #handle succesful save
    else
      render 'new'
    end
  end

  private

    def user_params
      params.require(:user).permit(:email, :first_name, :last_name, :phone_number, :admin)
    end
end
</code>```

Edit Ok, I have confirmed by inserting test pieces into the code that this is something to do with HTML rendering. It is definitely not an issue with the instance variable passing into the partial (although I've now learned why that's poor practice!). Example below outputs to the command line exactly as expected, however the plaintext "False" doesn't change to "True" when erroneous data is submitted in the form. It almost seems like this is something with Ajax or similar where the form is submitted and the ruby/rails runs, but the html isn't refreshed? Furthermore - I've now written tests for the errors to appear and the tests pass! This is messing with my head.

app/views/shared/_error_messages.html.erb:

```<code><% puts @user.errors.any? %>
<% if @user.errors.any? %>
  True
  <% puts @user.errors.count %>

  <div id="error_explanation">
    <div class="alert alert-danger">
      The form contains <%= pluralize(@user.errors.count, "error") %>
    </div>
    <ul>
      <% @user.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
    </ul>
  </div>
<% else %>
  <% puts @user.email %>
  False
<% end %>
</code>```

答:
Try this in app/views/users/new.html.erb

<%= render 'shared/error_messages', user: @user %>

If it's a shared partial, maybe make the instance variable generic rather than  @user also.  That way it can be reused and less confusing later.

Title: Rails - errors partial not rendering

Body:
I'm very new to Rails and full-stack development in general. I've just finished Michael Hartl's Ruby on Rails Tutorial 6th edition and am walking through it again to build my first project (i.e. an app that's different from the sample app built in the book, but draws on a lot of the same lessons). Catch is that new project is using Rails 7.

It was going well until I ran into issues around Chapter 7; my app will not render a partial with error messages for bad submissions to the new user form. The code in the partial executes (as verified with debugger, and later with a puts statement to output on console), but the HTML doesn't output (i.e. it cannot be found when inspecting the page in Chrome). There is a CSS issue related to newer version of bootstrap, but I even tried downgrading to the bootstrap version from the book (3.4.1) with no luck. (the offending CSS segment is commented out below)

I've banged my head on this for a few hours. Hoping it's just something dumb I'm missing. If it's a broader issue with Bootstrap vs Importmaps or something I'd also appreciate references on good places to learn these. I am extremely grateful for any ideas!

Edit This definitely isn't an issue with passing local variables into the partial; see code snippet and comment added at the end of this post.

app/views/users/new.html.erb:

<% provide(:title, 'Create New User') %>

Create New User

        <%= form_with(model: @user, local: true) do |f| %>
            <%= render 'shared/error_messages' %>

            <%= f.label :email %>* required
            <%= f.email_field :email %>

            <%= f.label :first_name %>
            <%= f.text_field :first_name %>

            <%= f.label :last_name %>
            <%= f.text_field :last_name %>

            <%= f.label :phone_number %>
            <%= f.text_field :phone_number %>

            <% # f.label :admin, "Company Admin" %>
            <% # f.radio_button :admin, "True" %>
            <% # f.label :admin, "Regular User" %>
            <% # f.radio_button :admin, "False", :checked => true %>

            <%= f.submit "Create New User", class: "btn btn-primary" %>
        <% end %>

app/views/shared/_error_messages.html.erb:

<% if @user.errors.any? %>
  <% puts "the error partial was called" %>

      The form contains <%= pluralize(@user.errors.count, "error") %>

      <% @user.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

<% end %>

Example server output when submitting bad data that should generate an error (fail email validation):

 Started POST "/users" for 24.85.170.222 at 2022-02-14 01:01:56 +0000
Cannot render console from 24.85.170.222! Allowed networks: 127.0.0.0/127.255.255.255, ::1
Processing by UsersController#create as TURBO_STREAM
  Parameters: {"authenticity_token"=>"[FILTERED]", "user"=>{"email"=>"no123@good-email", "first_name"=>"Jeff", "last_name"=>"Lebowski", "phone_number"=>""}, "commit"=>"Create New User"}
   (0.1ms)  SELECT sqlite_version(*)
  ↳ app/controllers/users_controller.rb:13:in `create'
  TRANSACTION (0.1ms)  begin transaction
  ↳ app/controllers/users_controller.rb:13:in `create'
  User Exists? (0.2ms)  SELECT 1 AS one FROM "users" WHERE "users"."email" = ? LIMIT ?  [["email", "no123@good-email"], ["LIMIT", 1]]
  ↳ app/controllers/users_controller.rb:13:in `create'
  TRANSACTION (0.1ms)  rollback transaction
  ↳ app/controllers/users_controller.rb:13:in `create'
  Rendering layout layouts/application.html.erb
  Rendering users/new.html.erb within layouts/application
the error partial was called
  Rendered shared/_error_messages.html.erb (Duration: 1.8ms | Allocations: 701)
  Rendered users/new.html.erb within layouts/application (Duration: 6.2ms | Allocations: 2949)
  Rendered layouts/_rails_default.html.erb (Duration: 6.7ms | Allocations: 6277)
  Rendered layouts/_shim.html.erb (Duration: 0.5ms | Allocations: 153)
  Rendered layouts/_header.html.erb (Duration: 0.8ms | Allocations: 318)
  Rendered layouts/_footer.html.erb (Duration: 0.8ms | Allocations: 258)
  Rendered layout layouts/application.html.erb (Duration: 18.8ms | Allocations: 11238)
Completed 200 OK in 35ms (Views: 23.0ms | ActiveRecord: 0.8ms | Allocations: 16412)

Gemfile:

source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby "3.0.3"

gem "rails", "~> 7.0.1"
gem "sprockets-rails"
gem "puma", "~> 5.0"
gem "importmap-rails"
gem "turbo-rails"           # Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev]
gem "stimulus-rails"        # Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
gem "jbuilder"              # Build JSON APIs with ease [https://github.com/rails/jbuilder]

gem "bootsnap", require: false
gem "sassc-rails"           # Use Sass to process CSS

gem 'image_processing'#,           '1.9.3'
gem 'mini_magick'#,                '4.9.5'
gem 'active_storage_validations'#, '0.8.9'
gem 'bcrypt'#,                     '3.1.13'
gem 'faker'#,                      '2.11.0'
gem 'will_paginate'#,              '3.3.0'
gem 'bootstrap-will_paginate'#,    '1.0.0'
gem 'bootstrap-sass'#,             '3.4.1'

group :development, :test do
  gem "sqlite3", "~> 1.4"
  gem "debug", platforms: %i[ mri mingw x64_mingw ]
end

group :development do
  gem "web-console"
  gem "rack-mini-profiler"
  gem "spring"
end

group :test do
  # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
  gem "capybara"
  gem "selenium-webdriver"
  gem "webdrivers"

  gem 'rails-controller-testing'#, '1.0.5'
  gem 'minitest'#,                 '5.11.3'
  gem 'minitest-reporters'#,       '1.3.8'
  gem 'guard'#,                    '2.16.2'
  gem 'guard-minitest'#,           '2.4.6'
end

group :production do
  gem "pg"
  gem 'aws-sdk-s3', require: false
end

app/assets/stylesheets/custom.scss:

@import "bootstrap-sprockets";
@import "bootstrap";

/* mixins, variables, etc. */

$gray-medium-light: #eaeaea;

/* universal */

body {
  padding-top: 60px;
}

section {
  overflow: auto;
}

textarea {
  resize: vertical;
}

.center {
  text-align: center;
  h1 {
    margin-bottom: 10px;
  }
}

@mixin box_sizing {
  -moz-box-sizing:    border-box;
  -webkit-box-sizing: border-box;
  box-sizing:         border-box;
}

/* typography */

h1, h2, h3, h4, h5, h6 {
  line-height: 1;
}

h1 {
  font-size: 3em;
  letter-spacing: -2px;
  margin-bottom: 30px;
  text-align: center;
}

h2 {
  font-size: 1.2em;
  letter-spacing: -1px;
  margin-bottom: 30px;
  text-align: center;
  font-weight: normal;
  color: $gray-light;

}

p {
  font-size: 1.1em;
  line-height: 1.7em;
}

/* header */

#logo {
  float: left;
  margin-right: 10px;
  font-size: 1.7em;
  color: white;
  /* text-transform: uppercase; */
  letter-spacing: -1px;
  padding-top: 9px;
  font-weight: bold;
  &:hover {
    color: white;
    text-decoration: none;
  }
}

/* footer */

footer {
  margin-top: 45px;
  padding-top: 5px;
  border-top: 1px solid #eaeaea;
  color: $gray-light;
  a {
    color: $gray;
    &:hover {
      color: $gray-darker;
    }
  }
  small {
    float: left;
  }

}

footer ul {
  float: right;
  list-style: none;
}

footer ul li {
  float: left;
  margin-left: 15px;
}

/* Forms */

input, textarea, select, .uneditable-input {
  border: 1px solid #bbb;
  width: 100%;
  margin-bottom: 15px;
  @include box_sizing
}

input {
  height: auto !important;
}

#error_explanation {
  color: red;
  ul {
    color: red;
    margin: 0 0 30px 0;
  }
}

/*
.field_with_errors {
  @extend .has-error;    /*this is breaking
  /*potential solution? https://jasoncharnes.com/bootstrap-4-rails-fields-with-errors/
  .form_control {

    color: $state-danger-text;
  }
}
*/

/* Miscellaneous */

.debug_dump {
  clear:       both;
  float:       left;
  width:       100%;
  margin-top:  45px;
  @include box_sizing;
}

app/controllers/users_controller.rb:

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def show
    @user = User.find(params[:id])
  end

  def create
    @user = User.new(user_params)   #strong params required by Rails
    #debugger
    if @user.save
      #handle succesful save
    else
      render 'new'
    end
  end

  private

    def user_params
      params.require(:user).permit(:email, :first_name, :last_name, :phone_number, :admin)
    end
end

Edit Ok, I have confirmed by inserting test pieces into the code that this is something to do with HTML rendering. It is definitely not an issue with the instance variable passing into the partial (although I've now learned why that's poor practice!). Example below outputs to the command line exactly as expected, however the plaintext "False" doesn't change to "True" when erroneous data is submitted in the form. It almost seems like this is something with Ajax or similar where the form is submitted and the ruby/rails runs, but the html isn't refreshed? Furthermore - I've now written tests for the errors to appear and the tests pass! This is messing with my head.

app/views/shared/_error_messages.html.erb:

<% puts @user.errors.any? %>
<% if @user.errors.any? %>
  True
  <% puts @user.errors.count %>

      The form contains <%= pluralize(@user.errors.count, "error") %>

      <% @user.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

<% else %>
  <% puts @user.email %>
  False
<% end %>


问:
How can I get the initial communalities for an exploratory factor analysis in R?
I would like to obtain the initial communalities for an exploratory factor analysis in R
(that is, the R squared of each item when predicted by the other items included in the analysis).

Is there a way to do this with either jmv::efa or psych::fa  ?

I only see the uniqueness, which informs me of the communalities AFTER factor extraction (1-uniqueness)...

Thank you for your consideration : )

答:
As you note, the initial communalities in a factor analysis are the squared multiple correlations (SMC) of each variable by the remaining variables.  Using the built-in attitude dataset as an example they are easily calculated without additional packages via:

```<code>1 - 1 / diag(solve(cor(attitude)))

    rating complaints privileges   learning     raises   critical    advance
 0.7326020  0.7700868  0.3831176  0.6194561  0.6770498  0.1881465  0.5186447
</code>```

The psych package includes the smc() function for convenience:

```<code>psych::smc(attitude)

    rating complaints privileges   learning     raises   critical    advance
 0.7326020  0.7700868  0.3831176  0.6194561  0.6770498  0.1881465  0.5186447
</code>```

Body:
As you note, the initial communalities in a factor analysis are the squared multiple correlations (SMC) of each variable by the remaining variables.  Using the built-in attitude dataset as an example they are easily calculated without additional packages via:

1 - 1 / diag(solve(cor(attitude)))

    rating complaints privileges   learning     raises   critical    advance
 0.7326020  0.7700868  0.3831176  0.6194561  0.6770498  0.1881465  0.5186447

The psych package includes the smc() function for convenience:

psych::smc(attitude)

    rating complaints privileges   learning     raises   critical    advance
 0.7326020  0.7700868  0.3831176  0.6194561  0.6770498  0.1881465  0.5186447


问:
How to see several lines under one grep line
I want to see the logs where log level is ERROR
and I want to see the stackTrace
but when I input like below
cat app.log | grep ERROR
I can't see the stackTrace
Is there a way to see several lines under the greped line?

答:
You can use -A NUM as part of the grep options.

For example: cat app.log | grep ERROR -A 10 will print 10 lines after the matching line(s).

From the grep man page:

-A NUM, --after-context=NUM
Print NUM lines of trailing context after  matching  lines.
Places a line containing a group separator (described under
--group-separator) between contiguous  groups  of  matches.
With  the  -o or --only-matching option, this has no effect
and a warning is given.


问:
Android authentication to google accounts passed on to Google App Engine
Before I dig into the details of implementing this particular design, I wanted some advice/validation on whether I was approaching it correctly. I have a beginners knowledge of Android, advanced beginner in Python, GAE, and OpenId.

Environment

Android application

Web Services built in Python on Google App Engine

User(s) with Google Account

Scenario

I want to enable sign-in capabilities in my Android application without writing my own authentication system in GAE. Within the app, the user should be able to play as a guest without the ability to save high scores. If a user would like to have his high scores saved, he would authenticate against his Google account on the Android device. At the end of the game, the authenticated users high score would be saved (associated with his Google Account) via the game's web services on Google App Engine. The user should also be able to sign-out and hand the device to a friend who could also log in, play a game, and save her high scores associated with her Google account.

Design

In the Android application, use OpenId for authentication whenever the user wishes to sign-in (using something along the lines of what Nick has posted here.

Grab the OpenId token from the cookie that is returned and associate it with the current user.

Make a web service call to the GAE services adding the token as a cookie and including the high score

The web service would authenticate that the token is valid

The web service would determine the unique Google accounts id associated with the token (don't know how to do this, but assuming there should be a means to do this) and lookup that unique id against a cross reference table to find the users in-game id (which was previously created during account setup)

Save the high score associated with the in-game id.

Allow logout so another user can login to the game with their Google Account and repeat above process

Thank you for your help

答: You might find the 2011 Android + App Engine IO talk helpful.</p>


问:
execute a command with each list from a text file
I would like to execute a command with each list from a text file. I tried doing this code but it is not giving me any output. Can you help me? Thank you!

```<code>for i in $(cat list_of_text.txt)
do
    commandtool some_input_file $i> new_"$i".fa

    cat > final.list
    echo -e "new_"$i"\t+" >> final.list
done
</code>```

list_of_text.txt looks like this

```<code>nameabc
namedef
nameghi
namejkl
</code>```

while final.list looks like this

```<code>new_nameabc.fa  +
new_namedef.fa  +
new_nameghi.fa  +
new_namejkl.fa  +
</code>```

In summary
the long version of the code is like this and I'm trying to make a shortcut:

```<code>commandtool some_input_file nameabc> new_nameabc.fa
commandtool some_input_file namedef> new_namedef.fa
commandtool some_input_file nameghi> new_nameghi.fa
commandtool some_input_file namejkl> new_namejkl.fa

echo -e "new_nameabc.fa\t+" > final.list
echo -e "new_namedef.fa\t+" >> final.list
echo -e "new_nameghi.fa\t+" >> final.list
echo -e "new_namejkl.fa\t+" >> final.list
</code>```

Edit: It is working now. I just replaced cat > final.list to echo > final.list and moved it at the beginning as suggested in the answer.

答:
```<code>> final.list

while IFS= read -r name; do
    new_name=new_${name}.fa

    cmd input-file "$name" > "$new_name"
    printf '%s\t\n' "$new_name" >> final.list
done < list_of_text.txt
</code>```

> final.list truncates (empties) the file before it gets appended.

while IFS= read -r line; ... loop is the canonical method of processing one line of an input stream at a time. It is also far more robust compared to looping over an unquoted command substitution.

< list_of_text.txt redirects the list as input for the while read loop.

Body:
I would like to execute a command with each list from a text file. I tried doing this code but it is not giving me any output. Can you help me? Thank you!

for i in $(cat list_of_text.txt)
do
    commandtool some_input_file $i> new_"$i".fa

    cat > final.list
    echo -e "new_"$i"\t+" >> final.list
done

list_of_text.txt looks like this

nameabc
namedef
nameghi
namejkl

while final.list looks like this

new_nameabc.fa  +
new_namedef.fa  +
new_nameghi.fa  +
new_namejkl.fa  +

In summary
the long version of the code is like this and I'm trying to make a shortcut:

commandtool some_input_file nameabc> new_nameabc.fa
commandtool some_input_file namedef> new_namedef.fa
commandtool some_input_file nameghi> new_nameghi.fa
commandtool some_input_file namejkl> new_namejkl.fa

echo -e "new_nameabc.fa\t+" > final.list
echo -e "new_namedef.fa\t+" >> final.list
echo -e "new_nameghi.fa\t+" >> final.list
echo -e "new_namejkl.fa\t+" >> final.list

Edit: It is working now. I just replaced cat > final.list to echo > final.list and moved it at the beginning as suggested in the answer.

Body:
> final.list

while IFS= read -r name; do
    new_name=new_${name}.fa

    cmd input-file "$name" > "$new_name"
    printf '%s\t\n' "$new_name" >> final.list
done < list_of_text.txt

> final.list truncates (empties) the file before it gets appended.

while IFS= read -r line; ... loop is the canonical method of processing one line of an input stream at a time. It is also far more robust compared to looping over an unquoted command substitution.

< list_of_text.txt redirects the list as input for the while read loop.


问:
multiple if statements into better structure
```<code>
list.forEach(el, i) {
  var isTrue = true;
  if (isTrue && i == 0) {
    ary[0] = obj.innerText;
  }
  if (isTrue && i == 1) {
    ary[0] = obj.closest(list[0]).innerText;
    ary[1] = obj.innerText;
  }
  if (isTrue && i == 2) {
    ary[0] = obj.closest(list[0]).innerText;
    ary[1] = obj.closest(list[1]).innerText;
    ary[2] = obj.innerText;
  }
  //same pattern continues up to dozens of if statements
})
</code>```

Hi,
I'm new to JS programming.
list contains css selectors.
obj is DOM element.
How can I improve this code?

答:
All the if statements look superfluous and repetitive - why not just do it all at once? Extract all .textContent from the matching elements, then put the obj.textContent at the end.

```<code>const ary = Array.from(
  { length: i - 1 },
  (_, i) => obj.closest(list[i]).textContent
).concat(obj.textContent);
</code>```

You almost certainly want .textContent, not .innerText.

If the list may not contain the same number of elements as the number of i conditions you have, just slice the array to the desired length before concating on the final obj.textContent.

Body:
list.forEach(el, i) {
  var isTrue = true;
  if (isTrue && i == 0) {
    ary[0] = obj.innerText;
  }
  if (isTrue && i == 1) {
    ary[0] = obj.closest(list[0]).innerText;
    ary[1] = obj.innerText;
  }
  if (isTrue && i == 2) {
    ary[0] = obj.closest(list[0]).innerText;
    ary[1] = obj.closest(list[1]).innerText;
    ary[2] = obj.innerText;
  }
  //same pattern continues up to dozens of if statements
})

Hi,
I'm new to JS programming.
list contains css selectors.
obj is DOM element.
How can I improve this code?

Body:
All the if statements look superfluous and repetitive - why not just do it all at once? Extract all .textContent from the matching elements, then put the obj.textContent at the end.

const ary = Array.from(
  { length: i - 1 },
  (_, i) => obj.closest(list[i]).textContent
).concat(obj.textContent);

You almost certainly want .textContent, not .innerText.

If the list may not contain the same number of elements as the number of i conditions you have, just slice the array to the desired length before concating on the final obj.textContent.


问:
Converting multi digit char to int in C++
While I know that you can convert single digits that are characters to integers by doing, for example:

```<code>int main()
{
    char var = '5';
    int num_var = var - 48;
}
</code>```

I know you can't do the same thing for a character with a value which is say, '148'. Is there an easy way to convert this character value to an integer value of 148?

答:
You can use atoi(buffer) function, which returns the integer from the string buffer.

You need to include <stdlib.h>

Here is the prototype of the function :

int atoi (const char * str);

Body:
While I know that you can convert single digits that are characters to integers by doing, for example:

int main()
{
    char var = '5';
    int num_var = var - 48;
}

I know you can't do the same thing for a character with a value which is say, '148'. Is there an easy way to convert this character value to an integer value of 148?


答:
Given the value of isTrue doesn't change, the body can be:

```<code>ary[i] = obj.textContent;
while (i--) {
  ary[i] = obj.closest(list[i]).textContent;
}
</code>```

You likely don't need the forEach loop either, just initialise i to ary.length - 1.

Title: multiple if statements into better structure

Body:
Given the value of isTrue doesn't change, the body can be:

ary[i] = obj.textContent;
while (i--) {
  ary[i] = obj.closest(list[i]).textContent;
}

You likely don't need the forEach loop either, just initialise i to ary.length - 1.


问:
Converting double to string
I am not sure it is me or what but I am having a problem converting a double to string.

here is my code:

```<code>double total = 44;
String total2 = Double.toString(total);
</code>```

Am i doing something wrong or am i missing a step here.

I get error NumberFormatException when trying to convert this.

```<code>totalCost.setOnTouchListener(new OnTouchListener() {
  public boolean onTouch(View v, MotionEvent event) {
    try {
      double priceG = Double.parseDouble(priceGal.getText().toString());
      double valG = Double.parseDouble(volGal.toString());
      double total = priceG * valG;
      String tot = new Double(total).toString();
      totalCost.setText(tot);
    } catch(Exception e) {
      Log.e("text", e.toString());
    }

    return false;
  }
});
</code>```

I am trying to do this in an onTouchListener. Ill post more code, basically when the user touches the edittext box i want the information to calculate a fill the edittext box.

答:
This is a very old post, but this may be the easiest way to convert it:</p>
```<code>double total = 44;
String total2 = "" + total;
</code>```

Title: Converting double to string

Body:
I am not sure it is me or what but I am having a problem converting a double to string.

here is my code:

double total = 44;
String total2 = Double.toString(total);

Am i doing something wrong or am i missing a step here.

I get error NumberFormatException when trying to convert this.

totalCost.setOnTouchListener(new OnTouchListener() {
  public boolean onTouch(View v, MotionEvent event) {
    try {
      double priceG = Double.parseDouble(priceGal.getText().toString());
      double valG = Double.parseDouble(volGal.toString());
      double total = priceG * valG;
      String tot = new Double(total).toString();
      totalCost.setText(tot);
    } catch(Exception e) {
      Log.e("text", e.toString());
    }

    return false;
  }
});

I am trying to do this in an onTouchListener. Ill post more code, basically when the user touches the edittext box i want the information to calculate a fill the edittext box.

Body:
This is a very old post, but this may be the easiest way to convert it:

double total = 44;
String total2 = "" + total;


问:
Persistent Cookie ( 4728 ) How to set .ASPXAUTH cookie's expires as session cookie?
I am having medium security issues with scanning software
[ Cookie Security: Persistent Cookie ( 4728 ) ]

Its seems that I used a persistent cookie.
I have found some answers tell to not set expiration ,but I am using System.Web.Security. Therefore I must set expiration as below ,or the class would be wrong. The FormsAuthenticationTicket.cs is a temp class there I could not edit the class.

Is there ways to set .ASPXAUTH cookie as session cookie ?

Not matter authTicket.expiration as 30 min or 1 hour the ASPXAUTH cookie's expiration still one day. How to make it work?

I set the IIS and made cookie's expriation as 30 mins, the cookie disappear at the right time, but on browser cookie's expriation still one day.

Here is my FormsAuthenticationTicket code:

Controllers:

```<code>ar authTicket = new FormsAuthenticationTicket(
                    version: 1,
                    name: _result.UserName,
                    issueDate: DTnow, DateTime
                    expiration:DTnow.AddHours(1),
                    isPersistent: false,
                    userData: _result.UserRank.ToString(),
                    cookiePath: FormsAuthentication.FormsCookiePath
                    );
 var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket))
                {
                    HttpOnly = true,
                    Secure = true
                };

authCookie.Expires = DTnow.AddMinutes(30);
if (authTicket.IsPersistent)
                {
                    authCookie.Expires = authTicket.Expiration;
                    authCookie.Expires = DateTime.MinValue;
                }
                Response.Cookies.Add(authCookie);
</code>```

Web.config:

```<code><system.web>
      <sessionState timeout="31"></sessionState>
<authentication mode="Forms">
  <forms loginUrl="~/AccountUser/Login" />
</authentication>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
  <httpCookies httpOnlyCookies="true" requireSSL="true" /></system.web>
</code>```

Global.asax:

```<code>protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.User == null) return;
        if (HttpContext.Current.User.Identity.IsAuthenticated == false) return;
        if (Request.IsAuthenticated == false) return;

        FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
        FormsAuthenticationTicket authTicket = id.Ticket;
        string[] arrRolles = authTicket.UserData.Split(',');
        HttpContext.Current.User = new GenericPrincipal(HttpContext.Current.User.Identity, arrRolles);
    }
</code>```

here is my IIS setting

答:
I had found my answer. Here is my solution:

First, in Controller should not set "authCookie.Expires". I had set "authCookie.Expires = DateTime.MinValue" but that would be not work either !!

```<code>authCookie.Expires = DTnow.AddMinutes(30);  ---delete it !
</code>```

Second, in Controller the FormsAuthenticationTicket's attribute  isPersistent should be false !

```<code>FormsAuthenticationTicket(
                version: 1,
                name: _result.UserName,
                issueDate: DTnow, DateTime
                expiration:DTnow.AddHours(1),
                isPersistent: false,
                userData: _result.UserRank.ToString(),
                cookiePath: FormsAuthentication.FormsCookiePath
                );
</code>```

Third, check the Web.config setting ,the <forms ' attribute should not show cookieless

```<code><forms cookieless="UseDeviceProfile" loginUrl="~/AccountUser/Login" name=".ASPXAUTH" requireSSL="false" slidingExpiration="false" timeout="30" />
</code>```

should be:

```<code><forms  loginUrl="~/AccountUser/Login" name=".ASPXAUTH" slidingExpiration="false" timeout="30" />
</code>```

Body:
I am having medium security issues with scanning software
[ Cookie Security: Persistent Cookie ( 4728 ) ]

Its seems that I used a persistent cookie.
I have found some answers tell to not set expiration ,but I am using System.Web.Security. Therefore I must set expiration as below ,or the class would be wrong. The FormsAuthenticationTicket.cs is a temp class there I could not edit the class.

Is there ways to set .ASPXAUTH cookie as session cookie ?

Not matter authTicket.expiration as 30 min or 1 hour the ASPXAUTH cookie's expiration still one day. How to make it work?

I set the IIS and made cookie's expriation as 30 mins, the cookie disappear at the right time, but on browser cookie's expriation still one day.

Here is my FormsAuthenticationTicket code:

Controllers:

ar authTicket = new FormsAuthenticationTicket(
                    version: 1,
                    name: _result.UserName,
                    issueDate: DTnow, DateTime
                    expiration:DTnow.AddHours(1),
                    isPersistent: false,
                    userData: _result.UserRank.ToString(),
                    cookiePath: FormsAuthentication.FormsCookiePath
                    );
 var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket))
                {
                    HttpOnly = true,
                    Secure = true
                };

authCookie.Expires = DTnow.AddMinutes(30);
if (authTicket.IsPersistent)
                {
                    authCookie.Expires = authTicket.Expiration;
                    authCookie.Expires = DateTime.MinValue;
                }
                Response.Cookies.Add(authCookie);

Web.config:

<system.web>
      <sessionState timeout="31"></sessionState>
<authentication mode="Forms">
  <forms loginUrl="~/AccountUser/Login" />
</authentication>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
  <httpCookies httpOnlyCookies="true" requireSSL="true" /></system.web>

Global.asax:

protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.User == null) return;
        if (HttpContext.Current.User.Identity.IsAuthenticated == false) return;
        if (Request.IsAuthenticated == false) return;

        FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
        FormsAuthenticationTicket authTicket = id.Ticket;
        string[] arrRolles = authTicket.UserData.Split(',');
        HttpContext.Current.User = new GenericPrincipal(HttpContext.Current.User.Identity, arrRolles);
    }

here is my IIS setting

Body:
I had found my answer. Here is my solution:

First, in Controller should not set "authCookie.Expires". I had set "authCookie.Expires = DateTime.MinValue" but that would be not work either !!

authCookie.Expires = DTnow.AddMinutes(30);  ---delete it !

Second, in Controller the FormsAuthenticationTicket's attribute  isPersistent should be false !

FormsAuthenticationTicket(
                version: 1,
                name: _result.UserName,
                issueDate: DTnow, DateTime
                expiration:DTnow.AddHours(1),
                isPersistent: false,
                userData: _result.UserRank.ToString(),
                cookiePath: FormsAuthentication.FormsCookiePath
                );

Third, check the Web.config setting ,the <forms ' attribute should not show cookieless

<forms cookieless="UseDeviceProfile" loginUrl="~/AccountUser/Login" name=".ASPXAUTH" requireSSL="false" slidingExpiration="false" timeout="30" />

should be:

<forms  loginUrl="~/AccountUser/Login" name=".ASPXAUTH" slidingExpiration="false" timeout="30" />


问:
collect user inputs using Nodejs and Stripe
I'm new with Node.js I want to collect user data like name, phone number, Gmail, city ...etc using nodejs & stripe. So that I can know the user from stripe dashboard with all their information.

server side

```<code>app.post("/charge", (req, res) => {
    try {
        stripe.customers
            .create({
                name: req.body.name,
                email: req.body.email,
                source: req.body.stripeToken
            })
            .then(() => res.render("succ.html"))
            .catch(err => console.log(err));
    } catch (err) {
        res.send(err);
    }
});
</code>```

when I use this code I just take the name and Gmail from user...IDK what elements can I use to take phone number and city ...etc.

scripts.js

```<code>const stripeTokenHandler = token => {
    const hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);

    form.submit();
}
</code>```

答:
you can save the phone number and address in customer object's shipping property. See https://stripe.com/docs/api/customers/object#customer_object-shipping

You might also want to check out Stripe Checkout. The Checkout page provides built-in input elements to collect customer info, including phone number and billing/shipping address. See https://stripe.com/docs/payments/checkout/phone-numbers

Body:
I'm new with Node.js I want to collect user data like name, phone number, Gmail, city ...etc using nodejs & stripe. So that I can know the user from stripe dashboard with all their information.

server side

app.post("/charge", (req, res) => {
    try {
        stripe.customers
            .create({
                name: req.body.name,
                email: req.body.email,
                source: req.body.stripeToken
            })
            .then(() => res.render("succ.html"))
            .catch(err => console.log(err));
    } catch (err) {
        res.send(err);
    }
});

when I use this code I just take the name and Gmail from user...IDK what elements can I use to take phone number and city ...etc.

scripts.js

const stripeTokenHandler = token => {
    const hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);

    form.submit();
}


问:
Trying to DELETE FROM
 using SQLAlchemy
Trying to DELETE FROM  using SQLAlchemy.  Error is sqlalchemy.exc.ArgumentError: subject table for an INSERT, UPDATE or DELETE expected, got 'organization'.

organization is the name of the table I am trying to delete from.

This for a utility that takes a list of tables from one database instance and copying  the rows to another database instance--but I want the target table to be empty--the user logged in is not an admin so can't do a TRUNCATE.  If there is a better way, I'm open.   Thanks.

Calling code stub:

```<code>for item in table_list:
    process_tbl(engine_in, engine_out, item["table"])
</code>```

called function:

```<code>def process_tbl(engine_in, engine_out, table):
    pd = pandas.read_sql(table, engine_in)
    print(pd.columns)

    stmt = delete(table)
    print(stmt)

    rows = pd.to_sql(table, engine_out, if_exists="append", index=False)
    print("Table: " + table + " inserted rows: " + str(rows))
</code>```

答:
Well, I could not get the delete(table) call to work, but because it was a simple delete statement, I was able to use:

```<code>command = "DELETE FROM " + table
engine_out.execute(command)
</code>```

Title: Trying to DELETE FROM <Table> using SQLAlchemy

Body:
Trying to DELETE FROM  using SQLAlchemy.  Error is sqlalchemy.exc.ArgumentError: subject table for an INSERT, UPDATE or DELETE expected, got 'organization'.

organization is the name of the table I am trying to delete from.

This for a utility that takes a list of tables from one database instance and copying  the rows to another database instance--but I want the target table to be empty--the user logged in is not an admin so can't do a TRUNCATE.  If there is a better way, I'm open.   Thanks.

Calling code stub:

for item in table_list:
    process_tbl(engine_in, engine_out, item["table"])

called function:

def process_tbl(engine_in, engine_out, table):
    pd = pandas.read_sql(table, engine_in)
    print(pd.columns)

    stmt = delete(table)
    print(stmt)

    rows = pd.to_sql(table, engine_out, if_exists="append", index=False)
    print("Table: " + table + " inserted rows: " + str(rows))

Body:
Well, I could not get the delete(table) call to work, but because it was a simple delete statement, I was able to use:

command = "DELETE FROM " + table
engine_out.execute(command)


问:
Can i use only one Firebase Project for many white-labeled apps? What is the best practice?
I have a Flutter white labeled project, i want to use only the Firebase Auth on login module of all differents apps i'll generate, can i make it with only one Firebase Project and work with the UID response on the backend after the login completes? What's the best practice?</p>

答:
firebaser here

The recommended practice is to use a project only for single family of apps, with a single set of users. So an example of this would be to have the iOS, Android, and web versions of your app, and maybe an administrative back-end you have for that same app, and then maybe pro versions for all platforms too.

White labeling the same app for many customers should be done with a separate project for each of those customers. Otherwise you'll quickly run into limitations, such as the number of API keys you can create in a single project.


问:
NodeJS: Async function still halts main function
I'm trying to make a function call some code while allowing my main function to continue and not have to wait for it.

So far it's not working:

```<code>function doSomething() {
  return new Promise((resolve, reject) => {
    if(1) {
        console.log("doing something");
        for(let i = 0; i < 10000; i++) {
            for(let j = 0; j < 10000; j++) {
                for(let k = 0; k < 100; k++) {
                 // Do something for a long time to check if async is working
                }
            }
        }
        console.log("finished doing something");
        resolve( {"dummydata": 10} );
    }
    else {
        reject("error!");
    }
  })
}

function main() {
    doSomething()
    .then(data => console.log(data))
    .catch(err => console.error(err))

    console.log("this should print before doSomething() is finished");
}

main();
</code>```

This is the output:

doing something

finished doing something

this should print before doSomething() is finished

{ dummydata: 10 }

Why is my program waiting for doSomething()? I want it to run in parallel / asynchronously. I also tried making main() an async function, same with doSomething(), but that didn't work.

答:
You can use worker_threads: https://nodejs.org/api/worker_threads.html#worker-threads

const { Worker } = require("worker_threads");

const worker = new Worker(
  `
const { parentPort } = require('worker_threads');

parentPort.postMessage("doing something");
  for (let i = 0; i < 10000; i++) {
    for (let j = 0; j < 10000; j++) {
      for (let k = 0; k < 100; k++) {
        // Do something for a long time to check if async is working
      }
    }
  }
  parentPort.postMessage("finished doing something");
  parentPort.postMessage({ dummydata: 10 });

`,
  { eval: true }
);
worker.on("message", (message) => console.log(message));

console.log("this should print before doSomething() is finished");
```

This is just a snippet. You can exchange data with worker and so on...

Body:
I'm trying to make a function call some code while allowing my main function to continue and not have to wait for it.

So far it's not working:

function doSomething() {
  return new Promise((resolve, reject) => {
    if(1) {
        console.log("doing something");
        for(let i = 0; i < 10000; i++) {
            for(let j = 0; j < 10000; j++) {
                for(let k = 0; k < 100; k++) {
                 // Do something for a long time to check if async is working
                }
            }
        }
        console.log("finished doing something");
        resolve( {"dummydata": 10} );
    }
    else {
        reject("error!");
    }
  })
}

function main() {
    doSomething()
    .then(data => console.log(data))
    .catch(err => console.error(err))

    console.log("this should print before doSomething() is finished");
}

main();

This is the output:

doing something

finished doing something

this should print before doSomething() is finished

{ dummydata: 10 }

Why is my program waiting for doSomething()? I want it to run in parallel / asynchronously. I also tried making main() an async function, same with doSomething(), but that didn't work.

Body:
You can use worker_threads: https://nodejs.org/api/worker_threads.html#worker-threads

const { Worker } = require("worker_threads");

const worker = new Worker(
  `
const { parentPort } = require('worker_threads');

parentPort.postMessage("doing something");
  for (let i = 0; i < 10000; i++) {
    for (let j = 0; j < 10000; j++) {
      for (let k = 0; k < 100; k++) {
        // Do something for a long time to check if async is working
      }
    }
  }
  parentPort.postMessage("finished doing something");
  parentPort.postMessage({ dummydata: 10 });

`,
  { eval: true }
);
worker.on("message", (message) => console.log(message));

console.log("this should print before doSomething() is finished");

This is just a snippet. You can exchange data with worker and so on...


问:
Understanding const reference returned from a function
I have a function

```<code>const std::string& getRecordingJobToken() { return getToken(); }
const std::string& getToken() const { return m_Token;  }
std::string m_Token;
</code>```

I am able to call it as below

```<code>const std::string jobToken = getRecordingJobToken();
</code>```

However when I do this,

```<code>const std::string jobToken;
jobToken = getRecordingJobToken();
</code>```

It throws me this error -

error: passing ‘const string’ {aka ‘const std::__cxx11::basic_string’} as ‘this’ argument discards qualifiers [-fpermissive]

What is the difference ?
I know that a reference variable has to be initialized immediately.

std::string &ref = a;

Is it some similiar logic ? The reason i am confused is that though getRecordingJobToken() returns a const reference, the variable jobToken that I have is not a reference variable. It is a variable that is used to take a string reference being returned from the getRecordingJobToken() function.

答:
Initialization and assignment are different things. jobToken is const, it could be initialized, e.g.

```<code>const std::string jobToken = getRecordingJobToken(); // copy-initialization
</code>```

but can't be assigned (modified) later, e.g.

```<code>const std::string jobToken;        // default-initialization
jobToken = getRecordingJobToken(); // fails; assignment
</code>```

Body:
I have a function

const std::string& getRecordingJobToken() { return getToken(); }
const std::string& getToken() const { return m_Token;  }
std::string m_Token;

I am able to call it as below

const std::string jobToken = getRecordingJobToken();

However when I do this,

const std::string jobToken;
jobToken = getRecordingJobToken();

It throws me this error -

error: passing ‘const string’ {aka ‘const std::__cxx11::basic_string’} as ‘this’ argument discards qualifiers [-fpermissive]

What is the difference ?
I know that a reference variable has to be initialized immediately.

std::string &ref = a;

Is it some similiar logic ? The reason i am confused is that though getRecordingJobToken() returns a const reference, the variable jobToken that I have is not a reference variable. It is a variable that is used to take a string reference being returned from the getRecordingJobToken() function.

Body:
Initialization and assignment are different things. jobToken is const, it could be initialized, e.g.

const std::string jobToken = getRecordingJobToken(); // copy-initialization

but can't be assigned (modified) later, e.g.

const std::string jobToken;        // default-initialization
jobToken = getRecordingJobToken(); // fails; assignment


问:
Is it possible to create a generic Int-to-Enum Converter?
I'd like to be able to say

```<code><DataTrigger Binding="{Binding SomeIntValue}"
             Value="{x:Static local:MyEnum.SomeValue}">
</code>```

and to have it resolve as True if the int value is equal to (int)MyEnum.Value

I know I could make a Converter that returns (MyEnum)intValue, however then I'd have to make a converter for every Enum type I use in my DataTriggers.

Is there a generic way to create a converter that would give me this kind of functionality?

答:
I think I figured it out

I just needed to set my ConverterParameter instead of the Value equal to the Enum I am looking for, and evaluate for True/False

```<code><DataTrigger Value="True"
             Binding="{Binding SomeIntValue,
                 Converter={StaticResource IsIntEqualEnumConverter},
                 ConverterParameter={x:Static local:MyEnum.SomeValue}}">
</code>```

Converter

```<code>public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (parameter == null || value == null) return false;

    if (parameter.GetType().IsEnum && value is int)
    {
        return (int)parameter == (int)value;
    }
    return false;
}
</code>```

Body:
I'd like to be able to say

<DataTrigger Binding="{Binding SomeIntValue}"
             Value="{x:Static local:MyEnum.SomeValue}">

and to have it resolve as True if the int value is equal to (int)MyEnum.Value

I know I could make a Converter that returns (MyEnum)intValue, however then I'd have to make a converter for every Enum type I use in my DataTriggers.

Is there a generic way to create a converter that would give me this kind of functionality?

Body:
I think I figured it out

I just needed to set my ConverterParameter instead of the Value equal to the Enum I am looking for, and evaluate for True/False

<DataTrigger Value="True"
             Binding="{Binding SomeIntValue,
                 Converter={StaticResource IsIntEqualEnumConverter},
                 ConverterParameter={x:Static local:MyEnum.SomeValue}}">

Converter

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (parameter == null || value == null) return false;

    if (parameter.GetType().IsEnum && value is int)
    {
        return (int)parameter == (int)value;
    }
    return false;
}


问:
Magento 2 observer, dispatch catalog_product_save_after event when update products programmatically
I have to dispatch event catalog_product_save_before or catalog_product_save_after event, while update a lot of products programmatically.
I run a script that call updateAttributes() method that dispatch event catalog_product_attribute_update_before, but m2epro module does not update amazon's price if I don't call catalog_product_save_after ord catalog_product_save_before

what do you think is the best solution for this need?
Thanks

答: I assume you are also trying to update price for the product along with amazon price when using your script. If you have any functionality/dependencies to customize the price before updating regular price, then catalog_product_save_after is better approach to fetch the calculated price and update amazon price attribute. If you don't have such dependencies, you can use either of them and there won't be any difference at all.


问:
Getting "type or namespace name could not be found" but everything seems ok?
I'm getting a:

type or namespace name could not be found

error for a C# WPF app in VS2010. This area of code was compiling fine, but suddenly I'm getting this error. I've tried removing the Project Reference and the using statement, shutting VS2010 and restarting, but still I have this issue.

Any ideas why this might be occurring, where it seems like I'm doing the right thing re Reference & using statement?

I also noted in VS2010 that intellisense for that namespace is working ok, so it seems like VS2010 has the project reference and is seeing the namespace on one hand, but during compile doesn't see it?

答:
I faced this issue while trying to build my project in cloud. It was building fine on my local device, but not on Gitlab CI/CD pipeline.

First thing to do is to check if you are uploading/pushing all the needed files. In my case, my .gitignore file was configured in a wrong way, and it was ignoring important *.meta files.

Fixing .gitignore and pushing again made the project in cloud equivalent with my local version and problem is solved.


问:
Encrypting a string by replacing letters between two strings
I want to create a function which will receive two strings as parameters. One will be the the phrase to be encrypted and the other one will be some sort of index used to encrypt. The process is based on a alphabet 'abcdefghijklmnopqrstuvwxyz .'. Each letter in the first string will have its corresponding letter found in the second string. Its position number will determine which letter of 'abcdefghijklmnopqrstuvwxyz .' will be used at the result. For example:

```<code>>>> func('hello world', '. zyxwvutsrqponmlkjihgfedcba')
    'uxqqnbfnkqy'
</code>```

While searching, I found out some methods to do it, but they used external libraries. Is there a way to do it without them?

Thanks in advance for any help.

答:
This function I wrote may help you.

```<code>def encrypt(message, key):
    alphabet = 'abcdefghijklmnopqrstuvwxyz .'
    encrypted_message = ""
    for character in message:
        index = key.find(character)
        encrypted_message += alphabet[index]
    return encrypted_message
</code>```

The most useful method to you is the find(character) method for strings. It is used to return the index of the first matching character in a string.

https://www.programiz.com/python-programming/methods/string/find

Body:
I want to create a function which will receive two strings as parameters. One will be the the phrase to be encrypted and the other one will be some sort of index used to encrypt. The process is based on a alphabet 'abcdefghijklmnopqrstuvwxyz .'. Each letter in the first string will have its corresponding letter found in the second string. Its position number will determine which letter of 'abcdefghijklmnopqrstuvwxyz .' will be used at the result. For example:

>>> func('hello world', '. zyxwvutsrqponmlkjihgfedcba')
    'uxqqnbfnkqy'

While searching, I found out some methods to do it, but they used external libraries. Is there a way to do it without them?

Thanks in advance for any help.

Body:
This function I wrote may help you.

def encrypt(message, key):
    alphabet = 'abcdefghijklmnopqrstuvwxyz .'
    encrypted_message = ""
    for character in message:
        index = key.find(character)
        encrypted_message += alphabet[index]
    return encrypted_message

The most useful method to you is the find(character) method for strings. It is used to return the index of the first matching character in a string.

https://www.programiz.com/python-programming/methods/string/find


问:
Unable to convert bytes into dict in python
How can i convert this json data which is bytes to a dict in python please.

[{"Value":-20,"Unit":"°C","WatchName":"AHU1 Room Temp2"},{"Value":"Normal","WatchName":"A: AHU1 Fan Mismatch"},{"Value":"Trading","WatchName":"Occupany Mode"},{"Value":"Close","WatchName":"Roller Door Input"},{"Value":"Disarmed","WatchName":"Security Input"},{"Value":-20,"Unit":"°C","WatchName":"AHU1 Room Temp1"},{"Value":"On","WatchName":"AHU1 Fan Status"},{"Value":"On","WatchName":"AHU1 Enable"}]

答:
Only a JSON 'object' becomes a Python dictionary.

A JSON array of objects becomes a list, like so:

import json
json_data = '[{"Value":-20,"Unit":"°C","WatchName":"AHU1 Room Temp2"},{"Value":"Normal","WatchName":"A: AHU1 Fan Mismatch"},{"Value":"Trading","WatchName":"Occupany Mode"},{"Value":"Close","WatchName":"Roller Door Input"},{"Value":"Disarmed","WatchName":"Security Input"},{"Value":-20,"Unit":"°C","WatchName":"AHU1 Room Temp1"},{"Value":"On","WatchName":"AHU1 Fan Status"},{"Value":"On","WatchName":"AHU1 Enable"}]'
result = json.loads(json_data)
```


问:
clang: error: cannot specify -o when generating multiple output files error
So I have the following files:

Then I have a makefile which contains the following:

```<code>CC = gcc

CFLAGS  = -g -Wall -std=c++11 -lstdc++

all: P0

P0: node.hpp tree.cpp tree.hpp main.cpp
    $(CC) -o $@ $^ $(CFLAGS)

clean:
    rm P0 *.inorder *.postorder *.preorder
    rm -r *.dSYM
</code>```

I'm getting the following error when attempting to compile all:

```<code>smajlovs@US3FHIM0XQ86TJG: ~/Personal/School/CMPSCI4280/project-0[main*]$ make
gcc -o P0 node.hpp tree.cpp tree.hpp main.cpp -g -Wall -std=c++11 -lstdc++
clang: error: cannot specify -o when generating multiple output files
</code>```

I'm looking at being able to run the following command at the end: ./P0 file.

答:
could you give me an example of a makefile for C++

This is an example how I'd start out with only the files I know exist in your project. This would be my debug or development Makefile since it uses a bit of static analysis and uses the AddressSanitizer and UndefinedBehaviorSanitizer libraries (which makes compiling and running the program a bit slower).

```<code># The C++ compiler to use
CXX = clang++

# Runtime sanitizers
# Using AddressSanitizer and UndefinedBehaviorSanitizer will make
# the program a bit slower but helps when debugging.
SANITIZERS = -fsanitize=address,undefined

# $(CXX) options
CXXFLAGS = -std=c++11 -Wall -Wextra -Werror -pedantic-errors -g $(SANITIZERS)

# Linking options
LDFLAGS = $(SANITIZERS)

# All your source files that needs to be compiled
SRC = main.cpp tree.cpp

# The object files you need from compiling the source files
OBJS = $(SRC:%.cpp=%.o)

# The final target
TARGET = P0

# clean target
CLEAN = $(TARGET) $(OBJS)

all: $(TARGET)

# linking - require all the object files
P0: $(OBJS)
        $(CXX) -o $@ $^ $(LDFLAGS)

clean:
        rm -f $(CLEAN)
</code>```

Example:

```<code>$ scan-build make -j
</code>```

Body:
So I have the following files:

Then I have a makefile which contains the following:

CC = gcc

CFLAGS  = -g -Wall -std=c++11 -lstdc++

all: P0

P0: node.hpp tree.cpp tree.hpp main.cpp
    $(CC) -o $@ $^ $(CFLAGS)

clean:
    rm P0 *.inorder *.postorder *.preorder
    rm -r *.dSYM

I'm getting the following error when attempting to compile all:

smajlovs@US3FHIM0XQ86TJG: ~/Personal/School/CMPSCI4280/project-0[main*]$ make
gcc -o P0 node.hpp tree.cpp tree.hpp main.cpp -g -Wall -std=c++11 -lstdc++
clang: error: cannot specify -o when generating multiple output files

I'm looking at being able to run the following command at the end: ./P0 file.

Body:
could you give me an example of a makefile for C++

This is an example how I'd start out with only the files I know exist in your project. This would be my debug or development Makefile since it uses a bit of static analysis and uses the AddressSanitizer and UndefinedBehaviorSanitizer libraries (which makes compiling and running the program a bit slower).

# The C++ compiler to use
CXX = clang++

# Runtime sanitizers
# Using AddressSanitizer and UndefinedBehaviorSanitizer will make
# the program a bit slower but helps when debugging.
SANITIZERS = -fsanitize=address,undefined

# $(CXX) options
CXXFLAGS = -std=c++11 -Wall -Wextra -Werror -pedantic-errors -g $(SANITIZERS)

# Linking options
LDFLAGS = $(SANITIZERS)

# All your source files that needs to be compiled
SRC = main.cpp tree.cpp

# The object files you need from compiling the source files
OBJS = $(SRC:%.cpp=%.o)

# The final target
TARGET = P0

# clean target
CLEAN = $(TARGET) $(OBJS)

all: $(TARGET)

# linking - require all the object files
P0: $(OBJS)
        $(CXX) -o $@ $^ $(LDFLAGS)

clean:
        rm -f $(CLEAN)

Example:

$ scan-build make -j


答:
You certainly don't need any external libraries.

Just use the index method to find the characters position within the alphabet, then use that index to get the corresponding character in the cypher key.

```<code>def func(string, key):
    letters = 'abcdefghijklmnopqrstuvwxyz .'
    output = ''
    for char in string:
        output += key[letters.index(char)]
    return output

</code>```

Title: Encrypting a string by replacing letters between two strings

Body:
You certainly don't need any external libraries.

Just use the index method to find the characters position within the alphabet, then use that index to get the corresponding character in the cypher key.

def func(string, key):
    letters = 'abcdefghijklmnopqrstuvwxyz .'
    output = ''
    for char in string:
        output += key[letters.index(char)]
    return output