问:
Spring config server return null for properties in client application
Spring config server work properly and return below response for URL:- http://localhost:8888/limits-service/default

```<code>{
    "name": "limits-service",
    "profiles": [
        "default"
    ],
    "label": null,
    "version": "08da3c031373162bca129f75a914f8f4a5ccee8f",
    "state": null,
    "propertySources": [
        {
            "name": "https://github.com/miccloudtest/miccloudtest/limits-service.properties",
            "source": {
                "limits-service.minimum": "1099999",
                "limits-service.maximum": "1008888"
            }
        },
        {
            "name": "https://github.com/miccloudtest/miccloudtest/application.properties",
            "source": {
                "spring.application.name": "spring-client-config-server",
                "server.port": "8888",
                "spring.cloud.config.server.git.uri": "https://github.com/miccloudtest/miccloudtest"
            }
        }
    ]
}
</code>```

But my client application limits-service return below response for URL:-http://localhost:8080/limits

```<code>{
    "maximum": null,
    "minimum": null
}
</code>```

My whole code uploaded to Git repository to below location

Client Application

Config Server Application

Please help me so that I continue my spring cloud learning.Thanks in advance.

Client application name is limit-service.

Config server application name is client config server.

Git resource file name is limits-servive.properties.

答: Your file name is having typo for limits-service.properties.

Body:
Spring config server work properly and return below response for URL:- http://localhost:8888/limits-service/default

{
    "name": "limits-service",
    "profiles": [
        "default"
    ],
    "label": null,
    "version": "08da3c031373162bca129f75a914f8f4a5ccee8f",
    "state": null,
    "propertySources": [
        {
            "name": "https://github.com/miccloudtest/miccloudtest/limits-service.properties",
            "source": {
                "limits-service.minimum": "1099999",
                "limits-service.maximum": "1008888"
            }
        },
        {
            "name": "https://github.com/miccloudtest/miccloudtest/application.properties",
            "source": {
                "spring.application.name": "spring-client-config-server",
                "server.port": "8888",
                "spring.cloud.config.server.git.uri": "https://github.com/miccloudtest/miccloudtest"
            }
        }
    ]
}

But my client application limits-service return below response for URL:-http://localhost:8080/limits

{
    "maximum": null,
    "minimum": null
}

My whole code uploaded to Git repository to below location

Client Application

Config Server Application

Please help me so that I continue my spring cloud learning.Thanks in advance.

Client application name is limit-service.

Config server application name is client config server.

Git resource file name is limits-servive.properties.


来源: stackexchange

问:
How can you stop a program from listening as soon as you stop talking?
I am making a simple program to listen to my michrophone and using google's api convert it to text.
It's going fine but my problem is that when i am stop talking, the program keeps listening and just after few seconds after i stopped talking it stops.

I know its probably a problem with my noise in the background although I have Blue yeti microphone so it should'nt rally happens but still I tried to adjust the noise and yet it showed the same result.

```<code>import speech_recognition as sr

# obtain audio from the microphone
r = sr.Recognizer()
with sr.Microphone(device_index = 1) as source:
    print("Say something!")
    #audio = r.adjust_for_ambient_noise(source) - Tried also that
    audio = r.listen(source)
    print('Stopped listening!')
try:
    print("Google Speech Recognition thinks you said " + r.recognize_google(audio, language="he-HE"))
except sr.UnknownValueError:
    print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
    print("Could not request results from Google Speech Recognition service; {0}".format(e))
</code>```

As expected the program keeps listening even when i'm not talking for few seconds which makes it really slow and bad..
Thanks for the help!

答: if all code is correct try with headphone Attached to the PC and please on the headphone setting with microphone on..... so basically program is working but some times microphone is the problem... That's why program is not showing any error .. because it try to listen but not able to understand because microphone or source is the problem....</p>

ContentLicense: CC BY-SA 4.0

Body:
I am making a simple program to listen to my michrophone and using google's api convert it to text.
It's going fine but my problem is that when i am stop talking, the program keeps listening and just after few seconds after i stopped talking it stops.

I know its probably a problem with my noise in the background although I have Blue yeti microphone so it should'nt rally happens but still I tried to adjust the noise and yet it showed the same result.

import speech_recognition as sr

# obtain audio from the microphone
r = sr.Recognizer()
with sr.Microphone(device_index = 1) as source:
    print("Say something!")
    #audio = r.adjust_for_ambient_noise(source) - Tried also that
    audio = r.listen(source)
    print('Stopped listening!')
try:
    print("Google Speech Recognition thinks you said " + r.recognize_google(audio, language="he-HE"))
except sr.UnknownValueError:
    print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
    print("Could not request results from Google Speech Recognition service; {0}".format(e))

As expected the program keeps listening even when i'm not talking for few seconds which makes it really slow and bad..
Thanks for the help!


问:
Is it possible to detect that your javascript code is executing because of an event?
If you don't control the invocation of your code, but would like to know if it's being executed by an event handler, is this possible?</p>

答: You could have it signal by modifying a global variable. For debugging purposes, there's an alert.</p>

OwnerDisplayName: daveb

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: sblundy


问:
Multi-line string with extra space (preserved indentation)
I want to write some pre-defined texts to a file with the following:

```<code>text="this is line one\n
this is line two\n
this is line three"

echo -e $text > filename
</code>```

I'm expecting something like this:

```<code>this is line one
this is line two
this is line three
</code>```

But got this:

```<code>this is line one
 this is line two
 this is line three
</code>```

I'm positive that there is no space after each \n, but how does the extra space come out?

答:
There are many ways to do it. For me, piping the indented string into sed works nicely.

printf_strip_indent() {
   printf "%s" "$1" | sed "s/^\s*//g"
}

printf_strip_indent "this is line one
this is line two
this is line three" > "file.txt"
```

This answer was based on Mateusz Piotrowski's answer but refined a bit.

ContentLicense: CC BY-SA 3.0

Body:
I want to write some pre-defined texts to a file with the following:

text="this is line one\n
this is line two\n
this is line three"

echo -e $text > filename

I'm expecting something like this:

this is line one
this is line two
this is line three

But got this:

this is line one
 this is line two
 this is line three

I'm positive that there is no space after each \n, but how does the extra space come out?

Body:
There are many ways to do it. For me, piping the indented string into sed works nicely.

printf_strip_indent() {
   printf "%s" "$1" | sed "s/^\s*//g"
}

printf_strip_indent "this is line one
this is line two
this is line three" > "file.txt"

This answer was based on Mateusz Piotrowski's answer but refined a bit.


问:
What are the parameters in arow function in JS?
please help the newbie figure it out.

There is such a code:

```<code>    function makeDouble (x) {
      return x * 2;
   }
    var doMath = (x, func) => func(x + 5);

   var num = 5;
</code>```

The task is:

*Using only makeDouble, doMath, and num, make the value of num equal to 20.

num = _____________________________________________________*

I can’t understand why there are two parameters in the parameters of an arrow function, but in the body of this function itself there is only one parameter. What am I doing wrong?

答: Both parameters in doMath() are being used. The first is argument x will be applied as an argument in the function call of the second argument func and the value returned from that function call will be returned by doMath() itself.

Body:
please help the newbie figure it out.

There is such a code:

    function makeDouble (x) {
      return x * 2;
   }
    var doMath = (x, func) => func(x + 5);

   var num = 5;

The task is:

*Using only makeDouble, doMath, and num, make the value of num equal to 20.

num = _____________________________________________________*

I can’t understand why there are two parameters in the parameters of an arrow function, but in the body of this function itself there is only one parameter. What am I doing wrong?


答:
You can translate the arrow function as:

```<code>function doMath(x, func) { return func(x+5); }
</code>```

So you pass a value (x) and a function (func) to the doMath function. func can be any function, for example makeDouble... You can call it like:

```<code>doMath(1, makeDouble)
</code>```

And the result will be (1+5)*2 = 12.

I think you can figure out the rest based on this.

Title: What are the parameters in arow function in JS?

Body:
You can translate the arrow function as:

function doMath(x, func) { return func(x+5); }

So you pass a value (x) and a function (func) to the doMath function. func can be any function, for example makeDouble... You can call it like:

doMath(1, makeDouble)

And the result will be (1+5)*2 = 12.

I think you can figure out the rest based on this.


问:
Problem while retrieving Button tags
my app requirements are as follows:-

1.) Make a Buttton  according to Number of images store in a library.(i have done it).
2.) Disable all buttons when user click on Disable Button.
to full fill the second requirement i set the tag of each button at the time of creation:

```<code>button.setTag=tag;
</code>```

where tag increase on e by one.

problem is that when i disable button it disable only last button.how can i acess button tag value one by one.?

```<code>for (int index = 0; index < [objectButtonArray count];index++) {
    UIButton *button = [objectButtonArray objectAtIndex:index];
    button.hidden = NO;
    imageButton.userInteractionEnabled = NO;
}
</code>```

答:
Try this</p>

```<code>    for (int index = minTag; index <= maxTag;index++) {
        UIView *aView = [self.view viewWithTag:index];
        if ([aView isKindOfClass:[UIButton Class]]) {
             [aView setUserInterationEnabled:NO];
         }
    }
</code>```

Title: Problem while retrieving Button tags

Body:
my app requirements are as follows:-

1.) Make a Buttton  according to Number of images store in a library.(i have done it).
2.) Disable all buttons when user click on Disable Button.
to full fill the second requirement i set the tag of each button at the time of creation:

button.setTag=tag;

where tag increase on e by one.

problem is that when i disable button it disable only last button.how can i acess button tag value one by one.?

for (int index = 0; index < [objectButtonArray count];index++) {
    UIButton *button = [objectButtonArray objectAtIndex:index];
    button.hidden = NO;
    imageButton.userInteractionEnabled = NO;
}

Body:
Try this

    for (int index = minTag; index <= maxTag;index++) {
        UIView *aView = [self.view viewWithTag:index];
        if ([aView isKindOfClass:[UIButton Class]]) {
             [aView setUserInterationEnabled:NO];
         }
    }


问:
Laravel status is not changing in the code
In my laravel project am trying to change the Clinic status based on status recived in URL. The problem is that it is not going to else case.
Following is my code

```<code>public function deactivate($id , $status)
    {

        $input_data['id'] = $id;
        $clinic = new Clinic;
        $clinc = Clinic::find($id);
        if ($status="deactive") {
            echo "here";
            die();
            $clinc->ClinicPub = "no";
        }
       else if ($status="active")
        {
            echo "ok";
            die();
            $clinc->ClinicPub = "yes";
        }
        if($clinc->save()){
            Session::flash('message', 'Clinic Deactivated Sucessfully');
            Session::flash('msgclass', 'alert-success');
        }
        return redirect('clinics');
    }
</code>```

Here if status is deactive its going inside that loop and priiting variable here. But the problem is that is status is active , it is not going inside status=active  case, it is going inside deactive case.

I have also printed to check wether recievd status is correct.but is correct and not going inside the loop

Kindly help

答:
Please use == for comparison

```<code>public function deactivate($id , $status)
    {

        $input_data['id'] = $id;
        $clinic = new Clinic;
        $clinc = Clinic::find($id);
        if ($status=="deactive") {
            $clinc->ClinicPub = "no";
        }
       else if ($status=="active")
        {
            $clinc->ClinicPub = "yes";
        }
        if($clinc->save()){
            Session::flash('message', 'Clinic Deactivated Sucessfully');
            Session::flash('msgclass', 'alert-success');
        }
        return redirect('clinics');
    }
</code>```

Body:
In my laravel project am trying to change the Clinic status based on status recived in URL. The problem is that it is not going to else case.
Following is my code

public function deactivate($id , $status)
    {

        $input_data['id'] = $id;
        $clinic = new Clinic;
        $clinc = Clinic::find($id);
        if ($status="deactive") {
            echo "here";
            die();
            $clinc->ClinicPub = "no";
        }
       else if ($status="active")
        {
            echo "ok";
            die();
            $clinc->ClinicPub = "yes";
        }
        if($clinc->save()){
            Session::flash('message', 'Clinic Deactivated Sucessfully');
            Session::flash('msgclass', 'alert-success');
        }
        return redirect('clinics');
    }

Here if status is deactive its going inside that loop and priiting variable here. But the problem is that is status is active , it is not going inside status=active  case, it is going inside deactive case.

I have also printed to check wether recievd status is correct.but is correct and not going inside the loop

Kindly help

Body:
Please use == for comparison

public function deactivate($id , $status)
    {

        $input_data['id'] = $id;
        $clinic = new Clinic;
        $clinc = Clinic::find($id);
        if ($status=="deactive") {
            $clinc->ClinicPub = "no";
        }
       else if ($status=="active")
        {
            $clinc->ClinicPub = "yes";
        }
        if($clinc->save()){
            Session::flash('message', 'Clinic Deactivated Sucessfully');
            Session::flash('msgclass', 'alert-success');
        }
        return redirect('clinics');
    }


问:
Removing substring of from a list of strings
There are several countries with numbers and/or parenthesis in my list. How I  remove these?

e.g.

'Bolivia (Plurinational State of)' should be 'Bolivia',

'Switzerland17' should be 'Switzerland'.

答:
Use Series.str.replace with regex for replacement, \s* is for possible spaces before (, then \(.*\) is for values () and values between | is for regex or and \d+ is for numbers with 1 or more digits:

```<code>df = pd.DataFrame({'a':['Bolivia (Plurinational State of)','Switzerland17']})

df['a'] = df['a'].str.replace('(\s*\(.*\)|\d+)','')
print (df)
             a
0      Bolivia
1  Switzerland
</code>```

Body:
Use Series.str.replace with regex for replacement, \s* is for possible spaces before (, then \(.*\) is for values () and values between | is for regex or and \d+ is for numbers with 1 or more digits:

df = pd.DataFrame({'a':['Bolivia (Plurinational State of)','Switzerland17']})

df['a'] = df['a'].str.replace('(\s*\(.*\)|\d+)','')
print (df)
             a
0      Bolivia
1  Switzerland


问:
Linq to SQL and Entity Framework in Same project
I have a project that is using l2s. We are going to expand with new modules. Now we are thinking of using entity framework for new modules as it is not possible for us to change our existing modules to EF. Can some one share experiences of using both l2s and EF in same mvc project

Regards

答: There wont be any problem in using both of them in same project. Both have their own way to access data and will not conflict with each other. But I would suggest you to slowly migrate your data access to either one of these technology as having two data access methods in same project may lead to maintenance issue </p>


问:
What is an undefined reference/unresolved external symbol error and how do I fix it?
What are undefined reference/unresolved external symbol errors? What are common causes and how to fix/prevent them?</p>

答:
My example:

header file

```<code>class GameCharacter : public GamePart
{
    private:
        static vector<GameCharacter*> characterList;
...
}
</code>```

.cpp file:

```<code>vector<GameCharacter*> characterList;
</code>```

This produced an "undefined" loader error because "characterList" was declared as a static member variable, but was defined as a global variable.

I added this because -- while someone else listed this case in a long list of things to look out for -- that listing did not give examples. This is an example of something more to look for, especially in C++.

The fix is to add qualification to the global variable to define the static data member:

```<code>vector<GameCharacter*> GameCharacter::characterList;
</code>```

While keeping the header the same.

Body:
My example:

header file

class GameCharacter : public GamePart
{
    private:
        static vector<GameCharacter*> characterList;
...
}

.cpp file:

vector<GameCharacter*> characterList;

This produced an "undefined" loader error because "characterList" was declared as a static member variable, but was defined as a global variable.

I added this because -- while someone else listed this case in a long list of things to look out for -- that listing did not give examples. This is an example of something more to look for, especially in C++.

The fix is to add qualification to the global variable to define the static data member:

vector<GameCharacter*> GameCharacter::characterList;

While keeping the header the same.


问:
How does AWS DynamoDB count read units for Query?
I am working on a table, in which every item is approx. 3KB in size.

Now as per the docs, the read units are calculated in 4s - i.e. For every item less than 4 kb, it would be counted as 4KB, and occupy 1 read unit.

Let's say i have a table of 100 items, of 3kb each in size (total table = 300kb). I do a query, in which 50 items satisfy under the query condition, and they are returned to me.

Now, will the read units be counted like : 50 items of 3kb size (rounded to 4kb) = 200kb = 200/4 = 50 read units ?

Any help is appreciated! :) Thanks!

答:
I think this should clarify the issue:

Capacity Units Consumed by Query

DynamoDB calculates the number of read capacity units consumed based on item size, not on the amount of data that is returned to an application.

When you do the query, you can specify a parameter ReturnConsumedCapacity to get the number of read capacity units consumed:

TOTAL — The response includes the aggregate number of read capacity units consumed.

It also depends if you use eventually consistent reads (by default for query) or strongly consistent:

for eventually consistent reads (1 unit is 2 reads): 200 / 4 / 2 = 25 units

for strongly consistent reads (1 unit is 1 read): 200 / 4 / 1 = 50 units


问:
Minimum number of steps to convert one integer to another
Recently i came across a problem, given 2 integers A and B, we need to convert A to B in minimum number of steps.
We can perform following operations on A:

If A is odd, decrease by 1

If A is even, increase by 1

Multiply A(even or odd) by 2

if A is even, divide by 2

again, we have to find the minimum number of steps needed to convert A to B.

The constraints are 0 < A, B < 10^18

My approach:
I tried to solve the problem using Breadth First Search, adding all the possible reachable numbers from a step into a queue, but it fails on higher constraints i.e. time outs.

Can anyone suggest a faster alternative?

EDIT: A is not necessarily less than B

答:
Basically you have the following operations:

flip the lowest bit

shift bits to the left or to the right

Assume, you have A == 0, how you would construct B? Right, you flip the lower bit one by one and shift the number to the left, for example if B == 5, which is 0x0101, you will need 2 flips and 2 shifts.

Now, we have to deal with the case when A != 0 -- in this case you have to turn the lower bit to 0 and shift right to clean up the mess. For example, if you have A == 32, which is 0x0100000 and you want to get 5 (0x0101), you have to do three shifts to the right, then flip the lower bit and you're done.

So, all you have to do is to:

count how many flips/r-shifts you have to do until the highest bit of A is equal to the highest bit of B.

then count how many flips/r-shifts you need to clean up the rest

count how many flips/left-shifts you need to rebuild the lower part of B.

ok, a few hours passed, here's the solution. First a useful function, that says how many ops we need to create a number:

```<code>def bit_count(num) :
    # the number of non-zero bits in a number
    return bin(num).count('1')

def num_ops(num) :
    # number of shifts + number of flips
    return num.bit_length() + bit_count(num)
</code>```

Now, well, assume A > B, because otherwise we can swap them while keeping the number of the operations the same. Here's how far we have to shift A to make it start from the same bit as B:

```<code>needed_shifts = A.bit_length() - B.bit_length()
</code>```

while doing that we need to flip a few bits:

```<code>mask = (1 << (needed_shifts+1)) - 1
needed_flips = bit_count(A & mask)
</code>```

Now we count how many ops are required to clean A and rebuild B:

```<code>A >>= needed_shifts
clean_shifts = (A & ~B).bit_length()
clean_flips = bit_count(A & ~B)
rebuild_shifts = (B & ~A).bit_length()
rebuild.flips = bit_count(B & ~A)
</code>```

Finally we sum up all together:

```<code>result_ops = needed_shifts + needed_flips + max(clean_shifts,rebuild_shifts) * 2 + clean_flips + rebuils_flips
</code>```

That's all, folks! =)

Body:
Basically you have the following operations:

flip the lowest bit

shift bits to the left or to the right

Assume, you have A == 0, how you would construct B? Right, you flip the lower bit one by one and shift the number to the left, for example if B == 5, which is 0x0101, you will need 2 flips and 2 shifts.

Now, we have to deal with the case when A != 0 -- in this case you have to turn the lower bit to 0 and shift right to clean up the mess. For example, if you have A == 32, which is 0x0100000 and you want to get 5 (0x0101), you have to do three shifts to the right, then flip the lower bit and you're done.

So, all you have to do is to:

count how many flips/r-shifts you have to do until the highest bit of A is equal to the highest bit of B.

then count how many flips/r-shifts you need to clean up the rest

count how many flips/left-shifts you need to rebuild the lower part of B.

ok, a few hours passed, here's the solution. First a useful function, that says how many ops we need to create a number:

def bit_count(num) :
    # the number of non-zero bits in a number
    return bin(num).count('1')

def num_ops(num) :
    # number of shifts + number of flips
    return num.bit_length() + bit_count(num)

Now, well, assume A > B, because otherwise we can swap them while keeping the number of the operations the same. Here's how far we have to shift A to make it start from the same bit as B:

needed_shifts = A.bit_length() - B.bit_length()

while doing that we need to flip a few bits:

mask = (1 << (needed_shifts+1)) - 1
needed_flips = bit_count(A & mask)

Now we count how many ops are required to clean A and rebuild B:

A >>= needed_shifts
clean_shifts = (A & ~B).bit_length()
clean_flips = bit_count(A & ~B)
rebuild_shifts = (B & ~A).bit_length()
rebuild.flips = bit_count(B & ~A)

Finally we sum up all together:

result_ops = needed_shifts + needed_flips + max(clean_shifts,rebuild_shifts) * 2 + clean_flips + rebuils_flips

That's all, folks! =)


问:
Rounding down to 2 decimal places in c#
How can I multiply two decimals and round the result down to 2 decimal places?

For example if the equation is 41.75 x 0.1 the result will be 4.175. If I do this in c# with decimals it will automatically round up to 4.18. I would like to round down to 4.17.

I tried using Math.Floor but it just rounds down to 4.00. Here is an example:

```<code>Math.Floor (41.75 * 0.1);
</code>```

答:
This is my Float-Proof Round Down.</p>

```<code>    public static class MyMath
{
    public static double RoundDown(double number, int decimalPlaces)
    {
        string pr = number.ToString();
        string[] parts = pr.Split('.');
        char[] decparts = parts[1].ToCharArray();
        parts[1] = "";
        for (int i = 0; i < decimalPlaces; i++)
        {
            parts[1] += decparts[i];
        }
        pr = string.Join(".", parts);
        return Convert.ToDouble(pr);
    }
}
</code>```

Title: Rounding down to 2 decimal places in c#

Body:
How can I multiply two decimals and round the result down to 2 decimal places?

For example if the equation is 41.75 x 0.1 the result will be 4.175. If I do this in c# with decimals it will automatically round up to 4.18. I would like to round down to 4.17.

I tried using Math.Floor but it just rounds down to 4.00. Here is an example:

Math.Floor (41.75 * 0.1);

Body:
This is my Float-Proof Round Down.

    public static class MyMath
{
    public static double RoundDown(double number, int decimalPlaces)
    {
        string pr = number.ToString();
        string[] parts = pr.Split('.');
        char[] decparts = parts[1].ToCharArray();
        parts[1] = "";
        for (int i = 0; i < decimalPlaces; i++)
        {
            parts[1] += decparts[i];
        }
        pr = string.Join(".", parts);
        return Convert.ToDouble(pr);
    }
}


问:
Axios post request renders entire file contents as response instead of executing serverside file
I am trying to send gmail using nodemmailer and axios in react application. But the response i get is the entire file contents. Any help is greatly appreciated. Thank you.

Here is my frontend axios post request. THis request is working fine its returing 200 status code. The problem is with the response.

```<code>const axios = require('axios');
 axios({
            method: "POST",
            url:"https://localhost/mail",
            data: {
                recepients: recepients,
                msgbody: msgbody,
                msgsubject: msgsubject
            }
        }).then((response)=>{
            if (response.data.msg === 'success'){
                console.log("Message Sent.");
               // this.resetForm()
            }else if(response.data.msg === 'fail'){
                console.log("Message failed to send.")
            }
        });
</code>```

This is my mail.js file.

```<code>    const express = require('express')
    const app = express();
    var nodemailer = require('nodemailer');

    var transport = {
      host: 'smtp.gmail.com',
      port: 587,
      domain:'gmail.com',
      secure:false,
      auth: {
        user: 'info@gmail.com',
        pass: 'password'
      }
    }

    var transporter = nodemailer.createTransport(transport)

    transporter.verify((error, success) => {
      if (error) {
        console.log(error);
      } else {
        console.log('Server is ready to take messages');
      }
    });

    app.post('/mail', (req, res, next) => {
      var name = "sender";
      var email = req.body.email;
      var message = req.body.message;

      var mail = {
        from: name,
        to: 'sender@gmail.com',  //Change to email address that you want to receive messages on
        subject: 'New Message from Contact Form',
        text: 'hi'
      }

      transporter.sendMail(mail, (err, data) => {
        if (err) {
          res.json({msg: 'fail'});
        } else {
          res.json({msg: 'success'});
        }
      }

)
});
</code>```

This file does not get executed. This same file content i get as response. Anyone please help with this problem. Thanks in advance.

This is my app.js file.

/* application specific logic */

```<code>import 'jquery';
import 'jquery-contextmenu';
import 'jQuery-Impromptu';

import conference from './conference';
import API from './modules/API';
import keyboardshortcut from './modules/keyboardshortcut/keyboardshortcut';
import remoteControl from './modules/remotecontrol/RemoteControl';
import translation from './modules/translation/translation';
import UI from './modules/UI/UI';
import axios from 'axios';

window.APP = {
    API,
    conference,

    // Used by do_external_connect.js if we receive the attach data after
    // connect was already executed. status property can be 'initialized',
    // 'ready', or 'connecting'. We are interested in 'ready' status only which
    // means that connect was executed but we have to wait for the attach data.
    // In status 'ready' handler property will be set to a function that will
    // finish the connect process when the attach data or error is received.
    connect: {
        handler: null,
        status: 'initialized'
    },

    // Used for automated performance tests.
    connectionTimes: {
        'index.loaded': window.indexLoadedTime
    },

    keyboardshortcut,
    remoteControl,
    translation,
    UI
};

// TODO The execution of the mobile app starts from react/index.native.js.
// Similarly, the execution of the Web app should start from react/index.web.js
// for the sake of consistency and ease of understanding. Temporarily though
// because we are at the beginning of introducing React into the Web app, allow
// the execution of the Web app to start from app.js in order to reduce the
// complexity of the beginning step.
import './react'
</code>```

;

答:
The issue is you have added mail.js file to public directory.

app.use('/static', express.static(path.join(__dirname, 'public')))

So what is happening is when ever you hit https://localhost/mail it is resolving any file matching in public and serving content.

Make sure you don't add it in public directory. or anyother directory which is used to add client side code.

Body:
I am trying to send gmail using nodemmailer and axios in react application. But the response i get is the entire file contents. Any help is greatly appreciated. Thank you.

Here is my frontend axios post request. THis request is working fine its returing 200 status code. The problem is with the response.

const axios = require('axios');
 axios({
            method: "POST",
            url:"https://localhost/mail",
            data: {
                recepients: recepients,
                msgbody: msgbody,
                msgsubject: msgsubject
            }
        }).then((response)=>{
            if (response.data.msg === 'success'){
                console.log("Message Sent.");
               // this.resetForm()
            }else if(response.data.msg === 'fail'){
                console.log("Message failed to send.")
            }
        });

This is my mail.js file.

    const express = require('express')
    const app = express();
    var nodemailer = require('nodemailer');

    var transport = {
      host: 'smtp.gmail.com',
      port: 587,
      domain:'gmail.com',
      secure:false,
      auth: {
        user: 'info@gmail.com',
        pass: 'password'
      }
    }

    var transporter = nodemailer.createTransport(transport)

    transporter.verify((error, success) => {
      if (error) {
        console.log(error);
      } else {
        console.log('Server is ready to take messages');
      }
    });

    app.post('/mail', (req, res, next) => {
      var name = "sender";
      var email = req.body.email;
      var message = req.body.message;

      var mail = {
        from: name,
        to: 'sender@gmail.com',  //Change to email address that you want to receive messages on
        subject: 'New Message from Contact Form',
        text: 'hi'
      }

      transporter.sendMail(mail, (err, data) => {
        if (err) {
          res.json({msg: 'fail'});
        } else {
          res.json({msg: 'success'});
        }
      }

)
});

This file does not get executed. This same file content i get as response. Anyone please help with this problem. Thanks in advance.

This is my app.js file.

/* application specific logic */

import 'jquery';
import 'jquery-contextmenu';
import 'jQuery-Impromptu';

import conference from './conference';
import API from './modules/API';
import keyboardshortcut from './modules/keyboardshortcut/keyboardshortcut';
import remoteControl from './modules/remotecontrol/RemoteControl';
import translation from './modules/translation/translation';
import UI from './modules/UI/UI';
import axios from 'axios';

window.APP = {
    API,
    conference,

    // Used by do_external_connect.js if we receive the attach data after
    // connect was already executed. status property can be 'initialized',
    // 'ready', or 'connecting'. We are interested in 'ready' status only which
    // means that connect was executed but we have to wait for the attach data.
    // In status 'ready' handler property will be set to a function that will
    // finish the connect process when the attach data or error is received.
    connect: {
        handler: null,
        status: 'initialized'
    },

    // Used for automated performance tests.
    connectionTimes: {
        'index.loaded': window.indexLoadedTime
    },

    keyboardshortcut,
    remoteControl,
    translation,
    UI
};

// TODO The execution of the mobile app starts from react/index.native.js.
// Similarly, the execution of the Web app should start from react/index.web.js
// for the sake of consistency and ease of understanding. Temporarily though
// because we are at the beginning of introducing React into the Web app, allow
// the execution of the Web app to start from app.js in order to reduce the
// complexity of the beginning step.
import './react'

;


问:
How to append some MP3s in Qt?
How to append some MP3s in Qt by C++?

Assume I have 1.mp3 and 2.mp3, now I want to join them by Qt.

3.mp3 = 1.mp3 + 2.mp3

答: Qt is a user interface library, not a swiss army knife. It doesn't process MP3s; nor does it make you breakfast. You will need to use an appropriate library or tool for this task.</p>

Title: How to append some MP3s in Qt?


问:
Get FCIV to scan hidden files within a batch script
I am attempting to hash all or most of the files off of a machine using a batch script.  What I thought would be straight forward was of course not as FCIV will not scan hidden files.  I attempted to make a for loop that would scan the individual files themselves but what works in the command line does not work in the batch file.

I would go to the root of my drive and attempt this:

```<code>FCIV -r -both c:\
</code>```

However I noticed that quite a few files were missing (even as admin) with most of them being hidden files.

Thanks,
Any help would be appreciated.

答:
I use this snippet of the code for CertUtil, it might also work for FCIV

```<code>cd /d %targetDir%
for /r %%e in (*) do (
    if exist "\\?\%%e" (
        FOR /F "tokens=* USEBACKQ" %%F IN (`certutil -hashfile "\\?\%%e" %hashType% ^| findstr /v "certutil hash"`) DO (SET var=%%F)
        echo !var! "%%e" >> %hashDatabaseOutput%
        SET /A fileCount += 1
    ) else (
        echo ERROR 1 - Failed to Hash file, File or Directory contains special characters >> %errorlog%
        echo %%e >> %errorlog%
        echo.>> %errorlog%
    )
)
cd /d "%workingDir%"
</code>```

I have a similar issue as you, I'm scanning some files in C:\ but those aren't hidden files.

EDIT: Seems that using this method makes no difference because even when the file path that is feed to FCIV, the hashing will fail because it cannot find the file. you can look at my question here https://stackoverflow.com/questions/62111957/fciv-fails-to-find-some-files-when-hashing-c-drive

EDIT2: Found the root cause, it's caused by redirection when you attempting to scan files in C:\Windows\System32. One guy explained it clearly here
The system cannot find the path specified

Since FCIV only have 32bit mode, the only solution is to use other hashing program like rHash with 64bit.

Body:
I am attempting to hash all or most of the files off of a machine using a batch script.  What I thought would be straight forward was of course not as FCIV will not scan hidden files.  I attempted to make a for loop that would scan the individual files themselves but what works in the command line does not work in the batch file.

I would go to the root of my drive and attempt this:

FCIV -r -both c:\

However I noticed that quite a few files were missing (even as admin) with most of them being hidden files.

Thanks,
Any help would be appreciated.

Body:
I use this snippet of the code for CertUtil, it might also work for FCIV

cd /d %targetDir%
for /r %%e in (*) do (
    if exist "\\?\%%e" (
        FOR /F "tokens=* USEBACKQ" %%F IN (`certutil -hashfile "\\?\%%e" %hashType% ^| findstr /v "certutil hash"`) DO (SET var=%%F)
        echo !var! "%%e" >> %hashDatabaseOutput%
        SET /A fileCount += 1
    ) else (
        echo ERROR 1 - Failed to Hash file, File or Directory contains special characters >> %errorlog%
        echo %%e >> %errorlog%
        echo.>> %errorlog%
    )
)
cd /d "%workingDir%"

I have a similar issue as you, I'm scanning some files in C:\ but those aren't hidden files.

EDIT: Seems that using this method makes no difference because even when the file path that is feed to FCIV, the hashing will fail because it cannot find the file. you can look at my question here https://stackoverflow.com/questions/62111957/fciv-fails-to-find-some-files-when-hashing-c-drive

EDIT2: Found the root cause, it's caused by redirection when you attempting to scan files in C:\Windows\System32. One guy explained it clearly here
The system cannot find the path specified

Since FCIV only have 32bit mode, the only solution is to use other hashing program like rHash with 64bit.


问:
Python : How to call csv files from the directory based on the list of items?
I have a list of items and I want to call only those csv files from the directory whose names are similar to the items in the list. I am doing something like below but its reading all the files from the directory. Please suggest.</p>

```<code>x_list = [ a,b,c,d]
files in directory = [a.csv, b.csv, c.csv, d.csv, e.csv, f.csv]

for files in os.listdir(dir + 'folder\\'):
    file_name = files[:files.find('.')]
    if file_name in x_list:
        print(file_name)
</code>```

答:
You can just open the CSVs on your list: This is what you could do:

# a b c d are names of CSVs without .csv extension
my_csvs_names =  'a b c d'.split()
my_csvs_folder = 'c/path/to/my_folder'

for csv_name in my_csvs_names:
    file_name = f'{my_csvs_folder}/{csv_name}.csv'
    try:
        with open(file_name, 'r') as f_in:
            for line in f_in:
                # do something with it
                print(line)

    except FileNotFoundError:
        print(f'{file_name} does not exist')
```

In doing something, you can append values to a variable or whatever you are trying to achieve.

Body:
I have a list of items and I want to call only those csv files from the directory whose names are similar to the items in the list. I am doing something like below but its reading all the files from the directory. Please suggest.

x_list = [ a,b,c,d]
files in directory = [a.csv, b.csv, c.csv, d.csv, e.csv, f.csv]

for files in os.listdir(dir + 'folder\\'):
    file_name = files[:files.find('.')]
    if file_name in x_list:
        print(file_name)

Body:
You can just open the CSVs on your list: This is what you could do:

# a b c d are names of CSVs without .csv extension
my_csvs_names =  'a b c d'.split()
my_csvs_folder = 'c/path/to/my_folder'

for csv_name in my_csvs_names:
    file_name = f'{my_csvs_folder}/{csv_name}.csv'
    try:
        with open(file_name, 'r') as f_in:
            for line in f_in:
                # do something with it
                print(line)

    except FileNotFoundError:
        print(f'{file_name} does not exist')

In doing something, you can append values to a variable or whatever you are trying to achieve.


问:
Is there a way to search just for the first coordinate in a list of tuples?
Assuming I have a list of tuples like the following:

a = [('a','b'), ('c','d'), ('e','f')]

If I were to execute this line 'a' in a I would get False.

Is there a way to tell python "search the just for the first argument and accept whatever in the second"?

So that I could search something like ('a', *) in a and get True?

答:
You can do it will list comprehension

```<code>a = [('a','b'), ('c','d'), ('e','f')]
'a' in [i[0] for i in a]
</code>```

Or for larger search

```<code>'a' in {i[0] for i in a}
</code>```

since finding an item in a set is way faster.

Both exprations will return

```<code>True
</code>```

Body:
You can do it will list comprehension

a = [('a','b'), ('c','d'), ('e','f')]
'a' in [i[0] for i in a]

Or for larger search

'a' in {i[0] for i in a}

since finding an item in a set is way faster.

Both exprations will return

True


问:
How to successfully upload video file to imgur using Swift and Alamofire?
This is my response from imgur:

```<code>{
  "status" : 200,
  "data" : {
    "errorCode" : null,
    "ticket" : "c4fb887c"
  },
  "success" : true
}
</code>```

How do I create a request?

```<code>let video = //here I have URL of video, for example: file:///private/var/mobile/Containers/Data/PluginKitPlugin/FAB4AFC7-56C6-4949-8938-31DCD65A13CB/tmp/trim.B31D7604-B991-4D89-AD61-18DE9D9FD7FD.MOV
let url = URL(string: "https://api.imgur.com/3/image")!
Alamofire.upload(multipartFormData: { multipart in
    if let video = image.video {
        let data = try! Data(contentsOf: video, options: .mappedIfSafe)
        multipart.append(data, withName: "video", fileName: "video.mp4", mimeType: "video/mp4")
    }
}, to: url, headers: headers, encodingCompletion: { result in
    if case .success(let upload, _, _) = result {
        upload.responseJSON { response in
            let json = JSON(response.data)
            print(json)
        }
    }
})

</code>```

What do I expect?

Some link to video

答:
All you need to do is to replace your url with:

```<code>let url = URL(string: "https://api.imgur.com/3/upload")!
</code>```

And then you will have a response like this:

```<code>{
  "data" : {
    "ad_url" : null,
    "mp4" : "https:\/\/i.imgur.com\/GD86Stz.mp4",
    "datetime" : 1590905085,
    "in_gallery" : false,
    "account_id" : null,
    "title" : null,
    "width" : 0,
    "height" : 0,
    "nsfw" : null,
    "bandwidth" : 0,
    "name" : "",
    "is_ad" : false,
    "size" : 0,
    "description" : null,
    "vote" : null,
    "views" : 0,
    "has_sound" : false,
    "ad_type" : null,
    "account_url" : null,
    "in_most_viral" : false,
    "link" : "https:\/\/i.imgur.com\/GD86Stz.mp4",
    "processing" : {
      "status" : "pending"
    },
    "deletehash" : "twCk1gbdjcp4FmH",
    "favorite" : false,
    "id" : "GD86Stz",
    "section" : null,
    "animated" : true,
    "type" : "video\/mp4",
    "tags" : [

    ],
    "hls" : ""
  },
  "status" : 200,
  "success" : true
}
</code>```

Body:
This is my response from imgur:

{
  "status" : 200,
  "data" : {
    "errorCode" : null,
    "ticket" : "c4fb887c"
  },
  "success" : true
}

How do I create a request?

let video = //here I have URL of video, for example: file:///private/var/mobile/Containers/Data/PluginKitPlugin/FAB4AFC7-56C6-4949-8938-31DCD65A13CB/tmp/trim.B31D7604-B991-4D89-AD61-18DE9D9FD7FD.MOV
let url = URL(string: "https://api.imgur.com/3/image")!
Alamofire.upload(multipartFormData: { multipart in
    if let video = image.video {
        let data = try! Data(contentsOf: video, options: .mappedIfSafe)
        multipart.append(data, withName: "video", fileName: "video.mp4", mimeType: "video/mp4")
    }
}, to: url, headers: headers, encodingCompletion: { result in
    if case .success(let upload, _, _) = result {
        upload.responseJSON { response in
            let json = JSON(response.data)
            print(json)
        }
    }
})

What do I expect?

Some link to video

Body:
All you need to do is to replace your url with:

let url = URL(string: "https://api.imgur.com/3/upload")!

And then you will have a response like this:

{
  "data" : {
    "ad_url" : null,
    "mp4" : "https:\/\/i.imgur.com\/GD86Stz.mp4",
    "datetime" : 1590905085,
    "in_gallery" : false,
    "account_id" : null,
    "title" : null,
    "width" : 0,
    "height" : 0,
    "nsfw" : null,
    "bandwidth" : 0,
    "name" : "",
    "is_ad" : false,
    "size" : 0,
    "description" : null,
    "vote" : null,
    "views" : 0,
    "has_sound" : false,
    "ad_type" : null,
    "account_url" : null,
    "in_most_viral" : false,
    "link" : "https:\/\/i.imgur.com\/GD86Stz.mp4",
    "processing" : {
      "status" : "pending"
    },
    "deletehash" : "twCk1gbdjcp4FmH",
    "favorite" : false,
    "id" : "GD86Stz",
    "section" : null,
    "animated" : true,
    "type" : "video\/mp4",
    "tags" : [

    ],
    "hls" : ""
  },
  "status" : 200,
  "success" : true
}


问:
What is the difference between "wait-die" and "wound-wait" deadlock prevention algorithms?
What is the difference between wait-die and wound-wait algorithms?

It seems that both of these deadlock prevention techniques are doing the same thing: A Rollback of older process.

What is the difference between the two?

Please provide a suitable example to contrast the two algorithms.

答:
The best way to understand two related topics can be achieved by comparison. So,
Similarity between wait-die and wound-wait:

The older transaction will "win" over the newer transaction.

When transactions restart, they keep their timestamps.

Eventually, the aborted (younger) transactions will become the oldest transactions in the system.

Difference between wait-die and wound wait:

In wait-die, The newer transactions are killed when the newer transaction makes a request for a lock being held by an older transactions.

In wound-wait, The newer transactions are killed when an older transaction makes a request for a lock being held by the newer transactions.


问:
Can javascript be used to delegate events to a native android application?
Is it possible to invoke a method or a function of a running android application using javascript?? OR Is there a possible way to communicate between Javascript and native android application??</p>

答: Yes, there's such a method. Just use the WebView.addJavascriptInterface() method. It creates a javascript variable which is bound to a java object. You'll be able to call methods of this object from your javascript code.


问:
Two identical messages are received at the same time as push notifications through FCM
I'm using Vue.js and FCM to implement WebPush notification. However when I test it, I receive one notification from the Firebase and TWO IDENTICAL PUSH NOTIFICATIONS that are received by the client regardless of browser or device.

Please any help will be highly appreciated!

The following is the excerpt of the JS.

```<code>const messaging = firebase.messaging();

function showNotification(data) {
    console.log(data);
    var title = data.notification.title;
    var tag = 'push';

    return self.registration.showNotification(title, {
        icon: data.notification.icon,
        body: data.notification.body,
        data: data.data,
        vibrate: [400,100,400],
        tag: tag
    });
}

self.addEventListener('install', (event) => {
    event.waitUntil(self.skipWaiting());
});

function receivePush(event) {

    console.log("receivePush");
    console.log(event.data.json());
    if(event.data) {
        data = event.data.json();
    }
    if('showNotification' in self.registration) {
        event.waitUntil(showNotification(data));
    }
}

function notificationClick(event) {
    event.notification.close();
    event.waitUntil(
        clients.openWindow(event.notification.data.url)
    );
    addClickCount(event.notification.data.record_id);
}

function addClickCount (record_id) {
    var api_url = 'https://' + location.host + '/_app/api/auth/push';
    fetch(api_url, {
        method: 'POST',
        mode: 'cors',
        headers: {
          'Accept': 'application/json',
          'content-type': 'application/json',
        },
        body: JSON.stringify({id: record_id}),
    })
    .then(response => response.text())
    .then(text => console.log(text));
}

self.addEventListener('push', receivePush, false);
self.addEventListener('notificationclick', notificationClick, false);
</code>```

The following is the excerpt of the token.

```<code><template>
        <div class="column-btn">
          <div class="col">
            <div class="btn btn-white">
              <a
                href="javascript:void(0);"
                class="btnItem push-yes"
                style="background:none"
                >Yes</a
              >
            </div>
          </div>
          <div class="col">
            <div class="btn btn-white">
              <a
                href="javascript:void(0);"
                class="btnItem push-no"
                style="background:none"
                >No</a
              >
            </div>
          </div>
</template>

export default {
  methods: {
  },
  mounted() {
    var pData = this.$parent;
    var thisData = this;
    $(document).on('click', '.push-yes', function() {
      pData.permission_off();
      thisData.modalClose();
    });
    $(document).on('click', '.push-no', function() {
      thisData.modalClose();
    });
  },
};
</code>```

答:
There are clear steps in FCM what code to add to Service Worker firebase-messaging-sw.js (https://firebase.google.com/docs/cloud-messaging/js/receive):

```<code>messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});
</code>```

I've implemented as written there and it's working just fine :)

Body:
I'm using Vue.js and FCM to implement WebPush notification. However when I test it, I receive one notification from the Firebase and TWO IDENTICAL PUSH NOTIFICATIONS that are received by the client regardless of browser or device.

Please any help will be highly appreciated!

The following is the excerpt of the JS.

const messaging = firebase.messaging();

function showNotification(data) {
    console.log(data);
    var title = data.notification.title;
    var tag = 'push';

    return self.registration.showNotification(title, {
        icon: data.notification.icon,
        body: data.notification.body,
        data: data.data,
        vibrate: [400,100,400],
        tag: tag
    });
}

self.addEventListener('install', (event) => {
    event.waitUntil(self.skipWaiting());
});

function receivePush(event) {

    console.log("receivePush");
    console.log(event.data.json());
    if(event.data) {
        data = event.data.json();
    }
    if('showNotification' in self.registration) {
        event.waitUntil(showNotification(data));
    }
}

function notificationClick(event) {
    event.notification.close();
    event.waitUntil(
        clients.openWindow(event.notification.data.url)
    );
    addClickCount(event.notification.data.record_id);
}

function addClickCount (record_id) {
    var api_url = 'https://' + location.host + '/_app/api/auth/push';
    fetch(api_url, {
        method: 'POST',
        mode: 'cors',
        headers: {
          'Accept': 'application/json',
          'content-type': 'application/json',
        },
        body: JSON.stringify({id: record_id}),
    })
    .then(response => response.text())
    .then(text => console.log(text));
}

self.addEventListener('push', receivePush, false);
self.addEventListener('notificationclick', notificationClick, false);

The following is the excerpt of the token.

<template>

              Yes

              No

</template>

export default {
  methods: {
  },
  mounted() {
    var pData = this.$parent;
    var thisData = this;
    $(document).on('click', '.push-yes', function() {
      pData.permission_off();
      thisData.modalClose();
    });
    $(document).on('click', '.push-no', function() {
      thisData.modalClose();
    });
  },
};

Body:
There are clear steps in FCM what code to add to Service Worker firebase-messaging-sw.js (https://firebase.google.com/docs/cloud-messaging/js/receive):

messaging.setBackgroundMessageHandler(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  return self.registration.showNotification(notificationTitle,
    notificationOptions);
});

I've implemented as written there and it's working just fine :)


问:
What are the parameters in arow function in JS?
please help the newbie figure it out.

There is such a code:

```<code>    function makeDouble (x) {
      return x * 2;
   }
    var doMath = (x, func) => func(x + 5);

   var num = 5;
</code>```

The task is:

*Using only makeDouble, doMath, and num, make the value of num equal to 20.

num = _____________________________________________________*

I can’t understand why there are two parameters in the parameters of an arrow function, but in the body of this function itself there is only one parameter. What am I doing wrong?

答:
The answer is
num = doMath(num, makeDouble)

There are also 2 parameters in the body of the function.
Let's look a little bit closer
func(x+5)

func is a second parameter of the function and x that we pass to it is a first parameter

Body:
please help the newbie figure it out.

There is such a code:

    function makeDouble (x) {
      return x * 2;
   }
    var doMath = (x, func) => func(x + 5);

   var num = 5;

The task is:

*Using only makeDouble, doMath, and num, make the value of num equal to 20.

num = _____________________________________________________*

I can’t understand why there are two parameters in the parameters of an arrow function, but in the body of this function itself there is only one parameter. What am I doing wrong?


答:
Here, func is a callback function. In javascript, you can pass a function as a parameter just like you pass any other variable, for e.g, an integer, object or an array. So here in doMatch you're passing a number and a callback function. When doMatch executes, it calls func with the parameter 10 (5+5). Func, now, will be executed and will return 2*10 (20)

  function makeDouble (x) {
      return x * 2;
   }
    var doMath = (x, func) => func(x + 5);

   var num = 5;

console.log(doMath(num, makeDouble))```


问:
How to convert ImageSource to Byte array?
I use LeadTools for scanning.

I want to convert scanning image to byte.

```<code>void twainSession_AcquirePage(object sender, TwainAcquirePageEventArgs e)
 {
   ScanImage = e.Image.Clone();
   ImageSource source = RasterImageConverter.ConvertToSource(ScanImage, ConvertToSourceOptions.None);
 }
</code>```

How to convert ImageSource to Byte array?

答:
If you are using Xamarin, you can use this:</p>
```<code>public async Task<byte[]> ConvertImageSourceToBytesAsync(ImageSource imageSource)
{
    Stream stream = await ((StreamImageSource)imageSource).Stream(CancellationToken.None);
    byte[] bytesAvailable = new byte[stream.Length];
    stream.Read(bytesAvailable, 0, bytesAvailable.Length);

    return bytesAvailable;
}
</code>```

Body:
I use LeadTools for scanning.

I want to convert scanning image to byte.

void twainSession_AcquirePage(object sender, TwainAcquirePageEventArgs e)
 {
   ScanImage = e.Image.Clone();
   ImageSource source = RasterImageConverter.ConvertToSource(ScanImage, ConvertToSourceOptions.None);
 }

How to convert ImageSource to Byte array?

Body:
If you are using Xamarin, you can use this:

public async Task<byte[]> ConvertImageSourceToBytesAsync(ImageSource imageSource)
{
    Stream stream = await ((StreamImageSource)imageSource).Stream(CancellationToken.None);
    byte[] bytesAvailable = new byte[stream.Length];
    stream.Read(bytesAvailable, 0, bytesAvailable.Length);

    return bytesAvailable;
}


问:
PHP not displaying username after login
I'm learning php and html from scratch, and I have this project in which I'd like to display the username after logging in.

I've stated that:

```<code><a>Hello, <?php
                        if(isset($_SESSION['username'])){
                            echo $_SESSION['username'];
                        } else {
                            echo "user";
                        }

                        ?>
                        </a>
</code>```

at the html field in which I want the username to show. It worked before.
However, after logging out, the username is no longer there.

This is the code for the logout:

```<code><?php

     session_start();
     session_unset();
     header("location:index.php");
     exit();

?>
</code>```

And the one for logging in:

```<code><?php
session_start();

$user = $_POST['login'];
$pass = md5($_POST['pword']);
$entrar = $_POST['entrar'];
$conn = mysqli_connect("localhost","root", "", "pdsys", "3308");

if(isset($entrar)){
    $verifica = mysqli_query($conn,"SELECT * FROM users WHERE username = '$user' AND pword = '$pass'") or die ("Usuário ou senha incorretos");
    if (mysqli_num_rows($verifica)<=0){
        echo "<script language='javascript' type='text/javascript'>
        alert('Login e/ou senha incorretos');window.location
        .href='index.php';</script>";
        die();
    } else {
        setcookie("login", $user);
        header("location: main.php");
    }
}?>
</code>```

I figure it might have something to do with the session_destroy(), but I can't figure it out how to make it work again. It just displays "user".

Everything else is functional = the connection with the database, the login system etc.

答:
Worked it out by adding a line to set the value of session username:</p>

```<code><?php
session_start();

$user = $_POST['login'];
$pass = md5($_POST['pword']);
$entrar = $_POST['entrar'];
$conn = mysqli_connect("localhost","root", "", "pdsys", "3308");

if(isset($entrar)){
    $verifica = mysqli_query($conn,"SELECT * FROM users WHERE username = '$user' AND pword = '$pass'") or die ("Usuário ou senha incorretos");
    if (mysqli_num_rows($verifica)<=0){
        echo "<script language='javascript' type='text/javascript'>
        alert('Login e/ou senha incorretos');window.location
        .href='index.php';</script>";
        die();
    } else {
        setcookie("login", $user);
        $_SESSION['username']=$user;
        header("location: main.php");
    }
}?>
</code>```

Title: PHP not displaying username after login

Body:
I'm learning php and html from scratch, and I have this project in which I'd like to display the username after logging in.

I've stated that:

Hello, <?php
                        if(isset($_SESSION['username'])){
                            echo $_SESSION['username'];
                        } else {
                            echo "user";
                        }

                        ?>

at the html field in which I want the username to show. It worked before.
However, after logging out, the username is no longer there.

This is the code for the logout:

<?php

     session_start();
     session_unset();
     header("location:index.php");
     exit();

?>

And the one for logging in:

<?php
session_start();

$user = $_POST['login'];
$pass = md5($_POST['pword']);
$entrar = $_POST['entrar'];
$conn = mysqli_connect("localhost","root", "", "pdsys", "3308");

if(isset($entrar)){
    $verifica = mysqli_query($conn,"SELECT * FROM users WHERE username = '$user' AND pword = '$pass'") or die ("Usuário ou senha incorretos");
    if (mysqli_num_rows($verifica)<=0){
        echo "";
        die();
    } else {
        setcookie("login", $user);
        header("location: main.php");
    }
}?>

I figure it might have something to do with the session_destroy(), but I can't figure it out how to make it work again. It just displays "user".

Everything else is functional = the connection with the database, the login system etc.

Body:
Worked it out by adding a line to set the value of session username:

<?php
session_start();

$user = $_POST['login'];
$pass = md5($_POST['pword']);
$entrar = $_POST['entrar'];
$conn = mysqli_connect("localhost","root", "", "pdsys", "3308");

if(isset($entrar)){
    $verifica = mysqli_query($conn,"SELECT * FROM users WHERE username = '$user' AND pword = '$pass'") or die ("Usuário ou senha incorretos");
    if (mysqli_num_rows($verifica)<=0){
        echo "<script language='javascript' type='text/javascript'>
        alert('Login e/ou senha incorretos');window.location
        .href='index.php';</script>";
        die();
    } else {
        setcookie("login", $user);
        $_SESSION['username']=$user;
        header("location: main.php");
    }
}?>


问:
Repository Interface(s) in Domain-Driven Design
Regarding the contract between the domain and repository, I gather it's best to avoid an all-encompassing generic IRepository interface with methods such as Create() and Delete()?  Unless, of course, it's natural to have these methods available for all the entities I'm working with.  Which I imagine is a rare scenario.

Instead, should I create a basic IRepository contract with as many - perhaps "as few" would be more appropriate - common methods (e.g., GetByID()) as makes sense?  All repositories could implement the contract and then specialize.

Or is it better to go the route of multiple specialized interfaces, à la ICreatable, IDeletable, IRetrievable, etc.?

答:
Generic interfaces are useless, especially in DDD, because they hide otherwise explicit concepts. Imagine your command handler / application service constructor:

```<code>public SomeCommandHandler(IRepository customerRepository, IRepository userRepository)
</code>```

and compare to this:

```<code>public SomeCommandHandler(ICustomerRepository customerRepository, IUserRepository userRepository)
</code>```

The latter is far more explicit and explicitness is what you seek by doing DDD. Moreover, if your repositories have all the same methods, you are probably creating a CRUD data access layer which usually doesn't fit well with DDD.

Body:
Generic interfaces are useless, especially in DDD, because they hide otherwise explicit concepts. Imagine your command handler / application service constructor:

public SomeCommandHandler(IRepository customerRepository, IRepository userRepository)

and compare to this:

public SomeCommandHandler(ICustomerRepository customerRepository, IUserRepository userRepository)

The latter is far more explicit and explicitness is what you seek by doing DDD. Moreover, if your repositories have all the same methods, you are probably creating a CRUD data access layer which usually doesn't fit well with DDD.


问:
Authentication by passport jwt and appending the req object with an object name 'user'
When using authentication by passport-jwt, does it always appends the req object with an object named "user"? Where does this name "user" come from?

app.post('/profile',
    passport.authenticate('jwt', { session: false }),
    function(req, res) {
            res.send(req.user.profile);
    }
);
```

Does this code always append the req object with an object named "user"?
From where is this name "user" coming?

答:
This is the definition of passport.authenticate from passport source code line 12. So basically, passport.authenticate is a middleware it will do the data extraction and then bind data into req.user.

```<code>* Applies the `name`ed strategy (or strategies) to the incoming request, in
* order to authenticate the request.  If authentication is successful, the user
* will be logged in and populated at `req.user` and a session will be
* established by default.  If authentication fails, an unauthorized response
</code>```

Body:
When using authentication by passport-jwt, does it always appends the req object with an object named "user"? Where does this name "user" come from?

app.post('/profile',
    passport.authenticate('jwt', { session: false }),
    function(req, res) {
            res.send(req.user.profile);
    }
);

Does this code always append the req object with an object named "user"?
From where is this name "user" coming?

Body:
This is the definition of passport.authenticate from passport source code line 12. So basically, passport.authenticate is a middleware it will do the data extraction and then bind data into req.user.

* Applies the `name`ed strategy (or strategies) to the incoming request, in
* order to authenticate the request.  If authentication is successful, the user
* will be logged in and populated at `req.user` and a session will be
* established by default.  If authentication fails, an unauthorized response


问:
iOS7 UIScrollView contentInset not working
When the keyboard was hidden, the scrollview should back to it's origin contentInset, but it's not working in iOS7. Setting scrollview's contentInset when keyboard was shown is working but when the keyboard was hidden, the scrollview's contentInset can't set to inset zero.
The code:</p>

```<code>- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}

- (void)keyboardWasShown:(NSNotification *)notif
{
    CGSize keyboardSize = [[[notif userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0);

    UIScrollView *scrollView = (UIScrollView *)self.view;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;

    CGRect rect = self.view.frame;
    rect.size.height -= keyboardSize.height;
    if (!CGRectContainsPoint(rect, self.wishContentField.frame.origin)) {
        CGPoint point = CGPointMake(0, self.wishContentField.frame.origin.y - keyboardSize.height);
        [scrollView setContentOffset:point animated:YES];
    }

}
- (void)keyboardWasHidden:(NSNotification *)notif
{
    UIEdgeInsets zeroInsets = UIEdgeInsetsZero;
    UIScrollView *scrollView = (UIScrollView *)self.view;
    [scrollView setContentInset:zeroInsets];
    scrollView.scrollIndicatorInsets = zeroInsets;
}
</code>```

答: I also found that if you set a new contentinset exactly the same as the existing inset, the scrollview may ignore it and revert to a zero inset. So an easy workaround is to check that the new contentinset you are setting is at least 1 point different than the last.</p>

Body:
When the keyboard was hidden, the scrollview should back to it's origin contentInset, but it's not working in iOS7. Setting scrollview's contentInset when keyboard was shown is working but when the keyboard was hidden, the scrollview's contentInset can't set to inset zero.
The code:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:Nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}

- (void)keyboardWasShown:(NSNotification *)notif
{
    CGSize keyboardSize = [[[notif userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0);

    UIScrollView *scrollView = (UIScrollView *)self.view;
    scrollView.contentInset = contentInsets;
    scrollView.scrollIndicatorInsets = contentInsets;

    CGRect rect = self.view.frame;
    rect.size.height -= keyboardSize.height;
    if (!CGRectContainsPoint(rect, self.wishContentField.frame.origin)) {
        CGPoint point = CGPointMake(0, self.wishContentField.frame.origin.y - keyboardSize.height);
        [scrollView setContentOffset:point animated:YES];
    }

}
- (void)keyboardWasHidden:(NSNotification *)notif
{
    UIEdgeInsets zeroInsets = UIEdgeInsetsZero;
    UIScrollView *scrollView = (UIScrollView *)self.view;
    [scrollView setContentInset:zeroInsets];
    scrollView.scrollIndicatorInsets = zeroInsets;
}


答:
Try using any (will return True if any of the elements is logically True) with map (to compare each first element in your tuples):

```<code>any(map(lambda x: x[0] == "a", a)))
</code>```

Title: Is there a way to search just for the first coordinate in a list of tuples?

Body:
Assuming I have a list of tuples like the following:

a = [('a','b'), ('c','d'), ('e','f')]

If I were to execute this line 'a' in a I would get False.

Is there a way to tell python "search the just for the first argument and accept whatever in the second"?

So that I could search something like ('a', *) in a and get True?

Body:
Try using any (will return True if any of the elements is logically True) with map (to compare each first element in your tuples):

any(map(lambda x: x[0] == "a", a)))


问:
How to optimize the query? t-sql
This query works about 3 minutes and returns 7279 rows:

```<code>SELECT identity(int,1,1) as id, c.client_code, a.account_num,
        c.client_short_name, u.uso, us.fio, null as new, null as txt
INTO #ttable
FROM accounts a INNER JOIN Clients c ON
    c.id = a.client_id INNER JOIN Uso u ON c.uso_id = u.uso_id INNER JOIN
    Magazin m ON a.account_id = m.account_id LEFT JOIN Users us ON
    m.user_id = us.user_id
WHERE m.status_id IN ('1','5','9') AND m.account_new_num is null
    AND u.branch_id = @branch_id
ORDER BY c.client_code;
</code>```

The type of 'client_code' field is VARCHAR(6).

Is it possible to somehow optimize this query?

答:
Make sure there is an index on every field used in the JOINs and in the WHERE clause

If one or the tables you select from are actually views, the problem may be in the performance of these views.

Title: How to optimize the query? t-sql

Body:
This query works about 3 minutes and returns 7279 rows:

SELECT identity(int,1,1) as id, c.client_code, a.account_num,
        c.client_short_name, u.uso, us.fio, null as new, null as txt
INTO #ttable
FROM accounts a INNER JOIN Clients c ON
    c.id = a.client_id INNER JOIN Uso u ON c.uso_id = u.uso_id INNER JOIN
    Magazin m ON a.account_id = m.account_id LEFT JOIN Users us ON
    m.user_id = us.user_id
WHERE m.status_id IN ('1','5','9') AND m.account_new_num is null
    AND u.branch_id = @branch_id
ORDER BY c.client_code;

The type of 'client_code' field is VARCHAR(6).

Is it possible to somehow optimize this query?


答:
```<code>function makeDouble (x) {
  return x * 2;
}
const doMath = (x, func) => func(x + 5);

const num = 5;

let result = doMath(num, makeDouble);

console.log(result);// 20
</code>```

doMath(x, func) is an arrow function which takes two parameters. The first para meters is your numeric value, and the second is a function which in this case is makeDouble(x). Inside the arrow function, the makeDouble(x) function is called with the numeric parameter + 5 like makeDouble( num + 5). In this case, num is added five inside the constructor, so this time makeDouble returns the product of 10 * 2. Also, I would suggest to revise the use of var. Currently the use of let and const is preferred over var.

Arrow functions can take other functions as parameters, which is great to work with recursion and functional programming.

Body:
function makeDouble (x) {
  return x * 2;
}
const doMath = (x, func) => func(x + 5);

const num = 5;

let result = doMath(num, makeDouble);

console.log(result);// 20

doMath(x, func) is an arrow function which takes two parameters. The first para meters is your numeric value, and the second is a function which in this case is makeDouble(x). Inside the arrow function, the makeDouble(x) function is called with the numeric parameter + 5 like makeDouble( num + 5). In this case, num is added five inside the constructor, so this time makeDouble returns the product of 10 * 2. Also, I would suggest to revise the use of var. Currently the use of let and const is preferred over var.

Arrow functions can take other functions as parameters, which is great to work with recursion and functional programming.


问:
How to populate my Django Model 'updated_by' field with logged in User automatically using a formset?
I am a beginner with Django and I have been enjoying it so far. I figured out how to use model formsets, but I cannot figure out how to make my form automatically use logged in User as the 'updated_by' field.

models.py

```<code>class Inventory(models.Model):
    item = models.CharField(max_length=50, unique=True)
    stock = models.IntegerField()
    par = models.IntegerField()
    date_updated = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(User, on_delete=models.PROTECT)

    def __str__(self):
        return self.item

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    phone = PhoneField(blank='True', help_text='Contact Phone Number')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()
</code>```

答:
i think you should have made form for Inventory if yes(let InvntoryForm) than in view.py file you have done something like this:-</p>

```<code>    if request.method == 'POST':
      Inven_form=InventoryForm(data=request.POST)

       if Inven_form.is_valid():
           user=Inven_form.save()
           #in between add this
           Inven_form.updated_by=request.user.username
           user.save()
</code>```

Body:
I am a beginner with Django and I have been enjoying it so far. I figured out how to use model formsets, but I cannot figure out how to make my form automatically use logged in User as the 'updated_by' field.

models.py

class Inventory(models.Model):
    item = models.CharField(max_length=50, unique=True)
    stock = models.IntegerField()
    par = models.IntegerField()
    date_updated = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(User, on_delete=models.PROTECT)

    def __str__(self):
        return self.item

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    phone = PhoneField(blank='True', help_text='Contact Phone Number')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()

Body:
i think you should have made form for Inventory if yes(let InvntoryForm) than in view.py file you have done something like this:-

    if request.method == 'POST':
      Inven_form=InventoryForm(data=request.POST)

       if Inven_form.is_valid():
           user=Inven_form.save()
           #in between add this
           Inven_form.updated_by=request.user.username
           user.save()


问:
Multiple threads accessing same model on GPU for inference
I have a cnn model that is loaded onto the GPU and for every image, a new thread has to be created and detached to run the model on this image. Is this possible and if so, Is it safe?</p>

答:
Yes, you definitely can. There are two aspects to it. If you want to run each model in parallel, then you have to load the same model in multiple GPUs. If you don't need that (just want the threading part), then you can load the model and use concurrent.futures.ThreadPoolExecutor(). In each call, you can pass an image.

I demonstrated one example with the darknet framework.

I loaded the model in two separate GPUs (for parallel operation, you can avoid that too) and each time I get a request, I use ThreadPoolExecutor to pass the images to the processing function.

```<code>from darknet import *
import concurrent.futures
import time

# you can avoid this part if you don't need multiple GPUs
set_gpu(0) # running on GPU 0
net1 = load_net(b"cfg/yolov3-lp_vehicles.cfg", b"backup/yolov3-lp_vehicles.backup", 0)
meta1 = load_meta(b"data/lp_vehicles.data")

set_gpu(1) # running on GPU 1
net2 = load_net(b"cfg/yolov3-lp_vehicles.cfg", b"backup/yolov3-lp_vehicles.backup", 0)
meta2 = load_meta(b"data/lp_vehicles.data")

def f(x):
    if x[0] == 0: # gpu 0
        return detect_np_lp(net1, meta1, x[1])
    else:
        return detect_np_lp(net2, meta2, x[1])

def func2(): # with threading
    a1 = cv2.imread("lp_tester/bug1.jpg")
    a2 = cv2.imread("lp_tester/bug2.jpg")
    nums = [(0, a1), (1, a2)] # the first element in tuple denotes GPU ID
    with concurrent.futures.ThreadPoolExecutor() as executor:
        r_m = [val for val in executor.map(f, nums)]
    print('out f2')
    #return r_m

t1 = time.time()
func2()
t2 = time.time()
print(t2-t1)
</code>```

Body:
Yes, you definitely can. There are two aspects to it. If you want to run each model in parallel, then you have to load the same model in multiple GPUs. If you don't need that (just want the threading part), then you can load the model and use concurrent.futures.ThreadPoolExecutor(). In each call, you can pass an image.

I demonstrated one example with the darknet framework.

I loaded the model in two separate GPUs (for parallel operation, you can avoid that too) and each time I get a request, I use ThreadPoolExecutor to pass the images to the processing function.

from darknet import *
import concurrent.futures
import time

# you can avoid this part if you don't need multiple GPUs
set_gpu(0) # running on GPU 0
net1 = load_net(b"cfg/yolov3-lp_vehicles.cfg", b"backup/yolov3-lp_vehicles.backup", 0)
meta1 = load_meta(b"data/lp_vehicles.data")

set_gpu(1) # running on GPU 1
net2 = load_net(b"cfg/yolov3-lp_vehicles.cfg", b"backup/yolov3-lp_vehicles.backup", 0)
meta2 = load_meta(b"data/lp_vehicles.data")

def f(x):
    if x[0] == 0: # gpu 0
        return detect_np_lp(net1, meta1, x[1])
    else:
        return detect_np_lp(net2, meta2, x[1])

def func2(): # with threading
    a1 = cv2.imread("lp_tester/bug1.jpg")
    a2 = cv2.imread("lp_tester/bug2.jpg")
    nums = [(0, a1), (1, a2)] # the first element in tuple denotes GPU ID
    with concurrent.futures.ThreadPoolExecutor() as executor:
        r_m = [val for val in executor.map(f, nums)]
    print('out f2')
    #return r_m

t1 = time.time()
func2()
t2 = time.time()
print(t2-t1)


问:
jquery ajax sends an array of objects as an object with index keys. How can I stop this?
Let's say I have var data = {name: "Something", coords: [{lat: 23.23, lng: 123.123}]}

I send it like this:

```<code>$.ajax({
            url: "/endpoint",
            type: "POST",
            dataType: "json",
            data: data,
            success: function(response){
                console.log(response);
            }
        });
</code>```

When looking at what I get server side, I see this.

```<code>%{
  "coords" => %{"0" => %{"lat" => "23.23", "lng" => "123.123"}},
  "name" => "Something",
}
</code>```

Why is [{lat: .., lng: ...}] getting converted to {0: {lat: ..., lng: ...}}? How can I stop this? Is this a jquery thing?

答:
When you send your data to the https://jsonplaceholder.typicode.com bounce-back dummy JSON-server you can see exactly how your data arrives there. Instead of sending the embedded array inside your structure as a whole (=array) its indiviudal elements are sent with their full keys "coords[0][lat]" and "coords[0][lng]":

```<code>{
  "name": "Something",
  "coords[0][lat]": "23.23",
  "coords[0][lng]": "123.123",
  "id": 101
}
</code>```

var data = {name: "Something", coords: [{lat: 23.23, lng: 123.123}]}
$.ajax({
  url: "https://jsonplaceholder.typicode.com/posts",
  type: "POST",
  dataType: "json",
  data: data,
  success: function(response){console.log(response);}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

If you want to avoid that behaviour you will have to send the object as a JSON-encoded string and (explicitly!) decode it on the receiving end:

var data = {name: "Something", coords: [{lat: 23.23, lng: 123.123}]}
$.ajax({
  url: "https://jsonplaceholder.typicode.com/posts",
  type: "POST",
  dataType: "json",
  data: {d: JSON.stringify(data)},
  success: function(response){console.log(JSON.parse(response.d));}
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></code>```

This will give you:

```<code>{
  "name": "Something",
  "coords": [
    {
      "lat": 23.23,
      "lng": 123.123
    }
  ]
}
</code>```

Body:
Let's say I have var data = {name: "Something", coords: [{lat: 23.23, lng: 123.123}]}

I send it like this:

$.ajax({
            url: "/endpoint",
            type: "POST",
            dataType: "json",
            data: data,
            success: function(response){
                console.log(response);
            }
        });

When looking at what I get server side, I see this.

%{
  "coords" => %{"0" => %{"lat" => "23.23", "lng" => "123.123"}},
  "name" => "Something",
}

Why is [{lat: .., lng: ...}] getting converted to {0: {lat: ..., lng: ...}}? How can I stop this? Is this a jquery thing?

Body:
When you send your data to the https://jsonplaceholder.typicode.com bounce-back dummy JSON-server you can see exactly how your data arrives there. Instead of sending the embedded array inside your structure as a whole (=array) its indiviudal elements are sent with their full keys "coords[0][lat]" and "coords[0][lng]":

{
  "name": "Something",
  "coords[0][lat]": "23.23",
  "coords[0][lng]": "123.123",
  "id": 101
}

var data = {name: "Something", coords: [{lat: 23.23, lng: 123.123}]}
$.ajax({
  url: "https://jsonplaceholder.typicode.com/posts",
  type: "POST",
  dataType: "json",
  data: data,
  success: function(response){console.log(response);}
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If you want to avoid that behaviour you will have to send the object as a JSON-encoded string and (explicitly!) decode it on the receiving end:

var data = {name: "Something", coords: [{lat: 23.23, lng: 123.123}]}
$.ajax({
  url: "https://jsonplaceholder.typicode.com/posts",
  type: "POST",
  dataType: "json",
  data: {d: JSON.stringify(data)},
  success: function(response){console.log(JSON.parse(response.d));}
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This will give you:

{
  "name": "Something",
  "coords": [
    {
      "lat": 23.23,
      "lng": 123.123
    }
  ]
}