问:
How to convert a localized timestamp to UTC using Python?
I need to convert a "localized" timestamp in an arbitrary timezone to a unix timestamp (in UTC).

>>> import pytz

# This represents 2019-09-11T16:14:00 (US/Central) or 2019-09-11T21:14:00 UTC!
>>> local_timestamp = 1568218440

>>> tz = pytz.timezone("US/Central")

>>> my_unix_timestamp = unix_timestamp(local_timestamp, tz)

>>> print(my_unix_timestamp)
1568236440 # 2019-09-11T21:14:00
```

I know this has been asked many times before, but I was getting hung up on the initial conversion of the timestamp from an arbitrary timezone, because you must explicitly set the tz when you construct your initial datetime object (as noted in my answer).

答:
As noted in the pytz documentation, the standard Python datetime.replace() method does not properly account for daylight-savings time. You should use pytz's timezone.localize() method.

The other gotcha is that you must explicitly define the tz info when creating a datetime object from the input timestamp. Otherwise, it is assumed that your timestamp is in local (system) time. As noted in the datetime documentation, you should avoid datetime.utcfromtimestamp() for this reason.

So:

from datetime import datetime, timezone

def unix_timestamp(local_timestamp, local_timezone):
    """turn the input timestamp into a UTC `datetime` object, even though
    the timestamp is not in UTC time, we must do this to construct a datetime
    object with the proper date/time values"""
    dt_fake_utc = datetime.fromtimestamp(local_timestamp, tz=timezone.utc)

    """remove the (incorrect) timezone info that we supplied """
    dt_naive = dt_fake_utc.replace(tzinfo=None)

    """localize the datetime object to our `timezone`. You cannot use
    datetime.replace() here, because it does not account for daylight savings
    time"""
    dt_local = local_timezone.localize(dt_naive)

    """Convert our datetime object back to a timestamp"""
    return int(dt_local.timestamp())
```

Body:
I need to convert a "localized" timestamp in an arbitrary timezone to a unix timestamp (in UTC).

>>> import pytz

# This represents 2019-09-11T16:14:00 (US/Central) or 2019-09-11T21:14:00 UTC!
>>> local_timestamp = 1568218440

>>> tz = pytz.timezone("US/Central")

>>> my_unix_timestamp = unix_timestamp(local_timestamp, tz)

>>> print(my_unix_timestamp)
1568236440 # 2019-09-11T21:14:00

I know this has been asked many times before, but I was getting hung up on the initial conversion of the timestamp from an arbitrary timezone, because you must explicitly set the tz when you construct your initial datetime object (as noted in my answer).


来源: stackexchange

问:
React Native - Drawer Navigation Gesture Start point
I'm using React native drawer navigation, when you swipe out from the left or right - it opens the drawer.

Does anyone know a way of changing the gesture start point, so that it starts slightly further into the screen?

My users are finding on curved screens it doesn't always drag out and feels un-natural to use.

I've looked through the documentation and couldn't find anything there.

Thank you!

答:
Use edgeWidth props in react-navigation drawer.

edgeWidth-
Allows for defining how far from the edge of the content view the swipe gesture should activate.

For more details https://reactnavigation.org/docs/drawer-navigator/#edgewidth

ContentLicense: CC BY-SA 4.0


问:
gunicorn with gaiohttp worker always returning 404 with flask app
I am running a flask app using gunicorn behind nginx proxy and am trying to get the gaiohttp worker to work. The app just returns 404 for all URLS when the gaiohttp worker is selected

When using the sync or gevent workers everything works fine. Also not running directly to gunicorn and gaiohttp i.e. not using nginx it works fine.

I have read everything I can find.

Am I missing something? Is gaiohttp worker valid when running behind a nginx proxy?

My nginx config:

```<code>location /app {
    proxy_pass http://127.0.0.1:9002;
    rewrite    /app(.*) /$1  break;
    proxy_redirect     off;
    proxy_buffering on;
    proxy_pass_header Server;
    proxy_set_header X-Scheme $scheme;
    proxy_set_header   Host             $host;
    proxy_set_header   X-Real-IP        $remote_addr;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Host $server_name;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Script-Name /app;
    }
</code>```

gunicorn:

```<code>/usr/bin/gunicorn --workers 2 -k gaiohttp -b 127.0.0.1:9002 app:app
</code>```

Using the latest versions of gunicorn etc etc.

答:
Another solution is to Add a prefix to all Flask routes.

Sub-mounted inside of another WSGI container

Assuming that you are going to run this application inside of a WSGI container (mod_wsgi, uwsgi, gunicorn, etc); you need to actually mount, at that prefix the application as a sub-part of that WSGI container (anything that speaks WSGI will do) and to set your APPLICATION_ROOT config value to your prefix:

```<code>app.config["APPLICATION_ROOT"] = "/app"

@app.route("/")
def index():
    return "The URL for this page is {}".format(url_for("index"))

# Will return "The URL for this page is /app"
</code>```

Setting the APPLICATION_ROOT config value simply limit Flask's session cookie to that URL prefix.  Everything else will be automatically handled for you by Flask and Werkzeug's excellent WSGI handling capabilities.

An example of properly sub-mounting your app

If you are not sure what the first paragraph means, take a look at this example application with Flask mounted inside of it:

```<code>from flask import Flask, url_for
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware

app = Flask(__name__)
app.config['APPLICATION_ROOT'] = '/app'

@app.route('/')
def index():
    return 'The URL for this page is {}'.format(url_for('index'))

def simple(env, resp):
    resp(b'200 OK', [(b'Content-Type', b'text/plain')])
    return [b'Hello WSGI World']

app.wsgi_app = DispatcherMiddleware(simple, {'/app': app.wsgi_app})

if __name__ == '__main__':
    app.run('localhost', 5000)
</code>```

Proxying requests to the app

If, on the other hand, you will be running your Flask application at the root of its WSGI container and proxying requests to it (for example, if it's being FastCGI'd to, or if nginx is proxy_pass-ing requests for a sub-endpoint to your stand-alone uwsgi / gevent server then you can either:

Use a Blueprint, as Miguel points out in his answer.

or use the DispatcherMiddleware from werkzeug (or the PrefixMiddleware from su27's answer) to sub-mount your application in the stand-alone WSGI server you're using.  (See An example of properly sub-mounting your app above for the code to use).

ContentLicense: CC BY-SA 3.0

Body:
I am running a flask app using gunicorn behind nginx proxy and am trying to get the gaiohttp worker to work. The app just returns 404 for all URLS when the gaiohttp worker is selected

When using the sync or gevent workers everything works fine. Also not running directly to gunicorn and gaiohttp i.e. not using nginx it works fine.

I have read everything I can find.

Am I missing something? Is gaiohttp worker valid when running behind a nginx proxy?

My nginx config:

location /app {
    proxy_pass http://127.0.0.1:9002;
    rewrite    /app(.*) /$1  break;
    proxy_redirect     off;
    proxy_buffering on;
    proxy_pass_header Server;
    proxy_set_header X-Scheme $scheme;
    proxy_set_header   Host             $host;
    proxy_set_header   X-Real-IP        $remote_addr;
    proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Host $server_name;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Script-Name /app;
    }

gunicorn:

/usr/bin/gunicorn --workers 2 -k gaiohttp -b 127.0.0.1:9002 app:app

Using the latest versions of gunicorn etc etc.

Body:
Another solution is to Add a prefix to all Flask routes.

Sub-mounted inside of another WSGI container

Assuming that you are going to run this application inside of a WSGI container (mod_wsgi, uwsgi, gunicorn, etc); you need to actually mount, at that prefix the application as a sub-part of that WSGI container (anything that speaks WSGI will do) and to set your APPLICATION_ROOT config value to your prefix:

app.config["APPLICATION_ROOT"] = "/app"

@app.route("/")
def index():
    return "The URL for this page is {}".format(url_for("index"))

# Will return "The URL for this page is /app"

Setting the APPLICATION_ROOT config value simply limit Flask's session cookie to that URL prefix.  Everything else will be automatically handled for you by Flask and Werkzeug's excellent WSGI handling capabilities.

An example of properly sub-mounting your app

If you are not sure what the first paragraph means, take a look at this example application with Flask mounted inside of it:

from flask import Flask, url_for
from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware

app = Flask(__name__)
app.config['APPLICATION_ROOT'] = '/app'

@app.route('/')
def index():
    return 'The URL for this page is {}'.format(url_for('index'))

def simple(env, resp):
    resp(b'200 OK', [(b'Content-Type', b'text/plain')])
    return [b'Hello WSGI World']

app.wsgi_app = DispatcherMiddleware(simple, {'/app': app.wsgi_app})

if __name__ == '__main__':
    app.run('localhost', 5000)

Proxying requests to the app

If, on the other hand, you will be running your Flask application at the root of its WSGI container and proxying requests to it (for example, if it's being FastCGI'd to, or if nginx is proxy_pass-ing requests for a sub-endpoint to your stand-alone uwsgi / gevent server then you can either:

Use a Blueprint, as Miguel points out in his answer.

or use the DispatcherMiddleware from werkzeug (or the PrefixMiddleware from su27's answer) to sub-mount your application in the stand-alone WSGI server you're using.  (See An example of properly sub-mounting your app above for the code to use).


问:
How to inject React Component inside WebView (react-native-webview)?
Is there a way to pass in a web React component to WebView directly? Something like this-</p>

```<code>import ReactContainer from 'somewhere';
import { WebView } from "react-native-webview";

<WebView
        source={{ html: "<ReactContainer/>" }}
></WebView>
</code>```

Body:
Is there a way to pass in a web React component to WebView directly? Something like this-

import ReactContainer from 'somewhere';
import { WebView } from "react-native-webview";

<WebView
        source={{ html: "<ReactContainer/>" }}
></WebView>

Body:
No, there is not. React.js and React native shares the same syntax but are really different framework: they follow different rules and are build in a different way.
Inside a webview, there is no react framework avaiable or runtime (unless you import React.js as a <script> tag as a website would).

However, as some other answer pointed, you can use renderToString() and it will work in some situations (it just precompile your component, it does not provide exactly what you want) - it's more a hack than a solution.


问:
Delete part of the string to the character encountered javascript
I would need to write a js function that would do this to me:

```<code>export const LOGIN_REQUEST = 'app/LoginPage/LOGIN_REQUEST';
</code>```

Normally it will be:

```<code>console.log(LOGIN_REQUEST); // app/LoginPage/LOGIN_REQUEST
</code>```

And I would need:

```<code>app/LoginPage/LOGIN
</code>```

I would like to cut the string to the first one I encountered _. How to do it using js?

答:
LOGIN_REQUEST.split('_')[0]

Splits LOGIN_REQUEST into an array of strings, divided by _, and returns the first element of the Array. So, everything up to the first _.

More fully:

```<code>const LOGIN_REQUEST = 'app/LoginPage/LOGIN_REQUEST';

console.log(LOGIN_REQUEST.split(`_`)) // ['app/LoginPage/LOGIN', 'REQUEST']

console.log(LOGIN_REQUEST.split(`_`)[0]) // 'app/LoginPage/LOGIN'
</code>```

Body:
I would need to write a js function that would do this to me:

export const LOGIN_REQUEST = 'app/LoginPage/LOGIN_REQUEST';

Normally it will be:

console.log(LOGIN_REQUEST); // app/LoginPage/LOGIN_REQUEST

And I would need:

app/LoginPage/LOGIN

I would like to cut the string to the first one I encountered _. How to do it using js?

Body:
LOGIN_REQUEST.split('_')[0]

Splits LOGIN_REQUEST into an array of strings, divided by _, and returns the first element of the Array. So, everything up to the first _.

More fully:

const LOGIN_REQUEST = 'app/LoginPage/LOGIN_REQUEST';

console.log(LOGIN_REQUEST.split(`_`)) // ['app/LoginPage/LOGIN', 'REQUEST']

console.log(LOGIN_REQUEST.split(`_`)[0]) // 'app/LoginPage/LOGIN'


答:
You get the index of this character using indexOf method, and then take the substring before its first occurrence using the substring method as follows:

let LOGIN_REQUEST = 'app/LoginPage/LOGIN_REQUEST';
let i = LOGIN_REQUEST.indexOf('_');
let str = (i==-1) ? LOGIN_REQUEST : LOGIN_REQUEST.substring(0,i);
console.log(str);```

Title: Delete part of the string to the character encountered javascript


问:
Installing pygrib Package
Apologies in advance for what is probably a bad/poorly phrased question, but I merely dabble in programming and am very unfamiliar with under the hood aspects of package installation, etc.

Basically, I am trying to install the pygrib package (available here: https://github.com/jswhit/pygrib) via a cygwin terminal.

I am running Python 2.7.3 32-bit on Windows 10.

Originally I encountered the missing vcvarsall.bat error the first time I tried to run 'python seteup.py build' and followed the advice here: error: Unable to find vcvarsall.bat

After installing the MS Visual Studio package, I have made it past that error and to another I do not understand with the following output:

```<code>$ python setup.py build
reading from setup.cfg...running build
running build_py
running build_ext
skipping 'pygrib.c' Cython extension (up-to-date)
building 'pygrib' extension

C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Users\Matthew\Anaconda2\lib\site-packages\numpy\core\include -I/usr/local\include -I/usr/local\include -I/usr/local\include/jasper -I/usr/local\include -I/usr\include -I/usr\include -Ig2clib_src -IC:\Users\Matthew\Anaconda2\include -IC:\Users\Matthew\Anaconda2\PC /Tcpygrib.c /Fobuild\temp.win32-2.7\Release\pygrib.obj
pygrib.c
c:\users\matthew\anaconda2\lib\site-packages\numpy\core\include\numpy\npy_1_7_deprecated_api.h(12) : Warning Msg: Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
pygrib.c(242) : fatal error C1083: Cannot open include file: 'grib_api.h': No such file or directory
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\BIN\\cl.exe' failed with exit status 2
</code>```

Obviously it's still looking for some other files, or needs other environment variables defined, but I'm at a loss as to how to proceed and I'm far from an expert when it comes to any of this.

I'd also be glad to try something completely different if you have a better way to go about this process entirely.

I have tried pip and the conda installer, but have not had any luck with them either.

Thank you in advance for anything you can offer.

答:
To use: pip install pygrib

you need to install python3-grib:

sudo apt install python3-grib

NOTE:

Ubuntu Linux:

python3-grib requires libeccodes-dev

if later you install libgrib-api-dev it requires libgrib-api-dev.

which is not compatable with libgrib-api-dev

Meaning, if you install libgrib-api-dev after you install python3-grib you break the python3-grib installation.

Title: Installing pygrib Package

Body:
Apologies in advance for what is probably a bad/poorly phrased question, but I merely dabble in programming and am very unfamiliar with under the hood aspects of package installation, etc.

Basically, I am trying to install the pygrib package (available here: https://github.com/jswhit/pygrib) via a cygwin terminal.

I am running Python 2.7.3 32-bit on Windows 10.

Originally I encountered the missing vcvarsall.bat error the first time I tried to run 'python seteup.py build' and followed the advice here: error: Unable to find vcvarsall.bat

After installing the MS Visual Studio package, I have made it past that error and to another I do not understand with the following output:

$ python setup.py build
reading from setup.cfg...running build
running build_py
running build_ext
skipping 'pygrib.c' Cython extension (up-to-date)
building 'pygrib' extension

C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG -IC:\Users\Matthew\Anaconda2\lib\site-packages\numpy\core\include -I/usr/local\include -I/usr/local\include -I/usr/local\include/jasper -I/usr/local\include -I/usr\include -I/usr\include -Ig2clib_src -IC:\Users\Matthew\Anaconda2\include -IC:\Users\Matthew\Anaconda2\PC /Tcpygrib.c /Fobuild\temp.win32-2.7\Release\pygrib.obj
pygrib.c
c:\users\matthew\anaconda2\lib\site-packages\numpy\core\include\numpy\npy_1_7_deprecated_api.h(12) : Warning Msg: Using deprecated NumPy API, disable it by #defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
pygrib.c(242) : fatal error C1083: Cannot open include file: 'grib_api.h': No such file or directory
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio 9.0\\VC\\BIN\\cl.exe' failed with exit status 2

Obviously it's still looking for some other files, or needs other environment variables defined, but I'm at a loss as to how to proceed and I'm far from an expert when it comes to any of this.

I'd also be glad to try something completely different if you have a better way to go about this process entirely.

I have tried pip and the conda installer, but have not had any luck with them either.

Thank you in advance for anything you can offer.


问:
Limit size of Queue<T> in .NET?
I have a Queue<T> object that I have initialised to a capacity of 2, but obviously that is just the capacity and it keeps expanding as I add items.  Is there already an object that automatically dequeues an item when the limit is reached, or is the best solution to create my own inherited class?</p>

答:
You can use a LinkedList<T> and add thread safety:

```<code>public class Buffer<T> : LinkedList<T>
{
    private int capacity;

    public Buffer(int capacity)
    {
        this.capacity = capacity;
    }

    public void Enqueue(T item)
    {
        // todo: add synchronization mechanism
        if (Count == capacity) RemoveLast();
        AddFirst(item);
    }

    public T Dequeue()
    {
        // todo: add synchronization mechanism
        var last = Last.Value;
        RemoveLast();
        return last;
    }
}
</code>```

One thing to note is the default enumeration order will be LIFO in this example. But that can be overridden if necessary.

ContentLicense: CC BY-SA 2.5

Title: Limit size of Queue<T> in .NET?

Body:
You can use a LinkedList<T> and add thread safety:

public class Buffer<T> : LinkedList<T>
{
    private int capacity;

    public Buffer(int capacity)
    {
        this.capacity = capacity;
    }

    public void Enqueue(T item)
    {
        // todo: add synchronization mechanism
        if (Count == capacity) RemoveLast();
        AddFirst(item);
    }

    public T Dequeue()
    {
        // todo: add synchronization mechanism
        var last = Last.Value;
        RemoveLast();
        return last;
    }
}

One thing to note is the default enumeration order will be LIFO in this example. But that can be overridden if necessary.


问:
C++ does not use the desired constructor
So there seems to be some problem with the solution to Problem 9-2 in the book "Object-Oriented Programming in C++, 4th edition" by Robert Lafore. So the problem is that if I would like to create a Pstring object with a statement like Pstring = "This is a string", the Pstring constructor will only call the constructor with no arguments in the String class, instead of the second one with uses one char[] argument. Does anyone know what causes this kind of problem, and a fix to this? Thanks!

```<code>#include <iostream>
#include <cstring>
using namespace std;
////////////////////////////////////////////////////////////////
class String                      //base class
{
protected:                     //Note: can't be private
    enum {
        SZ = 80
    };           //size of all String objects
    char str[SZ];               //holds a C-string
public:
    String()                    //constructor 0, no args
    {
        str[0] = '\0';
    }
    String(char s[])          //constructor 1, one arg
            {
        strcpy(str, s);
    }      //  convert string to String
    void display() const        //display the String
    {
        cout << str;
    }
    operator char*()            //conversion function
    {
        return str;
    }          //convert String to C-string
};
////////////////////////////////////////////////////////////////
class Pstring: public String     //derived class
{
public:
    Pstring(char s[]);        //constructor
};
//--------------------------------------------------------------
Pstring::Pstring(char s[])      //constructor for Pstring
        {
    if (strlen(s) > SZ - 1)           //if too long,
            {
        for (int j = 0; j < SZ - 1; j++) {  //copy the first SZ-1
            str[j] = s[j];           //characters "by hand"
            str[j] = '\0';
        }           //add the null character
    } else
        //not too long,
        String(s);                  //so construct normally
}
////////////////////////////////////////////////////////////////
int main() {                                        //define String
    String s1 = "This is a string"; // This works great
    s1.display();
    Pstring s2 = "This is a string"; // *** Here, nothing will be assigned to s2****
    s2.display();                    // *** Nothing will be printed here***
    return 0;
}
</code>```

答:
In this conversion constructor

```<code>Pstring::Pstring(char s[])      //constructor for Pstring
        {
    if (strlen(s) > SZ - 1)           //if too long,
            {
        for (int j = 0; j < SZ - 1; j++) {  //copy the first SZ-1
            str[j] = s[j];           //characters "by hand"
            str[j] = '\0';
        }           //add the null character
    } else
        //not too long,
        String(s);                  //so construct normally
}
</code>```

at first the default constructor of the class String is called before the control will be passed to the constructor of the class Pstring.

So the data member is set like

```<code>String()                    //constructor 0, no args
{
    str[0] = '\0';
}
</code>```

As the argument that is the string literal "This is a string" that by the way as the argument has the type const char * due to the implicit conversion of arrays to  pointers has the length that is less than SZ then within the body of the constructor Pstring nothing is done with the data member str. This statement

```<code>String(s);
</code>```

creates a temporary object of the type String that is at once deleted.

What you need is to write at least

```<code>strcpy( str, s );
</code>```

instead of creating the temporary object.

Pay attention to that the constructors with parameters shall be declared like

```<code>String( const char s[] );
</code>```

and

```<code>Pstring( const char s[]);
</code>```

if you are going to use string literals as arguments of the constructors.

You could move this code snippet

```<code>if (strlen(s) > SZ - 1)           //if too long,
        {
    for (int j = 0; j < SZ - 1; j++) {  //copy the first SZ-1
        str[j] = s[j];           //characters "by hand"
        str[j] = '\0';
    }           //add the null character
} else
    //not too long,
    String(s);                  //so construct normally
</code>```

form the constructor Pstring to the constructor String with parameter and substitute it for one call of strncpy like

```<code>strncpy( str, s, SZ - 1 );
str[SZ-1] = '\0';
</code>```

Body:
So there seems to be some problem with the solution to Problem 9-2 in the book "Object-Oriented Programming in C++, 4th edition" by Robert Lafore. So the problem is that if I would like to create a Pstring object with a statement like Pstring = "This is a string", the Pstring constructor will only call the constructor with no arguments in the String class, instead of the second one with uses one char[] argument. Does anyone know what causes this kind of problem, and a fix to this? Thanks!

#include <iostream>
#include <cstring>
using namespace std;
////////////////////////////////////////////////////////////////
class String                      //base class
{
protected:                     //Note: can't be private
    enum {
        SZ = 80
    };           //size of all String objects
    char str[SZ];               //holds a C-string
public:
    String()                    //constructor 0, no args
    {
        str[0] = '\0';
    }
    String(char s[])          //constructor 1, one arg
            {
        strcpy(str, s);
    }      //  convert string to String
    void display() const        //display the String
    {
        cout << str;
    }
    operator char*()            //conversion function
    {
        return str;
    }          //convert String to C-string
};
////////////////////////////////////////////////////////////////
class Pstring: public String     //derived class
{
public:
    Pstring(char s[]);        //constructor
};
//--------------------------------------------------------------
Pstring::Pstring(char s[])      //constructor for Pstring
        {
    if (strlen(s) > SZ - 1)           //if too long,
            {
        for (int j = 0; j < SZ - 1; j++) {  //copy the first SZ-1
            str[j] = s[j];           //characters "by hand"
            str[j] = '\0';
        }           //add the null character
    } else
        //not too long,
        String(s);                  //so construct normally
}
////////////////////////////////////////////////////////////////
int main() {                                        //define String
    String s1 = "This is a string"; // This works great
    s1.display();
    Pstring s2 = "This is a string"; // *** Here, nothing will be assigned to s2****
    s2.display();                    // *** Nothing will be printed here***
    return 0;
}

Body:
In this conversion constructor

Pstring::Pstring(char s[])      //constructor for Pstring
        {
    if (strlen(s) > SZ - 1)           //if too long,
            {
        for (int j = 0; j < SZ - 1; j++) {  //copy the first SZ-1
            str[j] = s[j];           //characters "by hand"
            str[j] = '\0';
        }           //add the null character
    } else
        //not too long,
        String(s);                  //so construct normally
}

at first the default constructor of the class String is called before the control will be passed to the constructor of the class Pstring.

So the data member is set like

String()                    //constructor 0, no args
{
    str[0] = '\0';
}

As the argument that is the string literal "This is a string" that by the way as the argument has the type const char * due to the implicit conversion of arrays to  pointers has the length that is less than SZ then within the body of the constructor Pstring nothing is done with the data member str. This statement

String(s);

creates a temporary object of the type String that is at once deleted.

What you need is to write at least

strcpy( str, s );

instead of creating the temporary object.

Pay attention to that the constructors with parameters shall be declared like

String( const char s[] );

and

Pstring( const char s[]);

if you are going to use string literals as arguments of the constructors.

You could move this code snippet

if (strlen(s) > SZ - 1)           //if too long,
        {
    for (int j = 0; j < SZ - 1; j++) {  //copy the first SZ-1
        str[j] = s[j];           //characters "by hand"
        str[j] = '\0';
    }           //add the null character
} else
    //not too long,
    String(s);                  //so construct normally

form the constructor Pstring to the constructor String with parameter and substitute it for one call of strncpy like

strncpy( str, s, SZ - 1 );
str[SZ-1] = '\0';


问:
I can't insert icons from the drawable folder
I am trying to insert an icon into a FAB from  the drawable folder but Android Studio doesn't recognize it. Could you please help me to figure out why it is not working? Thank you.

答:
Don't use @android:drawable/favorite. Instead use @drawable/favorite

@android:drawable/ is for accessing drawable folder packed with the studio.
To use the drawable folder of your project, use @drawable/


问:
AttributeError: module 'time' has no attribute 'clock' in Python 3.8
I have written code to generate public and private keys. It works great at Python 3.7 but it fails in Python 3.8. I don't know how it fails in the latest version. Help me with some solutions.

Here's the Code:

```<code>from Crypto.PublicKey import RSA

def generate_keys():
    modulus_length = 1024
    key = RSA.generate(modulus_length)
    pub_key = key.publickey()
    private_key = key.exportKey()
    public_key = pub_key.exportKey()
    return private_key, public_key

a = generate_keys()
print(a)
</code>```

Error in Python 3.8 version:

```<code>Traceback (most recent call last):
  File "temp.py", line 18, in <module>
    a = generate_keys()
  File "temp.py", line 8, in generate_keys
    key = RSA.generate(modulus_length)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/PublicKey/RSA.py", line 508, in generate
    obj = _RSA.generate_py(bits, rf, progress_func, e)    # TODO: Don't use legacy _RSA module
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/PublicKey/_RSA.py", line 50, in generate_py
    p = pubkey.getStrongPrime(bits>>1, obj.e, 1e-12, randfunc)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Util/number.py", line 282, in getStrongPrime
    X = getRandomRange (lower_bound, upper_bound, randfunc)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Util/number.py", line 123, in getRandomRange
    value = getRandomInteger(bits, randfunc)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Util/number.py", line 104, in getRandomInteger
    S = randfunc(N>>3)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 202, in read
    return self._singleton.read(bytes)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 178, in read
    return _UserFriendlyRNG.read(self, bytes)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 129, in read
    self._ec.collect()
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 77, in collect
    t = time.clock()
AttributeError: module 'time' has no attribute 'clock'
</code>```

答:
time.clock() was removed in 3.8 because it had platform-dependent behavior:

On Unix, this returns the current processor time (in seconds)

On Windows, this returns wall-clock time (in seconds)

```<code># I ran this test on my dual-boot system as demonstration:
print(time.clock()); time.sleep(10); print(time.clock())
# Linux:    0.0382 --------------------------->  0.0384
# Windows: 26.1224 ---------------------------> 36.1566
</code>```

So  which function to pick instead?

Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this.

Use time.process_time()

Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time.

Use time.perf_counter()

time.time() also measures wall-clock time but can be reset, so you could go back in time

time.monotonic() cannot be reset (monotonic = only goes  forward) but has lower precision than time.perf_counter()

Body:
I have written code to generate public and private keys. It works great at Python 3.7 but it fails in Python 3.8. I don't know how it fails in the latest version. Help me with some solutions.

Here's the Code:

from Crypto.PublicKey import RSA

def generate_keys():
    modulus_length = 1024
    key = RSA.generate(modulus_length)
    pub_key = key.publickey()
    private_key = key.exportKey()
    public_key = pub_key.exportKey()
    return private_key, public_key

a = generate_keys()
print(a)

Error in Python 3.8 version:

Traceback (most recent call last):
  File "temp.py", line 18, in <module>
    a = generate_keys()
  File "temp.py", line 8, in generate_keys
    key = RSA.generate(modulus_length)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/PublicKey/RSA.py", line 508, in generate
    obj = _RSA.generate_py(bits, rf, progress_func, e)    # TODO: Don't use legacy _RSA module
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/PublicKey/_RSA.py", line 50, in generate_py
    p = pubkey.getStrongPrime(bits>>1, obj.e, 1e-12, randfunc)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Util/number.py", line 282, in getStrongPrime
    X = getRandomRange (lower_bound, upper_bound, randfunc)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Util/number.py", line 123, in getRandomRange
    value = getRandomInteger(bits, randfunc)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Util/number.py", line 104, in getRandomInteger
    S = randfunc(N>>3)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 202, in read
    return self._singleton.read(bytes)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 178, in read
    return _UserFriendlyRNG.read(self, bytes)
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 129, in read
    self._ec.collect()
  File "/home/paulsteven/.local/lib/python3.8/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 77, in collect
    t = time.clock()
AttributeError: module 'time' has no attribute 'clock'

Body:
time.clock() was removed in 3.8 because it had platform-dependent behavior:

On Unix, this returns the current processor time (in seconds)

On Windows, this returns wall-clock time (in seconds)

# I ran this test on my dual-boot system as demonstration:
print(time.clock()); time.sleep(10); print(time.clock())
# Linux:    0.0382 --------------------------->  0.0384
# Windows: 26.1224 ---------------------------> 36.1566

So  which function to pick instead?

Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this.

Use time.process_time()

Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time.

Use time.perf_counter()

time.time() also measures wall-clock time but can be reset, so you could go back in time

time.monotonic() cannot be reset (monotonic = only goes  forward) but has lower precision than time.perf_counter()


问:
How do i put a link in a table
I have a table on my website, which gets data from a database, in the table I have delete buttons on a row, I have just made the table searchable with jQuery, but now I can't figure out how to keep the delete buttons.

index.php:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta charset="utf-8">
    <meta name="description" content="Inventar">
    <meta name="author" content="Martin Eide Bjørndal">
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="/src/css/style.css">
       <!-- jQuery library -->
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
        <!-- Popper JS -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
        <!-- Latest compiled JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>

</head>
<body>

    <button class="back" onclick="window.location='../'">
      <img src="/src/icons/back.png">
    </button> <!-- Tilbake knapp -->

    <button class="ny_inventar" onclick="window.location='/admin/brukere/ny'">
      <img src="/src/icons/add.png">
    </button> <!-- Ny Bruker knapp -->

    <div class="container-fluid" id="utskjekkcontainer">
      <div class="row justify-content-center">
        <div class="col-mv-10 bg-light mt-5 rounded p-3">
          <h1 class="text-primary p-2">Brukere</h1>
          <hr>
          <div class="form-inline">
            <label for="search" class="font-weight-bold lead text-dark">Søk</label>
            <input type="text" name="search" id="search_text" class="form-control form-control-lg rounded-0 border-primary" placeholder="Søk...">
          </div>
          <hr>
          <?php
            include "../../src/fn/init.php";
            $stmt=$conn->prepare("SELECT * FROM brukere");
            $stmt->execute();
            $result=$stmt->get_result();
          ?>
          <table class="table table-hover table-light table-striped" id="table_data">
            <thead>
              <tr>
                <th>#</th>
                <th>Fornavn</th>
                <th>Etternavn</th>
                <th>Utskjekket</th>
                <th>Admin</th>
                <th>Slett</th>
              </tr>
            </thead>
            <tbody>
              <?php while($row=$result->fetch_assoc()){ ?>
                <tr>
                  <td><?php echo $row["id"]; ?></td>
                  <td><?php echo $row["fornavn"]; ?></td>
                  <td><?php echo $row["etternavn"]; ?></td>
                  <td><?php echo $row["utskjekket"]; ?></td>
                  <td><?php echo $row["is_admin"]; ?></td>
                  <td><a href="delete.php?id=<?php echo urlencode($row['id']); ?>" onclick="return confirm('Er du sikker?');">Slett</a></td>
                </tr>
              <?php }
              $conn->close();
              ?>
             </tbody>

           </table>

        </div>
      </div>
    </div>

    <script type="text/javascript">
      $(document).ready(function(){
        $('#search_text').keyup(function(){
          var search = $(this).val();
          $.ajax({
            url:'action.php',
            method:'post',
            data:{query:search},
            success:function(response){
              $('#table_data').html(response);
            }
          });
        });
      });
    </script>

</body>
</html>
</code>```

action.php:

```<code><?php

    include "../../src/fn/init.php";
    $output = "";

    if(isset($_POST["query"])){
        $search = $_POST["query"];
        $stmt = $conn->prepare("SELECT * FROM brukere WHERE fornavn LIKE CONCAT('%',?,'%') OR etternavn LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%')");
        $stmt->bind_param("sss",$search, $search, $search);
    } else {
        $stmt=$conn->prepare("SELECT * FROM brukere");
    };
    $stmt->execute();
    $result=$stmt->get_result();

    if($result->num_rows>0){
        $output = "<thead>
                    <tr>
                    <th>#</th>
                    <th>Fornavn</th>
                    <th>Etternavn</th>
                    <th>Utskjekket</th>
                    <th>Admin</th>
                    <th>Slett</th>
                    </tr>
                </thead>
                <tbody>";

        while($row=$result->fetch_assoc()){
            $output .= "
                <tr>
                    <td>".$row["id"]."</td>
                    <td>".$row["fornavn"]."</td>
                    <td>".$row["etternavn"]."</td>
                    <td>".$row["utskjekket"]."</td>
                    <td>".$row["is_admin"]."</td>
                    <td>".<a href="delete.php?id=<?php echo urlencode($row['id']); ?>" onclick="return confirm('Er du sikker?');">Slett</a>."</td>
                </tr>";
        };
        $output .= "</tbody>";
        echo $output;
    } else {
        echo "<h3>No match found!</h3>";
    };

?>
</code>```

This is the search script, the problem is in the while loop where the link is added, I can't figure out how to make it work.

答:
You can use it</p>

```<code><?php

include "../../src/fn/init.php";
$output = "";

if(isset($_POST["query"])){
    $search = $_POST["query"];
    $stmt = $conn->prepare("SELECT * FROM brukere WHERE fornavn LIKE CONCAT('%',?,'%') OR etternavn LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%')");
    $stmt->bind_param("sss",$search, $search, $search);
} else {
    $stmt=$conn->prepare("SELECT * FROM brukere");
};
$stmt->execute();
$result=$stmt->get_result();

if($result->num_rows>0){
    $output = "<thead>
                <tr>
                <th>#</th>
                <th>Fornavn</th>
                <th>Etternavn</th>
                <th>Utskjekket</th>
                <th>Admin</th>
                <th>Slett</th>
                </tr>
            </thead>
            <tbody>";

    while($row=$result->fetch_assoc()){
        $output .= "
            <tr>
                <td>".$row["id"]."</td>
                <td>".$row["fornavn"]."</td>
                <td>".$row["etternavn"]."</td>
                <td>".$row["utskjekket"]."</td>
                <td>".$row["is_admin"]."</td>
                <td><a href=\"delete.php=".urlencode($row['id'])."\" onclick=\"return confirm('Er du sikker?');\">Slett</a> </td>
            </tr>";
    };
    $output .= "</tbody>";
    echo $output;
} else {
    echo "<h3>No match found!</h3>";
};
</code>```

Title: How do i put a link in a table

Body:
I have a table on my website, which gets data from a database, in the table I have delete buttons on a row, I have just made the table searchable with jQuery, but now I can't figure out how to keep the delete buttons.

index.php:

<!DOCTYPE html>

    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta charset="utf-8">
    <meta name="description" content="Inventar">
    <meta name="author" content="Martin Eide Bjørndal">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="/src/css/style.css">

    <button class="back" onclick="window.location='../'">

    </button>

    <button class="ny_inventar" onclick="window.location='/admin/brukere/ny'">

    </button>

Brukere

            Søk
            <input type="text" name="search" id="search_text" class="form-control form-control-lg rounded-0 border-primary" placeholder="Søk...">

          <?php
            include "../../src/fn/init.php";
            $stmt=$conn->prepare("SELECT * FROM brukere");
            $stmt->execute();
            $result=$stmt->get_result();
          ?>

                #
                Fornavn
                Etternavn
                Utskjekket
                Admin
                Slett

              <?php while($row=$result->fetch_assoc()){ ?>

                  <?php echo $row["id"]; ?>
                  <?php echo $row["fornavn"]; ?>
                  <?php echo $row["etternavn"]; ?>
                  <?php echo $row["utskjekket"]; ?>
                  <?php echo $row["is_admin"]; ?>
                  <a href="delete.php?id=<?php echo urlencode($row['id']); ?>" onclick="return confirm('Er du sikker?');">Slett

              <?php }
              $conn->close();
              ?>

action.php:

<?php

    include "../../src/fn/init.php";
    $output = "";

    if(isset($_POST["query"])){
        $search = $_POST["query"];
        $stmt = $conn->prepare("SELECT * FROM brukere WHERE fornavn LIKE CONCAT('%',?,'%') OR etternavn LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%')");
        $stmt->bind_param("sss",$search, $search, $search);
    } else {
        $stmt=$conn->prepare("SELECT * FROM brukere");
    };
    $stmt->execute();
    $result=$stmt->get_result();

    if($result->num_rows>0){
        $output = "

                    #
                    Fornavn
                    Etternavn
                    Utskjekket
                    Admin
                    Slett

";

        while($row=$result->fetch_assoc()){
            $output .= "

                    ".$row["id"]."
                    ".$row["fornavn"]."
                    ".$row["etternavn"]."
                    ".$row["utskjekket"]."
                    ".$row["is_admin"]."
                    ".<a href="delete.php?id=<?php echo urlencode($row['id']); ?>" onclick="return confirm('Er du sikker?');">Slett."

";
        };
        $output .= "
";
        echo $output;
    } else {
        echo "
No match found!
";
    };

?>

This is the search script, the problem is in the while loop where the link is added, I can't figure out how to make it work.

Body:
You can use it

<?php

include "../../src/fn/init.php";
$output = "";

if(isset($_POST["query"])){
    $search = $_POST["query"];
    $stmt = $conn->prepare("SELECT * FROM brukere WHERE fornavn LIKE CONCAT('%',?,'%') OR etternavn LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%')");
    $stmt->bind_param("sss",$search, $search, $search);
} else {
    $stmt=$conn->prepare("SELECT * FROM brukere");
};
$stmt->execute();
$result=$stmt->get_result();

if($result->num_rows>0){
    $output = "<thead>
                <tr>
                <th>#</th>
                <th>Fornavn</th>
                <th>Etternavn</th>
                <th>Utskjekket</th>
                <th>Admin</th>
                <th>Slett</th>
                </tr>
            </thead>
            <tbody>";

    while($row=$result->fetch_assoc()){
        $output .= "
            <tr>
                <td>".$row["id"]."</td>
                <td>".$row["fornavn"]."</td>
                <td>".$row["etternavn"]."</td>
                <td>".$row["utskjekket"]."</td>
                <td>".$row["is_admin"]."</td>
                <td><a href=\"delete.php=".urlencode($row['id'])."\" onclick=\"return confirm('Er du sikker?');\">Slett</a> </td>
            </tr>";
    };
    $output .= "</tbody>";
    echo $output;
} else {
    echo "<h3>No match found!</h3>";
};


问:
Make div height the max-height of container div
I have a container
 which has a max-height property. This
 contains another
, and I want the child
 to grow to the maximum height of its container.

```<code><div id='parent'>
  <div id='child'>
  </div>
</div>
</code>```

This is easy enough when the parent
 has a fixed height, but I cannot find a solution for making the child
 assume the max-height of the container. There is no padding or margin or anything to worry about - I simply need the child
 to assume the max-height of the parent.

How can I do this?

答:
Set the parent's display property to flex, and the flex direction to column:

#parent {
  display: flex;
  flex-direction: column;
  max-height: 100px;
  border-bottom: 2px solid red; /** example - to show the effect on the parent **/
}

#child {
  height: 100vh;
  background: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="parent">
  <div id="child">
  </div>
</div></code>```

Body:
I have a container
 which has a max-height property. This
 contains another
, and I want the child
 to grow to the maximum height of its container.

This is easy enough when the parent
 has a fixed height, but I cannot find a solution for making the child
 assume the max-height of the container. There is no padding or margin or anything to worry about - I simply need the child
 to assume the max-height of the parent.

How can I do this?

Body:
Set the parent's display property to flex, and the flex direction to column:

#parent {
  display: flex;
  flex-direction: column;
  max-height: 100px;
  border-bottom: 2px solid red; /** example - to show the effect on the parent **/
}

#child {
  height: 100vh;
  background: blue;
}

<div id="parent">
  <div id="child">
  </div>
</div>


问:
best approch among EXE and MSI
I have an application that needs to be delivered as a package.

What are the best among EXE and MSI Installers, and why?

Is there any open source tool to decompile the EXE or MSI?

答: check Difference between EXE and MSI</p>

Title: best approch among EXE and MSI

Body: check Difference between EXE and MSI


问:
Backup GCS bucket to an archive-class GCS bucket
The GCS Transfer Service is a nice solution for regular transfer of data.  What would the appropriate settings be to sync a bucket to another, where the destination bucket has the archive storage class?

One of my concerns is possible expensive operations on archive class objects, if the service is checking for identical objects.  If, to avoid these checks, I just copy files daily that are new within the last 24 hours, how accurate is that timing -- can I miss a file due to timing jitter of several minutes on job start?

答:
While "the appropriate settings" would completely depend on your business needs. A good approach could be to use a Cloud Function triggered on create/finalize on your standard bucket that creates a copy of that object in your second bucket.

You can use this function in python as a guide:

```<code>from google.cloud import storage
from google.cloud.storage.blob import Blob

def hello_gcs(event, context):
    client = storage.Client()
    source_bucket = client.get_bucket("my_source_bucket)
    dest_bucket = client.get_bucket("my_destination_bucket")
    filename = str(event['id']).rsplit('/',1)[0]
    blob = Blob.from_string("gs://" + filename)
    source_bucket.copy_blob(blob,dest_bucket)
</code>```

Body:
While "the appropriate settings" would completely depend on your business needs. A good approach could be to use a Cloud Function triggered on create/finalize on your standard bucket that creates a copy of that object in your second bucket.

You can use this function in python as a guide:

from google.cloud import storage
from google.cloud.storage.blob import Blob

def hello_gcs(event, context):
    client = storage.Client()
    source_bucket = client.get_bucket("my_source_bucket)
    dest_bucket = client.get_bucket("my_destination_bucket")
    filename = str(event['id']).rsplit('/',1)[0]
    blob = Blob.from_string("gs://" + filename)
    source_bucket.copy_blob(blob,dest_bucket)


答:
There are few things to note,

1. Height should be in vh to achieve responsiveness, better when dealing with height CSS
 2. it's preferable to use vh as the unit for height.

.parent {
  max-height: 25vh;
  width: 15vw;
  background-color: aquamarine;
}

.child {
  background-color: brown;
  height: 25vh;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>

<div id='parent' class='parent'>
  <div id='child' class='child'>
  </div>
</div>

</body>

</html></code>```

Title: Make div height the max-height of container div

Body:
There are few things to note,

1. Height should be in vh to achieve responsiveness, better when dealing with height CSS
 2. it's preferable to use vh as the unit for height.

.parent {
  max-height: 25vh;
  width: 15vw;
  background-color: aquamarine;
}

.child {
  background-color: brown;
  height: 25vh;
}

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>

<div id='parent' class='parent'>
  <div id='child' class='child'>
  </div>
</div>

</body>

</html>


问:
PowerShell: unable to loop through files located in other directory than the script file itself
I am trying to test if I can loop through .xml files located in a different directory than the .ps1 script itself:

```<code>$files = Get-ChildItem -Path 'C:\ps_scripts\configs'

foreach ($file in $files) {
    $xml = [xml](Get-Content $file.FullName)
    Write-Host $xml
}
</code>```

When I run the above script, I get several empty lines as the output. I also tried to add -Recurse parameter in the first line, but the problem persists.
If I type in the PowerShell terminal $files = Get-ChildItem -Path 'C:\ps_scripts\configs', then the $files variable returns a list of files as I expect:

```<code>PS C:\ps_scripts> $files = Get-ChildItem -Path 'C:\ps_scripts\configs'
PS C:\ps_scripts> $files

    Directory: C:\ps_scripts\configs

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        12/2/2019   9:09 AM           3820 ams_merge_ab.xml
-a----        12/2/2019   9:09 AM           3894 ams_merge_ba.xml
-a----        12/2/2019   9:09 AM           4451 ams_merge_cg.xml
-a----        2/10/2020  12:28 PM           4029 ams_merge_de.xml
-a----        12/3/2019   3:22 PM           4222 ams_merge_so.xml
</code>```

If $files actually do contain the list of files in the directory, then why the foreach block fails to return anything?

答:
$files = Get-ChildItem -Path 'C\ps_scripts\configs'
$files  = $files.FullName

foreach ($file in $files) {  Write-Host $file }

Body:
I am trying to test if I can loop through .xml files located in a different directory than the .ps1 script itself:

$files = Get-ChildItem -Path 'C:\ps_scripts\configs'

foreach ($file in $files) {
    $xml = [xml](Get-Content $file.FullName)
    Write-Host $xml
}

When I run the above script, I get several empty lines as the output. I also tried to add -Recurse parameter in the first line, but the problem persists.
If I type in the PowerShell terminal $files = Get-ChildItem -Path 'C:\ps_scripts\configs', then the $files variable returns a list of files as I expect:

PS C:\ps_scripts> $files = Get-ChildItem -Path 'C:\ps_scripts\configs'
PS C:\ps_scripts> $files

    Directory: C:\ps_scripts\configs

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----        12/2/2019   9:09 AM           3820 ams_merge_ab.xml
-a----        12/2/2019   9:09 AM           3894 ams_merge_ba.xml
-a----        12/2/2019   9:09 AM           4451 ams_merge_cg.xml
-a----        2/10/2020  12:28 PM           4029 ams_merge_de.xml
-a----        12/3/2019   3:22 PM           4222 ams_merge_so.xml

If $files actually do contain the list of files in the directory, then why the foreach block fails to return anything?


问:
Render local html file in React Native
I run React Native using Expo for android and I'm trying to render html file (it shows a map image) in local directory, but it doesn't work properly.

I followed several references, installed webview dependencies in expo and npm both.

The problem is that the result is just html code view, not a map image

Please see my result below:

And my react native code is this (very simple) :

```<code>import React, { Component } from 'react';
import { WebView } from 'react-native-webview';

const testHtml = require('./arcgis/arc1.html');

export default function App() {

  return (
    <WebView source={testHtml} startInLoadingState
    scalesPageToFit
    javaScriptEnabled
    style={{ flex: 1 }}/>
  );

}
</code>```

When I compile the html file in online html website, it appears like this:

left - html code, right - result

This html file is just sample file from official gis website so my react native code must be wrong I guess.

How can I fix the problem ?

Thanks.

答:
You can use react-native-webview for rendering html file.

Here is an example

```<code>import React, { Component } from 'react';
import { WebView } from 'react-native-webview';

const myHtmlFile = require("./my-asset-folder/local-site.html");

class MyWeb extends Component {
  render() {
    return (
      <WebView source={myHtmlFile} />
    );
  }
}
</code>```

Title: Render local html file in React Native

Body:
I run React Native using Expo for android and I'm trying to render html file (it shows a map image) in local directory, but it doesn't work properly.

I followed several references, installed webview dependencies in expo and npm both.

The problem is that the result is just html code view, not a map image

Please see my result below:

And my react native code is this (very simple) :

import React, { Component } from 'react';
import { WebView } from 'react-native-webview';

const testHtml = require('./arcgis/arc1.html');

export default function App() {

  return (
    <WebView source={testHtml} startInLoadingState
    scalesPageToFit
    javaScriptEnabled
    style={{ flex: 1 }}/>
  );

}

When I compile the html file in online html website, it appears like this:

left - html code, right - result

This html file is just sample file from official gis website so my react native code must be wrong I guess.

How can I fix the problem ?

Thanks.

Body:
You can use react-native-webview for rendering html file.

Here is an example

import React, { Component } from 'react';
import { WebView } from 'react-native-webview';

const myHtmlFile = require("./my-asset-folder/local-site.html");

class MyWeb extends Component {
  render() {
    return (
      <WebView source={myHtmlFile} />
    );
  }
}


问:
regex from scraped data using lookaround not working
I'm trying to figure out why one of my regex commands works but the other doesn't. Here's a sample of two strings it would pull from. There is consistency in the new line garbage which resulted from the scrape so I used that to my advantage as best I could:

```<code>"\n\tMenghe a'Nyam\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-5, 215lb (196cm,
97kg) \n  \n\n  \n\n  \n  \n  \n\n  School: Canisius\n\n\n\n\n\n  More player info\n\n\n\n\n\n"

"\n\tJordan Aaberg\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Guard\n\n\n\n  6-9, 225lb (206cm,
102kg) \n  \n\n  Hometown: Rothsay, MN\n\n\n\n  \n\n  High School: Rothsay\n\n\n\n  \n  \n  \n\n
School: North Dakota State\n\n\n\n\n\n  More player info\n\n\n\n\n\n"
</code>```

My goal is to pull desired data from this such as position (Forward, Guard respectively) and most importantly, height (6-5, 6-9, respectively). I had success pulling the position with the following:

```<code>test <- df %>%
  mutate(position = str_extract(player, "(?<=Position:\n  \n  ).*?(?=\n\n\n\n  \\d-\\d)"))
</code>```

But when I follow a similar lookaround to add another col for height, it returns NA:

```<code>test <- df %>%
  mutate(position = str_extract(player, "(?<=Position:\n  \n  ).*?(?=\n\n\n\n  \\d-\\d)")) %>%
  mutate(height = str_extract(player, "(?<=\\w+\n\n\n\n  ).*?(?=, \\d{3}lb)"))
</code>```

Here is a sample of the result from above call on the first 3 rows of my df if it's helpful:

```<code>structure(list(player = c("\n\tMenghe a'Nyam\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-5, 215lb (196cm, 97kg) \n  \n\n  \n\n  \n  \n  \n\n  School: Canisius\n\n\n\n\n\n  More player info\n\n\n\n\n\n"  ,
"\n\tJordan Aaberg\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-9, 225lb (206cm, 102kg) \n  \n\n  Hometown: Rothsay, MN\n\n\n\n  \n\n  High School: Rothsay\n\n\n\n  \n  \n  \n\n  School: North Dakota State\n\n\n\n\n\n  More player info\n\n\n\n\n\n"  ,
"\n\tKarl Aaker\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-5, 210lb (196cm, 95kg) \n  \n\n  Hometown: Reno, NV\n\n\n\n  \n\n  \n  \n  \n\n  School: Portland\n\n\n\n\n\n  More player info\n\n\n\n\n\n"
), position = c("Forward", "Forward", "Forward"), height = c(NA_character_,
NA_character_, NA_character_)), row.names = c(NA, 3L), class = "data.frame")
</code>```

答:
Here is an approach using stringr and tidyr. First I remove all \n and  \t because they really annoy me.

test <- df %>%
  mutate(player = str_replace_all(player, "\n|\r|\t", ""),
         position = str_extract(player, "(?<=Position:).+(?=\\s\\d-\\d)"),
         height = str_extract(player, "\\d-\\d?(?=,\\s\\d{3}lb)"))
```

We can do all mutations in on step. Hopefully this solves your problem.

Body:
I'm trying to figure out why one of my regex commands works but the other doesn't. Here's a sample of two strings it would pull from. There is consistency in the new line garbage which resulted from the scrape so I used that to my advantage as best I could:

"\n\tMenghe a'Nyam\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-5, 215lb (196cm,
97kg) \n  \n\n  \n\n  \n  \n  \n\n  School: Canisius\n\n\n\n\n\n  More player info\n\n\n\n\n\n"

"\n\tJordan Aaberg\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Guard\n\n\n\n  6-9, 225lb (206cm,
102kg) \n  \n\n  Hometown: Rothsay, MN\n\n\n\n  \n\n  High School: Rothsay\n\n\n\n  \n  \n  \n\n
School: North Dakota State\n\n\n\n\n\n  More player info\n\n\n\n\n\n"

My goal is to pull desired data from this such as position (Forward, Guard respectively) and most importantly, height (6-5, 6-9, respectively). I had success pulling the position with the following:

test <- df %>%
  mutate(position = str_extract(player, "(?<=Position:\n  \n  ).*?(?=\n\n\n\n  \\d-\\d)"))

But when I follow a similar lookaround to add another col for height, it returns NA:

test <- df %>%
  mutate(position = str_extract(player, "(?<=Position:\n  \n  ).*?(?=\n\n\n\n  \\d-\\d)")) %>%
  mutate(height = str_extract(player, "(?<=\\w+\n\n\n\n  ).*?(?=, \\d{3}lb)"))

Here is a sample of the result from above call on the first 3 rows of my df if it's helpful:

structure(list(player = c("\n\tMenghe a'Nyam\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-5, 215lb (196cm, 97kg) \n  \n\n  \n\n  \n  \n  \n\n  School: Canisius\n\n\n\n\n\n  More player info\n\n\n\n\n\n"  ,
"\n\tJordan Aaberg\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-9, 225lb (206cm, 102kg) \n  \n\n  Hometown: Rothsay, MN\n\n\n\n  \n\n  High School: Rothsay\n\n\n\n  \n  \n  \n\n  School: North Dakota State\n\n\n\n\n\n  More player info\n\n\n\n\n\n"  ,
"\n\tKarl Aaker\n\t\n\n  \n\n  \n\n  \n\n  \n  Position:\n  \n  Forward\n\n\n\n  6-5, 210lb (196cm, 95kg) \n  \n\n  Hometown: Reno, NV\n\n\n\n  \n\n  \n  \n  \n\n  School: Portland\n\n\n\n\n\n  More player info\n\n\n\n\n\n"
), position = c("Forward", "Forward", "Forward"), height = c(NA_character_,
NA_character_, NA_character_)), row.names = c(NA, 3L), class = "data.frame")

Body:
Here is an approach using stringr and tidyr. First I remove all \n and  \t because they really annoy me.

test <- df %>%
  mutate(player = str_replace_all(player, "\n|\r|\t", ""),
         position = str_extract(player, "(?<=Position:).+(?=\\s\\d-\\d)"),
         height = str_extract(player, "\\d-\\d?(?=,\\s\\d{3}lb)"))

We can do all mutations in on step. Hopefully this solves your problem.


问:
How to remove keys from a params array of hashes
I have a list of params.

I have a sales_attributes key, which can contain an unlimited array of hashes.

I'm trying to remove the name and code keys and values from each sales_attributes array.

I tried iterating over each sales_attributes and doing delete, except or reject, but they only return the sales_attributes instead of the original param list. I want to return the exact same list as below, but not including the name or code key/values.

I looked at quite a few other posts on here and nothing has worked so far.

```<code><ActionController::Parameters {"patient_id"=>"22", "location_id"=>"5", "practitioner_id"=>"1", "confidential"=>"1", "billpayer_id"=>"20", "sales_attributes"=>
[<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"first",
"code"=>"G32"} permitted: true>, <ActionController::Parameters
{"sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"second", "code"=>"G33"} permitted: true>,
<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"third", "code"=>"G34"} permitted: true>]} permitted: true>
</code>```

答:
We are given (simplified from the example in the question):

```<code>params = {
  "patient_id"=>"22", "sales_attributes"=>[
    { "type"=>"Product1", "price"=>"0", "name"=>"first", "code"=>"G32" },
    { "type"=>"Product2", "price"=>"1", "name"=>"second", "code"=>"G33" },
    { "type"=>"Product3", "price"=>"3", "name"=>"third", "code"=>"G34" }
  ]
}
</code>```

and

```<code>unwanted_keys = ["name", "code"]
</code>```

We can then obtain the desired hash as follows.

```<code>params.merge("sales_attributes"=>unwanted_keys) do |_key,old_val,new_val|
  old_val.map { |h| h.reject { |k,_| new_val.include?(k) } }
end
  #=> {"patient_id"=>"22", "sales_attributes"=>[
  #     {"type"=>"Product1", "price"=>"0"},
  #     {"type"=>"Product2", "price"=>"1"},
  #     {"type"=>"Product3", "price"=>"3"}
  #    ]
  #   }
</code>```

The uses the form of Hash#merge that employs a block to determine the values of keys that are present in both hashes being merged. The only key common to both params and { "sales_attributes"=>unwanted_keys } is "sales_attributes", so that it is the only key for which the block is called.

When the block is called,

```<code>_key = "sales_attributes"
old_val = [
  { "type"=>"Product1", "price"=>"0", "name"=>"first", "code"=>"G32" },
  { "type"=>"Product2", "price"=>"1", "name"=>"second", "code"=>"G33" },
  { "type"=>"Product3", "price"=>"3", "name"=>"third", "code"=>"G34" }
]
new_val = unwanted_keys
  #=> ["name", "code"]
</code>```

so

```<code>old_val.map { |h| h.reject { |k,_| new_val.include?(k) } }
  #=> [{"type"=>"Product1", "price"=>"0"},
  #    {"type"=>"Product2", "price"=>"1"},
  #    {"type"=>"Product3", "price"=>"3"}]
</code>```

becomes the value of "sales_attributes" in the merged hash.

I used _key, rather than key, for the first block variable to signal to the reader that it is not used in the block calculation. I might instead have written just _, which is often used for block variables not used in the block calculation. Unlike other local variables, _ can represent multiple block variables (e.g, |_,a,_,b|).

Use Hash#merge! (a.k.a update) if params is to be mutated.

Body:
I have a list of params.

I have a sales_attributes key, which can contain an unlimited array of hashes.

I'm trying to remove the name and code keys and values from each sales_attributes array.

I tried iterating over each sales_attributes and doing delete, except or reject, but they only return the sales_attributes instead of the original param list. I want to return the exact same list as below, but not including the name or code key/values.

I looked at quite a few other posts on here and nothing has worked so far.

<ActionController::Parameters {"patient_id"=>"22", "location_id"=>"5", "practitioner_id"=>"1", "confidential"=>"1", "billpayer_id"=>"20", "sales_attributes"=>
[<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"first",
"code"=>"G32"} permitted: true>, <ActionController::Parameters
{"sellable_type"=>"Product", "sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"second", "code"=>"G33"} permitted: true>,
<ActionController::Parameters {"sellable_type"=>"Product",
"sellable_id"=>"-2", "discount"=>"0", "price"=>"0", "name"=>"third", "code"=>"G34"} permitted: true>]} permitted: true>

Body:
We are given (simplified from the example in the question):

params = {
  "patient_id"=>"22", "sales_attributes"=>[
    { "type"=>"Product1", "price"=>"0", "name"=>"first", "code"=>"G32" },
    { "type"=>"Product2", "price"=>"1", "name"=>"second", "code"=>"G33" },
    { "type"=>"Product3", "price"=>"3", "name"=>"third", "code"=>"G34" }
  ]
}

and

unwanted_keys = ["name", "code"]

We can then obtain the desired hash as follows.

params.merge("sales_attributes"=>unwanted_keys) do |_key,old_val,new_val|
  old_val.map { |h| h.reject { |k,_| new_val.include?(k) } }
end
  #=> {"patient_id"=>"22", "sales_attributes"=>[
  #     {"type"=>"Product1", "price"=>"0"},
  #     {"type"=>"Product2", "price"=>"1"},
  #     {"type"=>"Product3", "price"=>"3"}
  #    ]
  #   }

The uses the form of Hash#merge that employs a block to determine the values of keys that are present in both hashes being merged. The only key common to both params and { "sales_attributes"=>unwanted_keys } is "sales_attributes", so that it is the only key for which the block is called.

When the block is called,

_key = "sales_attributes"
old_val = [
  { "type"=>"Product1", "price"=>"0", "name"=>"first", "code"=>"G32" },
  { "type"=>"Product2", "price"=>"1", "name"=>"second", "code"=>"G33" },
  { "type"=>"Product3", "price"=>"3", "name"=>"third", "code"=>"G34" }
]
new_val = unwanted_keys
  #=> ["name", "code"]

so

old_val.map { |h| h.reject { |k,_| new_val.include?(k) } }
  #=> [{"type"=>"Product1", "price"=>"0"},
  #    {"type"=>"Product2", "price"=>"1"},
  #    {"type"=>"Product3", "price"=>"3"}]

becomes the value of "sales_attributes" in the merged hash.

I used _key, rather than key, for the first block variable to signal to the reader that it is not used in the block calculation. I might instead have written just _, which is often used for block variables not used in the block calculation. Unlike other local variables, _ can represent multiple block variables (e.g, |_,a,_,b|).

Use Hash#merge! (a.k.a update) if params is to be mutated.


问:
JavaScript - Force select element to dropdown?
How can I force the select element to dropdown using Javascript? Is it possible?

```<code><select id="MiamiPlayers">
    <option value="0">Bosh</option>
    <option value="1">Wade</option>
    <option value="2">LeBron</option>
</select>

<input type="button" onclick="Show()" />

<script type="text/javascript">
    function Show()
    {
        //force the select to dropdown...
    }
</script>
</code>```

Thanks in advance!

答:
You can't open the drop down, but you can do something like this:

```<code>document.getElementById('MiamiPlayers').setAttribute('size', 3);
</code>```

See http://jsfiddle.net/MdCBB/

Body:
How can I force the select element to dropdown using Javascript? Is it possible?

<select id="MiamiPlayers">
    <option value="0">Bosh</option>
    <option value="1">Wade</option>
    <option value="2">LeBron</option>
</select>

<input type="button" onclick="Show()" />

Thanks in advance!

Body:
You can't open the drop down, but you can do something like this:

document.getElementById('MiamiPlayers').setAttribute('size', 3);

See http://jsfiddle.net/MdCBB/


问:
How to start working with GTest and CMake
I have recently been sold on using CMake for compiling my C++ projects, and would now like to start writing some unit tests for my code. I have decided to use the Google Test utility to help with this, but require some help in getting started.

All day I have been reading various guides and examples include the Primer, an introduction at IBM and some questions on SO (here and here) as well as other sources I've lost track of. I realise there's plenty out there but somehow I am still having difficulties.

I'm currently trying to implement the most basic test, to confirm I've compiled/installed gtest right and it's not working. The only source file (testgtest.cpp) is taken almost exactly from this previous answer:

```<code>#include <iostream>

#include "gtest/gtest.h"

TEST(sample_test_case, sample_test)
{
    EXPECT_EQ(1, 1);
}
</code>```

and my associated CMakeLists.txt is as follows:

```<code>cmake_minimum_required(VERSION 2.6)
project(basic_test)

# Setup testing
enable_testing()
find_package(GTest REQUIRED)
include_directories(${GTEST_INCLUDE_DIR})

# Add test cpp file
add_executable(runUnitTests
    testgtest.cpp
)

# Link test executable against gtest & gtest_main
target_link_libraries(runUnitTests ${GTEST_LIBRARY_DEBUG} ${GTEST_MAIN_LIBRARY_DEBUG})

add_test(
    NAME runUnitTests
    COMMAND runUnitTests
)
</code>```

Note that I have chosen to link against gtest_main instead of providing the main at the end of the cpp file as I believe this will allow me to scale testing up more easily to multiple files.

When building the generated .sln file (in Visual C++ 2010 Express) I unfortunately get a long list of errors of the form

```<code>2>msvcprtd.lib(MSVCP100D.dll) : error LNK2005: "public: virtual __thiscall std::basic_iostream<char,struct std::char_traits<char> >::~basic_iostream<char,struct std::char_traits<char> >(void)" (??1?$basic_iostream@DU?$char_traits@D@std@@@std@@UAE@XZ) already defined in gtestd.lib(gtest-all.obj)
</code>```

which I think means that I'm not successfully linking to the gtest libraries. I have made sure that when linking against the debug libraries, I have then tried to build in debug mode.

EDIT

Having done some more digging, I think my issue is something to do with the type of library I am building gtest into. When building gtest with CMake, if BUILD_SHARED_LIBS is un-checked, and I link my program against these .lib files I get the errors mentioned above. However, if BUILD_SHARED_LIBS is checked then I produce a set of .lib and .dll files. When now linking against these .lib files the program compiles, but when run complains that it can't find gtest.dll.

What are the differences between a SHARED and a not SHARED library, and if I choose not shared, why doesn't it work? Is there an option in the CMakeLists.txt for my project that I am missing?

答:
The OP is using Windows, and a much easier way to use GTest today is with vcpkg+cmake.

Install vcpkg as per https://github.com/microsoft/vcpkg , and make sure you can run vcpkg from the cmd line. Take note of the vcpkg installation folder, eg. C:\bin\programs\vcpkg.

Install gtest using vcpkg install gtest: this will download, compile, and install GTest.

Use a CmakeLists.txt as below: note we can use targets instead of including folders.

```<code>cmake_minimum_required(VERSION 3.15)
project(sample CXX)
enable_testing()
find_package(GTest REQUIRED)
add_executable(test1 test.cpp source.cpp)
target_link_libraries(test1 GTest::GTest GTest::Main)
add_test(test-1 test1)
</code>```

Run cmake with: (edit the vcpkg folder if necessary, and make sure the path to the vcpkg.cmake toolchain file is correct)

cmake -B build -DCMAKE_TOOLCHAIN_FILE=C:\bin\programs\vcpkg\scripts\buildsystems\vcpkg.cmake

and build using cmake --build build as usual.
Note that, vcpkg will also copy the required gtest(d).dll/gtest(d)_main.dll from the install folder to the Debug/Release folders.

Test with cd build & ctest.

Body:
I have recently been sold on using CMake for compiling my C++ projects, and would now like to start writing some unit tests for my code. I have decided to use the Google Test utility to help with this, but require some help in getting started.

All day I have been reading various guides and examples include the Primer, an introduction at IBM and some questions on SO (here and here) as well as other sources I've lost track of. I realise there's plenty out there but somehow I am still having difficulties.

I'm currently trying to implement the most basic test, to confirm I've compiled/installed gtest right and it's not working. The only source file (testgtest.cpp) is taken almost exactly from this previous answer:

#include <iostream>

#include "gtest/gtest.h"

TEST(sample_test_case, sample_test)
{
    EXPECT_EQ(1, 1);
}

and my associated CMakeLists.txt is as follows:

cmake_minimum_required(VERSION 2.6)
project(basic_test)

# Setup testing
enable_testing()
find_package(GTest REQUIRED)
include_directories(${GTEST_INCLUDE_DIR})

# Add test cpp file
add_executable(runUnitTests
    testgtest.cpp
)

# Link test executable against gtest & gtest_main
target_link_libraries(runUnitTests ${GTEST_LIBRARY_DEBUG} ${GTEST_MAIN_LIBRARY_DEBUG})

add_test(
    NAME runUnitTests
    COMMAND runUnitTests
)

Note that I have chosen to link against gtest_main instead of providing the main at the end of the cpp file as I believe this will allow me to scale testing up more easily to multiple files.

When building the generated .sln file (in Visual C++ 2010 Express) I unfortunately get a long list of errors of the form

2>msvcprtd.lib(MSVCP100D.dll) : error LNK2005: "public: virtual __thiscall std::basic_iostream<char,struct std::char_traits<char> >::~basic_iostream<char,struct std::char_traits<char> >(void)" (??1?$basic_iostream@DU?$char_traits@D@std@@@std@@UAE@XZ) already defined in gtestd.lib(gtest-all.obj)

which I think means that I'm not successfully linking to the gtest libraries. I have made sure that when linking against the debug libraries, I have then tried to build in debug mode.

EDIT

Having done some more digging, I think my issue is something to do with the type of library I am building gtest into. When building gtest with CMake, if BUILD_SHARED_LIBS is un-checked, and I link my program against these .lib files I get the errors mentioned above. However, if BUILD_SHARED_LIBS is checked then I produce a set of .lib and .dll files. When now linking against these .lib files the program compiles, but when run complains that it can't find gtest.dll.

What are the differences between a SHARED and a not SHARED library, and if I choose not shared, why doesn't it work? Is there an option in the CMakeLists.txt for my project that I am missing?

Body:
The OP is using Windows, and a much easier way to use GTest today is with vcpkg+cmake.

Install vcpkg as per https://github.com/microsoft/vcpkg , and make sure you can run vcpkg from the cmd line. Take note of the vcpkg installation folder, eg. C:\bin\programs\vcpkg.

Install gtest using vcpkg install gtest: this will download, compile, and install GTest.

Use a CmakeLists.txt as below: note we can use targets instead of including folders.

cmake_minimum_required(VERSION 3.15)
project(sample CXX)
enable_testing()
find_package(GTest REQUIRED)
add_executable(test1 test.cpp source.cpp)
target_link_libraries(test1 GTest::GTest GTest::Main)
add_test(test-1 test1)

Run cmake with: (edit the vcpkg folder if necessary, and make sure the path to the vcpkg.cmake toolchain file is correct)

cmake -B build -DCMAKE_TOOLCHAIN_FILE=C:\bin\programs\vcpkg\scripts\buildsystems\vcpkg.cmake

and build using cmake --build build as usual.
Note that, vcpkg will also copy the required gtest(d).dll/gtest(d)_main.dll from the install folder to the Debug/Release folders.

Test with cd build & ctest.


问:
Missing prefix in pivot_longer with paired columns
I have a "wide" data.frame with a series of paired columns. My goal is to unpivot this using pivot_longer.
There is lot's of help for paired columns with prefixes in all columns. But in my case only half of the pairs has prefixes and I don't know how to define the "names_pattern", if this is even possible.

In the following example all paired columns have a prefix which I can split with the names_pattern attribute of pivot_longer:

```<code>df_wide <- tribble(
  ~id , ~f_start , ~d_start , ~f_end , ~d_end ,
  'A' , 'p' , '2018-01-01' , 'p' , '2018-02-01' ,
  'B' , 'i' , '2019-04-01' , 'p' , '2020-01-01' ,
  'C' , 'i' , '2018-06-01' , 'i' , '2019-03-01' ,
  'D' , 'p' , '2019-12-01' , 'p' , '2020-05-01' ,
  'E' , 'p' , '2019-02-01' , 'p' , '2019-05-01' ,
  'F' , 'i' , '2018-04-01' , 'i' , '2018-07-01' ,
)

df_wide %>%
  pivot_longer(-id ,
               names_to = c('.value' , 'status') ,
               names_pattern = '(.*)_(.*)'
               )
</code>```

This leads to my expected output:

```<code>   id    status f     d
   <chr> <chr>  <chr> <chr>
 1 A     start  p     2018-01-01
 2 A     end    p     2018-02-01
 3 B     start  i     2019-04-01
 4 B     end    p     2020-01-01
 5 C     start  i     2018-06-01
 6 C     end    i     2019-03-01
 7 D     start  p     2019-12-01
 8 D     end    p     2020-05-01
 9 E     start  p     2019-02-01
10 E     end    p     2019-05-01
11 F     start  i     2018-04-01
12 F     end    i     2018-07-01
</code>```

Unfortunately my data.frame looks like this with missing prefix in one half of the pairs.

```<code>df_wide<- tribble(
  ~id , ~f_start , ~start , ~f_end , ~end ,
  'A' , 'p' , '2018-01-01' , 'p' , '2018-02-01' ,
  'B' , 'i' , '2019-04-01' , 'p' , '2020-01-01' ,
  'C' , 'i' , '2018-06-01' , 'i' , '2019-03-01' ,
  'D' , 'p' , '2019-12-01' , 'p' , '2020-05-01' ,
  'E' , 'p' , '2019-02-01' , 'p' , '2019-05-01' ,
  'F' , 'i' , '2018-04-01' , 'i' , '2018-07-01' ,
)
</code>```

Has anyone an idea how to achieve the expected output?

Thanks in advance

答:
If we can rename the missing prefixes with rename_at, the OP's solution would work

```<code>library(dplyr)
library(tidyr)
library(stringr)
df_wide %>%
     rename_at(vars(matches('^(start|end)')), ~ str_c('d_', .)) %>%
     pivot_longer(-id ,
               names_to = c('.value' , 'status') ,
               names_pattern = '(.*)_(.*)'
               )
# A tibble: 12 x 4
#   id    status f     d
#   <chr> <chr>  <chr> <chr>
# 1 A     start  p     2018-01-01
# 2 A     end    p     2018-02-01
# 3 B     start  i     2019-04-01
# 4 B     end    p     2020-01-01
# 5 C     start  i     2018-06-01
# 6 C     end    i     2019-03-01
# 7 D     start  p     2019-12-01
# 8 D     end    p     2020-05-01
# 9 E     start  p     2019-02-01
#10 E     end    p     2019-05-01
#11 F     start  i     2018-04-01
#12 F     end    i     2018-07-01
</code>```

Body:
I have a "wide" data.frame with a series of paired columns. My goal is to unpivot this using pivot_longer.
There is lot's of help for paired columns with prefixes in all columns. But in my case only half of the pairs has prefixes and I don't know how to define the "names_pattern", if this is even possible.

In the following example all paired columns have a prefix which I can split with the names_pattern attribute of pivot_longer:

df_wide <- tribble(
  ~id , ~f_start , ~d_start , ~f_end , ~d_end ,
  'A' , 'p' , '2018-01-01' , 'p' , '2018-02-01' ,
  'B' , 'i' , '2019-04-01' , 'p' , '2020-01-01' ,
  'C' , 'i' , '2018-06-01' , 'i' , '2019-03-01' ,
  'D' , 'p' , '2019-12-01' , 'p' , '2020-05-01' ,
  'E' , 'p' , '2019-02-01' , 'p' , '2019-05-01' ,
  'F' , 'i' , '2018-04-01' , 'i' , '2018-07-01' ,
)

df_wide %>%
  pivot_longer(-id ,
               names_to = c('.value' , 'status') ,
               names_pattern = '(.*)_(.*)'
               )

This leads to my expected output:

   id    status f     d
   <chr> <chr>  <chr> <chr>
 1 A     start  p     2018-01-01
 2 A     end    p     2018-02-01
 3 B     start  i     2019-04-01
 4 B     end    p     2020-01-01
 5 C     start  i     2018-06-01
 6 C     end    i     2019-03-01
 7 D     start  p     2019-12-01
 8 D     end    p     2020-05-01
 9 E     start  p     2019-02-01
10 E     end    p     2019-05-01
11 F     start  i     2018-04-01
12 F     end    i     2018-07-01

Unfortunately my data.frame looks like this with missing prefix in one half of the pairs.

df_wide<- tribble(
  ~id , ~f_start , ~start , ~f_end , ~end ,
  'A' , 'p' , '2018-01-01' , 'p' , '2018-02-01' ,
  'B' , 'i' , '2019-04-01' , 'p' , '2020-01-01' ,
  'C' , 'i' , '2018-06-01' , 'i' , '2019-03-01' ,
  'D' , 'p' , '2019-12-01' , 'p' , '2020-05-01' ,
  'E' , 'p' , '2019-02-01' , 'p' , '2019-05-01' ,
  'F' , 'i' , '2018-04-01' , 'i' , '2018-07-01' ,
)

Has anyone an idea how to achieve the expected output?

Thanks in advance

Body:
If we can rename the missing prefixes with rename_at, the OP's solution would work

library(dplyr)
library(tidyr)
library(stringr)
df_wide %>%
     rename_at(vars(matches('^(start|end)')), ~ str_c('d_', .)) %>%
     pivot_longer(-id ,
               names_to = c('.value' , 'status') ,
               names_pattern = '(.*)_(.*)'
               )
# A tibble: 12 x 4
#   id    status f     d
#   <chr> <chr>  <chr> <chr>
# 1 A     start  p     2018-01-01
# 2 A     end    p     2018-02-01
# 3 B     start  i     2019-04-01
# 4 B     end    p     2020-01-01
# 5 C     start  i     2018-06-01
# 6 C     end    i     2019-03-01
# 7 D     start  p     2019-12-01
# 8 D     end    p     2020-05-01
# 9 E     start  p     2019-02-01
#10 E     end    p     2019-05-01
#11 F     start  i     2018-04-01
#12 F     end    i     2018-07-01


问:
Creating a div by pressing a button
I was trying to create Divs by clicking a button but it just fill the button range with red.

```<code><div class="app">
  <button onclick="createDiv()">Make a cube</button>
</div>
<script>

  function createDiv ()
  {
  var boxEle = document.querySelector('.app');
  boxEle.style.width = 100;
  boxEle.style.height = 100;
  boxEle.style.backgroundColor = '#f00';

  }
</script>
</code>```

答:
Firstly , in your function you are selecting an already created div in your html, so you are not creating a div. If you want to create a div using javascript you can do it like this. </p>

```<code>function createDiv() {
let box = document.createElement('div'); // creates div
box.classlist.add('box-styling') // you can add a class and style it using that instead
let container = document.querySelector('.container') // div has to be placed somewhere in html, so create a container and select it.
container.appendChild(box) // then append to container

}

</code>```

Title: Creating a div by pressing a button

Body:
I was trying to create Divs by clicking a button but it just fill the button range with red.

  <button onclick="createDiv()">Make a cube</button>

Body:
Firstly , in your function you are selecting an already created div in your html, so you are not creating a div. If you want to create a div using javascript you can do it like this.

function createDiv() {
let box = document.createElement('div'); // creates div
box.classlist.add('box-styling') // you can add a class and style it using that instead
let container = document.querySelector('.container') // div has to be placed somewhere in html, so create a container and select it.
container.appendChild(box) // then append to container

}


问:
place tensorflow.js into a React component
I'm looking for the simplest way to translate some vanilla tf.js into a react component.

Here is a React component:

```<code>class KMeans extends Component {
render() {
      return (
        <div className="KMeansMonitor">
        </div>
      )
  }
}
export default KMeans;
</code>```

and I have an async function to calculate MSE:

```<code>async function learnLinear(){
  const model = tf.sequential();
  model.add(tf.layers.dense({units: 1, inputShape: [1]}));
  model.compile({
   loss: 'meanSquaredError',
   optimizer: 'sgd'
  });

  const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
  const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);

  await model.fit(xs, ys, {epochs: 500});

  document.getElementById('output_field').innerText =
   model.predict(tf.tensor2d([10], [1, 1]));
 }
 learnLinear();
</code>```

I would just like to have this vanilla js running in the React component. Any help, as always, is appreciated.

答:
It's simple. Change learnLinear function so it just returns Promise with value and use necessary hooks to wait for data & update state

Example

const { useState, useEffect } = React;

async function learnLinear() {

 const model = tf.sequential();
  const layer = tf.layers.dense({units: 1, inputShape: [1]});

  model.add(layer);
  model.compile({
   loss: 'meanSquaredError',
   optimizer: 'sgd'
  });

  const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
  const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);

  await model.fit(xs, ys, {epochs: 500});
  const prediction = await model.predict(tf.tensor2d([10], [1, 1]));

  return prediction.toString();
}

const App = () => {
  const [value, setValue] = useState(null);
  const [dots, setDots] = useState(['.']);

  useEffect(() => {
    let isUnmounted = false;
    let handle = null;

    learnLinear()
      .then(result => {
        if(isUnmounted) {
          return;
        }
      console.log(result);
        setValue(result);
      });

    const dotsAnimation = () => {
      setDots(dots => {
        const newDots = [...dots, dots[0]];

        return newDots.length === 4 ? ['.'] : newDots;
        })

      handle = setTimeout(dotsAnimation, 100);
    }

    handle = setTimeout(dotsAnimation, 100);

    return () => {
      isUnmounted = true;
      clearTimeout(handle);
    }
  }, [])

return

  {value ?  value : 'Predicting value' + dots.join('')}

}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
<div id="root"></div></code>```

Body:
I'm looking for the simplest way to translate some vanilla tf.js into a react component.

Here is a React component:

class KMeans extends Component {
render() {
      return (

      )
  }
}
export default KMeans;

and I have an async function to calculate MSE:

async function learnLinear(){
  const model = tf.sequential();
  model.add(tf.layers.dense({units: 1, inputShape: [1]}));
  model.compile({
   loss: 'meanSquaredError',
   optimizer: 'sgd'
  });

  const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
  const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);

  await model.fit(xs, ys, {epochs: 500});

  document.getElementById('output_field').innerText =
   model.predict(tf.tensor2d([10], [1, 1]));
 }
 learnLinear();

I would just like to have this vanilla js running in the React component. Any help, as always, is appreciated.

Body:
It's simple. Change learnLinear function so it just returns Promise with value and use necessary hooks to wait for data & update state

Example

const { useState, useEffect } = React;

async function learnLinear() {

 const model = tf.sequential();
  const layer = tf.layers.dense({units: 1, inputShape: [1]});

  model.add(layer);
  model.compile({
   loss: 'meanSquaredError',
   optimizer: 'sgd'
  });

  const xs = tf.tensor2d([-1, 0, 1, 2, 3, 4], [6, 1]);
  const ys = tf.tensor2d([-3, -1, 1, 3, 5, 7], [6, 1]);

  await model.fit(xs, ys, {epochs: 500});
  const prediction = await model.predict(tf.tensor2d([10], [1, 1]));

  return prediction.toString();
}

const App = () => {
  const [value, setValue] = useState(null);
  const [dots, setDots] = useState(['.']);

  useEffect(() => {
    let isUnmounted = false;
    let handle = null;

    learnLinear()
      .then(result => {
        if(isUnmounted) {
          return;
        }
      console.log(result);
        setValue(result);
      });

    const dotsAnimation = () => {
      setDots(dots => {
        const newDots = [...dots, dots[0]];

        return newDots.length === 4 ? ['.'] : newDots;
        })

      handle = setTimeout(dotsAnimation, 100);
    }

    handle = setTimeout(dotsAnimation, 100);

    return () => {
      isUnmounted = true;
      clearTimeout(handle);
    }
  }, [])

return <div>
  {value ?  value : 'Predicting value' + dots.join('')}
</div>
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );

<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
<div id="root"></div>