问:
How can I implement this more efficiently
So I have a function (I'm writing this in a pseudo-functional language, I hope its clear):

```<code>dampen (lr : Num, x : Num) = x + lr*(1-x)
</code>```

And I wish to apply this n times to a value x.  I could implement it recursively:

```<code>dampenN (0, lr, x) = dampen(lr, x)
dampenN (n, lr, x) = dampenN(n-1, lr, dampen(x))
</code>```

But there must be a way I can do it mathematically without resorting to an iterative procedure (recursive, or a loop).

Unfortunately my algebra skills are rusty beyond belief, can anyone help?

答:
My algebra skill suck too, but I decided to refactor the equation a bit and started examining some of the cases, d0, and d1:

```<code>d0 = x + lr(1-x) => x + lr - lr*x => (1 - lr)x + lr
d1 = (1 - lr)[(1 - lr)x + lr] + lr => (1 - lr)^2 x + lr(1 - lr) + lr
</code>```

Basically if you start seeing the quadratic, you can start seeing the cubic form and so on.

At which point the x is only used once, and you just have to deal with the exponentiation of all the sub terms of the form (1 - lr)^n.

OwnerDisplayName: sanity

Body:
So I have a function (I'm writing this in a pseudo-functional language, I hope its clear):

dampen (lr : Num, x : Num) = x + lr*(1-x)

And I wish to apply this n times to a value x.  I could implement it recursively:

dampenN (0, lr, x) = dampen(lr, x)
dampenN (n, lr, x) = dampenN(n-1, lr, dampen(x))

But there must be a way I can do it mathematically without resorting to an iterative procedure (recursive, or a loop).

Unfortunately my algebra skills are rusty beyond belief, can anyone help?

Body:
My algebra skill suck too, but I decided to refactor the equation a bit and started examining some of the cases, d0, and d1:

d0 = x + lr(1-x) => x + lr - lr*x => (1 - lr)x + lr
d1 = (1 - lr)[(1 - lr)x + lr] + lr => (1 - lr)^2 x + lr(1 - lr) + lr

Basically if you start seeing the quadratic, you can start seeing the cubic form and so on.

At which point the x is only used once, and you just have to deal with the exponentiation of all the sub terms of the form (1 - lr)^n.

OwnerDisplayName: Saem


来源: stackexchange

问:
Have to change subdomain to get page to update
I am working with XML on a site and each time I run a script to update the XML file, I have to change the subdomain (I've gone from "" to "www" to "fdasekjlfw" and so on) to have the refresh do anything. After about an hour, the update is seen regardless of the subdomain.

I'm wondering if I'm doing something incorrectly. It doesn't seem right to have to do this each time.

My web host is FatCow and the script was in PHP, if that helps.

Thanks

ADDITIONAL INFO:

I spoke with a fellow that uses the same server (different site though). He says he's had the exact same problem periodically when updating a MySQL db, and usually when changing an external CSS file (but not always). The scripts for both his and mine are PHP (no scripting with the CSS files though).

In my case, submitting a form sends about 4 files (images) and 10 variables to the script. I'm using the DOMDocument class to remove, add, and update. Here is one of the scripts used (they are all independent, but the same problem arises).

```<code><?php

## Deletes shirt row ##

$delMark = $_GET['href'];
$doc = new DOMDocument;
$doc->load('../xml/shirts.xml');
$docRoot = $doc->documentElement;

$shirts = $docRoot->getElementsByTagName('shirt');

$nodeToRemove = null;

// find the delete marker
foreach ($shirts as $domElement)
{
  $attrValue = $domElement->getAttribute('href');

  if ($attrValue == $delMark)
  {
    $nodeToRemove = $domElement;
    break;
  }

}

if ($nodeToRemove != null)
    $docRoot->removeChild($nodeToRemove);

// save to XML file
$fp = fopen("../xml/shirts.xml", wb);
fwrite($fp, $doc->saveXML());
fclose($fp);

?>
</code>```

Thank you

答: I know that XML files are usually cached in the browser. So the script is probably doing its job, but the XML is not being reloaded because of that.  Perhaps you can change the script to append a querystring to the XML file, which should force a refresh (untested, so I am not sure this works).  For example (although with css): Force refresh of cached CSS data

ContentLicense: CC BY-SA 3.0

Body:
I am working with XML on a site and each time I run a script to update the XML file, I have to change the subdomain (I've gone from "" to "www" to "fdasekjlfw" and so on) to have the refresh do anything. After about an hour, the update is seen regardless of the subdomain.

I'm wondering if I'm doing something incorrectly. It doesn't seem right to have to do this each time.

My web host is FatCow and the script was in PHP, if that helps.

Thanks

ADDITIONAL INFO:

I spoke with a fellow that uses the same server (different site though). He says he's had the exact same problem periodically when updating a MySQL db, and usually when changing an external CSS file (but not always). The scripts for both his and mine are PHP (no scripting with the CSS files though).

In my case, submitting a form sends about 4 files (images) and 10 variables to the script. I'm using the DOMDocument class to remove, add, and update. Here is one of the scripts used (they are all independent, but the same problem arises).

<?php

## Deletes shirt row ##

$delMark = $_GET['href'];
$doc = new DOMDocument;
$doc->load('../xml/shirts.xml');
$docRoot = $doc->documentElement;

$shirts = $docRoot->getElementsByTagName('shirt');

$nodeToRemove = null;

// find the delete marker
foreach ($shirts as $domElement)
{
  $attrValue = $domElement->getAttribute('href');

  if ($attrValue == $delMark)
  {
    $nodeToRemove = $domElement;
    break;
  }

}

if ($nodeToRemove != null)
    $docRoot->removeChild($nodeToRemove);

// save to XML file
$fp = fopen("../xml/shirts.xml", wb);
fwrite($fp, $doc->saveXML());
fclose($fp);

?>

Thank you


问:
Check if Python Package is installed
What's a good way to check if a package is installed while within a Python script? I know it's easy from the interpreter, but I need to do it within a script.

I guess I could check if there's a directory on the system that's created during the installation, but I feel like there's a better way. I'm trying to make sure the Skype4Py package is installed, and if not I'll install it.

My ideas for accomplishing the check

check for a directory in the typical install path

try to import the package and if an exception is throw, then install package

答:
I would like to comment to @ice.nicer reply but I cannot, so ...
My observations is that packages with dashes are saved with underscores, not only with dots as pointed out by @dwich comment

For example, you do pip3 install sphinx-rtd-theme, but:

importlib.util.find_spec(sphinx_rtd_theme) returns an Object

importlib.util.find_spec(sphinx-rtd-theme) returns None

importlib.util.find_spec(sphinx.rtd.theme) raises ModuleNotFoundError

Moreover, some names are totally changed.
For example, you do pip3 install pyyaml but it is saved simply as yaml

I am using python3.8

Title: Check if Python Package is installed

ContentLicense: CC BY-SA 4.0


问:
Problem with conditional inside while loop
i'm doing exercise 7-4 from "Python Crash Course", which is about writing a while loop to prompt customers to input pizza toppings until they type "quit". While i'm running the following code it prints once every third time and breaks after typing "quit" twice. Can someone please point out what i'm doing wrong. Thank you.

```<code>prompt = "Enter your topping: "

while True:
  topping = input(prompt)
  if input(prompt) == "quit":
    break
  else:
    print(f"{input(prompt)} is added")
</code>```

Here is an example of it running:

```<code>>>> Enter your topping: pepperoni
>>> Enter your topping: pepperoni
>>> Enter your topping: cheese
cheese is added
>>> Enter your topping: quit
>>> Enter your topping: quit
</code>```

答:
You probably must be using this - if topping == "quit":

In your code, you are using if input(prompt) == "quit": which is asking for input twice and this is where you are going wrong.

Also, I don't know what you are doing in the last line, but the last line should be something like this - print("topping is added") OR print(topping+"topping is added") if you want to display the topping which user inputted as well.

Once you have taken input using input(prompt), there's no need to call the same expression again and again as it will take input again (which is not what we want). Instead use topping which has already stored the input that user has given.

Hope it clears where you where going wrong.

Body:
i'm doing exercise 7-4 from "Python Crash Course", which is about writing a while loop to prompt customers to input pizza toppings until they type "quit". While i'm running the following code it prints once every third time and breaks after typing "quit" twice. Can someone please point out what i'm doing wrong. Thank you.

prompt = "Enter your topping: "

while True:
  topping = input(prompt)
  if input(prompt) == "quit":
    break
  else:
    print(f"{input(prompt)} is added")

Here is an example of it running:

>>> Enter your topping: pepperoni
>>> Enter your topping: pepperoni
>>> Enter your topping: cheese
cheese is added
>>> Enter your topping: quit
>>> Enter your topping: quit


问:
Errors compiling google-fhir proto files in Go
I am unable to compile google's fhir proto for go

1. I was able to generate annotations.pb.go with warnings which can be resolved

```<code>protoc --proto_path=proto  --go_out=.  proto/annotations.proto
2020/05/27 12:42:17 WARNING: Missing 'go_package' option in "annotations.proto",
please specify it with the full Go package path as
a future release of protoc-gen-go will require this be specified.
See https://developers.google.com/protocol-buffers/docs/reference/go-generated#package for more information.
</code>```

2. Unfortunately, I am unable to resolve fixing issues surrounding file not found.

Example the profile_config.proto which contained the following imports

```<code>import "proto/annotations.proto";
import "proto/r4/core/codes.proto";
import "proto/r4/core/datatypes.proto";
</code>```

Attempting to executed resulted in "not found"

```<code>protoc --proto_path=proto  --go_out=.  proto/profile_config.proto
proto/annotations.proto: File not found.
proto/r4/core/codes.proto: File not found.
proto/r4/core/datatypes.proto: File not found.
</code>```

Perhaps these proto files can only be used only with java and any other language would require modification on the files.

答:
Regarding 1., you need to edit every .proto you want to compile and add the go_package option. For instance:

```<code>option go_package = "github.com/my-org/my-proj/go/gen/fhir/proto"
</code>```

Regarding 2., you are setting --proto_path=proto, which leads protoc to search for proto/annotations.proto into the following path:

```<code>./proto/proto/annotations.proto
</code>```

If you don't set this option or set it to --proto_path=. you will be able to compile.

I also suggest taking a look at this pull-request.

Body:
I am unable to compile google's fhir proto for go

1. I was able to generate annotations.pb.go with warnings which can be resolved

protoc --proto_path=proto  --go_out=.  proto/annotations.proto
2020/05/27 12:42:17 WARNING: Missing 'go_package' option in "annotations.proto",
please specify it with the full Go package path as
a future release of protoc-gen-go will require this be specified.
See https://developers.google.com/protocol-buffers/docs/reference/go-generated#package for more information.

2. Unfortunately, I am unable to resolve fixing issues surrounding file not found.

Example the profile_config.proto which contained the following imports

import "proto/annotations.proto";
import "proto/r4/core/codes.proto";
import "proto/r4/core/datatypes.proto";

Attempting to executed resulted in "not found"

protoc --proto_path=proto  --go_out=.  proto/profile_config.proto
proto/annotations.proto: File not found.
proto/r4/core/codes.proto: File not found.
proto/r4/core/datatypes.proto: File not found.

Perhaps these proto files can only be used only with java and any other language would require modification on the files.

Body:
Regarding 1., you need to edit every .proto you want to compile and add the go_package option. For instance:

option go_package = "github.com/my-org/my-proj/go/gen/fhir/proto"

Regarding 2., you are setting --proto_path=proto, which leads protoc to search for proto/annotations.proto into the following path:

./proto/proto/annotations.proto

If you don't set this option or set it to --proto_path=. you will be able to compile.

I also suggest taking a look at this pull-request.


问:
ReactJS JSX Use Shorthand to Perform Multiple Executions
I understand a shorthand can be used to return a single execution, but is there a way to make a shorthand return multiple executions?

Take the following example (working):

```<code>import React from 'react';

const CompName = () => {
  const condition = true;
  return (
    <div>{condition && console.log("one")}</div>
  )
}

export default CompName;
</code>```

Output:
one

Now I want to execute two console logs if the condition is true:

```<code>import React from 'react';

const CompName = () => {
  const condition = true;
  return (
    <div>{condition && (console.log("one") && console.log("two"))}</div>
  )
}

export default CompName;
</code>```

Output:
one

Expected Output:
one
two

Anyone have any idea on the syntax I should be using to get the expected output?

答:
you can use comma operator

```<code>import React from 'react';

const CompName = () => {
  const condition = true;
  return (
    <div>{condition && (console.log("one"), console.log("two"))}</div>
  )
}

export default CompName;
</code>```

ReactDOM.render( <CompName/>, root )

function CompName () {
  const condition = true;
  return (

      {condition && (console.log("one"), console.log("two"))}

  )
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'></div></code>```

Body:
I understand a shorthand can be used to return a single execution, but is there a way to make a shorthand return multiple executions?

Take the following example (working):

import React from 'react';

const CompName = () => {
  const condition = true;
  return (

{condition && console.log("one")}

  )
}

export default CompName;

Output:
one

Now I want to execute two console logs if the condition is true:

import React from 'react';

const CompName = () => {
  const condition = true;
  return (

{condition && (console.log("one") && console.log("two"))}

  )
}

export default CompName;

Output:
one

Expected Output:
one
two

Anyone have any idea on the syntax I should be using to get the expected output?

Body:
you can use comma operator

import React from 'react';

const CompName = () => {
  const condition = true;
  return (
    <div>{condition && (console.log("one"), console.log("two"))}</div>
  )
}

export default CompName;

ReactDOM.render( <CompName/>, root )

function CompName () {
  const condition = true;
  return (
    <div>
      {condition && (console.log("one"), console.log("two"))}</div>
  )
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id='root'></div>


问:
How can I make this php database class more secure?
I'm using the following PHP MySQL database class. I'm curious as to what I could do to make it more secure. I'm happy with it so far, but without suggesting to "use PDO" what can I do to improve this currently?</p>

```<code>    <?

    class DbConnector {

    public static function getInstance(){
   static $instance = null;
   if($instance === null){
      $instance = new DbConnector();
   }

   return $instance;
    }

    var $theQuery;
    var $link;

    function DbConnector() {

        $host = 'localhost';
        $db     = '';
        $user = '';
        $pass = '';

        // connect to the db
        $this->link = mysql_connect($host, $user, $pass);
        mysql_select_db($db);
        register_shutdown_function(array(&$this, 'close'));
    }

    function find($query) {
        $ret = mysql_query($query, $this->link);
        if (mysql_num_rows($ret) == 0)
            return array();
        $retArray = array();

        while ($row = mysql_fetch_array($ret))
            $retArray[] = $row;

        return $retArray;
    }

    function insert($query) {
        $ret = mysql_query($query, $this->link);

        if (mysql_affected_rows() < 1)
            return false;
        return true;
    }

    function query($query) {
        $this->theQuery = $query;
        return mysql_query($query, $this->link);
    }

    function fetchArray($result) {

        return mysql_fetch_array($result);
    }

    function close() {
        mysql_close($this->link);
    }

    function exists($query) {
        $ret = mysql_query($query, $this->link);
        if (mysql_num_rows($ret) == 0)
            return false;
    }

    function last_id($query) {
        return mysql_insert_id($query);
    }

}

?>
</code>```

答:
If you don't want to use something that would automatically escape strings for you, you should at least provide an escapeString($string) method (which would call mysql_real_escape_string()) that you can use to escape strings when composing the query.

If you want to start using PDO (highly recommended) then you will probably have different methods and won't need to include an escaping method.

As for general considerations:

don't use var, but rather use public, protected or private (var has been deprecated as of PHP 5.0, and is currently an alias for public)

the __construct() method is preferred instead of the method with the name of the class

it would be better not to connect in the constructor, but rather only connect when you really need to connect in order to perform a query; a constructor should do as little as possible, and generally only initialize properties

mysql_connect() and mysql_select_db() will return false if they cannot do what they're supposed to; you should throw an exception if that happens and catch it where you use the class

the mysql_query() call in the find() and exists() methods might return something other than a resource (false for example) so you should check for that before calling mysql_num_rows()

if you're not using $theQuery at all, you should remove it

if you want to have access to $theQuery, you should make it private and provide a getQuery() accssor method

if you're setting the $link property to the resource returned by mysql_connect(), you should use that property in all your mysql_* calls, such as the one at last_id()

you should make $link private (as a rule of thumb, all properties should be private or protected, and accessor methods should be provided when needed - read about the concept of encapsulation)

even though all methods are by default public, having an explicit public keyword before each of them will make things clearer

Body:
I'm using the following PHP MySQL database class. I'm curious as to what I could do to make it more secure. I'm happy with it so far, but without suggesting to "use PDO" what can I do to improve this currently?

    <?

    class DbConnector {

    public static function getInstance(){
   static $instance = null;
   if($instance === null){
      $instance = new DbConnector();
   }

   return $instance;
    }

    var $theQuery;
    var $link;

    function DbConnector() {

        $host = 'localhost';
        $db     = '';
        $user = '';
        $pass = '';

        // connect to the db
        $this->link = mysql_connect($host, $user, $pass);
        mysql_select_db($db);
        register_shutdown_function(array(&$this, 'close'));
    }

    function find($query) {
        $ret = mysql_query($query, $this->link);
        if (mysql_num_rows($ret) == 0)
            return array();
        $retArray = array();

        while ($row = mysql_fetch_array($ret))
            $retArray[] = $row;

        return $retArray;
    }

    function insert($query) {
        $ret = mysql_query($query, $this->link);

        if (mysql_affected_rows() < 1)
            return false;
        return true;
    }

    function query($query) {
        $this->theQuery = $query;
        return mysql_query($query, $this->link);
    }

    function fetchArray($result) {

        return mysql_fetch_array($result);
    }

    function close() {
        mysql_close($this->link);
    }

    function exists($query) {
        $ret = mysql_query($query, $this->link);
        if (mysql_num_rows($ret) == 0)
            return false;
    }

    function last_id($query) {
        return mysql_insert_id($query);
    }

}

?>


问:
get userPackagerOpts.sourceExts is not iterable while runing the expo app
I am getting the following error while runing the expo app.</p>

```<code>   $ expo-cli start --tunnel
    [00:24:51] Starting project at C:\Users\DEMO\Desktop\worldsweets
    [00:24:51] Expo DevTools is running at http://localhost:19002
    [00:24:59] userPackagerOpts.sourceExts is not iterable
    [00:24:59] TypeError: userPackagerOpts.sourceExts is not iterable
        at startReactNativeServerAsync (C:\@expo\xdl@57.9.12\src\Project.ts:1788:80)
        at Object.startAsync (C:\@expo\xdl@57.9.12\src\Project.ts:2407:5)
        at action (C:\Users\DEMO\AppData\Roaming\npm\node_modules\expo-cli\src\commands\start.ts:181:3)
        at C:\Users\DEMO\AppData\Roaming\npm\node_modules\expo-cli\src\commands\start.ts:354:16
        at Command.<anonymous> (C:\Users\DEMO\AppData\Roaming\npm\node_modules\expo-cli\src\exp.ts:80:7)
</code>```

答:
I believe this is an old bug that has been reintroduced in expo-cli v3.21.2 or v3.21.3. I am using expo-cli v3.21.3 and ran into this issue too.

This post on the expo forum suggested adding "sourceExts": ["js", "jsx", "svg", "svgx"] to your app.json under packagerOpts and worked to get my project running again.

app.json

```<code>    "packagerOpts": {
      "assetExts": ["ttf"],
      "sourceExts": ["js", "jsx", "svg", "svgx"]
    }
</code>```

Body:
I am getting the following error while runing the expo app.

   $ expo-cli start --tunnel
    [00:24:51] Starting project at C:\Users\DEMO\Desktop\worldsweets
    [00:24:51] Expo DevTools is running at http://localhost:19002
    [00:24:59] userPackagerOpts.sourceExts is not iterable
    [00:24:59] TypeError: userPackagerOpts.sourceExts is not iterable
        at startReactNativeServerAsync (C:\@expo\xdl@57.9.12\src\Project.ts:1788:80)
        at Object.startAsync (C:\@expo\xdl@57.9.12\src\Project.ts:2407:5)
        at action (C:\Users\DEMO\AppData\Roaming\npm\node_modules\expo-cli\src\commands\start.ts:181:3)
        at C:\Users\DEMO\AppData\Roaming\npm\node_modules\expo-cli\src\commands\start.ts:354:16
        at Command.<anonymous> (C:\Users\DEMO\AppData\Roaming\npm\node_modules\expo-cli\src\exp.ts:80:7)

Body:
I believe this is an old bug that has been reintroduced in expo-cli v3.21.2 or v3.21.3. I am using expo-cli v3.21.3 and ran into this issue too.

This post on the expo forum suggested adding "sourceExts": ["js", "jsx", "svg", "svgx"] to your app.json under packagerOpts and worked to get my project running again.

app.json

    "packagerOpts": {
      "assetExts": ["ttf"],
      "sourceExts": ["js", "jsx", "svg", "svgx"]
    }


问:
Multiplying characters in a vector in R
Suppose I have the vector:

```<code>x = c("a","b","c")
</code>```

I would like to create a function that returns the following:

```<code>[1] "a*b" "a*c" "b*c"
</code>```

I assume we would use the paste0() function or use some sort of for loop to loop through the characters in the vector but I am not fully sure how to go about this. Just to clarify, I am looking for an output that takes two characters from the vector at a time and uses some sort of paste0(...,sep="*") to get the desired output above. I do not want to multiply all the characters in the vector at once, just two characters at a time.

答:
We can use combn from base R

```<code>combn(x, 2, FUN = paste, collapse="*")
#[1] "a*b" "a*c" "b*c"
</code>```

Title: Multiplying characters in a vector in R

Body:
Suppose I have the vector:

x = c("a","b","c")

I would like to create a function that returns the following:

[1] "a*b" "a*c" "b*c"

I assume we would use the paste0() function or use some sort of for loop to loop through the characters in the vector but I am not fully sure how to go about this. Just to clarify, I am looking for an output that takes two characters from the vector at a time and uses some sort of paste0(...,sep="*") to get the desired output above. I do not want to multiply all the characters in the vector at once, just two characters at a time.

Body:
We can use combn from base R

combn(x, 2, FUN = paste, collapse="*")
#[1] "a*b" "a*c" "b*c"


问:
Error in prediction in digit recognition using cnn
I want to predict the digit is 5 or not from 0 to 9.I have used cmaterdb dataset.

For this task I have changed all the digit label 0 except 5 in the training and test dataset

```<code>new_train_label=np.copy(train_labels)
for i, label in enumerate(new_train_label):
     new_train_label[i] = 0 if (label == 5) else 1

new_test_label=np.copy(test_labels)
for i, label in enumerate(new_test_label):
     new_test_label[i] = 0 if (label == 5) else 1

#train up model using cnn

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils

model = Sequential()

model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Conv2D(15, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Dropout(0.02))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
model.fit(train_examples, new_train_label, epochs=30)

val_loss, val_acc = model.evaluate(test_examples,new_test_label)
print(val_loss)
print(val_acc)
</code>```

Although accuracy is good, it can't predict 5. what is the wrong in my code or logic?

答:
I can guess, you have an accuracy of about 90%, but your model almost always predicts 0 ( not 5), right?

If it is the case, the reason can be the imbalanced classes. Your original dataset, I guess is balanced, like we have almost N 0s, almost N 1s, ... and almost N 9s. What you did, you kept the almost N 5s, and labeled it to 1, and turn the rest of almost 9*N examples to label 0. It means now you have 10% of data labeled 1( which are 5s) and 90% of data labeled 0. This is an imbalance case, and it is very normal you get a good accuracy of around 90%, but a poor prediction for the minority class. For imbalanced cases, accuracy is not a good metric or maybe it is not enough. Try to trace Precision,recall, and F1 as well.

my suggestion, sample from the non 5 classes ( 1/10 from each ) and keep all the
5s. You should get better predictions.

Body:
I want to predict the digit is 5 or not from 0 to 9.I have used cmaterdb dataset.

For this task I have changed all the digit label 0 except 5 in the training and test dataset

new_train_label=np.copy(train_labels)
for i, label in enumerate(new_train_label):
     new_train_label[i] = 0 if (label == 5) else 1

new_test_label=np.copy(test_labels)
for i, label in enumerate(new_test_label):
     new_test_label[i] = 0 if (label == 5) else 1

#train up model using cnn

from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils

model = Sequential()

model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Conv2D(15, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Dropout(0.02))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
model.fit(train_examples, new_train_label, epochs=30)

val_loss, val_acc = model.evaluate(test_examples,new_test_label)
print(val_loss)
print(val_acc)

Although accuracy is good, it can't predict 5. what is the wrong in my code or logic?


问:
EFCore scaffold database and migrate to another context at runtime
Recently I've started to create some PostgreSQL to Mdb/Accdb database converter. I've managed to do it in a bit generic way:

```<code>public static void TransferData<TSource, TDest>(DbContext sourceContext, DbContext destContext)
    where TSource : class where TDest : class
{
            destContext.Set<TDest>().AddRange(sourceContext.Set<TSource>().Select(_mapper.Map<TDest>));
}
</code>```

Specifying mappings in AutoMapper also in generic way:

```<code>public void RegisterGenericMapping<TSource, TDest>() => CreateMap<TSource, TDest>();

foreach (var entityName in EntitiesList.DestinationDb)
{
    var sourceType = ReflectionHelper.GetType($"{EntitiesList.sourceNamespace}.{entityName}"); // My helper class to search in all assemblies
    var destType = ReflectionHelper.GetType($"{EntitiesList.destNamespace}.{entityName}");

    typeof(MappingProfile).GetMethods().First(x => x.Name == nameof(RegisterGenericMapping))
        .MakeGenericMethod(sourceType, destType).Invoke(this, null);
}
</code>```

Getting the desired entities list this way:

```<code>public static List<string> DestinationDb = typeof(MsAccessContext).GetProperties()
    .Where(x => x.PropertyType.Name == "DbSet`1")
    .Select(x => x.PropertyType.GenericTypeArguments[0]?.Name).ToList();

public static string sourceNamespace = "DbConverter.NpgsqlSupport.Entities";
public static string destNamespace = "DbConverter.MsAccessSupport.Entities";
</code>```

But the problem is that I still have models in the core. For the source and destination context... It cannot be used without doing database first migration before runtime and paste the same classes to the destination context.

What I want to achieve is to get rid of all model classes and DbSets in contexts' classes:

During runtime scaffold source database and add DbSets, then basing on the source scaffolded models create destination models and DbSets, apply migration to the destination database and then start the process.

For now my solution works only for one PREPARED database. I need it to be prepared automatically during runtime for every database.

答: Don't use EF for this.  Just use ADO.NET DataReaders and DataTables.  They work perfectly without design-time metadata.</p>

Body:
Recently I've started to create some PostgreSQL to Mdb/Accdb database converter. I've managed to do it in a bit generic way:

public static void TransferData<TSource, TDest>(DbContext sourceContext, DbContext destContext)
    where TSource : class where TDest : class
{
            destContext.Set<TDest>().AddRange(sourceContext.Set<TSource>().Select(_mapper.Map<TDest>));
}

Specifying mappings in AutoMapper also in generic way:

public void RegisterGenericMapping<TSource, TDest>() => CreateMap<TSource, TDest>();

foreach (var entityName in EntitiesList.DestinationDb)
{
    var sourceType = ReflectionHelper.GetType($"{EntitiesList.sourceNamespace}.{entityName}"); // My helper class to search in all assemblies
    var destType = ReflectionHelper.GetType($"{EntitiesList.destNamespace}.{entityName}");

    typeof(MappingProfile).GetMethods().First(x => x.Name == nameof(RegisterGenericMapping))
        .MakeGenericMethod(sourceType, destType).Invoke(this, null);
}

Getting the desired entities list this way:

public static List<string> DestinationDb = typeof(MsAccessContext).GetProperties()
    .Where(x => x.PropertyType.Name == "DbSet`1")
    .Select(x => x.PropertyType.GenericTypeArguments[0]?.Name).ToList();

public static string sourceNamespace = "DbConverter.NpgsqlSupport.Entities";
public static string destNamespace = "DbConverter.MsAccessSupport.Entities";

But the problem is that I still have models in the core. For the source and destination context... It cannot be used without doing database first migration before runtime and paste the same classes to the destination context.

What I want to achieve is to get rid of all model classes and DbSets in contexts' classes:

During runtime scaffold source database and add DbSets, then basing on the source scaffolded models create destination models and DbSets, apply migration to the destination database and then start the process.

For now my solution works only for one PREPARED database. I need it to be prepared automatically during runtime for every database.


问:
How to properly use SendDataAsync method defined on the web service using Microsoft WCF Web Service Reference Provider client?
I have access to WSDL file of a specific .asmx web service that contains a SendDataAsync method - basically I specify the TimeStamp and Value to be send. I uploaded the WSDL file to my project in Visual Studio 2019 as a connected service (Add->Connected Service->Microsoft WCF Web Service Reference Provider->Browse->I added location of the WSDL file and specified the service that included SendDataAsync method). After that I created a new client and tried to use my method like that:

```<code>ServiceSoapClient client = new ServiceSoapClient(ServiceSoapClient.EndpointConfiguration.ServiceSoap);
client.SampleData sd = new client.SampleData();
sd.TStamp = DateTime.Now;
sd.Value = 10;
client.SendDataAsync(sd);
</code>```

Unfortunately, it doesn't work. I don't receive any errors or exceptions so I tried to check the response from the web service via Fiddler. I found out that actually nothing is being transmitted. No connection is being made, nothing. Now I try to understand what I'm doing wrong. Is my way of using the method defined on the web service wrong? Or maybe the method doesn't actually do what the name suggests? Or could the problem be related to the fact that the method is Async? Any suggestions are welcome! :)

答:
Okay, thanks to both the comment from Paulo Morgado and the answer from Ding peng I managed to solve my problem. The proper way of using asynchronous method, such as SendDataAsync in my case, is with the await operator. I changed the method invocation from:

client.SendDataAsync(sd);

to:

response = await client.SendDataAsync(sd);

I also had to change void Main to async Main and the method works now :)

Body:
I have access to WSDL file of a specific .asmx web service that contains a SendDataAsync method - basically I specify the TimeStamp and Value to be send. I uploaded the WSDL file to my project in Visual Studio 2019 as a connected service (Add->Connected Service->Microsoft WCF Web Service Reference Provider->Browse->I added location of the WSDL file and specified the service that included SendDataAsync method). After that I created a new client and tried to use my method like that:

ServiceSoapClient client = new ServiceSoapClient(ServiceSoapClient.EndpointConfiguration.ServiceSoap);
client.SampleData sd = new client.SampleData();
sd.TStamp = DateTime.Now;
sd.Value = 10;
client.SendDataAsync(sd);

Unfortunately, it doesn't work. I don't receive any errors or exceptions so I tried to check the response from the web service via Fiddler. I found out that actually nothing is being transmitted. No connection is being made, nothing. Now I try to understand what I'm doing wrong. Is my way of using the method defined on the web service wrong? Or maybe the method doesn't actually do what the name suggests? Or could the problem be related to the fact that the method is Async? Any suggestions are welcome! :)


问:
Editing scale-bar in non-geographic maps
I am working on non-geographic maps in Leaflet. Since the coordinates are Cartesian with no geographic reference, it should not be m by default as follows (I have disabled the imperial units in the scale bar):

Is there any solution to convert 100 m to 100 in the scale bar or even replace the m with something else?

答:
You want to be aware of this piece of code from Leaflet's L.Control.Scale:

```<code>_updateMetric: function (maxMeters) {
    var meters = this._getRoundNum(maxMeters),
        label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';

    this._updateScale(this._mScale, label, meters / maxMeters);
},
</code>```

Now, to change that behaviour there's an ugly hacky way and a bit cleaner way.

The hacky way is to replace either the (private, undocumented) _updateMetric method from either the prototype or the instance of L.Control.Scale, e.g.:

```<code>L.Control.Scale.prototype._updateMetric = function (maxMeters) {
    var meters = this._getRoundNum(maxMeters),
        label = meters + ' units';

    this._updateScale(this._mScale, label, meters / maxMeters);
};
var myScaleControl = L.control.scale().addTo(map);
</code>```

or

```<code>var myScaleControl = L.control.scale();
myScaleControl._updateMetric = function (maxMeters) {
    var meters = this._getRoundNum(maxMeters),
        label = meters + ' units';

    this._updateScale(this._mScale, label, meters / maxMeters);
};
myScaleControl.addTo(map);
</code>```

Replacing non-documented internal methods is usually seen as a dirty hack, and can lead to confusion. In my experience, nobel programmers tend to trust the hack without understanding how JS prototypal inheritance works.

The "a bit cleaner" way is to read Leaflet's tutorial on subclassing controls, and then create a subclass of L.Control.Scale, e.g.:

```<code>L.Control.MeterlessScale = L.Control.Scale.extend({
    _updateMetric: function (maxMeters) {
        var meters = this._getRoundNum(maxMeters),
            label = meters + ' units';

        this._updateScale(this._mScale, label, meters / maxMeters);
    }
});

var scale = (new L.Control.MeterlessScale()).addTo(map);
</code>```

One should not be afraid to read Leaflet's source code. At the same time, please read up on JS prototypal inheritance and read Leaflet's own tutorials before jumping into it.

It is also true that the distance method of L.CRS is assumed to return distance in meters, and cannot inform any caller of the units of that CRS; hence, L.Control.Scale assumes that the distances are in meters. Architecturally speaking, there is no good simple way of abstracting distance units depending on the CRS (unfortunately).

Body:
You want to be aware of this piece of code from Leaflet's L.Control.Scale:

_updateMetric: function (maxMeters) {
    var meters = this._getRoundNum(maxMeters),
        label = meters < 1000 ? meters + ' m' : (meters / 1000) + ' km';

    this._updateScale(this._mScale, label, meters / maxMeters);
},

Now, to change that behaviour there's an ugly hacky way and a bit cleaner way.

The hacky way is to replace either the (private, undocumented) _updateMetric method from either the prototype or the instance of L.Control.Scale, e.g.:

L.Control.Scale.prototype._updateMetric = function (maxMeters) {
    var meters = this._getRoundNum(maxMeters),
        label = meters + ' units';

    this._updateScale(this._mScale, label, meters / maxMeters);
};
var myScaleControl = L.control.scale().addTo(map);

or

var myScaleControl = L.control.scale();
myScaleControl._updateMetric = function (maxMeters) {
    var meters = this._getRoundNum(maxMeters),
        label = meters + ' units';

    this._updateScale(this._mScale, label, meters / maxMeters);
};
myScaleControl.addTo(map);

Replacing non-documented internal methods is usually seen as a dirty hack, and can lead to confusion. In my experience, nobel programmers tend to trust the hack without understanding how JS prototypal inheritance works.

The "a bit cleaner" way is to read Leaflet's tutorial on subclassing controls, and then create a subclass of L.Control.Scale, e.g.:

L.Control.MeterlessScale = L.Control.Scale.extend({
    _updateMetric: function (maxMeters) {
        var meters = this._getRoundNum(maxMeters),
            label = meters + ' units';

        this._updateScale(this._mScale, label, meters / maxMeters);
    }
});

var scale = (new L.Control.MeterlessScale()).addTo(map);

One should not be afraid to read Leaflet's source code. At the same time, please read up on JS prototypal inheritance and read Leaflet's own tutorials before jumping into it.

It is also true that the distance method of L.CRS is assumed to return distance in meters, and cannot inform any caller of the units of that CRS; hence, L.Control.Scale assumes that the distances are in meters. Architecturally speaking, there is no good simple way of abstracting distance units depending on the CRS (unfortunately).


问:
How can I fix node
When I try to build my react application by running

```<code>react-scripts build
</code>```

I get an error which is :

```<code>react-scripts build
Creating an optimized production build...
Failed to compile.

./src/components/header/Header.scss
To import Sass files, you first need to install node-sass.
Run `npm install node-sass` or `yarn add node-sass` inside your workspace.
Require stack:
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\sass-loader\dist\getDefaultSassImplementation.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\sass-loader\dist\getSassImplementation.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\sass-loader\dist\index.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\sass-loader\dist\cjs.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\loader-runner\lib\loadLoader.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\loader-runner\lib\LoaderRunner.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\webpack\lib\NormalModule.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\webpack\lib\NormalModuleFactory.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\webpack\lib\Compiler.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\webpack\lib\webpack.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\scripts\build.js
</code>```

So install node-sass by following command :

```<code>npm install node-sass
</code>```

and this is the log :

```<code>> node-sass@4.14.1 install C:\Ecommerce\ecommerce\node_modules\node-sass
> node scripts/install.js

Cached binary found at C:\Users\ITland\AppData\Roaming\npm-cache\node-sass\4.14.1\win32-x64-72_binding.node

> node-sass@4.14.1 postinstall C:\Ecommerce\ecommerce\node_modules\node-sass
> node scripts/build.js

Binary found at C:\Ecommerce\ecommerce\node_modules\node-sass\vendor\win32-x64-72\binding.node
Testing binary
Binary is fine
npm WARN bootstrap@4.5.0 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@3.17.1 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta ||
>= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack-chokidar2\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\jest-haste-map\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\webpack-dev-server\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ node-sass@4.14.1
updated 1 package and audited 1794 packages in 21.637s

65 packages are looking for funding
  run `npm fund` for details

found 1 low severity vulnerability
  run `npm audit fix` to fix them, or `npm audit` for details
</code>```

Then I run react-scripts build and I get the same error which I got at first .

This is package.json file to be sure that node-sass is installed  :

```<code>{
  "name": "ecommerce",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.9.14",
    "@material-ui/icons": "^4.9.1",
    "@material-ui/lab": "^4.0.0-alpha.54",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "bootstrap": "^4.5.0",
    "clsx": "^1.1.0",
    "framer-motion": "^1.11.0",
    "node-sass": "^4.14.1",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-dom": "^16.13.1",
    "react-redux": "^7.2.0",
    "react-router-dom": "^5.2.0",
    "react-router-scroll-memory": "^2.0.6",
    "react-scripts": "3.4.1",
    "react-scroll": "^1.7.16",
    "redux": "^4.0.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

</code>```

Now I get no problems by running it in development mode on localhost but only when I'm trying to build the application .

How can I solve this you need to install node-sass error ?

答:
I did solve this error by running following commands : </p>

```<code>npm i node-sass -g
</code>```

```<code>npm i sass-loader -g
</code>```

Title: How can I fix node

Body:
When I try to build my react application by running

react-scripts build

I get an error which is :

react-scripts build
Creating an optimized production build...
Failed to compile.

./src/components/header/Header.scss
To import Sass files, you first need to install node-sass.
Run `npm install node-sass` or `yarn add node-sass` inside your workspace.
Require stack:
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\sass-loader\dist\getDefaultSassImplementation.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\sass-loader\dist\getSassImplementation.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\sass-loader\dist\index.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\sass-loader\dist\cjs.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\loader-runner\lib\loadLoader.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\loader-runner\lib\LoaderRunner.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\webpack\lib\NormalModule.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\webpack\lib\NormalModuleFactory.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\webpack\lib\Compiler.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\node_modules\webpack\lib\webpack.js
- C:\Users\ITland\AppData\Roaming\npm\node_modules\react-scripts\scripts\build.js

So install node-sass by following command :

npm install node-sass

and this is the log :

> node-sass@4.14.1 install C:\Ecommerce\ecommerce\node_modules\node-sass
> node scripts/install.js

Cached binary found at C:\Users\ITland\AppData\Roaming\npm-cache\node-sass\4.14.1\win32-x64-72_binding.node

> node-sass@4.14.1 postinstall C:\Ecommerce\ecommerce\node_modules\node-sass
> node scripts/build.js

Binary found at C:\Ecommerce\ecommerce\node_modules\node-sass\vendor\win32-x64-72\binding.node
Testing binary
Binary is fine
npm WARN bootstrap@4.5.0 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself.
npm WARN tsutils@3.17.1 requires a peer of typescript@>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta ||
>= 3.7.0-dev || >= 3.7.0-beta but none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2 (node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.1.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack-chokidar2\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\jest-haste-map\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\webpack-dev-server\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ node-sass@4.14.1
updated 1 package and audited 1794 packages in 21.637s

65 packages are looking for funding
  run `npm fund` for details

found 1 low severity vulnerability
  run `npm audit fix` to fix them, or `npm audit` for details

Then I run react-scripts build and I get the same error which I got at first .

This is package.json file to be sure that node-sass is installed  :

{
  "name": "ecommerce",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.9.14",
    "@material-ui/icons": "^4.9.1",
    "@material-ui/lab": "^4.0.0-alpha.54",
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "bootstrap": "^4.5.0",
    "clsx": "^1.1.0",
    "framer-motion": "^1.11.0",
    "node-sass": "^4.14.1",
    "react": "^16.13.1",
    "react-bootstrap": "^1.0.1",
    "react-dom": "^16.13.1",
    "react-redux": "^7.2.0",
    "react-router-dom": "^5.2.0",
    "react-router-scroll-memory": "^2.0.6",
    "react-scripts": "3.4.1",
    "react-scroll": "^1.7.16",
    "redux": "^4.0.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Now I get no problems by running it in development mode on localhost but only when I'm trying to build the application .

How can I solve this you need to install node-sass error ?

Body:
I did solve this error by running following commands :

npm i node-sass -g

npm i sass-loader -g


问:
How do I measure execution time of a command on the Windows command line?
Is there a built-in way to measure execution time of a command on the Windows command line?</p>

答:
If you want

To measure execution time down to the hundredth of a second in (hh:mm:ss.ff format)

To not have to download and install a resource pack

To look like a huge DOS nerd (who doesn't)

Try copying the following script into a new batch file (e.g. timecmd.bat):

```<code>@echo off
@setlocal

set start=%time%

:: Runs your command
cmd /c %*

set end=%time%
set options="tokens=1-4 delims=:.,"
for /f %options% %%a in ("%start%") do set start_h=%%a&set /a start_m=100%%b %% 100&set /a start_s=100%%c %% 100&set /a start_ms=100%%d %% 100
for /f %options% %%a in ("%end%") do set end_h=%%a&set /a end_m=100%%b %% 100&set /a end_s=100%%c %% 100&set /a end_ms=100%%d %% 100

set /a hours=%end_h%-%start_h%
set /a mins=%end_m%-%start_m%
set /a secs=%end_s%-%start_s%
set /a ms=%end_ms%-%start_ms%
if %ms% lss 0 set /a secs = %secs% - 1 & set /a ms = 100%ms%
if %secs% lss 0 set /a mins = %mins% - 1 & set /a secs = 60%secs%
if %mins% lss 0 set /a hours = %hours% - 1 & set /a mins = 60%mins%
if %hours% lss 0 set /a hours = 24%hours%
if 1%ms% lss 100 set ms=0%ms%

:: Mission accomplished
set /a totalsecs = %hours%*3600 + %mins%*60 + %secs%
echo command took %hours%:%mins%:%secs%.%ms% (%totalsecs%.%ms%s total)
</code>```

Usage

If you put timecmd.bat in a directory in your path, you can call it from anywhere like this:

```<code>timecmd [your command]
</code>```

E.g.

```<code>C:\>timecmd pause
Press any key to continue . . .
command took 0:0:1.18
</code>```

If you want to do output redirection, you can quote the command like this:

```<code>timecmd "dir c:\windows /s > nul"
</code>```

This should handle commands that run from before- to after-midnight, but the output will be wrong if your command runs for 24 hours or more.

OwnerDisplayName: Kuroki Kaze

Body:
If you want

To measure execution time down to the hundredth of a second in (hh:mm:ss.ff format)

To not have to download and install a resource pack

To look like a huge DOS nerd (who doesn't)

Try copying the following script into a new batch file (e.g. timecmd.bat):

@echo off
@setlocal

set start=%time%

:: Runs your command
cmd /c %*

set end=%time%
set options="tokens=1-4 delims=:.,"
for /f %options% %%a in ("%start%") do set start_h=%%a&set /a start_m=100%%b %% 100&set /a start_s=100%%c %% 100&set /a start_ms=100%%d %% 100
for /f %options% %%a in ("%end%") do set end_h=%%a&set /a end_m=100%%b %% 100&set /a end_s=100%%c %% 100&set /a end_ms=100%%d %% 100

set /a hours=%end_h%-%start_h%
set /a mins=%end_m%-%start_m%
set /a secs=%end_s%-%start_s%
set /a ms=%end_ms%-%start_ms%
if %ms% lss 0 set /a secs = %secs% - 1 & set /a ms = 100%ms%
if %secs% lss 0 set /a mins = %mins% - 1 & set /a secs = 60%secs%
if %mins% lss 0 set /a hours = %hours% - 1 & set /a mins = 60%mins%
if %hours% lss 0 set /a hours = 24%hours%
if 1%ms% lss 100 set ms=0%ms%

:: Mission accomplished
set /a totalsecs = %hours%*3600 + %mins%*60 + %secs%
echo command took %hours%:%mins%:%secs%.%ms% (%totalsecs%.%ms%s total)

Usage

If you put timecmd.bat in a directory in your path, you can call it from anywhere like this:

timecmd [your command]

E.g.

C:\>timecmd pause
Press any key to continue . . .
command took 0:0:1.18

If you want to do output redirection, you can quote the command like this:

timecmd "dir c:\windows /s > nul"

This should handle commands that run from before- to after-midnight, but the output will be wrong if your command runs for 24 hours or more.


问:
How to get exchange by coins with two denominations?
Develop a method change(amount) that for any integer amount in the range from 24 to 1000 returns a list consisting of numbers 5 and 7 only, such that their sum is equal to amount. For example, change(28) may return [7, 7, 7, 7], while change(49) may return [7, 7, 7, 7, 7, 7, 7] or [5, 5, 5, 5, 5, 5, 5, 7, 7] or [7, 5, 5, 5, 5, 5, 5, 5, 7].

I have written something like this. But it isn't working right.

```<code>enter code here

def change (amount):
assert (amount >=24)
if amount == 24:
    return [5, 5, 7, 7]
if amount == 29:
    return [5, 5, 5, 7, 7]
if amount == 40:
    return [5, 5, 5, 5, 5, 5, 5, 5]

coins = change(amount - 5)
coins.append(5)
return coins
</code>```

for coins in range(24, 1000):
    print(coins)

答:
Actually, you should find two numbers:

the number of coins with value 7 (let it be countA) and

the number of coins with value 5 (let it be countB)

As you can see 0 <= countA <= sum/7. Then sum - countA * 7 should be divided by 5 without remainder.

So, the simple implementation in java can be like this:

import java.util.Collections;
// ...
public List<Integer> getExchange(int sum)
{
   int coinA = 7;
   int coinB = 5;

   int maxCountOfCoinA = sum / coinA;
   int countA = 0;
   int countB = 0;
   for (int count = 0; count <= maxCountOfCoinA; count++)
   {
      int remains = sum - count * coinA;
      if (remains % coinB == 0)
      {
         countA = count;
         countB = remains / coinB;
         break;
      }
   }

   List<Integer> result = new ArrayList<>();
   result.addAll(Collections.nCopies(countA, coinA));
   result.addAll(Collections.nCopies(countB, coinB));
   return result;
}
```

Body:
Develop a method change(amount) that for any integer amount in the range from 24 to 1000 returns a list consisting of numbers 5 and 7 only, such that their sum is equal to amount. For example, change(28) may return [7, 7, 7, 7], while change(49) may return [7, 7, 7, 7, 7, 7, 7] or [5, 5, 5, 5, 5, 5, 5, 7, 7] or [7, 5, 5, 5, 5, 5, 5, 5, 7].

I have written something like this. But it isn't working right.

enter code here

def change (amount):
assert (amount >=24)
if amount == 24:
    return [5, 5, 7, 7]
if amount == 29:
    return [5, 5, 5, 7, 7]
if amount == 40:
    return [5, 5, 5, 5, 5, 5, 5, 5]

coins = change(amount - 5)
coins.append(5)
return coins

for coins in range(24, 1000):
    print(coins)


问:
Error: Invalid hook call. But can't understand where. React JS
It's my firt time on react, and I'm trying to build a sign up form with steps. I read the documentation on material-ui and about ReactJS, but can't understand where I do mistakes.

I'll paste the error:
"Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See link for tips about how to debug and fix this problem."

I think the error is in this two classes, but can't understand why or where.

FormUtentiPersonali.js

```<code>import React, { Component } from 'react';
import TextField from '@material-ui/core/TextField';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

    const useStyles=makeStyles((theme)=>({
        root: {
            '& .MuiTextField-root': {
              margin: theme.spacing(1),
              width: '25ch',
            },
        },
    }));

export class FormUtentiPersonali extends Component {
    continue = e =>{
        e.preventDefault();
        this.props.nextStep();
    };
    back = e =>{
        e.preventDefault();
        this.props.prevStep();
    };
    render() {
        //const classes = useStyles();
        const {values,handleChange}=this.props;
        return (
            <form noValidate autoComplete="off">
                <TextField
                required
                id="email-utente"
                label="E-mail"
                defaultValue={values.email}
                onChange={handleChange('email')}
                 />
                 <br/>
                 <TextField
                required
                id="password-utente"
                label="Imposta password"
                defaultValue={values.password}
                onChange={handleChange('password')}
                type="password"
                 />
                 <br/>
                 <TextField
                required
                id="conferma-password-utente"
                label="Conferma password"
                defaultValue={values.confermaPassword}
                onChange={handleChange('confermaPassword')}
                type="password"
                 />
                 <Button
                        label="Indietro"
                        variant="contained"
                        onClick={this.back}
                    >
                        Indietro
                        </Button>

                    <Button
                        label="Continua"
                        color="secondary"
                        variant="contained"
                        onClick={this.continue}
                    >
                        Continua
                        </Button>
            </form>
        );
    }
}

export default FormUtentiPersonali;

</code>```

FormUtentiAnagrafica.js

```<code>import React, { Component } from 'react';
import TextField from '@material-ui/core/TextField';
import { makeStyles } from '@material-ui/core/styles';
import MenuItem from '@material-ui/core/MenuItem';
import Button from '@material-ui/core/Button';

    const useStyles=makeStyles((theme)=>({
        root: {
            '& .MuiTextField-root': {
              margin: theme.spacing(1),
              width: '25ch',
            },
        },
    }));

export class FormUtenteAnagrafica extends Component {
    continue = e =>{
        e.preventDefault();
        this.props.nextStep();
    };

    render() {
        const giorni=[
            {
                value:'01',
                label:'01',
            },
            {
                value:'02',
                label:'02',
            },
            {
                value:'03',
                label:'03',
            },
            {
                value:'04',
                label:'04',
            },
            {
                value:'05',
                label:'05',
            },
            {
                value:'06',
                label:'06',
            },
            {
                value:'07',
                label:'07',
            },
            {
                value:'08',
                label:'08',
            },
            {
                value:'09',
                label:'09',
            },
            {
                value:'10',
                label:'10',
            },
            {
                value:'11',
                label:'11',
            },
            {
                value:'12',
                label:'12',
            },
            {
                value:'13',
                label:'13',
            },
            {
                value:'14',
                label:'14',
            },
            {
                value:'15',
                label:'15',
            },
            {
                value:'16',
                label:'16',
            },
            {
                value:'17',
                label:'17',
            },
            {
                value:'18',
                label:'18',
            },
            {
                value:'19',
                label:'19',
            },
            {
                value:'20',
                label:'20',
            },
            {
                value:'21',
                label:'21',
            },
            {
                value:'22',
                label:'22',
            },
            {
                value:'23',
                label:'23',
            },
            {
                value:'24',
                label:'24',
            },
            {
                value:'25',
                label:'25',
            },
            {
                value:'26',
                label:'26',
            },
            {
                value:'27',
                label:'27',
            },
            {
                value:'28',
                label:'28',
            },
            {
                value:'29',
                label:'29',
            },
            {
                value:'30',
                label:'30',
            },
            {
                value:'31',
                label:'31',
            },
        ];
        const mesi=[
            {
                value: 'Gen',
                label: 'Gen',
            },
            {
                value: 'Feb',
                label: 'Feb',
            },
            {
                value: 'Mar',
                label: 'Mar',
            },
            {
                value: 'Apr',
                label: 'Apr',
            },
            {
                value: 'Mag',
                label: 'Mag',
            },
            {
                value: 'Giu',
                label: 'Giu',
            },
            {
                value: 'Lug',
                label: 'Lug',
            },
            {
                value: 'Ago',
                label: 'Ago',
            },
            {
                value: 'Set',
                label: 'Set',
            },
            {
                value: 'Ott',
                label: 'Ott',
            },
            {
                value: 'Nov',
                label: 'Nov',
            },
            {
                value: 'Dic',
                label: 'Dic',
            },
        ]

        const {values,handleChange}=this.props;
        //const classes=useStyles();
        const [giorno,setGiorno]=React.useState('01');
        const [mese,setMese]=React.useState('Gen');
        const cambiaGiorno=event=>{
            setGiorno(event.target.value);
        };
        const cambiaMese=event=>{
            setMese(event.target.value);
        }
        return (
            <form noValidate autoComplete="off">
                <TextField
                required
                id="nome-utente"
                label="Inserisci nome"
                onChange={handleChange('nome')}
                defaultValue={values.nome}
                />
                <br/>
                <TextField
                required
                id="cognnome-utente"
                label="Inserisci cognome"
                onChange={handleChange('cognome')}
                defaultValue={values.cognome}
                />
                <br/>
                <TextField
                required
                id="numero-telefono-utente"
                label="Numero di telefono"
                onChange={handleChange('numeroDiTelefono')}
                defaultValue={values.numeroDiTelefono}
                />
                <br/>
                <TextField
                required
                id="giorno-nascita-utente"
                label="Giorno di nascita"
                value={giorno}
                onChange={handleChange('birthdayDay')}
                onChange={cambiaGiorno}
                >
                {giorni.map((option) => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
          </TextField>

          <TextField
                required
                id="mese-nascita-utente"
                label="Mese di nascita"
                value={mese}
                onChange={handleChange('birthdayMonth')}
                onChange={cambiaMese}
                >
                {mesi.map((option) => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
          </TextField>
          <br/>
          <TextField
          id="anno-nascita-utente"
          label="Anno di nascita"
          type="number"
          InputLabelProps={{
            shrink: true,
          }}
          onChange={handleChange('birthdayYear')}
          defaultValue={values.birthdayYear}
        />
        <br/>
        <Button
            label="Continua"
            color="secondary"
            variant="contained"
            onClick={this.continue}
        >
            Continua
        </Button>
        </form>
        );
    }
}

export default FormUtenteAnagrafica;
</code>```

答:
Welcome to React!

Some things that occurred to me straight off here.

React hooks such as useState cannot be used in class components, you will have to use a functional component. This is because the normal way you'd manipulate state in a class is defining a constructor and declaring a state object like so:

```<code>export default class App extends component {
 constructor(){
  props(){
   this.state = {
    //declare state items here
   }
  }

  render() {
   //render state and html here
   this.setState({}) //to update properties on the state
  }
 }
</code>```

}

Like I said, if you want to use hooks, you must define a functional component and import useState from react.

```<code>import React, { useState } from 'react'
function App() {
 const [value, setValue] = useState('')
 return(
  //return things here
 )
}
</code>```

I'd recommend looking at the react docs about hooks here: https://reactjs.org/docs/hooks-intro.html

Hope this helps :)

Body:
It's my firt time on react, and I'm trying to build a sign up form with steps. I read the documentation on material-ui and about ReactJS, but can't understand where I do mistakes.

I'll paste the error:
"Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See link for tips about how to debug and fix this problem."

I think the error is in this two classes, but can't understand why or where.

FormUtentiPersonali.js

import React, { Component } from 'react';
import TextField from '@material-ui/core/TextField';
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

    const useStyles=makeStyles((theme)=>({
        root: {
            '& .MuiTextField-root': {
              margin: theme.spacing(1),
              width: '25ch',
            },
        },
    }));

export class FormUtentiPersonali extends Component {
    continue = e =>{
        e.preventDefault();
        this.props.nextStep();
    };
    back = e =>{
        e.preventDefault();
        this.props.prevStep();
    };
    render() {
        //const classes = useStyles();
        const {values,handleChange}=this.props;
        return (
            <form noValidate autoComplete="off">
                <TextField
                required
                id="email-utente"
                label="E-mail"
                defaultValue={values.email}
                onChange={handleChange('email')}
                 />

                 <TextField
                required
                id="password-utente"
                label="Imposta password"
                defaultValue={values.password}
                onChange={handleChange('password')}
                type="password"
                 />

                 <TextField
                required
                id="conferma-password-utente"
                label="Conferma password"
                defaultValue={values.confermaPassword}
                onChange={handleChange('confermaPassword')}
                type="password"
                 />
                 <Button
                        label="Indietro"
                        variant="contained"
                        onClick={this.back}
                    >
                        Indietro
                        </Button>

                    <Button
                        label="Continua"
                        color="secondary"
                        variant="contained"
                        onClick={this.continue}
                    >
                        Continua
                        </Button>
            </form>
        );
    }
}

export default FormUtentiPersonali;

FormUtentiAnagrafica.js

import React, { Component } from 'react';
import TextField from '@material-ui/core/TextField';
import { makeStyles } from '@material-ui/core/styles';
import MenuItem from '@material-ui/core/MenuItem';
import Button from '@material-ui/core/Button';

    const useStyles=makeStyles((theme)=>({
        root: {
            '& .MuiTextField-root': {
              margin: theme.spacing(1),
              width: '25ch',
            },
        },
    }));

export class FormUtenteAnagrafica extends Component {
    continue = e =>{
        e.preventDefault();
        this.props.nextStep();
    };

    render() {
        const giorni=[
            {
                value:'01',
                label:'01',
            },
            {
                value:'02',
                label:'02',
            },
            {
                value:'03',
                label:'03',
            },
            {
                value:'04',
                label:'04',
            },
            {
                value:'05',
                label:'05',
            },
            {
                value:'06',
                label:'06',
            },
            {
                value:'07',
                label:'07',
            },
            {
                value:'08',
                label:'08',
            },
            {
                value:'09',
                label:'09',
            },
            {
                value:'10',
                label:'10',
            },
            {
                value:'11',
                label:'11',
            },
            {
                value:'12',
                label:'12',
            },
            {
                value:'13',
                label:'13',
            },
            {
                value:'14',
                label:'14',
            },
            {
                value:'15',
                label:'15',
            },
            {
                value:'16',
                label:'16',
            },
            {
                value:'17',
                label:'17',
            },
            {
                value:'18',
                label:'18',
            },
            {
                value:'19',
                label:'19',
            },
            {
                value:'20',
                label:'20',
            },
            {
                value:'21',
                label:'21',
            },
            {
                value:'22',
                label:'22',
            },
            {
                value:'23',
                label:'23',
            },
            {
                value:'24',
                label:'24',
            },
            {
                value:'25',
                label:'25',
            },
            {
                value:'26',
                label:'26',
            },
            {
                value:'27',
                label:'27',
            },
            {
                value:'28',
                label:'28',
            },
            {
                value:'29',
                label:'29',
            },
            {
                value:'30',
                label:'30',
            },
            {
                value:'31',
                label:'31',
            },
        ];
        const mesi=[
            {
                value: 'Gen',
                label: 'Gen',
            },
            {
                value: 'Feb',
                label: 'Feb',
            },
            {
                value: 'Mar',
                label: 'Mar',
            },
            {
                value: 'Apr',
                label: 'Apr',
            },
            {
                value: 'Mag',
                label: 'Mag',
            },
            {
                value: 'Giu',
                label: 'Giu',
            },
            {
                value: 'Lug',
                label: 'Lug',
            },
            {
                value: 'Ago',
                label: 'Ago',
            },
            {
                value: 'Set',
                label: 'Set',
            },
            {
                value: 'Ott',
                label: 'Ott',
            },
            {
                value: 'Nov',
                label: 'Nov',
            },
            {
                value: 'Dic',
                label: 'Dic',
            },
        ]

        const {values,handleChange}=this.props;
        //const classes=useStyles();
        const [giorno,setGiorno]=React.useState('01');
        const [mese,setMese]=React.useState('Gen');
        const cambiaGiorno=event=>{
            setGiorno(event.target.value);
        };
        const cambiaMese=event=>{
            setMese(event.target.value);
        }
        return (
            <form noValidate autoComplete="off">
                <TextField
                required
                id="nome-utente"
                label="Inserisci nome"
                onChange={handleChange('nome')}
                defaultValue={values.nome}
                />

                <TextField
                required
                id="cognnome-utente"
                label="Inserisci cognome"
                onChange={handleChange('cognome')}
                defaultValue={values.cognome}
                />

                <TextField
                required
                id="numero-telefono-utente"
                label="Numero di telefono"
                onChange={handleChange('numeroDiTelefono')}
                defaultValue={values.numeroDiTelefono}
                />

                <TextField
                required
                id="giorno-nascita-utente"
                label="Giorno di nascita"
                value={giorno}
                onChange={handleChange('birthdayDay')}
                onChange={cambiaGiorno}
                >
                {giorni.map((option) => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
          </TextField>

          <TextField
                required
                id="mese-nascita-utente"
                label="Mese di nascita"
                value={mese}
                onChange={handleChange('birthdayMonth')}
                onChange={cambiaMese}
                >
                {mesi.map((option) => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
          </TextField>

          <TextField
          id="anno-nascita-utente"
          label="Anno di nascita"
          type="number"
          InputLabelProps={{
            shrink: true,
          }}
          onChange={handleChange('birthdayYear')}
          defaultValue={values.birthdayYear}
        />

        <Button
            label="Continua"
            color="secondary"
            variant="contained"
            onClick={this.continue}
        >
            Continua
        </Button>
        </form>
        );
    }
}

export default FormUtenteAnagrafica;

Body:
Welcome to React!

Some things that occurred to me straight off here.

React hooks such as useState cannot be used in class components, you will have to use a functional component. This is because the normal way you'd manipulate state in a class is defining a constructor and declaring a state object like so:

export default class App extends component {
 constructor(){
  props(){
   this.state = {
    //declare state items here
   }
  }

  render() {
   //render state and html here
   this.setState({}) //to update properties on the state
  }
 }

}

Like I said, if you want to use hooks, you must define a functional component and import useState from react.

import React, { useState } from 'react'
function App() {
 const [value, setValue] = useState('')
 return(
  //return things here
 )
}

I'd recommend looking at the react docs about hooks here: https://reactjs.org/docs/hooks-intro.html

Hope this helps :)


问:
Refresh in Repository get called every time onCreate() of Activity called ( not in screen rotation )
I have following project in Github : https://github.com/AliRezaeiii/TVMaze

I have started to using Koin as dependency injection framework in a sample app :

```<code>class TVMazeApplication : Application() {

    override fun onCreate() {
        super.onCreate()

        startKoin {
            androidContext(this@TVMazeApplication)
            modules(networkModule)
            modules(persistenceModule)
            modules(repositoryModule)
            modules(viewModelModule)
        }
    }
}
</code>```

This is my repository class :

```<code>class ShowRepository(
    private val dao: ShowDao,
    private val api: TVMazeService,
    private val context: Context
) {

    /**
     * A list of shows that can be shown on the screen.
     */
    val shows = resultLiveData(
        databaseQuery = {
            Transformations.map(dao.getShows()) {
                it.asDomainModel()
            }
        },
        networkCall = { refreshShows() })

    /**
     * Refresh the shows stored in the offline cache.
     */
    private suspend fun refreshShows(): Result<List<Show>> =
        try {
            if (isNetworkAvailable(context)) {
                val shows = api.fetchShowList().await()
                dao.insertAll(*shows.asDatabaseModel())
                Result.success(shows)
            } else {
                Result.error(context.getString(R.string.failed_internet_msg))
            }
        } catch (err: HttpException) {
            Result.error(context.getString(R.string.failed_loading_msg))
        }
}
</code>```

And my ViewModel :

```<code>class MainViewModel(
    repository: ShowRepository
) : ViewModel() {

    private val _shows = repository.shows
    val shows: LiveData<Result<List<Show>>>
        get() = _shows
}
</code>```

And I observe LiveData in my Activity :

```<code>viewModel.shows.observe(this, Observer { result ->
            when (result.status) {
                Result.Status.SUCCESS -> {
                    binding.loadingSpinner.hide()
                    viewModelAdapter.submitList(result.data)
                }
                Result.Status.LOADING -> binding.loadingSpinner.show()
                Result.Status.ERROR -> {
                    binding.loadingSpinner.hide()
                    Snackbar.make(binding.root, result.message!!, Snackbar.LENGTH_LONG).show()
                }
            }
        })
</code>```

When I click on Back button, Activity get destroyed ( but instance of app still exist as I can access it from recent apps). What I expect is a call to refreshShows() method when I start the app again, but it never get called.

But when I destroy instance of app by clearing from recent app and start the app, refreshShows() get called.

What should I do to have a call on refreshShows() every time onCreate() callback of Activity get called?

```<code>fun <T, A> resultLiveData(databaseQuery: () -> LiveData<T>,
                          networkCall: suspend () -> Result<A>): LiveData<Result<T>> =
    liveData(Dispatchers.IO) {
        emit(Result.loading<T>())
        val source = databaseQuery.invoke().map { Result.success(it) }
        emitSource(source)

        val result = networkCall.invoke()
        if (result.status == Result.Status.ERROR) {
            emit(Result.error<T>(result.message!!))
            emitSource(source)
        }
    }
</code>```

答:
Your refreshShows() in your repository is only get called when a new network request is done. The idea of your livedata is to provide the latest result when its fragment/activity is recreated, so when your screen rotates or you resume an activity it doesnt triggers another request as the livedata already have the latest result and you dont have a stateful connection with your network database/server (if you were observing data from Room it would receive the latest change if any).

The simpliest way I find to "fix" this, is to actually have your viewmodel val shows to be a fun, like this:

```<code>class MainViewModel(
    repository: ShowRepository
) : ViewModel() {

    private val _shows = repository.shows()
    val shows: LiveData<Result<List<Show>>>
        get() = _shows
}
</code>```

However using like this, everytime the screen rotates a new network call will be made thus calling your refreshShows()

Body:
I have following project in Github : https://github.com/AliRezaeiii/TVMaze

I have started to using Koin as dependency injection framework in a sample app :

class TVMazeApplication : Application() {

    override fun onCreate() {
        super.onCreate()

        startKoin {
            androidContext(this@TVMazeApplication)
            modules(networkModule)
            modules(persistenceModule)
            modules(repositoryModule)
            modules(viewModelModule)
        }
    }
}

This is my repository class :

class ShowRepository(
    private val dao: ShowDao,
    private val api: TVMazeService,
    private val context: Context
) {

    /**
     * A list of shows that can be shown on the screen.
     */
    val shows = resultLiveData(
        databaseQuery = {
            Transformations.map(dao.getShows()) {
                it.asDomainModel()
            }
        },
        networkCall = { refreshShows() })

    /**
     * Refresh the shows stored in the offline cache.
     */
    private suspend fun refreshShows(): Result<List<Show>> =
        try {
            if (isNetworkAvailable(context)) {
                val shows = api.fetchShowList().await()
                dao.insertAll(*shows.asDatabaseModel())
                Result.success(shows)
            } else {
                Result.error(context.getString(R.string.failed_internet_msg))
            }
        } catch (err: HttpException) {
            Result.error(context.getString(R.string.failed_loading_msg))
        }
}

And my ViewModel :

class MainViewModel(
    repository: ShowRepository
) : ViewModel() {

    private val _shows = repository.shows
    val shows: LiveData<Result<List<Show>>>
        get() = _shows
}

And I observe LiveData in my Activity :

viewModel.shows.observe(this, Observer { result ->
            when (result.status) {
                Result.Status.SUCCESS -> {
                    binding.loadingSpinner.hide()
                    viewModelAdapter.submitList(result.data)
                }
                Result.Status.LOADING -> binding.loadingSpinner.show()
                Result.Status.ERROR -> {
                    binding.loadingSpinner.hide()
                    Snackbar.make(binding.root, result.message!!, Snackbar.LENGTH_LONG).show()
                }
            }
        })

When I click on Back button, Activity get destroyed ( but instance of app still exist as I can access it from recent apps). What I expect is a call to refreshShows() method when I start the app again, but it never get called.

But when I destroy instance of app by clearing from recent app and start the app, refreshShows() get called.

What should I do to have a call on refreshShows() every time onCreate() callback of Activity get called?

fun <T, A> resultLiveData(databaseQuery: () -> LiveData<T>,
                          networkCall: suspend () -> Result): LiveData<Result<T>> =
    liveData(Dispatchers.IO) {
        emit(Result.loading<T>())
        val source = databaseQuery.invoke().map { Result.success(it) }
        emitSource(source)

        val result = networkCall.invoke()
        if (result.status == Result.Status.ERROR) {
            emit(Result.error<T>(result.message!!))
            emitSource(source)
        }
    }

Body:
Your refreshShows() in your repository is only get called when a new network request is done. The idea of your livedata is to provide the latest result when its fragment/activity is recreated, so when your screen rotates or you resume an activity it doesnt triggers another request as the livedata already have the latest result and you dont have a stateful connection with your network database/server (if you were observing data from Room it would receive the latest change if any).

The simpliest way I find to "fix" this, is to actually have your viewmodel val shows to be a fun, like this:

class MainViewModel(
    repository: ShowRepository
) : ViewModel() {

    private val _shows = repository.shows()
    val shows: LiveData<Result<List<Show>>>
        get() = _shows
}

However using like this, everytime the screen rotates a new network call will be made thus calling your refreshShows()


问:
Message not updated in UIAlertController using a Timer
I'm trying to add a countdown timer message in the UIAlertController, the timer fires correctly and logs in the console everytime it fires up. However the alertController's message is not updated. I tried updated the message outside of the Timer it works. Not sure why it does not work inside the timer. Here's my code:

```<code>var ttimer = new System.Timers.Timer(1000);

alertController = UIAlertController.Create("title", "initial message", UIAlertControllerStyle.Alert);
using (var cancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (t) => { ttimer.Stop(); ttimer.Dispose(); }))
{
    alertController.AddAction(cancelAction);
}
PresentViewController(alertController, true, null);

var counter = 5; // 5 seconds count down timer, dismiss alert after 5 seconds

ttimer.Elapsed += (Object source, ElapsedEventArgs e) =>
{
    Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
        e.SignalTime); // This logs to the console fine
    if (counter > 0)
    {
        counter--;
        alertController.Message ="new message"; // This doesn't work
    }
    else
    {
        alertController.DismissViewController(false, null); // This doesn't work
        ttimer.Stop();
        ttimer.Dispose();
    }
};

ttimer.AutoReset = true;
ttimer.Enabled = true;

alertController.Message = "new message for testing"; // This works
</code>```

What did I do wrong? This is in Xamarin iOS/C#.

答:
the Elapsed event is not occuring on the main thread.  You can force your UI update to use the UI thread

```<code>InvokeOnMainThread ( () => {
  alertController.Message ="new message";
});
</code>```

Body:
I'm trying to add a countdown timer message in the UIAlertController, the timer fires correctly and logs in the console everytime it fires up. However the alertController's message is not updated. I tried updated the message outside of the Timer it works. Not sure why it does not work inside the timer. Here's my code:

var ttimer = new System.Timers.Timer(1000);

alertController = UIAlertController.Create("title", "initial message", UIAlertControllerStyle.Alert);
using (var cancelAction = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (t) => { ttimer.Stop(); ttimer.Dispose(); }))
{
    alertController.AddAction(cancelAction);
}
PresentViewController(alertController, true, null);

var counter = 5; // 5 seconds count down timer, dismiss alert after 5 seconds

ttimer.Elapsed += (Object source, ElapsedEventArgs e) =>
{
    Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
        e.SignalTime); // This logs to the console fine
    if (counter > 0)
    {
        counter--;
        alertController.Message ="new message"; // This doesn't work
    }
    else
    {
        alertController.DismissViewController(false, null); // This doesn't work
        ttimer.Stop();
        ttimer.Dispose();
    }
};

ttimer.AutoReset = true;
ttimer.Enabled = true;

alertController.Message = "new message for testing"; // This works

What did I do wrong? This is in Xamarin iOS/C#.

Body:
the Elapsed event is not occuring on the main thread.  You can force your UI update to use the UI thread

InvokeOnMainThread ( () => {
  alertController.Message ="new message";
});


问:
A question about scrolling backgrounds in XNA
I'm working on scrolling backgrounds for my game and I'm kind of stumped on how I should repeat the texture. Thus far I have it so that the background class takes five variables: two floats (one for each axis, both clamped to 0.01 and 1.0), two bools (to see if it should repeat on either axis) and the camera. It draws the texture to a rectangle and the rectangle's position moves with the camera's position multiplied by the appropriate float.

The movement code thus far is just:

```<code>source.X = (int)(camera.Pos.X * scrollX);
source.Y = (int)(camera.Pos.Y * scrollY);
</code>```

So what I'd like to do is make it so that the texture repeats on the appropriate axis (or axes) when one or both of the repeat bools is true, but I have no idea how I can do it with my current system. I was thinking I could add three or more rectangles (I usually make my backgrounds pretty big), have them all draw the same texture and move around according to where the camera is, but I'm not exactly sure how I could do that. Any suggestions?

答:
I haven't tested this, but I'm pretty sure you should be able to use the overload of SpriteBatch.Draw that takes both a source and a destination rectangle. Set your destination rectangle to cover your screen. Set your source rectangle to the negation of your background's position (or something like that; it will go beyond the edges of your texture).

You will probably have to set the SamplerState for the sprite batch to one of the sampler states that wraps (eg LinearWrap).

Body:
I'm working on scrolling backgrounds for my game and I'm kind of stumped on how I should repeat the texture. Thus far I have it so that the background class takes five variables: two floats (one for each axis, both clamped to 0.01 and 1.0), two bools (to see if it should repeat on either axis) and the camera. It draws the texture to a rectangle and the rectangle's position moves with the camera's position multiplied by the appropriate float.

The movement code thus far is just:

source.X = (int)(camera.Pos.X * scrollX);
source.Y = (int)(camera.Pos.Y * scrollY);

So what I'd like to do is make it so that the texture repeats on the appropriate axis (or axes) when one or both of the repeat bools is true, but I have no idea how I can do it with my current system. I was thinking I could add three or more rectangles (I usually make my backgrounds pretty big), have them all draw the same texture and move around according to where the camera is, but I'm not exactly sure how I could do that. Any suggestions?


问:
How do I access a meta-property in the  element to determine whether or not to inject some CSS?
I don't have access to the HTML of a website I've been asked to work on but I can insert Javascript via a custom Javascript input box on the site builder tool.

```<code><meta property="og:url" content="https://www.whyottawa.ca/speakers/jeff-jeffrey/">
</code>```

I need to set an element to "display:none" if the line above from the  element includes the content, "https://www.whyottawa.ca/speakers/*" using * as a wildcard.

I've tried something like

```<code>if (document.head.og:url.content === "https://www.whyottawa.ca/speakers/*") {
    document.getElementById('hide').style.display = "none";
};
</code>```

but it doesn't like the ":" in the og:url property. Is there a way to escape this? Or a better syntax?

I also tried an attribute selector such as meta[content|="https://www.whyottawa.ca/speakers/"]
but I got the error, 'ReferenceError: meta is not defined'

答:
In that case you can do this.

```<code>document.getElementById("hide").style.display="none";
</code>```

Or you can use other selectors if you have some other attributes or queries.

```<code>document.querySelector("#hide").style.display="none";
</code>```

Example for attribute selector
Here name is the attribute name hiddenElement is the value.

```<code>document.querySelector("#hide[name='hiddenElement'").style.display="none";
</code>```

For meta tag attribute selector

```<code>document.querySelector("meta[property='og:url']").getAttribute('content')
</code>```

Title: How do I access a meta-property in the <head> element to determine whether or not to inject some CSS?

Body:
I don't have access to the HTML of a website I've been asked to work on but I can insert Javascript via a custom Javascript input box on the site builder tool.

<meta property="og:url" content="https://www.whyottawa.ca/speakers/jeff-jeffrey/">

I need to set an element to "display:none" if the line above from the  element includes the content, "https://www.whyottawa.ca/speakers/*" using * as a wildcard.

I've tried something like

if (document.head.og:url.content === "https://www.whyottawa.ca/speakers/*") {
    document.getElementById('hide').style.display = "none";
};

but it doesn't like the ":" in the og:url property. Is there a way to escape this? Or a better syntax?

I also tried an attribute selector such as meta[content|="https://www.whyottawa.ca/speakers/"]
but I got the error, 'ReferenceError: meta is not defined'

Body:
In that case you can do this.

document.getElementById("hide").style.display="none";

Or you can use other selectors if you have some other attributes or queries.

document.querySelector("#hide").style.display="none";

Example for attribute selector
Here name is the attribute name hiddenElement is the value.

document.querySelector("#hide[name='hiddenElement'").style.display="none";

For meta tag attribute selector

document.querySelector("meta[property='og:url']").getAttribute('content')


问:
react native scrollview not smooth when app opend from background
i created simple app in react native ,everything works fine
but when the app go to background then active again
Scrollview not working smoothly
can some one have solution?</p>

答:
i find the solution

i Uninstalled react-native-fbsdk and everything works fine