问:
Crash in react-native-Uuid-generator when using library in expo app
I want to generate a uuid in ReactNative app built with expo cli.. when I install UUIDGenerator from React-native-uuid-generator, I get undefined is not an object(evaluating ‘RNUUIDGenerator.getRandomUUID’..)

Tried two dif libraries, react-native-uuid, and React-native-uuid-generator, same problem, think it might have to do with expo not liking the link command.

```<code>UUIDGenerator.getRandomUUID().then(uuid => console.log(uuid));
</code>```

Expecting new uuid to be printed, actually getting error message.

答:
react-native-uuid works with expo.

```<code>npm install react-native-uuid --save

import uuid from 'react-native-uuid';
</code>```

then generatte uuid like

```<code>const uuid = uuid.v1();
</code>```

Body:
I want to generate a uuid in ReactNative app built with expo cli.. when I install UUIDGenerator from React-native-uuid-generator, I get undefined is not an object(evaluating ‘RNUUIDGenerator.getRandomUUID’..)

Tried two dif libraries, react-native-uuid, and React-native-uuid-generator, same problem, think it might have to do with expo not liking the link command.

UUIDGenerator.getRandomUUID().then(uuid => console.log(uuid));

Expecting new uuid to be printed, actually getting error message.

Body:
react-native-uuid works with expo.

npm install react-native-uuid --save

import uuid from 'react-native-uuid';

then generatte uuid like

const uuid = uuid.v1();


来源: stackexchange

问:
Node-Cron not installing on Heroku
I am using Node js for a personal project but I keep getting the same problem when installing node-cron.
When deploying on Heroku, it keeps giving me the same error message seen below but does not occur when installing it locally.

I tried finding others with similar problems online but nothing seems to pop up. Would be much appreciated if someone could find a solution!

```<code>> node-cron@2.0.3 postinstall /tmp/build_13203812b696ff71f401fd657fdd6fdd/node_modules/node-cron
remote:        > opencollective-postinstall
remote:
remote:        sh: 1: opencollective-postinstall: Permission denied
remote:        npm ERR! code ELIFECYCLE
remote:        npm ERR! errno 126
remote:        npm ERR! node-cron@2.0.3 postinstall: `opencollective-postinstall`
remote:        npm ERR! Exit status 126
remote:        npm ERR!
remote:        npm ERR! Failed at the node-cron@2.0.3 postinstall script.
remote:        npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

答: Try to add || exit 0 at the end of the postinstall script in package.json to make sure this never stops the npm install process.

ContentLicense: CC BY-SA 4.0

Title: Node-Cron not installing on Heroku

Body:
I am using Node js for a personal project but I keep getting the same problem when installing node-cron.
When deploying on Heroku, it keeps giving me the same error message seen below but does not occur when installing it locally.

I tried finding others with similar problems online but nothing seems to pop up. Would be much appreciated if someone could find a solution!

> node-cron@2.0.3 postinstall /tmp/build_13203812b696ff71f401fd657fdd6fdd/node_modules/node-cron
remote:        > opencollective-postinstall
remote:
remote:        sh: 1: opencollective-postinstall: Permission denied
remote:        npm ERR! code ELIFECYCLE
remote:        npm ERR! errno 126
remote:        npm ERR! node-cron@2.0.3 postinstall: `opencollective-postinstall`
remote:        npm ERR! Exit status 126
remote:        npm ERR!
remote:        npm ERR! Failed at the node-cron@2.0.3 postinstall script.
remote:        npm ERR! This is probably not a problem with npm. There is likely additional logging output above.


问:
How to make an input variable global in python 3.7?
I'm making a basic dice game and have created a process in which the the player can confirm their name or redo it. and the p1 variable i've used to store the players name only works within the function but I want to use it in the whole program

I've already tried define the variable before the function, which isn't working, and have tried writing Global before it in the function but it says "invalid syntax"

#Functions
p1 = ""

def P1Start():
   print("Player 1 type your name")
   p1 =  str(input())
   print("Are you sure this is your name", p1)
   time.sleep(timesleep)
   print("Type YES to confirm")
   time.sleep(timesleep)
   print("Type NO to decline")

def P1Creation():
   P1confirmation = str(input())
   if P1confirmation =="yes":
        print("carry on")
        #elif P1confirmation == "NO" or "no":
        #P1Start()
        print(p1)
   else:
        print("Restarting the Player 1 Name Collection")
        time.sleep(1)
        P1Start()
#End of Functions

print("Welcome to the Dice game")
time.sleep(timesleep)
P1Start()
time.sleep(timesleep)
P1Creation()

print(p1)
```

<p>or</p>

<pre class="lang-py prettyprint-override"><code>#Functions
p1 = ""

def P1Start():
   print("Player 1 type your name")
   global p1 =  str(input())
   print("Are you sure this is your name", p1)
   time.sleep(timesleep)
   print("Type YES to confirm")
   time.sleep(timesleep)
   print("Type NO to decline")

def P1Creation():
   P1confirmation = str(input())
   if P1confirmation =="yes":
        print("carry on")
        #elif P1confirmation == "NO" or "no":
        #P1Start()
        print(p1)
   else:
        print("Restarting the Player 1 Name Collection")
        time.sleep(1)
        P1Start()
#End of Functions

print("Welcome to the Dice game")
time.sleep(timesleep)
P1Start()
time.sleep(timesleep)
P1Creation()

print(p1)
</code>```

Putting Global in front just shows "invalid syntax"
What should I do to make this work?

答:
You can define it as global in your function itself.
Just an example:</p>

```<code>def f():
        global s
        s=" I am global"
        print(s)

f()
print(s)
</code>```

Body:
I'm making a basic dice game and have created a process in which the the player can confirm their name or redo it. and the p1 variable i've used to store the players name only works within the function but I want to use it in the whole program

I've already tried define the variable before the function, which isn't working, and have tried writing Global before it in the function but it says "invalid syntax"

#Functions
p1 = ""

def P1Start():
   print("Player 1 type your name")
   p1 =  str(input())
   print("Are you sure this is your name", p1)
   time.sleep(timesleep)
   print("Type YES to confirm")
   time.sleep(timesleep)
   print("Type NO to decline")

def P1Creation():
   P1confirmation = str(input())
   if P1confirmation =="yes":
        print("carry on")
        #elif P1confirmation == "NO" or "no":
        #P1Start()
        print(p1)
   else:
        print("Restarting the Player 1 Name Collection")
        time.sleep(1)
        P1Start()
#End of Functions

print("Welcome to the Dice game")
time.sleep(timesleep)
P1Start()
time.sleep(timesleep)
P1Creation()

print(p1)

or

#Functions
p1 = ""

def P1Start():
   print("Player 1 type your name")
   global p1 =  str(input())
   print("Are you sure this is your name", p1)
   time.sleep(timesleep)
   print("Type YES to confirm")
   time.sleep(timesleep)
   print("Type NO to decline")

def P1Creation():
   P1confirmation = str(input())
   if P1confirmation =="yes":
        print("carry on")
        #elif P1confirmation == "NO" or "no":
        #P1Start()
        print(p1)
   else:
        print("Restarting the Player 1 Name Collection")
        time.sleep(1)
        P1Start()
#End of Functions

print("Welcome to the Dice game")
time.sleep(timesleep)
P1Start()
time.sleep(timesleep)
P1Creation()

print(p1)

Putting Global in front just shows "invalid syntax"
What should I do to make this work?

Body:
You can define it as global in your function itself.
Just an example:

def f():
        global s
        s=" I am global"
        print(s)

f()
print(s)


问:
Avoiding <sos> and <eos> being parsed by Spacy
I am stuck with a basic thing but I could not figure out how to make it work. My apologies if it is something super basic. It is just that I am very new to Spacy and do not know how to do this. Could not find any resource on the internet as well.

I have a bunch of sentences like so

a = "<sos> Hello There! <eos>"
```

<p>I am using this following lines of code to tokenize it using Spacy</p>

<pre class="lang-py prettyprint-override"><code>import spacy
nlp = spacy.load('en_core_web_sm')
for token in nlp(a):
    print(token.text)
</code>```

What it prints is something like this

```<code><
sos
>
Hello
There
!
<
eos
>
</code>```

As you can see, it parsed the <sos> and <eos> metatags. How can I avoid that? The output I would like to see is something like the following

```<code><sos>
Hello
There
!
<eos>
</code>```

I could not figure out how to achieve this. Any help will be great.

Thanks in advance

答:
In spaCy, tokenizer checks for exceptions before splitting text.
You need to add an exception to tokenizer to treat your symbols as full tokens.

Your code should look like this:

import spacy
from spacy.attrs import ORTH, LEMMA

sent = "<sos> Hello There! <eos>"

nlp = spacy.load('en_core_web_sm')

nlp.tokenizer.add_special_case('<sos>', [{ORTH: "<sos>"}])
nlp.tokenizer.add_special_case('<eos>', [{ORTH: "<eos>"}])

for token in nlp(sent):
    print(token.text)
```

You can read more about it here:
https://spacy.io/api/tokenizer#add_special_case

Body:
I am stuck with a basic thing but I could not figure out how to make it work. My apologies if it is something super basic. It is just that I am very new to Spacy and do not know how to do this. Could not find any resource on the internet as well.

I have a bunch of sentences like so

a = "<sos> Hello There! <eos>"

I am using this following lines of code to tokenize it using Spacy

import spacy
nlp = spacy.load('en_core_web_sm')
for token in nlp(a):
    print(token.text)

What it prints is something like this

<
sos
>
Hello
There
!
<
eos
>

As you can see, it parsed the <sos> and <eos> metatags. How can I avoid that? The output I would like to see is something like the following

<sos>
Hello
There
!
<eos>

I could not figure out how to achieve this. Any help will be great.

Thanks in advance

Body:
In spaCy, tokenizer checks for exceptions before splitting text.
You need to add an exception to tokenizer to treat your symbols as full tokens.

Your code should look like this:

import spacy
from spacy.attrs import ORTH, LEMMA

sent = "<sos> Hello There! <eos>"

nlp = spacy.load('en_core_web_sm')

nlp.tokenizer.add_special_case('<sos>', [{ORTH: "<sos>"}])
nlp.tokenizer.add_special_case('<eos>', [{ORTH: "<eos>"}])

for token in nlp(sent):
    print(token.text)

You can read more about it here:
https://spacy.io/api/tokenizer#add_special_case


问:
TypeError: Cannot read property 'push' of undefined in node-red function node
I am using node-red, the function node to generate some random matrix. However, every time when I deploy the node, the error "TypeError: Cannot read property 'push' of undefined" will appear, can someone help me to take a look at the code?</p>

```<code>// Generate some random data
// See https://www.patrick-wied.at/static/heatmapjs/example-minimal-config.html

var len = 200;

msg.payload = [];

while (len--) {
  var value = Math.floor(Math.random() * 100);
  msg.payload.push(value);
}

return msg;
</code>```

答: The error tells , push cannot be done on 'undefined'. This suggests that msg is undefined or msg.payload is undefined. In your case, declare the payload separately before push and then assign it to the msg finally.</p>

Body:
I am using node-red, the function node to generate some random matrix. However, every time when I deploy the node, the error "TypeError: Cannot read property 'push' of undefined" will appear, can someone help me to take a look at the code?

// Generate some random data
// See https://www.patrick-wied.at/static/heatmapjs/example-minimal-config.html

var len = 200;

msg.payload = [];

while (len--) {
  var value = Math.floor(Math.random() * 100);
  msg.payload.push(value);
}

return msg;


问:
uasort() ? - sorting posts from a bank account
How can I sort an array with some posts from a bank account?

I need to sort by three fields: date, amount, accumulated amount

ie.

```<code>date | amount | accum_amount
01-01-11 500 500 ('amount' + previous 'accum_amount' = 'accum_amount' => 500 + 0 = 500)
01-01-11 100 600 ('amount' + previous 'accum_amount' = 'accum_amount' => 100 + 500 = 600)
01-02-11 -25 575 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 600 = 575)
01-02-11 150 725 ('amount' + previous 'accum_amount' = 'accum_amount' => 150 + 575 = 725)
01-03-11 200 925 ('amount' + previous 'accum_amount' = 'accum_amount' => 200 + 725 = 925)
01-04-11 -25 900 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 925 = 900)
</code>```

btw. the date field is an UNIX timestamp

```<code>array(
    array(
        'time' => 1200000000,
        'amount' => 500,
        'accum_amount' => 500
        ),
    array(
        'time' => 1200000000,
        'amount' => 150,
        'accum_amount' => 725
        ),
    array(
        'time' => 1200000000,
        'amount' => 100,
        'accum_amount' => 600
        ),
    array(
        'time' => 1300000000,
        'amount' => 200,
        'accum_amount' => 925
        ),
    array(
        'time' => 1300000000,
        'amount' => -25,
        'accum_amount' => 900
        ),
    array(
        'time' => 1200000000,
        'amount' => -25,
        'accum_amount' => 575
        )
    )
</code>```

答:
Change your array structure to something like:

```<code>$tmp = array(
   time => array(1200000000, 1200000000, 1200000000, ...),
   amount => array(500, 150, 100, ...),
   accum_amount => array(500, 725, 600, ...),
)
</code>```

and then use array_multisort for sorting (http://php.net/manual/en/function.array-multisort.php) like:

```<code>array_multisort($tmp['time'], SORT_ASC, $tmp['amount'], SORT_DESC, $tmp['accum_amount'], SORT_ASC);
</code>```

It's not very intuitive, but it should work.

Of course you can write a helper function to map the new sorting order on other array structure.

Example:

```<code>function mySort($array, $sort) {
    $tmp = array();
    foreach ($array as $row) {
        foreach ($row as $field => $value) {
            if (!isset($tmp[$field])) {
                $tmp[$field] = array();
            }

            $tmp[$field][] = $value;
        }
    }

    $params = array();
    foreach ($sort as $field => $direction) {
        $params[] = $tmp[$field];
        $params[] = $direction;
    }

    $keys = array_keys($array);
    $params[] =& $keys;

    call_user_func_array('array_multisort', $params);

    $result = array();
    foreach ($keys as $key) {
        $result[$key] = $array[$key];
    }

    return $result;
}
</code>```

Call:

```<code>$data = mySort($data, array(
    'time' => SORT_ASC,
    'amount' => SORT_ASC,
    'accum_amount' => SORT_ASC
));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I sort an array with some posts from a bank account?

I need to sort by three fields: date, amount, accumulated amount

ie.

date | amount | accum_amount
01-01-11 500 500 ('amount' + previous 'accum_amount' = 'accum_amount' => 500 + 0 = 500)
01-01-11 100 600 ('amount' + previous 'accum_amount' = 'accum_amount' => 100 + 500 = 600)
01-02-11 -25 575 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 600 = 575)
01-02-11 150 725 ('amount' + previous 'accum_amount' = 'accum_amount' => 150 + 575 = 725)
01-03-11 200 925 ('amount' + previous 'accum_amount' = 'accum_amount' => 200 + 725 = 925)
01-04-11 -25 900 ('amount' + previous 'accum_amount' = 'accum_amount' => -25 + 925 = 900)

btw. the date field is an UNIX timestamp

array(
    array(
        'time' => 1200000000,
        'amount' => 500,
        'accum_amount' => 500
        ),
    array(
        'time' => 1200000000,
        'amount' => 150,
        'accum_amount' => 725
        ),
    array(
        'time' => 1200000000,
        'amount' => 100,
        'accum_amount' => 600
        ),
    array(
        'time' => 1300000000,
        'amount' => 200,
        'accum_amount' => 925
        ),
    array(
        'time' => 1300000000,
        'amount' => -25,
        'accum_amount' => 900
        ),
    array(
        'time' => 1200000000,
        'amount' => -25,
        'accum_amount' => 575
        )
    )

Body:
Change your array structure to something like:

$tmp = array(
   time => array(1200000000, 1200000000, 1200000000, ...),
   amount => array(500, 150, 100, ...),
   accum_amount => array(500, 725, 600, ...),
)

and then use array_multisort for sorting (http://php.net/manual/en/function.array-multisort.php) like:

array_multisort($tmp['time'], SORT_ASC, $tmp['amount'], SORT_DESC, $tmp['accum_amount'], SORT_ASC);

It's not very intuitive, but it should work.

Of course you can write a helper function to map the new sorting order on other array structure.

Example:

function mySort($array, $sort) {
    $tmp = array();
    foreach ($array as $row) {
        foreach ($row as $field => $value) {
            if (!isset($tmp[$field])) {
                $tmp[$field] = array();
            }

            $tmp[$field][] = $value;
        }
    }

    $params = array();
    foreach ($sort as $field => $direction) {
        $params[] = $tmp[$field];
        $params[] = $direction;
    }

    $keys = array_keys($array);
    $params[] =& $keys;

    call_user_func_array('array_multisort', $params);

    $result = array();
    foreach ($keys as $key) {
        $result[$key] = $array[$key];
    }

    return $result;
}

Call:

$data = mySort($data, array(
    'time' => SORT_ASC,
    'amount' => SORT_ASC,
    'accum_amount' => SORT_ASC
));


问:
Creating proxy_pass from s3 static web server bucket to instance docket

I'm trying to load our current application to CloudFront-s3 static web site architecture.

after creating s3 bucket and CloudFront which work, I'm trying to configure our backend to go to a specific instance and port.

Currently, I'm doing it with nginx:

```<code> location /api {
        proxy_pass http://my_app:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
  client_max_body_size 1000M;
  server_tokens off;
</code>```

is there a way to configure it on the s3bucket I created?

答:
No, you cannot proxy a path to another server within S3, that only supports static objects served by S3 directly.

But you can handle this in Cloudfront by adding an extra behaviour which points to your other instance/port
see https://aws.amazon.com/premiumsupport/knowledge-center/cloudfront-distribution-serve-content/

Body:
I'm trying to load our current application to CloudFront-s3 static web site architecture.

after creating s3 bucket and CloudFront which work, I'm trying to configure our backend to go to a specific instance and port.

Currently, I'm doing it with nginx:

 location /api {
        proxy_pass http://my_app:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
  client_max_body_size 1000M;
  server_tokens off;

is there a way to configure it on the s3bucket I created?


问:
Count div from codility. StackOverflowError in program using recursion
I wrote program for one of lessons from Codility. Its called count div.

For example. I give number 6, 11 and 2. There are 3 numbers from 6 to 11 that we can divide by 2, its 6, 8, 10 so method should return 3.

At first I made program with recursion with only ints but I got error so I changed it to BigIntegers, but it doesnt help at all. It's working good for small numbers but with for example input:

A = 0, B = 20000, K = 1 it gives errors:

```<code>Exception in thread "main" java.lang.StackOverflowError
at java.math.MutableBigInteger.divideKnuth(Unknown Source)
at java.math.MutableBigInteger.divideKnuth(Unknown Source)
at java.math.BigInteger.remainderKnuth(Unknown Source)
at java.math.BigInteger.remainder(Unknown Source)
at java.math.BigInteger.mod(Unknown Source)
at count_div.Solution.bigIntegerSolution(Solution.java:29)
at count_div.Solution.bigIntegerSolution(Solution.java:35)
</code>```

Here's my code:

```<code>public int solution(int A, int B, int K){

    BigInteger minValue = BigInteger.valueOf(A);
    BigInteger maxValue = BigInteger.valueOf(B);
    BigInteger div = BigInteger.valueOf(K);

    finalCounter = bigIntegerSolution(minValue, maxValue, div).intValue();

    return finalCounter;
}

public BigInteger bigIntegerSolution(BigInteger minValue, BigInteger maxValue, BigInteger div){

    int comparator = minValue.compareTo(maxValue);

    if(comparator <= 0){

        BigInteger modValue = minValue.mod(div);

        if( modValue.compareTo(zero) == 0){
            divCounter = divCounter.add(one);
        }
        minValue = minValue.add(one);
        bigIntegerSolution(minValue, maxValue, div);
    }

    return divCounter;
}
</code>```

Is there anything I can do or my solution idea is just bad for this purpose? I know that they are other solutions but I first came up with this and I would like to know if I can fix it.

答:
Here is my solution. Idea is that I'm looking for first number that can be divided on K after that number of divisibles in range is ((B - first) / K) + 1. We need to know difference between biggest limit (which is B) and first divisible and count how many K can be fit between them because firs number won't be included we need to add one for correct result.

```<code>class Solution {

    public int solution(int A, int B, int K) {
        if (A == B) {
            if (A % K == 0) return 1;
            else return 0;
        }
        int first = (A % K == 0) ? A : A + (K - (A % K));
        if (A != 0 && (first > B || first == 0)) return 0;

        return ((B - first) / K) + 1;
    }
}
</code>```

Body:
I wrote program for one of lessons from Codility. Its called count div.

For example. I give number 6, 11 and 2. There are 3 numbers from 6 to 11 that we can divide by 2, its 6, 8, 10 so method should return 3.

At first I made program with recursion with only ints but I got error so I changed it to BigIntegers, but it doesnt help at all. It's working good for small numbers but with for example input:

A = 0, B = 20000, K = 1 it gives errors:

Exception in thread "main" java.lang.StackOverflowError
at java.math.MutableBigInteger.divideKnuth(Unknown Source)
at java.math.MutableBigInteger.divideKnuth(Unknown Source)
at java.math.BigInteger.remainderKnuth(Unknown Source)
at java.math.BigInteger.remainder(Unknown Source)
at java.math.BigInteger.mod(Unknown Source)
at count_div.Solution.bigIntegerSolution(Solution.java:29)
at count_div.Solution.bigIntegerSolution(Solution.java:35)

Here's my code:

public int solution(int A, int B, int K){

    BigInteger minValue = BigInteger.valueOf(A);
    BigInteger maxValue = BigInteger.valueOf(B);
    BigInteger div = BigInteger.valueOf(K);

    finalCounter = bigIntegerSolution(minValue, maxValue, div).intValue();

    return finalCounter;
}

public BigInteger bigIntegerSolution(BigInteger minValue, BigInteger maxValue, BigInteger div){

    int comparator = minValue.compareTo(maxValue);

    if(comparator <= 0){

        BigInteger modValue = minValue.mod(div);

        if( modValue.compareTo(zero) == 0){
            divCounter = divCounter.add(one);
        }
        minValue = minValue.add(one);
        bigIntegerSolution(minValue, maxValue, div);
    }

    return divCounter;
}

Is there anything I can do or my solution idea is just bad for this purpose? I know that they are other solutions but I first came up with this and I would like to know if I can fix it.

Body:
Here is my solution. Idea is that I'm looking for first number that can be divided on K after that number of divisibles in range is ((B - first) / K) + 1. We need to know difference between biggest limit (which is B) and first divisible and count how many K can be fit between them because firs number won't be included we need to add one for correct result.

class Solution {

    public int solution(int A, int B, int K) {
        if (A == B) {
            if (A % K == 0) return 1;
            else return 0;
        }
        int first = (A % K == 0) ? A : A + (K - (A % K));
        if (A != 0 && (first > B || first == 0)) return 0;

        return ((B - first) / K) + 1;
    }
}


问:
Refactoring problem from class to function with hooks
I am refactoring some code and now I am stuck.
The original code is from a tuto :
https://github.com/EricLondon/rails5-react-reactstrap-crud-example
All is fine there.
I try to use hooks new feature.
The new code I wrote just fail.

"Original code" is ok tested
"new code" fails

```<code>//"New code"
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

export default function Posts() {
  const [posts, setPosts] = useState([])
  const [isLoaded, setIsLoaded] = useState(false)
  const [error, setError] = useState(null)

  useEffect( () => {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setIsLoaded(true)
          setPosts([])
          setError(data)
        } else {
          setIsLoaded(true)
          setPosts(data)
        }
      })
  })

  if (error) {

    return (
      <Alert color="danger">
          Error: {error}
      </Alert>
    )

  } else if (!isLoaded) {

    return (
      <Alert color="primary">
          Loading...
      </Alert>
    )

  } else {

    return (
      <Container>
        <Row>
          <Col>
            <PostsTable posts={posts}></PostsTable>
            <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
          </Col>
        </Row>
      </Container>
    )

  }
}

//"Original code"
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

class Posts extends Component {
  constructor(props) {
    super(props)
    this.state = {
      posts: [],
      isLoaded: false,
      error: null
    }
  }

  componentDidMount() {
    Api.getPosts()
      .then(response => {
        const [error, data] = response
        if (error) {
          this.setState({
            isLoaded: true,
            posts: [],
            error: data
          })
        } else {
          this.setState({
            isLoaded: true,
            posts: data
          })
        }
      })
  }

  render() {
    const { error, isLoaded, posts } = this.state

    if (error) {

      return (
        <Alert color="danger">
          Error: {error}
        </Alert>
      )

    } else if (!isLoaded) {

      return (
        <Alert color="primary">
          Loading...
        </Alert>
      )

    } else {

      return (
        <Container>
          <Row>
            <Col>
              <PostsTable posts={posts}></PostsTable>
              <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
            </Col>
          </Row>
        </Container>
      )

    }

  }
}

export default Posts
</code>```

With "new code" my backend server is driving crazy:
....
Started GET "/api/posts" for 127.0.0.1 at 2019-05-26 20:45:39 +0200
Processing by Api::PostsController#index as HTML
  Post Load (1.3ms)  SELECT "posts".* FROM "posts"
  ↳ app/controllers/api/posts_controller.rb:5
Completed 200 OK in 6ms (Views: 4.4ms | ActiveRecord: 1.3ms)
....
etc.

答:
Right now, your `useEffect is running on every render. You should add an empty array as the 2nd argument to only run on mount:

```<code>useEffect(() => {
  ...
}, []);
</code>```

By providing an array as the 2nd argument, you're telling the useEffect function "Run again any time one of these values changes." If you don't provide an array at all, it will run every time the component renders (in this case, any time setIsLoading, setError, or setPosts is called).

Giving it an empty dependency array still tells the function "run anytime one of these values changes," but because there are no values that will change, it will only run once.

Body:
I am refactoring some code and now I am stuck.
The original code is from a tuto :
https://github.com/EricLondon/rails5-react-reactstrap-crud-example
All is fine there.
I try to use hooks new feature.
The new code I wrote just fail.

"Original code" is ok tested
"new code" fails

//"New code"
import React, { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

export default function Posts() {
  const [posts, setPosts] = useState([])
  const [isLoaded, setIsLoaded] = useState(false)
  const [error, setError] = useState(null)

  useEffect( () => {
    Api.getPosts()
      .then( response => {
        const [errata, data] = response
        if (errata) {
          setIsLoaded(true)
          setPosts([])
          setError(data)
        } else {
          setIsLoaded(true)
          setPosts(data)
        }
      })
  })

  if (error) {

    return (
      <Alert color="danger">
          Error: {error}
      </Alert>
    )

  } else if (!isLoaded) {

    return (
      <Alert color="primary">
          Loading...
      </Alert>
    )

  } else {

    return (
      <Container>
        <Row>
          <Col>
            <PostsTable posts={posts}></PostsTable>
            <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
          </Col>
        </Row>
      </Container>
    )

  }
}

//"Original code"
import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Container, Row, Col, Alert } from 'reactstrap'
import PostsTable from '../PostsTable'

const Api = require('../../api/Api.js')

class Posts extends Component {
  constructor(props) {
    super(props)
    this.state = {
      posts: [],
      isLoaded: false,
      error: null
    }
  }

  componentDidMount() {
    Api.getPosts()
      .then(response => {
        const [error, data] = response
        if (error) {
          this.setState({
            isLoaded: true,
            posts: [],
            error: data
          })
        } else {
          this.setState({
            isLoaded: true,
            posts: data
          })
        }
      })
  }

  render() {
    const { error, isLoaded, posts } = this.state

    if (error) {

      return (
        <Alert color="danger">
          Error: {error}
        </Alert>
      )

    } else if (!isLoaded) {

      return (
        <Alert color="primary">
          Loading...
        </Alert>
      )

    } else {

      return (
        <Container>
          <Row>
            <Col>
              <PostsTable posts={posts}></PostsTable>
              <Link className="btn btn-primary" to="/posts/new">Add Post</Link>
            </Col>
          </Row>
        </Container>
      )

    }

  }
}

export default Posts

With "new code" my backend server is driving crazy:
....
Started GET "/api/posts" for 127.0.0.1 at 2019-05-26 20:45:39 +0200
Processing by Api::PostsController#index as HTML
  Post Load (1.3ms)  SELECT "posts".* FROM "posts"
  ↳ app/controllers/api/posts_controller.rb:5
Completed 200 OK in 6ms (Views: 4.4ms | ActiveRecord: 1.3ms)
....
etc.

Body:
Right now, your `useEffect is running on every render. You should add an empty array as the 2nd argument to only run on mount:

useEffect(() => {
  ...
}, []);

By providing an array as the 2nd argument, you're telling the useEffect function "Run again any time one of these values changes." If you don't provide an array at all, it will run every time the component renders (in this case, any time setIsLoading, setError, or setPosts is called).

Giving it an empty dependency array still tells the function "run anytime one of these values changes," but because there are no values that will change, it will only run once.


问:
image upload in django
Could someone point me towards an example on image uploading in django. I have tried the documentation and the djangobook, but all I found were examples with file uploads. I am new to Django and I would like to first try to see how an example works before writing my own form. Thanks a lot.</p>

答:
Maybe this will help a little:

forms.py

```<code>class SomeForm(forms.Form):
    picture = forms.ImageField(required=False)
</code>```

views.py

```<code>if request.method == 'POST':
    form = SomeForm(request.POST, request.FILES)
    if form.is_valid():
        dest_file = open('some_image_file.jpg', 'wb+')
        for chunk in  request.FILES['picture_field'].chunks():
            dest_file.write(chunk)
        dest_file.close()
</code>```

I haven't ran this peace of code, could be that I miss something... But in general it is like this and the file will be saved to the disk (by default chunks should be 2.5 megs). Just remember that in template where is your form, form must have enctype="multipart/form-data".

When you have file savedm you can use PIL to resize, add watermarks and everything you like to edit image ;)

Good luck.
Ignas

Title: image upload in django

Body:
Maybe this will help a little:

forms.py

class SomeForm(forms.Form):
    picture = forms.ImageField(required=False)

views.py

if request.method == 'POST':
    form = SomeForm(request.POST, request.FILES)
    if form.is_valid():
        dest_file = open('some_image_file.jpg', 'wb+')
        for chunk in  request.FILES['picture_field'].chunks():
            dest_file.write(chunk)
        dest_file.close()

I haven't ran this peace of code, could be that I miss something... But in general it is like this and the file will be saved to the disk (by default chunks should be 2.5 megs). Just remember that in template where is your form, form must have enctype="multipart/form-data".

When you have file savedm you can use PIL to resize, add watermarks and everything you like to edit image ;)

Good luck.
Ignas


问:
Check if an attribute has changed in Laravel 5.5 model events
I've seen that there is a function called wasChanged() where you can check if an attribute was changed on an update. Not is dirty, but was changed and persisted

However I'm trying to check this inside my model events boot function:

```<code>public static function boot()
{
    parent::boot();

    self::updated(function($appointment){

        if($appointment->wasChanged('appointment_date')) {
         // do something
        }

    });
}
</code>```

This never works for me. Any ideas how I can check this?

the isDirty function has different behavior as that is used to check if an attribute was submitted in the request.

答:
After a bit of searching I found that there is a useful function called getOriginal() which returns an array of the original attribute values.

So I just had to access my attribute and do a compare:

```<code>$original_date = $appointment->getOriginal()['appointment_date'];

if($appointment->appointment_date != $original_date) {

 ...

}
</code>```

Answer taken from here

Body:
I've seen that there is a function called wasChanged() where you can check if an attribute was changed on an update. Not is dirty, but was changed and persisted

However I'm trying to check this inside my model events boot function:

public static function boot()
{
    parent::boot();

    self::updated(function($appointment){

        if($appointment->wasChanged('appointment_date')) {
         // do something
        }

    });
}

This never works for me. Any ideas how I can check this?

the isDirty function has different behavior as that is used to check if an attribute was submitted in the request.

Body:
After a bit of searching I found that there is a useful function called getOriginal() which returns an array of the original attribute values.

So I just had to access my attribute and do a compare:

$original_date = $appointment->getOriginal()['appointment_date'];

if($appointment->appointment_date != $original_date) {

 ...

}

Answer taken from here


问:
How to escape current SQLite3 query if row in table exists, but continue if it doesn't
So I an integrating my Discord.JS bot with SQLite3 and I am adding a function where users can store their ID and username within a table. Currently, what I have will only create a new row in the table, if the ID and name of the user does not already exist within a row of the table, and creates a new row if the data doesn't exist. What I want to know is if there is a way to throw something out of the query if the row does exist, and for me to be able to catch it, and then do something else.

I have tried if..else statements, but I want to know if there is a simpler way to achieve this.

This is what I have currently, that functions as described above.

let userC = message.mentions.members.first()

    db.serialize(() => {
        db.run('CREATE TABLE IF NOT EXISTS user (id TEXT, name TEXT)');
        db.run(`INSERT INTO user (id, name) SELECT '${userC.id}', '${userC.user.username}' WHERE NOT EXISTS(SELECT 1 FROM user WHERE id = '${userC.id}' AND name = '${userC.user.username}')`)
    });
    message.reply('Added the user to the database.');
```

Ideally, if the row does exist, message.reply('Added the user to the database.'); will not execute, and instead will continue with message.reply('That user already exists within the database'); But if the row doesn't exist, it inserts the row and data, and only continues with message.reply('Added the user to the database.');

答:
According to the API docs here, you can use Database.get() instead of Database.run(). It functions the same way, but the callback will return the rows from the SQL which you can check.

In the code below, you'll notice that I've also implemented placeholders to prevent SQL injection. Consider this normal practice for user-provided variables.

const userC = message.mentions.users.first();

db.get(`SELECT 1 FROM user WHERE id = '${userC.id}' AND name = '?'`, [userC.username], (err, rows) => {
  if (err) return console.error(err);

  if (!rows[0]) {
    db.run(`INSERT INTO user (id, name) VALUES ('${userC.id}', '?'), [userC.username], err => {
      if (err) return console.error(err);

      message.reply('Added the user to the database.');
    });
  } else return message.reply('That user already exists within the database.');
});
```

Make sure to also catch the promises returned by message.reply().

Body:
So I an integrating my Discord.JS bot with SQLite3 and I am adding a function where users can store their ID and username within a table. Currently, what I have will only create a new row in the table, if the ID and name of the user does not already exist within a row of the table, and creates a new row if the data doesn't exist. What I want to know is if there is a way to throw something out of the query if the row does exist, and for me to be able to catch it, and then do something else.

I have tried if..else statements, but I want to know if there is a simpler way to achieve this.

This is what I have currently, that functions as described above.

let userC = message.mentions.members.first()

    db.serialize(() => {
        db.run('CREATE TABLE IF NOT EXISTS user (id TEXT, name TEXT)');
        db.run(`INSERT INTO user (id, name) SELECT '${userC.id}', '${userC.user.username}' WHERE NOT EXISTS(SELECT 1 FROM user WHERE id = '${userC.id}' AND name = '${userC.user.username}')`)
    });
    message.reply('Added the user to the database.');

Ideally, if the row does exist, message.reply('Added the user to the database.'); will not execute, and instead will continue with message.reply('That user already exists within the database'); But if the row doesn't exist, it inserts the row and data, and only continues with message.reply('Added the user to the database.');

Body:
According to the API docs here, you can use Database.get() instead of Database.run(). It functions the same way, but the callback will return the rows from the SQL which you can check.

In the code below, you'll notice that I've also implemented placeholders to prevent SQL injection. Consider this normal practice for user-provided variables.

const userC = message.mentions.users.first();

db.get(`SELECT 1 FROM user WHERE id = '${userC.id}' AND name = '?'`, [userC.username], (err, rows) => {
  if (err) return console.error(err);

  if (!rows[0]) {
    db.run(`INSERT INTO user (id, name) VALUES ('${userC.id}', '?'), [userC.username], err => {
      if (err) return console.error(err);

      message.reply('Added the user to the database.');
    });
  } else return message.reply('That user already exists within the database.');
});

Make sure to also catch the promises returned by message.reply().


问:
Bokeh slider with CustomJS callback fails to use callback_policy='mouseup' option
I am trying to create a simple flask graphical app using bokeh for plotting. My code uses the json_item function to embed a plot into an html page and is based on the bokeh example.To control plot parameters, I have just added two sliders, for which I have set the option callback_policy='mouseup'. However, when I drag any of the sliders, it produces multiple plots instead of one plot. I am using the latest bokeh version 1.1.0.

I have searched web on that topic, but it looks that people have no such the problem with callback_policy='mouseup'. Probably, it does not work in my specific setup or I have an error, which I cannot catch.
My python app.py code is here and index.html from templates folder is here.
 I will be very grateful for any advice.

答:
For Bokeh versions 1.1 and earlier, the callback_policy only applies to the old-style callback property of the Slider, not the newer generic js_on_change methods. So you should be doing this:

```<code>fs.callback = cbk
ss.callback = cbk
</code>```

However, in the upcoming release of Bokeh, things have been improved and clarified. The above method will continue to work (until Bokeh 2.0), but the recommended way to do things will be to watch the new value_throttled property:

```<code># use this for version 1.2 and later:

fs.js_on_change('value_throttled', cbk)
ss.js_on_change('value_throttled', cbk)
</code>```

Note that in the new method above will work for both JS callbacks, and now also for python callbacks in Bokeh server apps (with on_change of js_on_change instead, of course).

Body:
For Bokeh versions 1.1 and earlier, the callback_policy only applies to the old-style callback property of the Slider, not the newer generic js_on_change methods. So you should be doing this:

fs.callback = cbk
ss.callback = cbk

However, in the upcoming release of Bokeh, things have been improved and clarified. The above method will continue to work (until Bokeh 2.0), but the recommended way to do things will be to watch the new value_throttled property:

# use this for version 1.2 and later:

fs.js_on_change('value_throttled', cbk)
ss.js_on_change('value_throttled', cbk)

Note that in the new method above will work for both JS callbacks, and now also for python callbacks in Bokeh server apps (with on_change of js_on_change instead, of course).


问:
Cant overwrite the custom stylesheet
I am trying to overwrite the CSS of react range slider.It uses the custom style sheet of which i need to add in the head section.My project is built on next.js

```<code> <link rel="stylesheet" href="https://unpkg.com/react-rangeslider/umd/rangeslider.min.css" />
</code>```

Otherwise, the slider doesn't show anything if i don't add the link in head even though I installed the library. It's not even overwriting the CSS. I want  to change the background color.This is my code:

```<code>import React, { Component } from 'react'
import 'react-rangeslider/lib/index.css';
import './slider.css';
import Slider from 'react-rangeslider'
class Horizontal extends Component {
    constructor (props, context) {
        super(props, context)
        this.state = {
            value: 850
        }
    }
    handleChangeStart = () => {
        console.log('Change event started')
    };
    handleChange = value => {
        this.setState({
            value: value
        })
    };

    handleChangeComplete = () => {
        console.log('Change event completed')
    };
    render () {
        const { value } = this.state
        return (
            <div>
                <div className='slider'  style={{ marginTop:'165px',marginLeft:'319px',width:'700px',backgroundColor:'EF5350'}} >

                    <div style={{ textAlign:'center',color:'gray',fontSize:'35px',marginBottom:'82px'}}>
                        <p> What is the size of your property?</p>
                    </div>
                    <Slider
                        min={850}
                        max={5000}
                        value={value}
                        onChangeStart={this.handleChangeStart}
                        onChange={this.handleChange}
                        onChangeComplete={this.handleChangeComplete}
                    />
                    <div className='value'>{value}</div>

                </div>
            </div>
        )
    }
}
export default Horizontal
</code>```

I tried to change the background color in slider.css.

```<code>.rangeslider-horizontal .rangeslider__fill {
    background-color: red;
}
</code>```

The library needs to be installed first:

```<code>npm install react-rangeslider --save
</code>```

答:
always make your own CSS stylesheet file the last file to import after any other CSS stylesheet files to make overwrite you need
otherwise, you can always use the console in the browser to auto-detect any error by pressing F12 in the browser then go to the tab called (console)

I think you can style element you want to live in the console to know the detail of how to nesting element

you also can open the CSS file in the editor and press Ctrl+F then find the line of code you want to style then copy its property and value to your own CSS file and then you can edit it so easy

Title: Cant overwrite the custom stylesheet

Body:
I am trying to overwrite the CSS of react range slider.It uses the custom style sheet of which i need to add in the head section.My project is built on next.js

 <link rel="stylesheet" href="https://unpkg.com/react-rangeslider/umd/rangeslider.min.css" />

Otherwise, the slider doesn't show anything if i don't add the link in head even though I installed the library. It's not even overwriting the CSS. I want  to change the background color.This is my code:

import React, { Component } from 'react'
import 'react-rangeslider/lib/index.css';
import './slider.css';
import Slider from 'react-rangeslider'
class Horizontal extends Component {
    constructor (props, context) {
        super(props, context)
        this.state = {
            value: 850
        }
    }
    handleChangeStart = () => {
        console.log('Change event started')
    };
    handleChange = value => {
        this.setState({
            value: value
        })
    };

    handleChangeComplete = () => {
        console.log('Change event completed')
    };
    render () {
        const { value } = this.state
        return (

 What is the size of your property?

                    <Slider
                        min={850}
                        max={5000}
                        value={value}
                        onChangeStart={this.handleChangeStart}
                        onChange={this.handleChange}
                        onChangeComplete={this.handleChangeComplete}
                    />

{value}

        )
    }
}
export default Horizontal

I tried to change the background color in slider.css.

.rangeslider-horizontal .rangeslider__fill {
    background-color: red;
}

The library needs to be installed first:

npm install react-rangeslider --save


问:
UnhandledPromiseRejectionWarning: Error: Cannot find module using ext-gen
I want start to using ExtJS Community Edition. I follow this instruction http://docs.sencha.com/extjs/6.6.0-CE/guides/getting_started/open_tooling.html.

I try execute command:

```<code> ext-gen app -a
</code>```

But, I have this error:

```<code>i [ext]: ext-gen: E:\/cool-universal-app created
i [ext]: ext-gen: package.json created for cool-universal-app
i [ext]: ext-gen: webpack.config.js created for cool-universal-app
i [ext]: ext-gen: npm install -s started for cool-universal-app
i [ext]: ext-gen: npm install -s completed for cool-universal-app
(node:4908) UnhandledPromiseRejectionWarning: Error: Cannot find module 'E:\cool-universal-app\node_modules\@sencha\ext\package.json'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
    at Function.Module._load (internal/modules/cjs/loader.js:507:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at stepCreate (C:\Users\pi\AppData\Roaming\npm\node_modules\@sencha\ext-gen\ext-gen.js:597:22)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:4908) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:4908) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

My versions:

```<code>E:\>node -v
v10.10.0

E:\>npm -v
6.4.1

E:\>java -version
java version "11.0.2" 2019-01-15 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.2+9-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.2+9-LTS, mixed mode)
</code>```

What's wrong? Why I get this error? How to can fix it?

答:
Looks like there is a package priority problem in ext-gen, because it requires two sencha packages to be installed in advance, and throw error because they are not.

Sencha still didn't fix this issue, so I made a tiny monkey-patch to solve it.
So, open your "C:\Users\pi\AppData\Roaming\npm\node_modules@sencha\ext-gen\ext-gen.js", and add the following line before line 597:

await util.spawnPromise(command, ['install', '@sencha/ext', '@sencha/cmd'], options, []);

At the end, it must look like this:

```<code>  await util.spawnPromise(command, ['install', '@sencha/ext', '@sencha/cmd'], options, []);

  var frameworkPath = path.join(destDir, 'node_modules', npmScope, 'ext', 'package.json');
  var cmdPath = path.join(destDir, 'node_modules', npmScope, 'cmd', 'package.json');

</code>```

Body:
I want start to using ExtJS Community Edition. I follow this instruction http://docs.sencha.com/extjs/6.6.0-CE/guides/getting_started/open_tooling.html.

I try execute command:

 ext-gen app -a

But, I have this error:

i [ext]: ext-gen: E:\/cool-universal-app created
i [ext]: ext-gen: package.json created for cool-universal-app
i [ext]: ext-gen: webpack.config.js created for cool-universal-app
i [ext]: ext-gen: npm install -s started for cool-universal-app
i [ext]: ext-gen: npm install -s completed for cool-universal-app
(node:4908) UnhandledPromiseRejectionWarning: Error: Cannot find module 'E:\cool-universal-app\node_modules\@sencha\ext\package.json'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
    at Function.Module._load (internal/modules/cjs/loader.js:507:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:20:18)
    at stepCreate (C:\Users\pi\AppData\Roaming\npm\node_modules\@sencha\ext-gen\ext-gen.js:597:22)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:4908) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:4908) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

My versions:

E:\>node -v
v10.10.0

E:\>npm -v
6.4.1

E:\>java -version
java version "11.0.2" 2019-01-15 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.2+9-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.2+9-LTS, mixed mode)

What's wrong? Why I get this error? How to can fix it?

Body:
Looks like there is a package priority problem in ext-gen, because it requires two sencha packages to be installed in advance, and throw error because they are not.

Sencha still didn't fix this issue, so I made a tiny monkey-patch to solve it.
So, open your "C:\Users\pi\AppData\Roaming\npm\node_modules@sencha\ext-gen\ext-gen.js", and add the following line before line 597:

await util.spawnPromise(command, ['install', '@sencha/ext', '@sencha/cmd'], options, []);

At the end, it must look like this:

  await util.spawnPromise(command, ['install', '@sencha/ext', '@sencha/cmd'], options, []);

  var frameworkPath = path.join(destDir, 'node_modules', npmScope, 'ext', 'package.json');
  var cmdPath = path.join(destDir, 'node_modules', npmScope, 'cmd', 'package.json');


问:
ReactJs and NodeJs JSON parser issue. app.use(bodyParser.json) seems not working
I'm a beginner of ReactJs, NodeJs, express, etc and all the Javascript things. I'm trying the following code sample to learn the basics.

My issue is when I commented out the following line

```<code>app.use(bodyParser.json);
</code>```

I can see the returning data. But if uncomment it back data will not appear. Anyway, the returning data is coming as an object array as below.

```<code>[object Object],[object Object],[object Object],[object Object]
</code>```

How can parse the JSON to see the actual data?
Do I really need to specify following two lines to get JSON data? if so, how to do it?

```<code>app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json);
</code>```

Following is the full code

```<code>const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

var Client = require('node-rest-client').Client;

var client = new Client();

const app = express();

app.use(bodyParser.urlencoded({extended:true}));
app.use(cors());
app.use(bodyParser.json);

app.post('/api',(req,res)=>{

client.get("https://url", function (data, response) {
    // parsed response body as js object
    console.log("DATA : "+data);
    res.json({msg:true,data:data});

    // raw response
    //console.log("RESPONSE: "+response);
 });

 });

app.listen(3001,()=>{
console.log("listning to port 3001");
 })
</code>```

Here is the dependency versions as in the package.json file

```<code>"dependencies": {
"body-parser": "^1.18.2",
"cors": "^2.8.4",
"express": "^4.16.2",
"node-rest-client": "^3.1.0"
</code>```

}

Highly appreciate your feedback

答:
you can use it like this my friend </p>

```<code>app.post('/api',(req,res)=>{

client.get("https://url", function (data, response) {

    console.log(req.body);
    res.json({msg:true,data:req.body});

 });
</code>```

Body:
I'm a beginner of ReactJs, NodeJs, express, etc and all the Javascript things. I'm trying the following code sample to learn the basics.

My issue is when I commented out the following line

app.use(bodyParser.json);

I can see the returning data. But if uncomment it back data will not appear. Anyway, the returning data is coming as an object array as below.

[object Object],[object Object],[object Object],[object Object]

How can parse the JSON to see the actual data?
Do I really need to specify following two lines to get JSON data? if so, how to do it?

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json);

Following is the full code

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

var Client = require('node-rest-client').Client;

var client = new Client();

const app = express();

app.use(bodyParser.urlencoded({extended:true}));
app.use(cors());
app.use(bodyParser.json);

app.post('/api',(req,res)=>{

client.get("https://url", function (data, response) {
    // parsed response body as js object
    console.log("DATA : "+data);
    res.json({msg:true,data:data});

    // raw response
    //console.log("RESPONSE: "+response);
 });

 });

app.listen(3001,()=>{
console.log("listning to port 3001");
 })

Here is the dependency versions as in the package.json file

"dependencies": {
"body-parser": "^1.18.2",
"cors": "^2.8.4",
"express": "^4.16.2",
"node-rest-client": "^3.1.0"

}

Highly appreciate your feedback

Body:
you can use it like this my friend

app.post('/api',(req,res)=>{

client.get("https://url", function (data, response) {

    console.log(req.body);
    res.json({msg:true,data:req.body});

 });


问:
Why unable to parse a string | Rust
I am making decimal to binary conversion program. Why am i unable to parse a string into a number? binary_vec[i] is a character. I applied to_string() method to convert it into a string because parse() doesn't apply to a character, but it still giving me an error.

```<code>use std::io;

fn main() {
    let mut binary = String::new();
    println!("Enter a decimal: ");
    io::stdin().read_line(&mut binary)
        .ok()
        .expect("Couldn't read line");
    println!("{}",to_decimal(binary));

}

fn to_decimal(mut binary_str:String) -> String {
    let mut binary_no: u32 = binary_str.trim().parse().expect("invalid input");
    if binary_no == 0 {
        format!("{}",binary_no)
                }
    else {
        let mut bits = String::new();
        let mut binary_vec: Vec<char> = binary_str.chars().collect();
        let mut result = 0;
        let mut i = 0;
        while i <=binary_str.len()-2{
            let mut result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
            i = i +1;
        }
        format!("{}",result)
        }
}
</code>```

Result:

```<code> Compiling sixteen v0.1.0 (C:\Users\Muhammad.3992348\Desktop\rust\hackathon\sixteen)
warning: unused variable: `bits`
  --> src\main.rs:19:17
   |
19 |         let mut bits = String::new();
   |                 ^^^^ help: consider prefixing with an underscore: `_bits`
   |
   = note: #[warn(unused_variables)] on by default

warning: unused variable: `result`
  --> src\main.rs:24:21
   |
24 |             let mut result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
   |                     ^^^^^^ help: consider prefixing with an underscore: `_result`

warning: variable does not need to be mutable
  --> src\main.rs:13:15
   |
13 | fn to_decimal(mut binary_str:String) -> String {
   |               ----^^^^^^^^^^
   |               |
   |               help: remove this `mut`
   |
   = note: #[warn(unused_mut)] on by default

warning: variable does not need to be mutable
  --> src\main.rs:14:9
   |
14 |     let mut binary_no: u32 = binary_str.trim().parse().expect("invalid input");
   |         ----^^^^^^^^^
   |         |
   |         help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:19:13
   |
19 |         let mut bits = String::new();
   |             ----^^^^
   |             |
   |             help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:20:13
   |
20 |         let mut binary_vec: Vec<char> = binary_str.chars().collect();
   |             ----^^^^^^^^^^
   |             |
   |             help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:21:13
   |
21 |         let mut result = 0;
   |             ----^^^^^^
   |             |
   |             help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:24:17
   |
24 |             let mut result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
   |                 ----^^^^^^
   |                 |
   |                 help: remove this `mut`

    Finished dev [unoptimized + debuginfo] target(s) in 1.04s
     Running `target\debug\sixteen.exe`
Enter a decimal:
100
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', src\libcore\result.rs:997:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
error: process didn't exit successfully: `target\debug\sixteen.exe` (exit code: 101)
</code>```

Edit:
I have input 100 and I expect to get 4 at output.

答:
There are a lot of problems with the code as written. The good news is that you can fix most of the problems by listening to the compiler warnings!

```<code>  --> src/main.rs:19:17
   |
19 |         let mut bits = String::new();
   |                 ^^^^ help: consider prefixing with an underscore: `_bits`
   |
   = note: #[warn(unused_variables)] on by default
</code>```

This tells you that the variable bits isn't used after this declaration. If you intend to use it later, you can just comment it out for now.

```<code>warning: unused variable: `result`
  --> src/main.rs:24:21
   |
24 |             let mut result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
   |                     ^^^^^^ help: consider prefixing with an underscore: `_result`
   |
   = note: #[warn(unused_variables)] on by default
</code>```

This is the big one. This tells us that the variable result is unused. But wait! we're using it right here! Nope! Actually, by using let mut here, we're making a new variable and shadowing the old one. What you want is to instead overwrite the old value. Simply change let mut result = ... to result = ....

Now if we run the program again and input 100, we'll get an output of 5. This still doesn't seem right, but we still have a few warnings to fix, so let's come back to this.

```<code>warning: variable does not need to be mutable
  --> src/main.rs:13:15
   |
13 | fn to_decimal(mut binary_str:String) -> String {
   |               ----^^^^^^^^^^
   |               |
   |               help: remove this `mut`
   |
   = note: #[warn(unused_mut)] on by default
</code>```

If we aren't going to mutate the input string, we shouldn't make it mutable. Just remove the mut. Same for the other two warnings (lines 14 and 20).

Alright! Now we can run the program without any warnings. However, there are some more advanced lints we can run using cargo clippy. If you don't have clippy installed yet, you can install it with rustup install component clippy.

Now we have a few more warnings to take care of.

```<code>warning: operator precedence can trip the unwary
  --> src/main.rs:24:32
   |
24 |             result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
   |                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider parenthesizing your expression: `(binary_vec[i].to_string().parse::<u32>().unwrap() * 2) ^ (i as u32)`
   |
   = note: #[warn(clippy::precedence)] on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#precedence
</code>```

Uh oh. Clippy is telling us that the precedence rules indicate that * is evaluated before ^. That's not what we'd expect from multiplication and exponents. It turns out that ^ is not the exponent operator. Instead, it's the bitwise xor. If we want powers of a number, we can use the pow method, so replace 2 ^ (i as u32) with 2.pow(i as u32). This will cause a compiler error with the message error[E0689]: can't call method `pow` on ambiguous numeric type `{integer}`. Ok. We can make the numeric type unambiguous using a suffix. Change it to 2_u32.pow(i as u32).

We can fix the other three warnings that Clippy gives us just by using the suggestion. After that, Clippy gives one more warning, which also is fixed with just the suggestion.

Before we continue, let's make our code a bit prettier by running cargo fmt. Finally, the code looks like this:

```<code>use std::io;

fn main() {
    let mut binary = String::new();
    println!("Enter a decimal: ");
    io::stdin()
        .read_line(&mut binary)
        .expect("Couldn't read line");
    println!("{}", to_decimal(binary));
}

fn to_decimal(binary_str: String) -> String {
    let binary_no: u32 = binary_str.trim().parse().expect("invalid input");
    if binary_no == 0 {
        format!("{}", binary_no)
    } else {
        //let mut bits = String::new();
        let binary_vec: Vec<char> = binary_str.chars().collect();
        let mut result = 0;
        let mut i = 0;
        while i <= binary_str.len() - 2 {
            result += binary_vec[i].to_string().parse::<u32>().unwrap() * 2_u32.pow(i as u32);
            i += 1;
        }
        format!("{}", result)
    }
}
</code>```

We fixed two bugs and cleaned up the code only using compiler warnings and basic tools! Pretty good, eh? But now if we input 100, our output is 1. That isn't right. Let's add some debug statements to see if we can see what's going on.

```<code>result += dbg!(binary_vec[i].to_string().parse::<u32>().unwrap()) * dbg!(2_u32.pow(i as u32));
</code>```

If we run it now, here's what we get.

```<code>Enter a decimal:
100
[src/main.rs:22] binary_vec[i].to_string().parse::<u32>().unwrap() = 1
[src/main.rs:22] 2u32.pow(i as u32) = 1
[src/main.rs:22] binary_vec[i].to_string().parse::<u32>().unwrap() = 0
[src/main.rs:22] 2u32.pow(i as u32) = 2
[src/main.rs:22] binary_vec[i].to_string().parse::<u32>().unwrap() = 0
[src/main.rs:22] 2u32.pow(i as u32) = 4
1
</code>```

We can see that it's parsing the digits correctly: binary_vec[i].to_string().parse::<u32>().unwrap() is 1, then 0, then 0. The powers of 2 look fine too. The problem here is that it's backwards! We want the left digit to be multiplied with the highest power of 2. Let me note that this is the part of the code where you're the least idiomatic. It's much better to use, at the very least, a for loop for this kind of thing. Iterators would be even better if you can manage it.

In any case, we can reverse the order by making our powers go from binary_str.len() - 2 down to 0 instead of the other way around. Thus, we can change the code to

```<code>while i <= binary_str.len() - 2 {
    result += dbg!(binary_vec[i].to_string().parse::<u32>().unwrap()) * dbg!(2_u32.pow((binary_str.len() - 2 - i) as u32));
    i += 1;
}
</code>```

We get

```<code>Enter a decimal:
100
[src/main.rs:22] binary_vec[i].to_string().parse::<u32>().unwrap() = 1
[src/main.rs:22] 2u32.pow((binary_str.len() - 2 - i) as u32) = 4
[src/main.rs:22] binary_vec[i].to_string().parse::<u32>().unwrap() = 0
[src/main.rs:22] 2u32.pow((binary_str.len() - 2 - i) as u32) = 2
[src/main.rs:22] binary_vec[i].to_string().parse::<u32>().unwrap() = 0
[src/main.rs:22] 2u32.pow((binary_str.len() - 2 - i) as u32) = 1
4
</code>```

so we see that the powers are correctly reversed from 4 down to 1. And our answer is finally correct! Test it on a few more inputs and try to find some edge cases. There are still some more bugs to find. Once you're happy with your code, take out the debug statements.

Title: Why unable to parse a string | Rust

Body:
I am making decimal to binary conversion program. Why am i unable to parse a string into a number? binary_vec[i] is a character. I applied to_string() method to convert it into a string because parse() doesn't apply to a character, but it still giving me an error.

use std::io;

fn main() {
    let mut binary = String::new();
    println!("Enter a decimal: ");
    io::stdin().read_line(&mut binary)
        .ok()
        .expect("Couldn't read line");
    println!("{}",to_decimal(binary));

}

fn to_decimal(mut binary_str:String) -> String {
    let mut binary_no: u32 = binary_str.trim().parse().expect("invalid input");
    if binary_no == 0 {
        format!("{}",binary_no)
                }
    else {
        let mut bits = String::new();
        let mut binary_vec: Vec<char> = binary_str.chars().collect();
        let mut result = 0;
        let mut i = 0;
        while i <=binary_str.len()-2{
            let mut result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
            i = i +1;
        }
        format!("{}",result)
        }
}

Result:

 Compiling sixteen v0.1.0 (C:\Users\Muhammad.3992348\Desktop\rust\hackathon\sixteen)
warning: unused variable: `bits`
  --> src\main.rs:19:17
   |
19 |         let mut bits = String::new();
   |                 ^^^^ help: consider prefixing with an underscore: `_bits`
   |
   = note: #[warn(unused_variables)] on by default

warning: unused variable: `result`
  --> src\main.rs:24:21
   |
24 |             let mut result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
   |                     ^^^^^^ help: consider prefixing with an underscore: `_result`

warning: variable does not need to be mutable
  --> src\main.rs:13:15
   |
13 | fn to_decimal(mut binary_str:String) -> String {
   |               ----^^^^^^^^^^
   |               |
   |               help: remove this `mut`
   |
   = note: #[warn(unused_mut)] on by default

warning: variable does not need to be mutable
  --> src\main.rs:14:9
   |
14 |     let mut binary_no: u32 = binary_str.trim().parse().expect("invalid input");
   |         ----^^^^^^^^^
   |         |
   |         help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:19:13
   |
19 |         let mut bits = String::new();
   |             ----^^^^
   |             |
   |             help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:20:13
   |
20 |         let mut binary_vec: Vec<char> = binary_str.chars().collect();
   |             ----^^^^^^^^^^
   |             |
   |             help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:21:13
   |
21 |         let mut result = 0;
   |             ----^^^^^^
   |             |
   |             help: remove this `mut`

warning: variable does not need to be mutable
  --> src\main.rs:24:17
   |
24 |             let mut result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
   |                 ----^^^^^^
   |                 |
   |                 help: remove this `mut`

    Finished dev [unoptimized + debuginfo] target(s) in 1.04s
     Running `target\debug\sixteen.exe`
Enter a decimal:
100
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', src\libcore\result.rs:997:5
note: Run with `RUST_BACKTRACE=1` environment variable to display a backtrace.
error: process didn't exit successfully: `target\debug\sixteen.exe` (exit code: 101)

Edit:
I have input 100 and I expect to get 4 at output.

Body:
There are a lot of problems with the code as written. The good news is that you can fix most of the problems by listening to the compiler warnings!

  --> src/main.rs:19:17
   |
19 |         let mut bits = String::new();
   |                 ^^^^ help: consider prefixing with an underscore: `_bits`
   |
   = note: #[warn(unused_variables)] on by default

This tells you that the variable bits isn't used after this declaration. If you intend to use it later, you can just comment it out for now.

warning: unused variable: `result`
  --> src/main.rs:24:21
   |
24 |             let mut result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
   |                     ^^^^^^ help: consider prefixing with an underscore: `_result`
   |
   = note: #[warn(unused_variables)] on by default

This is the big one. This tells us that the variable result is unused. But wait! we're using it right here! Nope! Actually, by using let mut here, we're making a new variable and shadowing the old one. What you want is to instead overwrite the old value. Simply change let mut result = ... to result = ....

Now if we run the program again and input 100, we'll get an output of 5. This still doesn't seem right, but we still have a few warnings to fix, so let's come back to this.

warning: variable does not need to be mutable
  --> src/main.rs:13:15
   |
13 | fn to_decimal(mut binary_str:String) -> String {
   |               ----^^^^^^^^^^
   |               |
   |               help: remove this `mut`
   |
   = note: #[warn(unused_mut)] on by default

If we aren't going to mutate the input string, we shouldn't make it mutable. Just remove the mut. Same for the other two warnings (lines 14 and 20).

Alright! Now we can run the program without any warnings. However, there are some more advanced lints we can run using cargo clippy. If you don't have clippy installed yet, you can install it with rustup install component clippy.

Now we have a few more warnings to take care of.

warning: operator precedence can trip the unwary
  --> src/main.rs:24:32
   |
24 |             result = result + (binary_vec[i].to_string().parse::<u32>().unwrap() * 2^(i as u32));
   |                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider parenthesizing your expression: `(binary_vec[i].to_string().parse::<u32>().unwrap() * 2) ^ (i as u32)`
   |
   = note: #[warn(clippy::precedence)] on by default
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#precedence

Uh oh. Clippy is telling us that the precedence rules indicate that * is evaluated before ^. That's not what we'd expect from multiplication and exponents. It turns out that ^ is not the exponent operator. Instead, it's the bitwise xor. If we want powers of a number, we can use the pow method, so replace 2 ^ (i as u32) with 2.pow(i as u32). This will cause a compiler error with the message error[E0689]: can't call method `pow` on ambiguous numeric type `{integer}`. Ok. We can make the numeric type unambiguous using a suffix. Change it to 2_u32.pow(i as u32).

We can fix the other three warnings that Clippy gives us just by using the suggestion. After that, Clippy gives one more warning, which also is fixed with just the suggestion.

Before we continue, let's make our code a bit prettier by running cargo fmt. Finally, the code looks like this:

use std::io;

fn main() {
    let mut binary = String::new();
    println!("Enter a decimal: ");
    io::stdin()
        .read_line(&mut binary)
        .expect("Couldn't read line");
    println!("{}", to_decimal(binary));
}

fn to_decimal(binary_str: String) -> String {
    let binary_no: u32 = binary_str.trim().parse().expect("invalid input");
    if binary_no == 0 {
        format!("{}", binary_no)
    } else {
        //let mut bits = String::new();
        let binary_vec: Vec<char> = binary_str.chars().collect();
        let mut result = 0;
        let mut i = 0;
        while i <= binary_str.len() - 2 {
            result += binary_vec[i].to_string().parse::<u32>().unwrap() * 2_u32.pow(i as u32);
            i += 1;
        }
        format!("{}", result)
    }
}

We fixed two bugs and cleaned up the code only using compiler warnings and basic tools! Pretty good, eh? But now if we input 100, our output is 1. That isn't right. Let's add some debug statements to see if we can see what's going on.

result += dbg!(binary_vec[i].to_string().parse::<u32>().unwrap()) * dbg!(2_u32.pow(i as u32));

If we run it now, here's what we get.

Enter a decimal:
100
[src/main.rs:22] binary_vec[i].to_string().parse::<u32>().unwrap() = 1
[src/main.rs:22] 2u32.pow(i as u32) = 1
[src/main.rs:22] binary_vec[i].to_string().parse::<u32>().unwrap() = 0
[src/main.rs:22] 2u32.pow(i as u32) = 2
[src/main.rs:22] binary_vec[i].to_string().parse::<u32>().unwrap() = 0
[src/main.rs:22] 2u32.pow(i as u32) = 4
1

We can see that it's parsing the digits correctly: binary_vec[i].to_string().parse::<u32>().unwrap() is 1, then 0, then 0. The powers of 2 look fine too. The problem here is that it's backwards! We want the left digit to be multiplied with the highest power of 2. Let me note that this is the part of the code where you're the least idiomatic. It's much better to use, at the very least, a for loop for this kind of thing. Iterators would be even better if you can manage it.

In any case, we can reverse the order by making our powers go from binary_str.len() - 2 down to 0 instead of the other way around. Thus, we can change the code to

while i <= binary_str.len() - 2 {
    result += dbg!(binary_vec[i].to_string().parse::<u32>().unwrap()) * dbg!(2_u32.pow((binary_str.len() - 2 - i) as u32));
    i += 1;
}

We get

Enter a decimal:
100
[src/main.rs:22] binary_vec[i].to_string().parse::<u32>().unwrap() = 1
[src/main.rs:22] 2u32.pow((binary_str.len() - 2 - i) as u32) = 4
[src/main.rs:22] binary_vec[i].to_string().parse::<u32>().unwrap() = 0
[src/main.rs:22] 2u32.pow((binary_str.len() - 2 - i) as u32) = 2
[src/main.rs:22] binary_vec[i].to_string().parse::<u32>().unwrap() = 0
[src/main.rs:22] 2u32.pow((binary_str.len() - 2 - i) as u32) = 1
4

so we see that the powers are correctly reversed from 4 down to 1. And our answer is finally correct! Test it on a few more inputs and try to find some edge cases. There are still some more bugs to find. Once you're happy with your code, take out the debug statements.


问:
Location Service no longer backgrounding
I have been using code from Xamarin's Background Location demo in my app for over a year and never had any issues with background location updates, until about two weeks ago. I'm no longer seeing my logs when the application is in the background from this code below:

LocationService.cs

```<code>#region ILocationListener implementation
        // ILocationListener is a way for the Service to subscribe for updates
        // from the System location Service

        public void OnLocationChanged(Android.Locations.Location location)
        {
            this.LocationChanged(this, new LocationChangedEventArgs(location));

            Log.Debug(logTag, DateTime.UtcNow.ToString());

            Log.Debug(logTag, "---- LOCATION UPDATED");

            if (!Settings.IsLoggedIn)
            {
                return;
            }
            else if (Settings.IsAuthExpired)
            {
                Task.Run(() => loginStore.Refresh());
            }

            // This should be updating every time we request new location updates
            // both when the app is in the background, and in the foreground
            //Log.Debug(logTag, String.Format("Latitude is {0}", location.Latitude));
            //Log.Debug(logTag, String.Format("Longitude is {0}", location.Longitude));

            Settings.Latitude = location.Latitude;
            Settings.Longitude = location.Longitude;

            Task.Run(() => dataStore.UpdateLocation(location.Latitude, location.Longitude));
        }
</code>```

Here is my manifest file (without the name of my app, etc). I checked through my history and this file has only gone under version number changes for 8 months (so nothing major within the past couple of weeks to warrant an issue with background locations).

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="60" android:versionName="0.1.7" package="REDACTED">
    <uses-sdk android:minSdkVersion="26" android:targetSdkVersion="28" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_SURFACE_FLINGER" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.PERSISTENT_ACTIVITY" />
    <application android:label="REDACTED" android:icon="@drawable/logo_size_icon">
        <provider android:name="android.support.v4.content.FileProvider" android:authorities="REDACTED.fileprovider" android:exported="false" android:grantUriPermissions="true">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
        </provider>
        <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
        <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="${applicationId}" />
            </intent-filter>
        </receiver>
    </application>
</manifest>
</code>```

答: Found the answer with this closed Issue on the Xamarin Repo: https://github.com/xamarin/mobile-samples/issues/99</p>

Body:
I have been using code from Xamarin's Background Location demo in my app for over a year and never had any issues with background location updates, until about two weeks ago. I'm no longer seeing my logs when the application is in the background from this code below:

LocationService.cs

#region ILocationListener implementation
        // ILocationListener is a way for the Service to subscribe for updates
        // from the System location Service

        public void OnLocationChanged(Android.Locations.Location location)
        {
            this.LocationChanged(this, new LocationChangedEventArgs(location));

            Log.Debug(logTag, DateTime.UtcNow.ToString());

            Log.Debug(logTag, "---- LOCATION UPDATED");

            if (!Settings.IsLoggedIn)
            {
                return;
            }
            else if (Settings.IsAuthExpired)
            {
                Task.Run(() => loginStore.Refresh());
            }

            // This should be updating every time we request new location updates
            // both when the app is in the background, and in the foreground
            //Log.Debug(logTag, String.Format("Latitude is {0}", location.Latitude));
            //Log.Debug(logTag, String.Format("Longitude is {0}", location.Longitude));

            Settings.Latitude = location.Latitude;
            Settings.Longitude = location.Longitude;

            Task.Run(() => dataStore.UpdateLocation(location.Latitude, location.Longitude));
        }

Here is my manifest file (without the name of my app, etc). I checked through my history and this file has only gone under version number changes for 8 months (so nothing major within the past couple of weeks to warrant an issue with background locations).

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="60" android:versionName="0.1.7" package="REDACTED">
    <uses-sdk android:minSdkVersion="26" android:targetSdkVersion="28" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_SURFACE_FLINGER" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.PERSISTENT_ACTIVITY" />
    <application android:label="REDACTED" android:icon="@drawable/logo_size_icon">
        <provider android:name="android.support.v4.content.FileProvider" android:authorities="REDACTED.fileprovider" android:exported="false" android:grantUriPermissions="true">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
        </provider>
        <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdInternalReceiver" android:exported="false" />
        <receiver android:name="com.google.firebase.iid.FirebaseInstanceIdReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <action android:name="com.google.android.c2dm.intent.REGISTRATION" />
                <category android:name="${applicationId}" />
            </intent-filter>
        </receiver>
    </application>
</manifest>


问:
How do I change the logic of a 2 dimension std::vector to have vector[row] [col] instead of vector[col] [row] in this example that I provide?
I am experimenting with vectors for the first time. So, to experiment, I created a class that constructs a 2d vector of integers and initializes them with numbers 0 through 9 in this order.

Here's the example I created:

#include <iostream>
#include <vector>

class VectorTest
{
private:
    std::vector< std::vector<int> > m_v;

public:
    VectorTest(int x, int y)
    {
        m_v.resize(y);
        for (auto &element : m_v)
            element.resize(x);

        int count {0};
        for (int i {0}; i < m_v.size(); ++i)
        {
            for (int j {0}; j < m_v[i].size(); ++j)
                m_v[i][j] = count++ % 10;
            }
        }
    }

    void print()
    {
        for (int i {0}; i < m_v.size(); ++i)
        {
            for (int j {0}; j < m_v[i].size(); ++j)
            {
                std::cout << m_v[i][j];
            }
            std::cout << '\n';
        }
    }

    void print(int x, int y)
    {
        std::cout << m_v[y][x];
    }

};

int main()
{
    VectorTest v(9, 9);
    v.print();
    std::cout << '\n';
    v.print (6, 4);

    return 0;
}
```

My question is: how can I modify this program to make m_v[x][y] instead of m_v[y][x] basically switch around the row and column indexes in the vector?

Considering that x is a row and y is a column, how can I make the inner vector store the columns and the outside vector store the rows? Because right now I have to access the coords as m_v[y][x] but I wanted this to be accessed as m_v[x][y].

答:
Why don't just swap places "x" and "y" in constructor? Nothing else is needed.

Or I misunderstood the problem?

```<code>    VectorTest(int x, int y)
    {
        m_v.resize(x /* was "y" */);
        for (auto &element : m_v)
            element.resize(y /* was "x" */);

        int count {0};
        for (int i {0}; i < m_v.size(); ++i)
        {
            for (int j {0}; j < m_v[i].size(); ++j)
                m_v[i][j] = count++ % 10;
            }
        }
    }
</code>```

Body:
I am experimenting with vectors for the first time. So, to experiment, I created a class that constructs a 2d vector of integers and initializes them with numbers 0 through 9 in this order.

Here's the example I created:

#include <iostream>
#include <vector>

class VectorTest
{
private:
    std::vector< std::vector<int> > m_v;

public:
    VectorTest(int x, int y)
    {
        m_v.resize(y);
        for (auto &element : m_v)
            element.resize(x);

        int count {0};
        for (int i {0}; i < m_v.size(); ++i)
        {
            for (int j {0}; j < m_v[i].size(); ++j)
                m_v[i][j] = count++ % 10;
            }
        }
    }

    void print()
    {
        for (int i {0}; i < m_v.size(); ++i)
        {
            for (int j {0}; j < m_v[i].size(); ++j)
            {
                std::cout << m_v[i][j];
            }
            std::cout << '\n';
        }
    }

    void print(int x, int y)
    {
        std::cout << m_v[y][x];
    }

};

int main()
{
    VectorTest v(9, 9);
    v.print();
    std::cout << '\n';
    v.print (6, 4);

    return 0;
}

My question is: how can I modify this program to make m_v[x][y] instead of m_v[y][x] basically switch around the row and column indexes in the vector?

Considering that x is a row and y is a column, how can I make the inner vector store the columns and the outside vector store the rows? Because right now I have to access the coords as m_v[y][x] but I wanted this to be accessed as m_v[x][y].

Body:
Why don't just swap places "x" and "y" in constructor? Nothing else is needed.

Or I misunderstood the problem?

    VectorTest(int x, int y)
    {
        m_v.resize(x /* was "y" */);
        for (auto &element : m_v)
            element.resize(y /* was "x" */);

        int count {0};
        for (int i {0}; i < m_v.size(); ++i)
        {
            for (int j {0}; j < m_v[i].size(); ++j)
                m_v[i][j] = count++ % 10;
            }
        }
    }


问:
Nuxt Layout update data on every route
I am new to Nuxt/Vue and am getting confused about how data works between different pages. I want to display a light or dark logo depending on if I am on the index page or not. When navigating between pages the data doesn't update the route name so the logo doesnt change: Layout page below.

```<code><template>
  <main>
    <img v-if="page != 'index'" src="~/assets/img/logo-white.svg">
    <img v-else src="~/assets/img/logo-dark.svg">
    <nuxt />
  </main>
</template>

<script>
  export default {
    data () {
      return {
         page: this.$route.name
      }
    }
  }
</script>
</code>```

Any help would be great.
Thanks,
Jamie

答:
In a nuxt layout, every page is rendered in place of the <nuxt /> tag.

You are setting the reactive property page in the layout which is mounted only once in the beginning, and all other pages are rendered inside it later. So when a page change occurs the layout doesn't re-mount and the value of page remains the same.

You can add a watcher on the route like this:

```<code><script>
  export default {
    data () {
      return {
        page: this.$route.name
      }
    }
    watch: {
     '$route': function (value) {
       this.page = value.name
      }
    }
  }
</script>
</code>```

So, now everytime the route changes, page will updated with the new name of the route.

Title: Nuxt Layout update data on every route

Body:
I am new to Nuxt/Vue and am getting confused about how data works between different pages. I want to display a light or dark logo depending on if I am on the index page or not. When navigating between pages the data doesn't update the route name so the logo doesnt change: Layout page below.

<template>

    <nuxt />

</template>

Any help would be great.
Thanks,
Jamie

Body:
In a nuxt layout, every page is rendered in place of the <nuxt /> tag.

You are setting the reactive property page in the layout which is mounted only once in the beginning, and all other pages are rendered inside it later. So when a page change occurs the layout doesn't re-mount and the value of page remains the same.

You can add a watcher on the route like this:

<script>
  export default {
    data () {
      return {
        page: this.$route.name
      }
    }
    watch: {
     '$route': function (value) {
       this.page = value.name
      }
    }
  }
</script>

So, now everytime the route changes, page will updated with the new name of the route.


问:
How to pass a value from a fluid page template into a ext:mask content element template?
In TYPO3 7 LTS with ext:mask, I would like to pass a value from my page template into the FLUIDTEMPLATE that is rendered via the mask extension.

An example for what I'm trying to achieve:

The content element has content that describes a car: A Volvo, 4WD...

In the page template, I want to display that "car" in different
  colors.  So the page template would be able to command: "get the first
  car, and show it in green. Then the second car and show it in yellow".
  (and no, it's got nothing to do with css..)

If this has to be done once onan entire page, I can use

```<code>`tt_content.default.mask_car.settings.color = green`
</code>```

Or (for the record) if the purpose of that variable would be to modify the presentation, I could use:

```<code>`tt_content.default.mask_car.settings.file = path/to/Mask/Content/Templates/car_green.html`
</code>```

But if there are several instances of the same content element on the page, that approach is no good.

How to pass different values into different instances of the same CE on a page?

答:
I'm revisiting this question, in TYPO3 9 with mask 4.x, this works:</p>

```<code>lib.my_content_element {
  renderObj.mask_content_text.settings.test = 123
}
</code>```

Body:
In TYPO3 7 LTS with ext:mask, I would like to pass a value from my page template into the FLUIDTEMPLATE that is rendered via the mask extension.

An example for what I'm trying to achieve:

The content element has content that describes a car: A Volvo, 4WD...

In the page template, I want to display that "car" in different
  colors.  So the page template would be able to command: "get the first
  car, and show it in green. Then the second car and show it in yellow".
  (and no, it's got nothing to do with css..)

If this has to be done once onan entire page, I can use

`tt_content.default.mask_car.settings.color = green`

Or (for the record) if the purpose of that variable would be to modify the presentation, I could use:

`tt_content.default.mask_car.settings.file = path/to/Mask/Content/Templates/car_green.html`

But if there are several instances of the same content element on the page, that approach is no good.

How to pass different values into different instances of the same CE on a page?

Body:
I'm revisiting this question, in TYPO3 9 with mask 4.x, this works:

lib.my_content_element {
  renderObj.mask_content_text.settings.test = 123
}


问:
Is it possible to disable automatic type casting for Mongoose SchemaTypes?
For a model with this Schema...

{
  name: { type: String }
}

...the following automatically casts the provided value to a string instead of enforcing the type:

document.name = 2;
document.validate(err => {
  // Err is null, document.name === '2'
})

Is there a simple way to disable this behaviour?

答: Just in case anyone else stumbles upon this, it looks like mongoose will be supporting this according to this issue.</p>


问:
Creating all possible ways of a boolean array of size n in Python3
I want to create a list of all possible booleans with a given length n, using Python 3.

```<code># suppose n = 2
# the expected output should be
output = [[0, 0], [0, 1], [1, 0], [1, 1]]
</code>```

In my real application, n is never larger than 10.

A similar post is here but for Java.

Could you please show me how to do it in Python 3? Thanks in advance.

答:
A good opportunity to leverage itertools:

```<code>def boolean_combinations(n):
    return [
        *itertools.product(
            *[range(2) for _ in range(n)]
    )]
</code>```

Body:
I want to create a list of all possible booleans with a given length n, using Python 3.

# suppose n = 2
# the expected output should be
output = [[0, 0], [0, 1], [1, 0], [1, 1]]

In my real application, n is never larger than 10.

A similar post is here but for Java.

Could you please show me how to do it in Python 3? Thanks in advance.

Body:
A good opportunity to leverage itertools:

def boolean_combinations(n):
    return [
        *itertools.product(
            *[range(2) for _ in range(n)]
    )]


问:
Best datatype to store logs
I have a MySQL table named requests. It's growing so fast. Currently, it has 3 million rows. Also, the current table engine is "InnoDB".

Few days ago, I got this error:

ERROR 1114 (HY000): The table is full

I've resolved the problem (temporary I guess) by adding this to MySQL configuration:

```<code>innodb_data_file_path = ibdata1:10M:autoextend
</code>```

But still sometimes my serves goes to down and I have to restart it to make it available. Recently, I've made that table empty and I got rid of being down.

But it will be full again soon. Any idea how can I fix that issue? Should I use another engine for that table? Should I use compressed type-row for it? or what?

Noted that, sometimes I need to select from that table and it has one index on a column (in addition to pk)

答:
You are limited by disk space.  You must keep an eye on that and take action before you get to "table full".

If you store the data in a MyISAM table, you can go twice as long before getting "table full".  If you simply write to a disk file (no database, no queries; etc), you can squeeze a little more in before "disk full".

Do you need to "purge" old data?  That way you could continue to receive new data without ever hitting "table full".  The best way to do that is via InnoDB and PARTITION BY RANGE(TO_DAYS(...)).  If you purge anything over a month old, use daily partitions.  For, say, 90 days, use weekly partitions.  More discussion:  http://mysql.rjweb.org/doc.php/partitionmaint

What will you do with the data?  Analyze it?  Search it?  What SQL queries do you envision?  Answer those; there could be other tips.

Title: Best datatype to store logs

Body:
I have a MySQL table named requests. It's growing so fast. Currently, it has 3 million rows. Also, the current table engine is "InnoDB".

Few days ago, I got this error:

ERROR 1114 (HY000): The table is full

I've resolved the problem (temporary I guess) by adding this to MySQL configuration:

innodb_data_file_path = ibdata1:10M:autoextend

But still sometimes my serves goes to down and I have to restart it to make it available. Recently, I've made that table empty and I got rid of being down.

But it will be full again soon. Any idea how can I fix that issue? Should I use another engine for that table? Should I use compressed type-row for it? or what?

Noted that, sometimes I need to select from that table and it has one index on a column (in addition to pk)