问:
on MAC OS X, py.test not recognized as a command
On MAC OS X 10.10; I installed pytest 2.6.4; however in Terminal If I write py.test or even py.test --version; I get the error:

```<code>-bash: py.test command not found
</code>```

(a) Am I missing anything? What do I do to make the pytest tool recognizable.
I searched alot; but couldn't find any info except http://teckla.idyll.org/~t/transfer/py.test.html

I checked in the PyCharm preferences, I don't see py.test interpreter listed there. However, pip freeze displays pytest 2.6.4 installed.

(b) Is PYTHONPATH required to be set on MAC? Although I've seen setting it is not required on Windows.

Appreciate any pointers to help me resolve this.

Update: Contents of my bash_profile:

```<code>echo export PATH="HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"

PATH="/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:$PATH"
PATH="/Users/admin/Library/Python/2.7/lib/python/site-packages:$PATH"
PATH="/System/Library/Frameworks/Python.framework/Versions/2.7/bin:$PATH"
export PATH
</code>```

答: pip3 install -U pytest is working with version Python 3.7</p>

Body:
On MAC OS X 10.10; I installed pytest 2.6.4; however in Terminal If I write py.test or even py.test --version; I get the error:

-bash: py.test command not found

(a) Am I missing anything? What do I do to make the pytest tool recognizable.
I searched alot; but couldn't find any info except http://teckla.idyll.org/~t/transfer/py.test.html

I checked in the PyCharm preferences, I don't see py.test interpreter listed there. However, pip freeze displays pytest 2.6.4 installed.

(b) Is PYTHONPATH required to be set on MAC? Although I've seen setting it is not required on Windows.

Appreciate any pointers to help me resolve this.

Update: Contents of my bash_profile:

echo export PATH="HOME/.rbenv/bin:$PATH"
eval "$(rbenv init -)"

PATH="/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:$PATH"
PATH="/Users/admin/Library/Python/2.7/lib/python/site-packages:$PATH"
PATH="/System/Library/Frameworks/Python.framework/Versions/2.7/bin:$PATH"
export PATH


来源: stackexchange

问:
Sending json as html over wordpress api
i am trying to send json as raw (html) to wordpress api but its not working for me

```<code>$json = json_encode([
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
]);

$query = http_build_query([
'title' => $titleFile,
'content' => json_decode(stripslashes($json))
]);
$username = 'admin';
$password = '123456';
$url = "http://mysite/wp-json/wp/v2/posts/?$query";
$cmd = "curl --request POST --user $username:$password \"$url\"";
$requestWP = shell_exec($cmd);
print_r($requestWP);
die();
</code>```

its working fine, but the post is made with json in the body format if I don't decode and if I decode the post is empty as its an array how can I send the value of the key in raw (html) not Json?

wordpress api endpoint https://developer.wordpress.org/rest-api/reference/posts/

output with json_decode()

```<code>stdClass Object ( [key1] => value1 [key2] => value2 [key3] => value3 )
</code>```

答:
OK, so there are a few different things in your code that should be addressed. I'm not a Wordpress expert, so I will give you some general guidelines:

Making a POST request

There are a few different ways of sending a HTTP request from PHP, either using native functions or libraries, but using shell_exec to call CURL is definitely not the best. If you want to use CURL, I'd suggest the CURL library. Otherwise try a library like Guzzle

Payload goes in the body

When sending a POST request, the correct way to send the data (and the way Wordpress is expecting it) is to send it in the body of the request, not as part of the query string as you seem to be doing.

Payload should be a JSON string

You should do something similar to the following snippet to generate the body of your request if you are going to use CURL:

$data = json_encode([
    'title' => 'my title',
    'content' => [
        'key1' => 'value1',
        'key2' => 'value2',
        'key3' => 'value3'
    ]
]);

```

<p><code>$data</code> will then have the JSON string:</p>

```"{"title":"my title","content":{"key1":"value1","key2":"value2","key3":"value3"}}"
```

<p>Guzzle for instance, will take care of that for you.</p>

<p><strong>Authentication</strong></p>

<p>The endpoint you are trying to hit is protected and using login/password won't work unless you are using the Basic Authentication plugin.</p>

<p><strong>Putting it all together</strong></p>

<p>This is all you should need if you decide to use Guzzle and Basic Authentication:</p>

<pre class="lang-php prettyprint-override"><code>$client = new GuzzleHttp\Client();

$client->post('http://mysite/wp-json/wp/v2/posts/', [
  'auth' => [$username, $password],
  'json' => $data
]);
</code>```

ContentLicense: CC BY-SA 4.0

Title: Sending json as html over wordpress api

Body:
i am trying to send json as raw (html) to wordpress api but its not working for me

$json = json_encode([
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
]);

$query = http_build_query([
'title' => $titleFile,
'content' => json_decode(stripslashes($json))
]);
$username = 'admin';
$password = '123456';
$url = "http://mysite/wp-json/wp/v2/posts/?$query";
$cmd = "curl --request POST --user $username:$password \"$url\"";
$requestWP = shell_exec($cmd);
print_r($requestWP);
die();

its working fine, but the post is made with json in the body format if I don't decode and if I decode the post is empty as its an array how can I send the value of the key in raw (html) not Json?

wordpress api endpoint https://developer.wordpress.org/rest-api/reference/posts/

output with json_decode()

stdClass Object ( [key1] => value1 [key2] => value2 [key3] => value3 )

Body:
OK, so there are a few different things in your code that should be addressed. I'm not a Wordpress expert, so I will give you some general guidelines:

Making a POST request

There are a few different ways of sending a HTTP request from PHP, either using native functions or libraries, but using shell_exec to call CURL is definitely not the best. If you want to use CURL, I'd suggest the CURL library. Otherwise try a library like Guzzle

Payload goes in the body

When sending a POST request, the correct way to send the data (and the way Wordpress is expecting it) is to send it in the body of the request, not as part of the query string as you seem to be doing.

Payload should be a JSON string

You should do something similar to the following snippet to generate the body of your request if you are going to use CURL:

$data = json_encode([
    'title' => 'my title',
    'content' => [
        'key1' => 'value1',
        'key2' => 'value2',
        'key3' => 'value3'
    ]
]);

$data will then have the JSON string:

"{"title":"my title","content":{"key1":"value1","key2":"value2","key3":"value3"}}"

Guzzle for instance, will take care of that for you.

Authentication

The endpoint you are trying to hit is protected and using login/password won't work unless you are using the Basic Authentication plugin.

Putting it all together

This is all you should need if you decide to use Guzzle and Basic Authentication:

$client = new GuzzleHttp\Client();

$client->post('http://mysite/wp-json/wp/v2/posts/', [
  'auth' => [$username, $password],
  'json' => $data
]);


问:
How to fix 'Object arrays cannot be loaded when allow_pickle=False' for imdb.load_data() function?
I'm trying to implement the binary classification example using the IMDb dataset in Google Colab. I have implemented this model before. But when I tried to do it again after a few days, it returned a value error: 'Object arrays cannot be loaded when allow_pickle=False' for the load_data() function.

I have already tried solving this, referring to an existing answer for a similar problem: How to fix 'Object arrays cannot be loaded when allow_pickle=False' in the sketch_rnn algorithm.
But it turns out that just adding an allow_pickle argument isn't sufficient.

My code:

```<code>from keras.datasets import imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
</code>```

The error:

```<code>ValueError                                Traceback (most recent call last)
<ipython-input-1-2ab3902db485> in <module>()
      1 from keras.datasets import imdb
----> 2 (train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)

2 frames
/usr/local/lib/python3.6/dist-packages/keras/datasets/imdb.py in load_data(path, num_words, skip_top, maxlen, seed, start_char, oov_char, index_from, **kwargs)
     57                     file_hash='599dadb1135973df5b59232a0e9a887c')
     58     with np.load(path) as f:
---> 59         x_train, labels_train = f['x_train'], f['y_train']
     60         x_test, labels_test = f['x_test'], f['y_test']
     61

/usr/local/lib/python3.6/dist-packages/numpy/lib/npyio.py in __getitem__(self, key)
    260                 return format.read_array(bytes,
    261                                          allow_pickle=self.allow_pickle,
--> 262                                          pickle_kwargs=self.pickle_kwargs)
    263             else:
    264                 return self.zip.read(key)

/usr/local/lib/python3.6/dist-packages/numpy/lib/format.py in read_array(fp, allow_pickle, pickle_kwargs)
    690         # The array contained Python objects. We need to unpickle the data.
    691         if not allow_pickle:
--> 692             raise ValueError("Object arrays cannot be loaded when "
    693                              "allow_pickle=False")
    694         if pickle_kwargs is None:

ValueError: Object arrays cannot be loaded when allow_pickle=False
</code>```

答:
I landed up here, tried your ways and could not figure out.

I was actually working on a pregiven code where

```<code>pickle.load(path)
</code>```

was used so i replaced it with

```<code>np.load(path, allow_pickle=True)
</code>```

Body:
I'm trying to implement the binary classification example using the IMDb dataset in Google Colab. I have implemented this model before. But when I tried to do it again after a few days, it returned a value error: 'Object arrays cannot be loaded when allow_pickle=False' for the load_data() function.

I have already tried solving this, referring to an existing answer for a similar problem: How to fix 'Object arrays cannot be loaded when allow_pickle=False' in the sketch_rnn algorithm.
But it turns out that just adding an allow_pickle argument isn't sufficient.

My code:

from keras.datasets import imdb
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)

The error:

ValueError                                Traceback (most recent call last)
<ipython-input-1-2ab3902db485> in <module>()
      1 from keras.datasets import imdb
----> 2 (train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)

2 frames
/usr/local/lib/python3.6/dist-packages/keras/datasets/imdb.py in load_data(path, num_words, skip_top, maxlen, seed, start_char, oov_char, index_from, **kwargs)
     57                     file_hash='599dadb1135973df5b59232a0e9a887c')
     58     with np.load(path) as f:
---> 59         x_train, labels_train = f['x_train'], f['y_train']
     60         x_test, labels_test = f['x_test'], f['y_test']
     61

/usr/local/lib/python3.6/dist-packages/numpy/lib/npyio.py in __getitem__(self, key)
    260                 return format.read_array(bytes,
    261                                          allow_pickle=self.allow_pickle,
--> 262                                          pickle_kwargs=self.pickle_kwargs)
    263             else:
    264                 return self.zip.read(key)

/usr/local/lib/python3.6/dist-packages/numpy/lib/format.py in read_array(fp, allow_pickle, pickle_kwargs)
    690         # The array contained Python objects. We need to unpickle the data.
    691         if not allow_pickle:
--> 692             raise ValueError("Object arrays cannot be loaded when "
    693                              "allow_pickle=False")
    694         if pickle_kwargs is None:

ValueError: Object arrays cannot be loaded when allow_pickle=False

Body:
I landed up here, tried your ways and could not figure out.

I was actually working on a pregiven code where

pickle.load(path)

was used so i replaced it with

np.load(path, allow_pickle=True)


问:
Is vectorization of Components defined on scalars possible in OpenMDAO?
In the context of functional programming, a function that takes and returns a scalar can be mapped onto lists/vectors to return a list/vector of the mapped values. In regular Python, I would do this either functionally or in NumPy's vectorized fashion:

```<code>import numpy as np # NumPy import

xs = [1,2,3,4,5] # List of inputs
f = lambda x: x**2 # Some function, which could be the equivalent of an ExplicitComponent

list(map(f, xs)) # Functional style
[ f(x) for x in xs ] # List comprehension
f(np.array(xs)) # NumPy vectorized style
</code>```

Is this type of behaviour attainable using Components? By this I mean a Component could take scalar inputs and perform like a normal function, but automatically performs the operations on vectors and lists of varying length as well.

I haven't been able to find anything similar in the documentation. I understand that most of the behaviour in OpenMDAO uses NumPy's vectorization for efficiency, but does this mean all components that could have vector inputs must be written using some kind of self.options.declare('num_nodes', default=1) method and passing a global state n for the number of nodes for lists/vectors of length/dimension n across all Components?

Regarding design considerations, I understand that vectorizations over Cartesian products of input vectors are not implemented by default in NumPy, and that they're more zip-like. But it does work like a partially-applied mapped function by default for a single NumPy array, e.g.:

```<code>>>> xs = [1,2,3,4,5]
>>> f = lambda x,y: x**2 + y**2
>>> f(np.array(xs), np.array([2,4,6,8]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
ValueError: operands could not be broadcast together with shapes (5,) (4,)
>>> f(np.array(xs), np.array([2,4,6,8,10]))
array([  5,  20,  45,  80, 125])
>>> f(np.array(xs), 1)
array([ 2,  5, 10, 17, 26])
</code>```

An alternative is to use NumPy's meshgrid() as follows:

```<code>xs, ys = [1,2,3,4,5], [2,4,6,8]
f = lambda x, y: x**2 + y**2
xys = np.meshgrid(xs, ys)
f(xys[0], xys[1])
</code>```

So would something like this be more feasible (and desirable!) behaviour for Components?

答:
As of OpenMDAO V3.1 the only way to do this in OpenMDAO is via an option/argument such as num_nodes or vec_size.

Other users have expressed an interest in allowing dynamically sized IO in components.  For instance, basing he size of an input on the output to which it is connected.  See https://github.com/OpenMDAO/POEMs/pull/51.

We're working on it, but we don't have a time table for when we'll find an acceptable solution at this time.

Body:
In the context of functional programming, a function that takes and returns a scalar can be mapped onto lists/vectors to return a list/vector of the mapped values. In regular Python, I would do this either functionally or in NumPy's vectorized fashion:

import numpy as np # NumPy import

xs = [1,2,3,4,5] # List of inputs
f = lambda x: x**2 # Some function, which could be the equivalent of an ExplicitComponent

list(map(f, xs)) # Functional style
[ f(x) for x in xs ] # List comprehension
f(np.array(xs)) # NumPy vectorized style

Is this type of behaviour attainable using Components? By this I mean a Component could take scalar inputs and perform like a normal function, but automatically performs the operations on vectors and lists of varying length as well.

I haven't been able to find anything similar in the documentation. I understand that most of the behaviour in OpenMDAO uses NumPy's vectorization for efficiency, but does this mean all components that could have vector inputs must be written using some kind of self.options.declare('num_nodes', default=1) method and passing a global state n for the number of nodes for lists/vectors of length/dimension n across all Components?

Regarding design considerations, I understand that vectorizations over Cartesian products of input vectors are not implemented by default in NumPy, and that they're more zip-like. But it does work like a partially-applied mapped function by default for a single NumPy array, e.g.:

>>> xs = [1,2,3,4,5]
>>> f = lambda x,y: x**2 + y**2
>>> f(np.array(xs), np.array([2,4,6,8]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
ValueError: operands could not be broadcast together with shapes (5,) (4,)
>>> f(np.array(xs), np.array([2,4,6,8,10]))
array([  5,  20,  45,  80, 125])
>>> f(np.array(xs), 1)
array([ 2,  5, 10, 17, 26])

An alternative is to use NumPy's meshgrid() as follows:

xs, ys = [1,2,3,4,5], [2,4,6,8]
f = lambda x, y: x**2 + y**2
xys = np.meshgrid(xs, ys)
f(xys[0], xys[1])

So would something like this be more feasible (and desirable!) behaviour for Components?


问:
this is the problem occured to me while installing docker engine using amazon ec2 ubuntu 18.04
E: The repository 'https://download.docker.com/linux/ubuntu \ Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.</p>

答:
Have you tried to update?
Try this:</p>

```<code>sudo apt update && sudo apt install docker.io -y
</code>```

Body:
Have you tried to update?
Try this:

sudo apt update && sudo apt install docker.io -y


问:
Count animation from number A to B
I am updating a numeric value inside an element by doing intervalled ajax requests.

To make the whole thing a bit more alive, I want to count from the current value to the new one, by partially in- or decreasing the value over a time of n sec.

So basically something like this:

```<code><div id="value">100</div>
<script type="text/javascript">
    /** Decrease $value (over a time of 2 seconds) till it reaches 25 */
    $value.increaseAnimation(-75, {duration:2});
</script>
</code>```

Is there a javascript library for doing so?

答:
Here is one version where increments grow by some defined multiplier (mul).
frameDelay is the time delay for each increment. This looks a bit better if you have values that camn </p>

```<code>function cAnimate(id, start, end, frameDelay = 100, mul = 1.2) {
    var obj = document.getElementById(id);
    var increment = 2;
    var current = start;
    var timer = setInterval(function() {
        current += increment;
        increment *= mul;
        if (current >= end) {
            current = end;
            clearInterval(timer);
        }

        obj.innerHTML = Math.floor(current).toLocaleString();

    }, frameDelay);
}

cAnimate("counter", 1, 260000, 50);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Count animation from number A to B

Body:
I am updating a numeric value inside an element by doing intervalled ajax requests.

To make the whole thing a bit more alive, I want to count from the current value to the new one, by partially in- or decreasing the value over a time of n sec.

So basically something like this:

100

Is there a javascript library for doing so?

Body:
Here is one version where increments grow by some defined multiplier (mul).
frameDelay is the time delay for each increment. This looks a bit better if you have values that camn

function cAnimate(id, start, end, frameDelay = 100, mul = 1.2) {
    var obj = document.getElementById(id);
    var increment = 2;
    var current = start;
    var timer = setInterval(function() {
        current += increment;
        increment *= mul;
        if (current >= end) {
            current = end;
            clearInterval(timer);
        }

        obj.innerHTML = Math.floor(current).toLocaleString();

    }, frameDelay);
}

cAnimate("counter", 1, 260000, 50);


问:
Convert six digits to date
I am trying to convert a string of six digits to valid date
example:
121200 is for 12 / 12 / 2000
Another example:
140585 is for 14/ 05 / 1985

I can use DateValue function and CDate but the problem for me is how to determine the correct century part .. I mean how to decide if it will be 20 or 19 before the last two number ..
I tried such line

```<code>Debug.Print Format("140585", "dd/mm/yyyy")
</code>```

But this prints 26/11/2284

答:
I would use Format to add the slashes here, and then use DateValue:

```<code>Debug.Print Format("1405085", "00\/00\/00") '<~ returns 14/05/85
</code>```

Slightly more detailed:

```<code>Dim textDate as String
textDate = "140585"
textDate = Format(textDate, "00\/00\/00")

Dim realDate as Date
realDate = DateValue(textDate)

Debug.Print realDate  '<~ returns 14/05/1985
</code>```

See this for how Excel handles two digit year numbers and converting to the appropriate century.

Title: Convert six digits to date

Body:
I am trying to convert a string of six digits to valid date
example:
121200 is for 12 / 12 / 2000
Another example:
140585 is for 14/ 05 / 1985

I can use DateValue function and CDate but the problem for me is how to determine the correct century part .. I mean how to decide if it will be 20 or 19 before the last two number ..
I tried such line

Debug.Print Format("140585", "dd/mm/yyyy")

But this prints 26/11/2284

Body:
I would use Format to add the slashes here, and then use DateValue:

Debug.Print Format("1405085", "00\/00\/00") '<~ returns 14/05/85

Slightly more detailed:

Dim textDate as String
textDate = "140585"
textDate = Format(textDate, "00\/00\/00")

Dim realDate as Date
realDate = DateValue(textDate)

Debug.Print realDate  '<~ returns 14/05/1985

See this for how Excel handles two digit year numbers and converting to the appropriate century.


问:
Servlet not updating value in database
I'm trying to create a basic password reset system. I'm creating an unique token for each user, storing in database and retrieving that token value in url like: http://localhost:8080/login/reset-password.jsp?token=0d1eaa1a-869c-4f40-8437-a3cdaeddf497

The problem here is that I'm trying to update the password in the database but the value isn't updated. It displays that the password is changed, but nothing happens in database. Please help.

Here's my servlet:

```<code>protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String password = request.getParameter("password");
        String token = request.getParameter("token");

                ForgotPasswordHandler.UpdatePassword(password, token);

                String message = "Password changed!";
                request.setAttribute("message", message);
                request.getRequestDispatcher("reset-password.jsp?token=" + token).forward(request, response);

    }
</code>```

Here's my method in class ForgotPasswordHandler.java:

```<code>public static void UpdatePassword(String password, String token) {

            try
              {

              if (con == null){
                 System.out.println("Failed connection");

              }else{

                PreparedStatement ps = con.prepareStatement(
                  "UPDATE user SET password = ? WHERE reset_token = ?");

                ps.setString(1,password);
                ps.setString(2,token);

                ps.executeUpdate();

                ps.close();

              }}
            catch (Exception e) {
                 e.printStackTrace(System.out);
              }

            }

</code>```

答:
Your connection may have autoCommit turned off. If that is the problem you can fix it with code like this:

```<code>   if (!con.getAutoCommit()) {
      con.commit();
   }
</code>```

One other thing to note is that if the call to ps.executeUpdate() fails, the prepared statement will not be cleaned up. To avoid that problem move the close to the finally block. Here is what the full code would look like:

```<code>PreparedStatement ps = null;
try
{
    if (con == null){
        System.out.println("Failed connection");
    } else {
        ps = con.prepareStatement(
            "UPDATE user SET password = ? WHERE reset_token = ?");

        ps.setString(1,password);
        ps.setString(2,token);

        ps.executeUpdate();

       if (!con.getAutoCommit()) {
          con.commit();
       }
    }
}
catch (Exception e) {
        e.printStackTrace(System.out);
}
finally {
    if (ps != null) {
        ps.close();
    }
}
</code>```

Title: Servlet not updating value in database

Body:
I'm trying to create a basic password reset system. I'm creating an unique token for each user, storing in database and retrieving that token value in url like: http://localhost:8080/login/reset-password.jsp?token=0d1eaa1a-869c-4f40-8437-a3cdaeddf497

The problem here is that I'm trying to update the password in the database but the value isn't updated. It displays that the password is changed, but nothing happens in database. Please help.

Here's my servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String password = request.getParameter("password");
        String token = request.getParameter("token");

                ForgotPasswordHandler.UpdatePassword(password, token);

                String message = "Password changed!";
                request.setAttribute("message", message);
                request.getRequestDispatcher("reset-password.jsp?token=" + token).forward(request, response);

    }

Here's my method in class ForgotPasswordHandler.java:

public static void UpdatePassword(String password, String token) {

            try
              {

              if (con == null){
                 System.out.println("Failed connection");

              }else{

                PreparedStatement ps = con.prepareStatement(
                  "UPDATE user SET password = ? WHERE reset_token = ?");

                ps.setString(1,password);
                ps.setString(2,token);

                ps.executeUpdate();

                ps.close();

              }}
            catch (Exception e) {
                 e.printStackTrace(System.out);
              }

            }

Body:
Your connection may have autoCommit turned off. If that is the problem you can fix it with code like this:

   if (!con.getAutoCommit()) {
      con.commit();
   }

One other thing to note is that if the call to ps.executeUpdate() fails, the prepared statement will not be cleaned up. To avoid that problem move the close to the finally block. Here is what the full code would look like:

PreparedStatement ps = null;
try
{
    if (con == null){
        System.out.println("Failed connection");
    } else {
        ps = con.prepareStatement(
            "UPDATE user SET password = ? WHERE reset_token = ?");

        ps.setString(1,password);
        ps.setString(2,token);

        ps.executeUpdate();

       if (!con.getAutoCommit()) {
          con.commit();
       }
    }
}
catch (Exception e) {
        e.printStackTrace(System.out);
}
finally {
    if (ps != null) {
        ps.close();
    }
}


问:
Not able to generate local database file.
I am using Visual Studio 2010 in which want to create a local DB file in my project.

When I register using the pre-built login, Visual Studio should create the DB file, but instead it shows a message box saying

Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.

When i try to add it manually it shows the same message.

What can be done to resolve this issue?

答:
Check your connection string on your App.Config file if its Correct.</p>

```<code><?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <connectionStrings>
    <add name="DB" connectionString="Data Source=MyPC\SQLEXPRESS;Initial Catalog=IIQR;Integrated Security=True"providerName="System.Data.SqlClient"/>
  </connectionStrings>

</configuration>
</code>```

Body:
Check your connection string on your App.Config file if its Correct.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <connectionStrings>
    <add name="DB" connectionString="Data Source=MyPC\SQLEXPRESS;Initial Catalog=IIQR;Integrated Security=True"providerName="System.Data.SqlClient"/>
  </connectionStrings>

</configuration>


问:
Overload Resolution differs between compilers
I have constructed the following minimal example of my problem:

```<code>#include <iostream>

struct Foo {
  Foo() {
    std::cout << "default" << std::endl;
  }
  Foo(Foo& f2) {
    std::cout << "non-const" << std::endl;
  }
  Foo(const Foo& f2) {
    std::cout << "const" << std::endl;
  }
};

int main() {
        std::pair<Foo, int> foop0(Foo(), 1);
        std::cout << std::endl;
        std::pair<const Foo, int>foop1(foop0);
}
</code>```

On my Ubuntu machine g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0 will print out the following:

```<code>$ g++ -std=c++14 test.cpp -o test && ./test
default
const

const
</code>```

However, Apple clang (version 11.0.3 (clang-1103.0.32.62)
Target: x86_64-apple-darwin19.4.0) on my Mac will print:

```<code>$ g++ -std=c++14 test.cpp -o test && ./test
default
const

non-const
</code>```

However, it gets worse: If i change the last line to

```<code>std::pair<Foo, int>foop1(foop0);
          ^ removed const
</code>```

both compilers will give the first output.

Why does this happen?

EDIT: I have now understood why, according to cppreference, std::pair's ctors should be selected as they are by g++. Still doesn't explain clang's weird behaviour here. A non-conforming implementation maybe?

答:
Like already said, probably the implementations of std::pair for both of them differ. I wrote two very similar implementations of a pair that exhibit exactly your differing behaviors, even without changing the type of the pair: godbolt

```<code>#include <iostream>

struct T {
    T() {
        std::cerr << "default\n";
    }

    T(T&) {
        std::cerr << "non-const\n";
    }

    T(const T&) {
        std::cerr << "const\n";
    }

};

// Comment or uncomment to change the behavior.
//#define MAC

template<class First, class Second>
struct pair {
    First first;
    Second second;

    pair(const First& f, const Second& s) : first(f), second(s) {
    }

#ifdef MAC

    pair(pair<First, Second>& p) : first(p.first), second(p.second) {
        std::cerr << "copy Mac-Like\n";
    }

#else

    pair( pair<First, Second>& p) : pair(p.first, p.second) {
        std::cerr << "copy Ubuntu-Like\n";
    }
#endif

};

int main() {
    T t;
    pair<T, int> u1(t, 0);

    pair<T, int> u2(u1);
}
</code>```

Of course, the pairs on mac and ubuntu are both written more reasonably (and standard-conforming) and have the standard-copy-constructor taking a const-reference (which is the reason for both of them using the const variant then). But I guess they handle the copy constructors from pairs with differing but convertible types differently. Finding out what exactly is different would require to compare the stl implementations on both systems.

The Ubuntu variant seems pretty clear to me, there the pair is just taken by const reference in the constructor from a pair of convertible types. When you have a const at any point of your construction chain you will end up with the const copy constructor of T.

I find the Mac behavior a bit weird since they have to either take the pair by value or by non-const reference (and really, you should not have a copy constructor taking by non-const reference, why should it ever change the thing it copies? This seems like std::auto_ptr-level weirdness). Maybe they are (trying to be) clever with some kind of "take it by value and then move" thing.

But I think this is non-conforming, since the pair constructor should take all other pairs by const-reference or by rvalue-reference. Since we are copying, it should use the copy constructor, taking a const reference and hence also have a const reference to the pair.first and by this taking its const copy constructor.

Body:
I have constructed the following minimal example of my problem:

#include <iostream>

struct Foo {
  Foo() {
    std::cout << "default" << std::endl;
  }
  Foo(Foo& f2) {
    std::cout << "non-const" << std::endl;
  }
  Foo(const Foo& f2) {
    std::cout << "const" << std::endl;
  }
};

int main() {
        std::pair<Foo, int> foop0(Foo(), 1);
        std::cout << std::endl;
        std::pair<const Foo, int>foop1(foop0);
}

On my Ubuntu machine g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0 will print out the following:

$ g++ -std=c++14 test.cpp -o test && ./test
default
const

const

However, Apple clang (version 11.0.3 (clang-1103.0.32.62)
Target: x86_64-apple-darwin19.4.0) on my Mac will print:

$ g++ -std=c++14 test.cpp -o test && ./test
default
const

non-const

However, it gets worse: If i change the last line to

std::pair<Foo, int>foop1(foop0);
          ^ removed const

both compilers will give the first output.

Why does this happen?

EDIT: I have now understood why, according to cppreference, std::pair's ctors should be selected as they are by g++. Still doesn't explain clang's weird behaviour here. A non-conforming implementation maybe?

Body:
Like already said, probably the implementations of std::pair for both of them differ. I wrote two very similar implementations of a pair that exhibit exactly your differing behaviors, even without changing the type of the pair: godbolt

#include <iostream>

struct T {
    T() {
        std::cerr << "default\n";
    }

    T(T&) {
        std::cerr << "non-const\n";
    }

    T(const T&) {
        std::cerr << "const\n";
    }

};

// Comment or uncomment to change the behavior.
//#define MAC

template<class First, class Second>
struct pair {
    First first;
    Second second;

    pair(const First& f, const Second& s) : first(f), second(s) {
    }

#ifdef MAC

    pair(pair<First, Second>& p) : first(p.first), second(p.second) {
        std::cerr << "copy Mac-Like\n";
    }

#else

    pair( pair<First, Second>& p) : pair(p.first, p.second) {
        std::cerr << "copy Ubuntu-Like\n";
    }
#endif

};

int main() {
    T t;
    pair<T, int> u1(t, 0);

    pair<T, int> u2(u1);
}

Of course, the pairs on mac and ubuntu are both written more reasonably (and standard-conforming) and have the standard-copy-constructor taking a const-reference (which is the reason for both of them using the const variant then). But I guess they handle the copy constructors from pairs with differing but convertible types differently. Finding out what exactly is different would require to compare the stl implementations on both systems.

The Ubuntu variant seems pretty clear to me, there the pair is just taken by const reference in the constructor from a pair of convertible types. When you have a const at any point of your construction chain you will end up with the const copy constructor of T.

I find the Mac behavior a bit weird since they have to either take the pair by value or by non-const reference (and really, you should not have a copy constructor taking by non-const reference, why should it ever change the thing it copies? This seems like std::auto_ptr-level weirdness). Maybe they are (trying to be) clever with some kind of "take it by value and then move" thing.

But I think this is non-conforming, since the pair constructor should take all other pairs by const-reference or by rvalue-reference. Since we are copying, it should use the copy constructor, taking a const reference and hence also have a const reference to the pair.first and by this taking its const copy constructor.


问:
How to add a new SwiftUI Color
How can i add a SwiftUI Color? Normally on UIKit you can create your own Colors but in SwiftUI con Color struct it's not easy like UIColor, but it's not complicate.</p>

```<code>extension UIColor {
    UIColor(red: 219/255, green: 175/255, blue: 15/255, alpha: 1.0)
}
</code>```

答:
You can create Color+Extension.swift file and add RGB's of your colors.

```<code>import SwiftUI

extension Color {
    public static var brokenWhite: Color {
        return Color(red: 238.0 / 255.0, green: 238.0 / 255.0, blue: 238.0 / 255.0)
    }

    public static var darkGray: Color {
        return Color(red: 57.0 / 255.0, green: 62.0 / 255.0, blue: 70.0 / 255.0)
    }
}
</code>```

Title: How to add a new SwiftUI Color

Body:
How can i add a SwiftUI Color? Normally on UIKit you can create your own Colors but in SwiftUI con Color struct it's not easy like UIColor, but it's not complicate.

extension UIColor {
    UIColor(red: 219/255, green: 175/255, blue: 15/255, alpha: 1.0)
}

Body:
You can create Color+Extension.swift file and add RGB's of your colors.

import SwiftUI

extension Color {
    public static var brokenWhite: Color {
        return Color(red: 238.0 / 255.0, green: 238.0 / 255.0, blue: 238.0 / 255.0)
    }

    public static var darkGray: Color {
        return Color(red: 57.0 / 255.0, green: 62.0 / 255.0, blue: 70.0 / 255.0)
    }
}


问:
how do i append content of a dictionary to a list in python?
```<code>import csv

with open('filename.csv') as csv_file:
    datarow = csv.reader(filename, delimiter=',')
    dict_places = {}
    list_places = []
    for row in datarow:
        dict_places['Continent'] = row[0]
        dict_places['Country'] = row[1]
        dict_places['Capital'] = row[2]
        print(list_places.append(dict_places))
</code>```

I am reading  a csv file filename.csv , I am not  getting the desired result like below.

[{'Continent': 'Europe', 'Country': 'Spain', 'Capital': 'Madrid'}, {'Continent': 'Europe', 'Country': 'Portugal', 'Capital': 'Lisbon'}', {'Continent': 'Europe', 'Country': 'England', 'Capital': 'London'}]

答:
You should consider using csv.DictReader for this. It will do the hard work for you and make errors like this less likely. You just pass in the list of column names:

```<code>import csv
with open(path) as csvfile:
    rows = csv.DictReader(csvfile, ['Continent','Country', 'Capital'])
    list_places = [dict(row) for row in rows]

print(list_places)
</code>```

prints:

```<code>[{'Continent': 'Europe', 'Country': 'Spain', 'Capital': 'Madrid'},
 {'Continent': 'Europe', 'Country': 'Portugal', 'Capital': 'Lisbon'},
 {'Continent': 'Europe', 'Country': 'England', 'Capital': 'London'}]
</code>```

Body:
import csv

with open('filename.csv') as csv_file:
    datarow = csv.reader(filename, delimiter=',')
    dict_places = {}
    list_places = []
    for row in datarow:
        dict_places['Continent'] = row[0]
        dict_places['Country'] = row[1]
        dict_places['Capital'] = row[2]
        print(list_places.append(dict_places))

I am reading  a csv file filename.csv , I am not  getting the desired result like below.

[{'Continent': 'Europe', 'Country': 'Spain', 'Capital': 'Madrid'}, {'Continent': 'Europe', 'Country': 'Portugal', 'Capital': 'Lisbon'}', {'Continent': 'Europe', 'Country': 'England', 'Capital': 'London'}]

Body:
You should consider using csv.DictReader for this. It will do the hard work for you and make errors like this less likely. You just pass in the list of column names:

import csv
with open(path) as csvfile:
    rows = csv.DictReader(csvfile, ['Continent','Country', 'Capital'])
    list_places = [dict(row) for row in rows]

print(list_places)

prints:

[{'Continent': 'Europe', 'Country': 'Spain', 'Capital': 'Madrid'},
 {'Continent': 'Europe', 'Country': 'Portugal', 'Capital': 'Lisbon'},
 {'Continent': 'Europe', 'Country': 'England', 'Capital': 'London'}]


问:
Efficient way of labelling based on start and end position
I have 2 dataframes

```<code>das <- data.frame(val=1:20,
              type =c("A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B","C","C","C","C"),
              weigh=c(20,22,23,32,34,54,19,22,24,26,31,34,36,37,51,54,31,35,43,45))

mapper <- data.frame(type=c("A","A","A","A","B","B","B","B","C","C","C","C"),start = c(19,23,27,37   ,17,25,39,50, 17,23,33,39),end = c(23,27,37,55  ,25,39,50,60, 23,33,39,48))
</code>```

The expected output is

```<code>val type weigh labelweight
1    1    A    20    A_19
2    2    A    22    A_19
3    3    A    23    A_23
4    4    A    32    A_27
5    5    A    34    A_27
6    6    A    54    A_37
7    7    B    19    B_17
8    8    B    22    B_17
9    9    B    24    B_17
10  10    B    26    B_25
11  11    B    31    B_25
12  12    B    34    B_25
13  13    B    36    B_25
14  14    B    37    B_25
15  15    B    51    B_50
16  16    B    54    B_50
17  17    C    31    C_23
18  18    C    35    C_33
19  19    C    43    C_39
20  20    C    45    C_39
</code>```

I am able to get the expected output with following code

```<code>p <- left_join(das,mapper)
q <- p%>%filter(weigh>=start & weigh<end)%>%mutate(labelweight= paste0(type,"_",start))
</code>```

The code whatever I came up with is throwing "Error: vector memory exhausted (limit reached?)" when dealing with large datasets.

I am thinking if there is any more efficient way of getting the desired output without doing a join.

Body:
I have 2 dataframes

das <- data.frame(val=1:20,
              type =c("A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B","C","C","C","C"),
              weigh=c(20,22,23,32,34,54,19,22,24,26,31,34,36,37,51,54,31,35,43,45))

mapper <- data.frame(type=c("A","A","A","A","B","B","B","B","C","C","C","C"),start = c(19,23,27,37   ,17,25,39,50, 17,23,33,39),end = c(23,27,37,55  ,25,39,50,60, 23,33,39,48))

The expected output is

val type weigh labelweight
1    1    A    20    A_19
2    2    A    22    A_19
3    3    A    23    A_23
4    4    A    32    A_27
5    5    A    34    A_27
6    6    A    54    A_37
7    7    B    19    B_17
8    8    B    22    B_17
9    9    B    24    B_17
10  10    B    26    B_25
11  11    B    31    B_25
12  12    B    34    B_25
13  13    B    36    B_25
14  14    B    37    B_25
15  15    B    51    B_50
16  16    B    54    B_50
17  17    C    31    C_23
18  18    C    35    C_33
19  19    C    43    C_39
20  20    C    45    C_39

I am able to get the expected output with following code

p <- left_join(das,mapper)
q <- p%>%filter(weigh>=start & weigh<end)%>%mutate(labelweight= paste0(type,"_",start))

The code whatever I came up with is throwing "Error: vector memory exhausted (limit reached?)" when dealing with large datasets.

I am thinking if there is any more efficient way of getting the desired output without doing a join.

Body:
Perhaps, you can use fuzzyjoin's here :

fuzzyjoin::fuzzy_left_join(das, mapper,
                   by = c('type' = 'type', 'weigh' = 'start', 'weigh' = 'end'),
                   match_fun = list(`==`, `>=`, `<=`)) %>%
     dplyr::transmute(type = type.x, val, weigh,
                      labelweight = paste(type.y, start, sep = '_'))

#   type val weigh labelweight
#1     A   1    20        A_19
#2     A   2    22        A_19
#3     A   3    23        A_19
#4     A   3    23        A_23
#5     A   4    32        A_27
#6     A   5    34        A_27
#7     A   6    54        A_37
#8     B   7    19        B_17
#9     B   8    22        B_17
#10    B   9    24        B_17
#11    B  10    26        B_25
#12    B  11    31        B_25
#13    B  12    34        B_25
#14    B  13    36        B_25
#15    B  14    37        B_25
#16    B  15    51        B_50
#17    B  16    54        B_50
#18    C  17    31        C_23
#19    C  18    35        C_33
#20    C  19    43        C_39
#21    C  20    45        C_39


问:
typescript for loop over HTMLCollection
I want to iterate over the results of

```<code>document.getElementsByTagName("...");
</code>```

It returns an HTMLCollection, not an array. So I can't simply use forEach.
The following is possible but doesn't look very nice:

```<code>let elements = document.getElementsByTagName("...");
for (var i = 0, m = elements.length; i < m; i++) {
    let element = elements[i];
}
</code>```

For javascript, there exists pretty much the exact same question:
For loop for HTMLCollection elements

And apparently, with the latest updates, modern browsers support:

```<code>var list = document.getElementsByClassName("events");
for (let item of list) {
    log(item.id);
}
</code>```

But the typescript compiler complains:

```<code>error TS2495: Type 'NodeListOf<HTMLParagraphElement>' is not an array type or a string type.
</code>```

It still transpiles to proper Javascript though. It's even aware of what I'm doing here and doesn't just copy over the sourcecode. The compiled output is this:

```<code>var elements = main_div.getElementsByTagName("p");
for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
    var element = elements_1[_i];
}
</code>```

This is great, since the generated code will be supported even on older browsers. But I would like to get rid of the error message.

My compilerOptions are this:

```<code>{
    "compilerOptions": {

        "module": "commonjs",
        "target": "es5",
        "sourceMap": true,
        "rootDir": "src",
        "lib": [
            "es2015",
            "dom"
        ]
    }
}
</code>```

I did try to edit my lib options. This specific feature was a part of ES6 and has been reworked a few times. So I tested the various ecmascript versions in lib but couldn't find a working setup.

答:
Example usage:</p>

```<code>const inputs = document.getElementsByTagName("input");
for (let index = 0; index < inputs.length; index++) {
  const input = inputs.item(index);
}
</code>```

Title: typescript for loop over HTMLCollection

Body:
I want to iterate over the results of

document.getElementsByTagName("...");

It returns an HTMLCollection, not an array. So I can't simply use forEach.
The following is possible but doesn't look very nice:

let elements = document.getElementsByTagName("...");
for (var i = 0, m = elements.length; i < m; i++) {
    let element = elements[i];
}

For javascript, there exists pretty much the exact same question:
For loop for HTMLCollection elements

And apparently, with the latest updates, modern browsers support:

var list = document.getElementsByClassName("events");
for (let item of list) {
    log(item.id);
}

But the typescript compiler complains:

error TS2495: Type 'NodeListOf<HTMLParagraphElement>' is not an array type or a string type.

It still transpiles to proper Javascript though. It's even aware of what I'm doing here and doesn't just copy over the sourcecode. The compiled output is this:

var elements = main_div.getElementsByTagName("p");
for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
    var element = elements_1[_i];
}

This is great, since the generated code will be supported even on older browsers. But I would like to get rid of the error message.

My compilerOptions are this:

{
    "compilerOptions": {

        "module": "commonjs",
        "target": "es5",
        "sourceMap": true,
        "rootDir": "src",
        "lib": [
            "es2015",
            "dom"
        ]
    }
}

I did try to edit my lib options. This specific feature was a part of ES6 and has been reworked a few times. So I tested the various ecmascript versions in lib but couldn't find a working setup.

Body:
Example usage:

const inputs = document.getElementsByTagName("input");
for (let index = 0; index < inputs.length; index++) {
  const input = inputs.item(index);
}


问:
Download from FTP server to client computer
I'm working on ASP.NET project and I need a function where a user downloads a file from FTP server and saved to his/her local machine. The files are in different FTP server and the ASP.NET project is hosted in different server. So to download, I passed the server address and FTP credentials. It works when I runs the project on localhost, but when I upload the project to server and try to download from the hosted site, the files doesn't download and save to my pc. </p>

<p>This my code below </p>

```<code> string inputfilepath = @"C:\Temp\"+_filename;
 string ftphost = "advhost11@14.182.126.8:3131";
 string ftpfilepath = _filename;

 string ftpfullpath = "ftp://" + ftphost +"/"+ ftpfilepath;

 using (WebClient request = new WebClient())
 {
      request.Credentials = new NetworkCredential("username", "password");
      byte[] fileData = request.DownloadData(ftpfullpath);

      Directory.CreateDirectory(Path.GetDirectoryName(inputfilepath));

      using (FileStream file = File.Create(inputfilepath))
      {
           file.Write(fileData, 0, fileData.Length);
           file.Close();
      }

      ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Receipt downloaded and saved at C:\\\\Temp\\\\BankTransfer.');", true);
 }
</code>```

答: After saving the file on your server, return it as a file to your client's browser. You don't mention your framework so here's how to do it on WebForm and MVC. Note that you can't decide where to save the file on their computer, it's their decision whether to save or not and where.</p>

Body:
I'm working on ASP.NET project and I need a function where a user downloads a file from FTP server and saved to his/her local machine. The files are in different FTP server and the ASP.NET project is hosted in different server. So to download, I passed the server address and FTP credentials. It works when I runs the project on localhost, but when I upload the project to server and try to download from the hosted site, the files doesn't download and save to my pc.

This my code below

 string inputfilepath = @"C:\Temp\"+_filename;
 string ftphost = "advhost11@14.182.126.8:3131";
 string ftpfilepath = _filename;

 string ftpfullpath = "ftp://" + ftphost +"/"+ ftpfilepath;

 using (WebClient request = new WebClient())
 {
      request.Credentials = new NetworkCredential("username", "password");
      byte[] fileData = request.DownloadData(ftpfullpath);

      Directory.CreateDirectory(Path.GetDirectoryName(inputfilepath));

      using (FileStream file = File.Create(inputfilepath))
      {
           file.Write(fileData, 0, fileData.Length);
           file.Close();
      }

      ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Receipt downloaded and saved at C:\\\\Temp\\\\BankTransfer.');", true);
 }


问:
pyinstaller issue with path and icons
How do I run my pyinstaller created script if it depends on functions stored in a different file?

I have a file, let's call file.py and in it, it has:

```<code>sys.path.insert(0, 'Functions')
from getDigits import getDigits
</code>```

In my pyinstaller executable script that I create, it runs file.py and file2.py but only file.py uses the import getDigits function.

My error code is: ModuleNotFoundError: No module named 'getDigits' even when I place the getDigits file in the same directory as the executable.

Do I need to use the full path or something and if so, how do I go about accomplishing this?

Also, another question how do I go about using icons for excutable: I used the following but it still doesn't show my executable file with desired icon. I have a folder.ico in the same directory.

pyinstaller --onefile --icon=folder.ico run_files.py

答:
PyInstaller can't see path manipulations. Add each extra path when building with the -p <path> option.

In your case -p path/to/script/directory/Functions.

Title: pyinstaller issue with path and icons

Body:
How do I run my pyinstaller created script if it depends on functions stored in a different file?

I have a file, let's call file.py and in it, it has:

sys.path.insert(0, 'Functions')
from getDigits import getDigits

In my pyinstaller executable script that I create, it runs file.py and file2.py but only file.py uses the import getDigits function.

My error code is: ModuleNotFoundError: No module named 'getDigits' even when I place the getDigits file in the same directory as the executable.

Do I need to use the full path or something and if so, how do I go about accomplishing this?

Also, another question how do I go about using icons for excutable: I used the following but it still doesn't show my executable file with desired icon. I have a folder.ico in the same directory.

pyinstaller --onefile --icon=folder.ico run_files.py


问:
Deep Cache? Changes I make on filezilla are successful but does not appear on my devices?
I have recently changed web host providers, (from 123-reg to SiteGround) and have a HTML website. Now when I make a change via FTP through Filezilla, it says upload successful however I cannot see the change on my computer. The changes are there however, as when I test it via kproxy.com I can see the changes. I have tried clearing my browser cache several times and this has not fixed the issue. The changes can not be seen on my ipad/ phone, and also cannot be seen on another friends laptop and phone either.

Does anyone know what the issue is here? I have been using Filezilla for a couple years now and the changes have always been instant and seen just via a page refresh.
Any help would be greatly appreciated!

答:
Try deleting any extension in your browser that could be hindering it e.g AdBlocker

OR

In your Chrome browser, open developers tools (CTRL + SHIFT + I).

Navigate to Application tab.

Choose Clear storage from the side menu

Hit Clear site data button.


问:
how to extaract data from file starting from 2nd line in c
Im very new to this language, can you help me:

Instead of making the user input col, row, and direction(scanf). I want to extract the data from file(format below)

From the file format i do not want to extract the first line(5,6), i only want to extract the remaining lines.

Below is a code of how to extract data from a file(using command line arguments), but this code extract the first line also, and only prints the lines.I do not want to print the line but to extract the data from a file instead of making the user input it.

File format:
colrow direction(starting from 2nd line)

```<code>5,6
A0 H
D0 V
C1 V
A4 H
F0 v
</code>```

code of scanf

```<code>
yourcolumn = getchar();
col = charToNum(yourcolumn);    //function to input column

printf("enter row");
scanf("%d",&row);

printf("h: horizontally or v: vertically?\n");
scanf(" %c",&direction);
</code>```

Code for extracting data from file:

```<code>#include <stdio.h>

int main(int argc, char* argv[])
{
    char const* const fileName = argv[1]; /* should check that argc > 1 */
    FILE* file = fopen(fileName, "r"); /* should check the result */
    char line[256];

    while (fgets(line, sizeof(line), file)) {
        /* note that fgets don't strip the terminating \n, checking its
           presence would allow to handle lines longer that sizeof(line) */
        printf("%s", line);
    }
    /* may check feof here to make a difference between eof and io failure -- network
       timeout for instance */

    fclose(file);

    return 0;
}

</code>```

答:
Read the first line also with fgets() into a string and then scan the string for row, direction.

```<code>char line[256];
if (fgets(line, sizeof(line), file)) {
  if (sscanf(line, "%d %c", &row, &direction) != 2) {
    printf("Invalid first line '%s'\n", line);
  } else {
    while (fgets(line, sizeof(line), file)) {
      printf("%s", line);
    }
  }
}
</code>```

Body:
Im very new to this language, can you help me:

Instead of making the user input col, row, and direction(scanf). I want to extract the data from file(format below)

From the file format i do not want to extract the first line(5,6), i only want to extract the remaining lines.

Below is a code of how to extract data from a file(using command line arguments), but this code extract the first line also, and only prints the lines.I do not want to print the line but to extract the data from a file instead of making the user input it.

File format:
colrow direction(starting from 2nd line)

5,6
A0 H
D0 V
C1 V
A4 H
F0 v

code of scanf

yourcolumn = getchar();
col = charToNum(yourcolumn);    //function to input column

printf("enter row");
scanf("%d",&row);

printf("h: horizontally or v: vertically?\n");
scanf(" %c",&direction);

Code for extracting data from file:

#include <stdio.h>

int main(int argc, char* argv[])
{
    char const* const fileName = argv[1]; /* should check that argc > 1 */
    FILE* file = fopen(fileName, "r"); /* should check the result */
    char line[256];

    while (fgets(line, sizeof(line), file)) {
        /* note that fgets don't strip the terminating \n, checking its
           presence would allow to handle lines longer that sizeof(line) */
        printf("%s", line);
    }
    /* may check feof here to make a difference between eof and io failure -- network
       timeout for instance */

    fclose(file);

    return 0;
}

Body:
Read the first line also with fgets() into a string and then scan the string for row, direction.

char line[256];
if (fgets(line, sizeof(line), file)) {
  if (sscanf(line, "%d %c", &row, &direction) != 2) {
    printf("Invalid first line '%s'\n", line);
  } else {
    while (fgets(line, sizeof(line), file)) {
      printf("%s", line);
    }
  }
}


问:
deep comparision: how does this code return false when values of 2 objects are not same?
code:

```<code>function deepEqual(a, b) {
 if (a === b) return true;

  //2nd block
 if (a == null || typeof a != "object" ||
     b == null || typeof b != "object") return false;

 let keysA = Object.keys(a), keysB = Object.keys(b);

 if (keysA.length != keysB.length) return false;

for (let key of keysA) {
 if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
 }

return true;
}

 one= {a:1, b:1};
 two = {a:1, b:5};
 console.log(deepEqual(one, two));  //returns false as expected
</code>```

1. can someone please explain what is the purpose of 2nd block? what is it doing?

2. which part deals with returning false when values in both objects are not the same? how is it being done?

答:
```<code>    function deepEqual(a, b) {
     // the line below checks whether two values are the same i.e 2 == 3 returns false;
     if (a === b) return true;

      /** This below if statement just checks to make sure that what is been passed
    is an object . the "typeof" is what checks for it. when you run typeof on null values
  returns objects . so we must also check whether the value is null */

     if (a == null || typeof a != "object" ||
         b == null || typeof b != "object") return false;

    // this puts into an array the object properties
     let keysA = Object.keys(a), keysB = Object.keys(b);

/** checks if the length of the array are the same. if they have the same number of properties the array length will be equal*/
     if (keysA.length != keysB.length) return false;

// this "let keys of keysA" was tricky for me but i figured it out
// it loops through the array and returns the value into the variable let
    for (let key of keysA) {
     /** the first checks whether keysB array includes the properties that key is returning from keyA. i would explain the "!deepEqual(a[key], b[key])" statement in the comments*/
     if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
     }

    return true;
    }

     one= {a:1, b:1};
     two = {a:1, b:5};
     console.log(deepEqual(one, two));  //returns false as expected
</code>```

Now for the recursion statement !deepEqual(a[key], b[key]), remember that !means not . so if deepequal() returns true the if statements will evaluate . the array keysA and keysB just stored the properties of the object, but we need a way to compare the values of that object.
Take for example we have objects benz and tesla

```<code>let benz = {
   color: "black",
   wheels : 4
}
 let tesla = {
   color: "red",
   wheels : 4
}
</code>```

when we call Object.keys(benz) we get an array ["color", "wheels"]

To then find out the values of the object we run the code benz[keys]... keeping strictly with the code.

when the values get called. if the values are both equal returning true. this makes the recursive function to call itself again until the final value is gotten.
i hope for all who read this will get it

Body:
code:

function deepEqual(a, b) {
 if (a === b) return true;

  //2nd block
 if (a == null || typeof a != "object" ||
     b == null || typeof b != "object") return false;

 let keysA = Object.keys(a), keysB = Object.keys(b);

 if (keysA.length != keysB.length) return false;

for (let key of keysA) {
 if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
 }

return true;
}

 one= {a:1, b:1};
 two = {a:1, b:5};
 console.log(deepEqual(one, two));  //returns false as expected

1. can someone please explain what is the purpose of 2nd block? what is it doing?

2. which part deals with returning false when values in both objects are not the same? how is it being done?

Body:
    function deepEqual(a, b) {
     // the line below checks whether two values are the same i.e 2 == 3 returns false;
     if (a === b) return true;

      /** This below if statement just checks to make sure that what is been passed
    is an object . the "typeof" is what checks for it. when you run typeof on null values
  returns objects . so we must also check whether the value is null */

     if (a == null || typeof a != "object" ||
         b == null || typeof b != "object") return false;

    // this puts into an array the object properties
     let keysA = Object.keys(a), keysB = Object.keys(b);

/** checks if the length of the array are the same. if they have the same number of properties the array length will be equal*/
     if (keysA.length != keysB.length) return false;

// this "let keys of keysA" was tricky for me but i figured it out
// it loops through the array and returns the value into the variable let
    for (let key of keysA) {
     /** the first checks whether keysB array includes the properties that key is returning from keyA. i would explain the "!deepEqual(a[key], b[key])" statement in the comments*/
     if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
     }

    return true;
    }

     one= {a:1, b:1};
     two = {a:1, b:5};
     console.log(deepEqual(one, two));  //returns false as expected

Now for the recursion statement !deepEqual(a[key], b[key]), remember that !means not . so if deepequal() returns true the if statements will evaluate . the array keysA and keysB just stored the properties of the object, but we need a way to compare the values of that object.
Take for example we have objects benz and tesla

let benz = {
   color: "black",
   wheels : 4
}
 let tesla = {
   color: "red",
   wheels : 4
}

when we call Object.keys(benz) we get an array ["color", "wheels"]

To then find out the values of the object we run the code benz[keys]... keeping strictly with the code.

when the values get called. if the values are both equal returning true. this makes the recursive function to call itself again until the final value is gotten.
i hope for all who read this will get it


问:
MSAccess - Minimize the Toolbar Ribbon OnLoad()?
I'm looking for a reliable method to minimize the default MSAccess Toolbar Ribbon during the OnLoad() event.

I realize can totally HIDE the toolbar, but that's not exactly what I am looking to do - I just want to minimize the ribbon:

```<code>DoCmd.ShowToolbar "Ribbon", acToolbarNo    'Hides the full toolbar
DoCmd.ShowToolbar "Ribbon", acToolbarYes   'Show
</code>```

I've tried a couple approaches, with mixed success:

In Access 2010 & 2013 (VB7):

```<code>CommandBars.ExecuteMso "MinimizeRibbon"
</code>```

Earlier Versions:

```<code>SendKeys "^{F1}", False
</code>```

Both of these approaches appear to operate as a TOGGLE between sessions.  Is there a method to determine the current state and then apply the appropriate code?

I have users with Access:  2007, 2010, 2013

Thanks for any suggestions!

Mark

答:
```<code>Sub ToggleRibbon(Optional Show)

    If IsMissing(Show) Then
        CommandBars.ExecuteMso "MinimizeRibbon"   'Toggle

    ElseIf Show = True Then
        If CommandBars("ribbon").Height < 100 Then
            CommandBars.ExecuteMso "MinimizeRibbon"
        End If

    ElseIf Show = False Then
        If CommandBars("ribbon").Height > 100 Then
            CommandBars.ExecuteMso "MinimizeRibbon"
        End If

    End If

End Sub
</code>```

Body:
I'm looking for a reliable method to minimize the default MSAccess Toolbar Ribbon during the OnLoad() event.

I realize can totally HIDE the toolbar, but that's not exactly what I am looking to do - I just want to minimize the ribbon:

DoCmd.ShowToolbar "Ribbon", acToolbarNo    'Hides the full toolbar
DoCmd.ShowToolbar "Ribbon", acToolbarYes   'Show

I've tried a couple approaches, with mixed success:

In Access 2010 & 2013 (VB7):

CommandBars.ExecuteMso "MinimizeRibbon"

Earlier Versions:

SendKeys "^{F1}", False

Both of these approaches appear to operate as a TOGGLE between sessions.  Is there a method to determine the current state and then apply the appropriate code?

I have users with Access:  2007, 2010, 2013

Thanks for any suggestions!

Mark


问:
Passing props and mapping data in React
I'm working on a project that requires me to pass data to two functional components.

My axios call to the API seems to work, as well as setting the state with hooks, but I keep receiving these two errors:

Error Cannot convert undefined or null to object I tried checking if the array is empty but that didn't seem to solve the problem

summaryMetrics is not defined - This I don't understand because summartMetrics is defined. Could it be that the elements are being displayed before the data is fetched ?

Here are the files in a codesandbox
Included the API's so people can see the structure of how the JSON is being returned.
Im not sure if I'm passing and mapping the data correctly.

Here are the files in a codesandbox

Any help is very much appreciated

答:
Your issue is that you're not waiting for summaryMetrics to load. It's trying to read the array before it's been fetched.

What I would do, is put the render inside a function and conditionally load it once the data is available.

So your Summary.js file would look like this:

```<code>
  const renderSummaryMetrics = () =>
    summary &&
    summary.summaryMetrics && (
    <div>
      <SummaryMetrics
        uniqueSocialMediaPost={summary.summaryMetrics[0]["uniqueSocialMediaPost"]}
        positiveScore={summary.summaryMetrics[0]["positiveScore"]}
        riskScore={summary.summaryMetrics[0]["riskScore"]}
      />
      {Object.keys(summary.summaryMetrics) &&
      Object.keys(summary.summaryMetrics).length > 0
        ? Object.keys(summary.summaryMetrics).map(keyName => (
            <SummaryByPlatform
              platform={keyName}
              mean_sentiment={summary.summaryMetrics[keyName].mean_sentiment}
              post_count={summary.summaryMetrics[keyName].post_count}
              positive_posts={summary.summaryMetrics[keyName].positive_posts}
              negative_posts={summary.summaryMetrics[keyName].negative_posts}
            />
          ))
        : null}
    </div>);

    return renderSummaryMetrics();

</code>```

Title: Passing props and mapping data in React

Body:
Your issue is that you're not waiting for summaryMetrics to load. It's trying to read the array before it's been fetched.

What I would do, is put the render inside a function and conditionally load it once the data is available.

So your Summary.js file would look like this:

  const renderSummaryMetrics = () =>
    summary &&
    summary.summaryMetrics && (
    <div>
      <SummaryMetrics
        uniqueSocialMediaPost={summary.summaryMetrics[0]["uniqueSocialMediaPost"]}
        positiveScore={summary.summaryMetrics[0]["positiveScore"]}
        riskScore={summary.summaryMetrics[0]["riskScore"]}
      />
      {Object.keys(summary.summaryMetrics) &&
      Object.keys(summary.summaryMetrics).length > 0
        ? Object.keys(summary.summaryMetrics).map(keyName => (
            <SummaryByPlatform
              platform={keyName}
              mean_sentiment={summary.summaryMetrics[keyName].mean_sentiment}
              post_count={summary.summaryMetrics[keyName].post_count}
              positive_posts={summary.summaryMetrics[keyName].positive_posts}
              negative_posts={summary.summaryMetrics[keyName].negative_posts}
            />
          ))
        : null}
    </div>);

    return renderSummaryMetrics();


问:
Deserialize a binary tree breadth-first in Functional Programming
I had an imperative program which deserializes to a Binary Tree from an array. Its a BFS algorithm. I was wondering how to do this in Scala with functional programming concepts.

```<code>class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
  val value: Int = _value
  val left: TreeNode = _left
  val right: TreeNode = _right
}
def createTree(list: Array[Int]): TreeNode = ???
</code>```

For reference this is the imperative version in Javascript. The algorithm is described here. https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-

```<code>class TreeNode {
  constructor(val){
    this.val = val;
    this.left = this.right = null;
  }
}

function makeTree(arr){
  let root = new TreeNode(arr[0]);
  let q = [root];

  let index = 1;
  while(q.length){
    let node = q.splice(0,1)[0];
    if(arr[index] != null){
      node.left = new TreeNode(arr[index]);
      q.push(node.left);
    }
    index++;

    if(arr[index] != null){
      node.right = new TreeNode(arr[index]);
      q.push(node.right);
    }
    index++;
  }
  return root;
}
</code>```

答:
This solution is a bit verbose but uses some functional concepts and defines the data structures thoroughly.

The algorithm you provided works better with mutable nodes. It's possible to have a shorter solution with just one mutable class, but here, there are two versions (one node class with mutable left/right and the other completely immutable).

Case classes automatically provide a lot of useful features such as comparison and friendly print-out

The processValues function tail-recursively performs the tasks equivalent to the makeTree function you provided.

The @tailrec annotation tells the compiler to check that the function is tail recursive.

Pattern matching using the match and case keywords replace checking for null-ness or different subtypes, and the compiler can check for a non-exhaustive match clause.

The App trait allows you to easily make an object (static class) into an entrypoint to run some examples.

import scala.annotation.tailrec

sealed trait TreeNode[T]
sealed trait MutableTreeNode[T]
object MutableTreeNode {
  final case class Empty[T]() extends MutableTreeNode[T]
  case class Branch[T](val value: T) extends MutableTreeNode[T] {
    protected var left: MutableTreeNode[T] = Empty()
    protected var right: MutableTreeNode[T] = Empty()
    def setLeft(newLeft: T): Branch[T] = {
      left = Branch(newLeft)
      left.asInstanceOf[Branch[T]] // shouldn't be necessary but compiler requires it
    }
    def setRight(newRight: T): Branch[T] = {
      right = Branch(newRight)
      right.asInstanceOf[Branch[T]]
    }
    override def toString: String = this.toImmutable().toString

    /* converts given node to immutable version */
    private def toImmutable(node: MutableTreeNode[T]): TreeNode[T] = {
      node match {
        case Empty() => TreeNode.Empty()
        case b@Branch(value) => TreeNode.Branch(value, toImmutable(b.left), toImmutable(b.right))
      }
    }
    def toImmutable():TreeNode[T] = toImmutable(this)
  }

  /**
    * Modifies nodes inside of queue
    */
  @tailrec def processValues[T](values: Seq[Option[T]], queue: Seq[MutableTreeNode.Branch[T]]): Unit = {
    (queue, values) match {
      case (Nil, _) => ()
      case (_, Nil) => ()
      case (qHead :: qTail, Some(vLeft) :: Some(vRight) :: vTail) =>
        processValues(vTail, qTail :+ qHead.setLeft(vLeft) :+ qHead.setRight(vRight))
      case (qHead :: qTail, Some(vLeft) :: None :: vTail) =>
        processValues(vTail, qTail :+ qHead.setLeft(vLeft))
      case (qHead :: qTail, None :: Some(vRight) :: vTail) =>
        processValues(vTail, qTail :+ qHead.setRight(vRight))
      case (qHead :: qTail, None :: None :: vTail) =>
        processValues(vTail, qTail)
    }
  }
}
object TreeNode {
  final case class Empty[T]() extends TreeNode[T]
  final case class Branch[T](value: T, left: TreeNode[T], right: TreeNode[T]) extends TreeNode[T]

  def deserialize[T](values: Seq[Option[T]]): TreeNode[T] = {
    values match {
      case Some(headVal) :: tail =>
        val root: MutableTreeNode.Branch[T] = MutableTreeNode.Branch(headVal)
        MutableTreeNode.processValues(tail, Seq(root))
        root.toImmutable()
      case Nil => Empty()
      case _ => throw new RuntimeException("Invalid argument values")
    }
  }
}

object TreeNodeTest extends App {
  val input = Seq(Some(5), Some(4), Some(7), None, None, Some(2), None)
  val treeNode:TreeNode[Int] = TreeNode.deserialize(input)
  println(treeNode)
}
```

Body:
I had an imperative program which deserializes to a Binary Tree from an array. Its a BFS algorithm. I was wondering how to do this in Scala with functional programming concepts.

class TreeNode(_value: Int = 0, _left: TreeNode = null, _right: TreeNode = null) {
  val value: Int = _value
  val left: TreeNode = _left
  val right: TreeNode = _right
}
def createTree(list: Array[Int]): TreeNode = ???

For reference this is the imperative version in Javascript. The algorithm is described here. https://support.leetcode.com/hc/en-us/articles/360011883654-What-does-1-null-2-3-mean-in-binary-tree-representation-

class TreeNode {
  constructor(val){
    this.val = val;
    this.left = this.right = null;
  }
}

function makeTree(arr){
  let root = new TreeNode(arr[0]);
  let q = [root];

  let index = 1;
  while(q.length){
    let node = q.splice(0,1)[0];
    if(arr[index] != null){
      node.left = new TreeNode(arr[index]);
      q.push(node.left);
    }
    index++;

    if(arr[index] != null){
      node.right = new TreeNode(arr[index]);
      q.push(node.right);
    }
    index++;
  }
  return root;
}


问:
how can get particular day of date when you have start and end date
I have a start date 4/10/2021 and end date 4/12/2021

I want get Tuesday, Thursday and Friday date in jquery

I found this solution:

```<code>var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);

//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var j = 1;
var count = 0;

//getting the all fridays in a financial year
for ( var i = 0; x<y; i += j) {
    if (x.getDay() == 5) {
       $("#append_text").append("Date : " + x.getDate() + "/"
                        + (x.getMonth() + 1) + "<br>");
       x = new Date(x.getTime() + (7 * 24 * 60 * 60 * 1000));
       j = 7;
       count++;
    } else {
       j = 1;
       x = new Date(x.getTime() + (24 * 60 * 60 * 1000));
    }
}
$("#append_text").append("total fridays : " + count + "<br>");
</code>```

but it return only Friday and i think it doesn't work truly

The result is:

```<code>Date : 5/11
Date : 12/11
Date : 19/11
Date : 26/11
Date : 3/12
Date : 10/12
Date : 17/12
Date : 24/12
Date : 31/12
total fridays : 9
</code>```

The solution link is here:
Get Friday Dates of Year in javascript using jquery

do you have any solution for that?

答:
You can do this by iterating over every date between the two dates and saving the ones that fit some criterion, or you can get the first of the required dates, then add 7 days to get each weekly until the end date, e.g.

// Parse date in day/month/year format
function parseDMY(s) {
  let [d, m, y] = s.split(/\D/);
  return new Date(y, m-1, d);
}
// Get next day by dayNumber on or after date, default today
function getDayOfWeek(day, date) {
  let d = date? new Date(+date) :  new Date();
  d.setDate(d.getDate() - d.getDay() + day +
    (day < d.getDay()? 7 : 0));
  return d;
}

// Format date as dd/mm/yyyy
function formatDMY(date) {
  return date.toLocaleString('en-GB', {
    year : 'numeric', // remove if year not required
    month: '2-digit',
    day  : '2-digit'
  });
}

// Given start and end date, get days by day number between
// dates inclusive
function getDaysBetweenDates(d0, d1, ...days){
  let dStart = parseDMY(d0);
  let dEnd   = parseDMY(d1);

  // Guard against endless loop
  if (dEnd < dStart) return;

  let dates = [];
  while (dStart <= dEnd) {
    days.forEach(day => {
      let d = getDayOfWeek(day, dStart);
      if (d <= dEnd) dates.push(formatDMY(d));
    });
    dStart.setDate(dStart.getDate() + 7);
  }
  return dates.sort(
    (a, b) => a.split(/\D/).reverse().join('').localeCompare(
              b.split(/\D/).reverse().join(''))
  );
}

// Get all Tue, Thu and Fri between 4 Oct 2021 and 4 Dec 2021 inclusive
console.log(getDaysBetweenDates('4/10/2021', '4/12/2021', 2, 4, 5));```
</div>
</div>
</p>

<p>I've left the year in the date, it's easily removed by removing <code>year: 'numeric',</code> from the formatting options.</p>

<p>Note that in the OP:</p>

```y.setFullYear(2021, 12, 04);
```

creates a Date for 4 Jan, 2022 not 4 Dec 2021 because months are zero indexed, so December is 11. A month value of 12 rolls over to January of the following year.

Body:
I have a start date 4/10/2021 and end date 4/12/2021

I want get Tuesday, Thursday and Friday date in jquery

I found this solution:

var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);

//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var j = 1;
var count = 0;

//getting the all fridays in a financial year
for ( var i = 0; x<y; i += j) {
    if (x.getDay() == 5) {
       $("#append_text").append("Date : " + x.getDate() + "/"
                        + (x.getMonth() + 1) + "
");
       x = new Date(x.getTime() + (7 * 24 * 60 * 60 * 1000));
       j = 7;
       count++;
    } else {
       j = 1;
       x = new Date(x.getTime() + (24 * 60 * 60 * 1000));
    }
}
$("#append_text").append("total fridays : " + count + "
");

but it return only Friday and i think it doesn't work truly

The result is:

Date : 5/11
Date : 12/11
Date : 19/11
Date : 26/11
Date : 3/12
Date : 10/12
Date : 17/12
Date : 24/12
Date : 31/12
total fridays : 9

The solution link is here:
Get Friday Dates of Year in javascript using jquery

do you have any solution for that?

Body:
You can do this by iterating over every date between the two dates and saving the ones that fit some criterion, or you can get the first of the required dates, then add 7 days to get each weekly until the end date, e.g.

// Parse date in day/month/year format
function parseDMY(s) {
  let [d, m, y] = s.split(/\D/);
  return new Date(y, m-1, d);
}
// Get next day by dayNumber on or after date, default today
function getDayOfWeek(day, date) {
  let d = date? new Date(+date) :  new Date();
  d.setDate(d.getDate() - d.getDay() + day +
    (day < d.getDay()? 7 : 0));
  return d;
}

// Format date as dd/mm/yyyy
function formatDMY(date) {
  return date.toLocaleString('en-GB', {
    year : 'numeric', // remove if year not required
    month: '2-digit',
    day  : '2-digit'
  });
}

// Given start and end date, get days by day number between
// dates inclusive
function getDaysBetweenDates(d0, d1, ...days){
  let dStart = parseDMY(d0);
  let dEnd   = parseDMY(d1);

  // Guard against endless loop
  if (dEnd < dStart) return;

  let dates = [];
  while (dStart <= dEnd) {
    days.forEach(day => {
      let d = getDayOfWeek(day, dStart);
      if (d <= dEnd) dates.push(formatDMY(d));
    });
    dStart.setDate(dStart.getDate() + 7);
  }
  return dates.sort(
    (a, b) => a.split(/\D/).reverse().join('').localeCompare(
              b.split(/\D/).reverse().join(''))
  );
}

// Get all Tue, Thu and Fri between 4 Oct 2021 and 4 Dec 2021 inclusive
console.log(getDaysBetweenDates('4/10/2021', '4/12/2021', 2, 4, 5));

I've left the year in the date, it's easily removed by removing year: 'numeric', from the formatting options.

Note that in the OP:

y.setFullYear(2021, 12, 04);

creates a Date for 4 Jan, 2022 not 4 Dec 2021 because months are zero indexed, so December is 11. A month value of 12 rolls over to January of the following year.


问:
C++ Gapful Numbers Crashing
I was doing this program in which I am supossed to print gapful numbers all the way up to a specific value. The operations are correct, however, for some reason after printing a couple of values the program crashes, what can I do to fix this problem?

Here's my code:

```<code>#include<math.h>
#include<stdlib.h>
using namespace std;

void gapful(int);
bool gapCheck(int);

int main(){
    int n;

    cout<<"Enter a top number: ";
    cin>>n;

    gapful(n);

    system("pause");
    return 0;
}

void gapful(int og){
    for(int i=0; i<=og; i++){
        fflush(stdin);
        if(gapCheck(i)){
            cout<<i<<" ";
        }
    }
}

bool gapCheck(int n){
    int digits=0;
    int n_save,n1,n2,n3;

    if(n<100){
        return false;
    }
    else{
        n_save=n;
        while(n>10){
            n/=10;
            digits++;
        }
        digits++;
        n=n_save;
        n1=n/pow(10, digits);
        n2=n%10;
        n3=n1*10 + n2;
        if(n%n3 == 0){
            return true;
        }
        else{
            return false;
        }
    }
}
</code>```

I'm open to any suggestions and comments, thank you. :)

答: For n == 110, you compute digits == 3. Then n1 == 110 / 1000 == 0, n2 == 110 % 10 == 0, n3 == 0*10 + 0 == 0, and finally n%n3 exhibits undefined behavior by way of division by zero.

Title: C++ Gapful Numbers Crashing

Body:
I was doing this program in which I am supossed to print gapful numbers all the way up to a specific value. The operations are correct, however, for some reason after printing a couple of values the program crashes, what can I do to fix this problem?

Here's my code:

#include<math.h>
#include<stdlib.h>
using namespace std;

void gapful(int);
bool gapCheck(int);

int main(){
    int n;

    cout<<"Enter a top number: ";
    cin>>n;

    gapful(n);

    system("pause");
    return 0;
}

void gapful(int og){
    for(int i=0; i<=og; i++){
        fflush(stdin);
        if(gapCheck(i)){
            cout<<i<<" ";
        }
    }
}

bool gapCheck(int n){
    int digits=0;
    int n_save,n1,n2,n3;

    if(n<100){
        return false;
    }
    else{
        n_save=n;
        while(n>10){
            n/=10;
            digits++;
        }
        digits++;
        n=n_save;
        n1=n/pow(10, digits);
        n2=n%10;
        n3=n1*10 + n2;
        if(n%n3 == 0){
            return true;
        }
        else{
            return false;
        }
    }
}

I'm open to any suggestions and comments, thank you. :)


问:
Optimizing queries for content popularity by hits

I've done some searching for this but haven't come up with anything, maybe someone could point me in the right direction.

I have a website with lots of content in a MySQL database and a PHP script that loads the most popular content by hits. It does this by logging each content hit in a table along with the access time. Then a select query is run to find the most popular content in the past 24 hours, 7 day or maximum 30 days. A cronjob deletes anything older than 30 days in the log table.

The problem I'm facing now is as the website grows the log table has 1m+ hit records and it is really slowing down my select query (10-20s). At first I though the problem was a join I had in the query to get the content title, url, etc. But now I'm not sure as in test removing the join does not speed the query as much as I though it would.

So my question is what is best practise of doing this kind of popularity storing/selecting? Are they any good open source scripts for this? Or what would you suggest?

Table scheme

"popularity" hit log table

  nid | insert_time | tid

  nid: Node ID of the content

  insert_time: timestamp (2011-06-02 04:08:45)

  tid: Term/category ID

"node" content table

  nid | title | status | (there are more but these are the important ones)

  nid: Node ID

  title: content title

  status: is the content published (0=false, 1=true)

SQL

```<code>SELECT node.nid, node.title, COUNT(popularity.nid) AS count
FROM `node` INNER JOIN `popularity` USING (nid)
WHERE node.status = 1
  AND  popularity.insert_time >= DATE_SUB(CURDATE(),INTERVAL 7 DAY)
GROUP BY popularity.nid
ORDER BY count DESC
LIMIT 10;
</code>```

答:
RRDtool

Many tools/systems do not build their own logging and log aggregation but use RRDtool (round-robin database tool) to efficiently handle time-series data. RRDtools also comes with powerful graphing subsystem, and (according to Wikipedia) there are bindings for PHP and other languages.

From your questions I assume you don't need any special and fancy analysis and RRDtool would efficiently do what you need without you having to implement and tune your own system.

Body:
I've done some searching for this but haven't come up with anything, maybe someone could point me in the right direction.

I have a website with lots of content in a MySQL database and a PHP script that loads the most popular content by hits. It does this by logging each content hit in a table along with the access time. Then a select query is run to find the most popular content in the past 24 hours, 7 day or maximum 30 days. A cronjob deletes anything older than 30 days in the log table.

The problem I'm facing now is as the website grows the log table has 1m+ hit records and it is really slowing down my select query (10-20s). At first I though the problem was a join I had in the query to get the content title, url, etc. But now I'm not sure as in test removing the join does not speed the query as much as I though it would.

So my question is what is best practise of doing this kind of popularity storing/selecting? Are they any good open source scripts for this? Or what would you suggest?

Table scheme

"popularity" hit log table

  nid | insert_time | tid

  nid: Node ID of the content

  insert_time: timestamp (2011-06-02 04:08:45)

  tid: Term/category ID

"node" content table

  nid | title | status | (there are more but these are the important ones)

  nid: Node ID

  title: content title

  status: is the content published (0=false, 1=true)

SQL

SELECT node.nid, node.title, COUNT(popularity.nid) AS count
FROM `node` INNER JOIN `popularity` USING (nid)
WHERE node.status = 1
  AND  popularity.insert_time >= DATE_SUB(CURDATE(),INTERVAL 7 DAY)
GROUP BY popularity.nid
ORDER BY count DESC
LIMIT 10;


问:
Recurrence Analysis (Time complexity)
im writing a boolean function that calculate if two binary trees are identical.
Lets see the program:

```<code>boolean func(Node head1 , Node head2){
if(head1 == null || head2 == null) return head1 == null && head2 == null;
return func(head1.left , head2.left) && (head1.right,head2.right);
}
</code>```

i know that in the worst case the program check n element so its O(n).
and i want to describe this recurrence function in T(n).
i dont know were to start becuse i dont know what is the value of the stopping point ,
i think that the function is T(n,m) = 2*t(n-1,m-1) + n + m.

答:
Let n be the number of nodes in the binary trees. If the binary trees have different number of nodes, then n is smaller of the two sizes (since you'll stop comparing once you reach the end of one tree).

On each call you are doing some comparisons between the nodes of the tree. This will be in constant time, so you can call this time spent d which represents some arbitrary constant.

Lastly, you're making 2 recursive calls for the current node's 2 children. Note that in the worst case, each of the children are the root of a subtree that holds half the total number of nodes in the tree. In other words if you have a tree with n nodes, and you are looking at the root node, then each child of the root has about n/2 nodes below it (and including it).

So your recurrence is as follows:

T(n) = 2*T((n-1)/2) + d

You can simplify this to:

T(n) = 2*T(n/2) + d

Title: Recurrence Analysis (Time complexity)

Body:
im writing a boolean function that calculate if two binary trees are identical.
Lets see the program:

boolean func(Node head1 , Node head2){
if(head1 == null || head2 == null) return head1 == null && head2 == null;
return func(head1.left , head2.left) && (head1.right,head2.right);
}

i know that in the worst case the program check n element so its O(n).
and i want to describe this recurrence function in T(n).
i dont know were to start becuse i dont know what is the value of the stopping point ,
i think that the function is T(n,m) = 2*t(n-1,m-1) + n + m.


问:
Android: How to start and stop a loop that fires on a timer?
I have two buttons in my GUI. "ONE TURN" and "AUTO PLAY". I want the AUTO PLAY button to start automatically pressing the ONE TURN button on a timer, whose speed I will eventually control with a slider or something. However, I want it so that when I press the AUTO PLAY button again it stops automatically activating the first button. The auto play works, but stopping the auto play does not work, and I don't know how to stop it. Maybe I'm using the wrong solution entirely, or maybe I just don't know how to properly stop the runnable? Any assistance would be greatly appreciated, I have done a lot of searching and haven't found anything too useful. My AUTO PLAY on click code is below:

```<code>public void autoClick(final View view) {
    final Handler handler = new Handler();

    isAutoPlaying = !isAutoPlaying;

    final View dummyView = view;
    Runnable runnable = null;

    if(isFirstAutoPlayClick) {
        runnable = new Runnable() {
            @Override
            public void run() {
                onClick(dummyView);
                handler.postDelayed(this, 1000);

            }
        };
        isFirstAutoPlayClick = !isFirstAutoPlayClick;
    }

    if(isAutoPlaying) {
        Toast.makeText(MainActivity.this,"isAutoPlaying is true", Toast.LENGTH_SHORT).show();
        handler.post(runnable);
    } else {
        Toast.makeText(MainActivity.this,"isAutoPlaying is false", Toast.LENGTH_SHORT).show();
        handler.removeCallbacks(null);
    }
}
</code>```

Here is a picture of the
GUI

Thank you for your time in advance.

答:
Try changing handler.removeCallbacks(null) to handler.removeCallbacksAndMessages(null) see if it's working for you

EDIT
You need to move your handler local variable to class field too.

```<code>public class Activity{
    Handler handler = new Handler(); //<-- Put it here
    public void autoClick(final View view) {
         final Handler handler = new Handler(); //<-- Remove this
         ...
    }
}
</code>```

So that when calling handler.removeCallbacksAndMessages() you are referring to that initial handler instead of a new instance

Body:
I have two buttons in my GUI. "ONE TURN" and "AUTO PLAY". I want the AUTO PLAY button to start automatically pressing the ONE TURN button on a timer, whose speed I will eventually control with a slider or something. However, I want it so that when I press the AUTO PLAY button again it stops automatically activating the first button. The auto play works, but stopping the auto play does not work, and I don't know how to stop it. Maybe I'm using the wrong solution entirely, or maybe I just don't know how to properly stop the runnable? Any assistance would be greatly appreciated, I have done a lot of searching and haven't found anything too useful. My AUTO PLAY on click code is below:

public void autoClick(final View view) {
    final Handler handler = new Handler();

    isAutoPlaying = !isAutoPlaying;

    final View dummyView = view;
    Runnable runnable = null;

    if(isFirstAutoPlayClick) {
        runnable = new Runnable() {
            @Override
            public void run() {
                onClick(dummyView);
                handler.postDelayed(this, 1000);

            }
        };
        isFirstAutoPlayClick = !isFirstAutoPlayClick;
    }

    if(isAutoPlaying) {
        Toast.makeText(MainActivity.this,"isAutoPlaying is true", Toast.LENGTH_SHORT).show();
        handler.post(runnable);
    } else {
        Toast.makeText(MainActivity.this,"isAutoPlaying is false", Toast.LENGTH_SHORT).show();
        handler.removeCallbacks(null);
    }
}

Here is a picture of the
GUI

Thank you for your time in advance.

Body:
Try changing handler.removeCallbacks(null) to handler.removeCallbacksAndMessages(null) see if it's working for you

EDIT
You need to move your handler local variable to class field too.

public class Activity{
    Handler handler = new Handler(); //<-- Put it here
    public void autoClick(final View view) {
         final Handler handler = new Handler(); //<-- Remove this
         ...
    }
}

So that when calling handler.removeCallbacksAndMessages() you are referring to that initial handler instead of a new instance


答:
There are several problems:

summaryMetrics is indeed not defined. It was actually defined as summary.summaryMetrics.

summary.summaryMetrics[0][...] will cause another "undefined error", because it was defined with default value of null.

Explanation for Problem 1:

No further explanation needed.

Explanation for Problem 2:

useEffect in React functional component will only be run after the component is being rendered.

This means that when you execute summary.summaryMetrics[0][...], summary.summaryMetrics is actually null because you defined it as the default value. Therefore, the steps behind will generate another error because null[0] is not possible.

What you need to do is to check whether each object properties down the tree is actually a valid object before you call the property. Otherwise, the error will happen down the property tree.

I can't show you how to correct your code, because I would need to change a big part of you code. What you can try is to mainly check the presence of values of summary.summaryMetrics first, before calling it's children properties.

Title: Passing props and mapping data in React

Body:
I'm working on a project that requires me to pass data to two functional components.

My axios call to the API seems to work, as well as setting the state with hooks, but I keep receiving these two errors:

Error Cannot convert undefined or null to object I tried checking if the array is empty but that didn't seem to solve the problem

summaryMetrics is not defined - This I don't understand because summartMetrics is defined. Could it be that the elements are being displayed before the data is fetched ?

Here are the files in a codesandbox
Included the API's so people can see the structure of how the JSON is being returned.
Im not sure if I'm passing and mapping the data correctly.

Here are the files in a codesandbox

Any help is very much appreciated


问:
Python, ValueError: x and y must have same first dimension issue
Im trying to read in a CSV file and plot that but when i try and plot the y variable it says there are only two elements to that variable when there should in fact be 6, the code is as followed:

```<code>import numpy as np
import csv

x = np.array([1,2,3,4,5,6])
y1=[]
y2=[]

with open('file.csv', 'r') as csvfile:
plots= csv.reader(csvfile, delimiter=',')
for row in plots:
    y1.append(int(row[1]))
print(len(y1))

with open('file.csv', 'r') as csvfile:
plots= csv.reader(csvfile, delimiter=',')
for row in plots:
    y2.append(int(row[2]))
print(len(y2))
</code>```

This produces 2,2 which is the issue, it should be producing 6,6 as there are 6 elements to both? the CSV file is set in the following format:
Dishwasher,1,1,1,1,1,1

Washing Machine,1,1,0,1,1,0

答:
It produces 2,2 because there are 2 rows in plots. Essentially you are storing the second column in y1 and the third column in y2.

If that is what you want then your code is fine, if you want to measure row lengths instead you could use this code:

```<code>import csv

with open('file.csv', 'r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    rows = [row for row in plots]
    print(len(rows[0]) - 1)  # -1 to exclude title
    print(len(rows[1]) - 1)
</code>```

Body:
Im trying to read in a CSV file and plot that but when i try and plot the y variable it says there are only two elements to that variable when there should in fact be 6, the code is as followed:

import numpy as np
import csv

x = np.array([1,2,3,4,5,6])
y1=[]
y2=[]

with open('file.csv', 'r') as csvfile:
plots= csv.reader(csvfile, delimiter=',')
for row in plots:
    y1.append(int(row[1]))
print(len(y1))

with open('file.csv', 'r') as csvfile:
plots= csv.reader(csvfile, delimiter=',')
for row in plots:
    y2.append(int(row[2]))
print(len(y2))

This produces 2,2 which is the issue, it should be producing 6,6 as there are 6 elements to both? the CSV file is set in the following format:
Dishwasher,1,1,1,1,1,1

Washing Machine,1,1,0,1,1,0

Body:
It produces 2,2 because there are 2 rows in plots. Essentially you are storing the second column in y1 and the third column in y2.

If that is what you want then your code is fine, if you want to measure row lengths instead you could use this code:

import csv

with open('file.csv', 'r') as csvfile:
    plots = csv.reader(csvfile, delimiter=',')
    rows = [row for row in plots]
    print(len(rows[0]) - 1)  # -1 to exclude title
    print(len(rows[1]) - 1)


问:
Best and shortest way to evaluate mathematical expressions
There are many algorithms to evaluate expressions, for example:

By Recursive Descent

Shunting-yard algorithm

Reverse Polish notation

Is there any way to evaluate any mathematical expression using C# .net reflection or other modern .net technology?

答:
You can use Math-Expression-Evaluator library which implements Shunting Yard algorithm that I am author of. It supports simple expressions such as 2.5+5.9, 17.89-2.47+7.16, 5/2/2+1.5*3+4.58, expressions with parentheses (((9-6/2)*2-4)/2-6-1)/(2+24/(2+4)) and expressions with variables:

```<code>var a = 6;
var b = 4.32m;
var c = 24.15m;
var engine = new ExpressionEvaluator();
engine.Evaluate("(((9-a/2)*2-b)/2-a-1)/(2+c/(2+4))", new { a, b, c});
</code>```

You can also pass parameters as named variables:

```<code>dynamic dynamicEngine = new ExpressionEvaluator();

var a = 6;
var b = 4.5m;
var c = 2.6m;

dynamicEngine.Evaluate("(c+b)*a", a: 6, b: 4.5, c: 2.6);
</code>```

It supports .Net Standard 2.0 so can be used from .Net Core as well as .Net Full Framework projects and it doesn't have any external dependencies.

Body:
You can use Math-Expression-Evaluator library which implements Shunting Yard algorithm that I am author of. It supports simple expressions such as 2.5+5.9, 17.89-2.47+7.16, 5/2/2+1.5*3+4.58, expressions with parentheses (((9-6/2)*2-4)/2-6-1)/(2+24/(2+4)) and expressions with variables:

var a = 6;
var b = 4.32m;
var c = 24.15m;
var engine = new ExpressionEvaluator();
engine.Evaluate("(((9-a/2)*2-b)/2-a-1)/(2+c/(2+4))", new { a, b, c});

You can also pass parameters as named variables:

dynamic dynamicEngine = new ExpressionEvaluator();

var a = 6;
var b = 4.5m;
var c = 2.6m;

dynamicEngine.Evaluate("(c+b)*a", a: 6, b: 4.5, c: 2.6);

It supports .Net Standard 2.0 so can be used from .Net Core as well as .Net Full Framework projects and it doesn't have any external dependencies.