问:
How to replace characters by strtok function - C?
I really want to change all spaces ' ' in my char array for NULL -

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

void ReplaceCharactersInString(char *pcString, char *cOldChar, char *cNewChar) {
    char *p = strtok(pcString, cOldChar);
    strcpy(pcString, p);
    while (p != NULL) {
        strcat(pcString, p);
        p = strtok(cNewChar, cOldChar);
    }
}

int main() {
    char pcString[] = "I am testing";
    ReplaceCharactersInString(pcString, " ", NULL);
    printf(pcString);
}
</code>```

OUTPUT: Iamtesting

If I simply put the printf(p) function before:

```<code>p = strtok(cNewChar, cOldChar);
</code>```

In the result I  have what I need - but the problem is how to store it in pcString (directly)?

Or there is maybe a better solution to simply do it?

答:
While some functions expect a [single] string to be pre-parsed to: I\0am\0testing, that is rare.

And, if you have multiple spaces/delimiters, you'll get (e.g.) foo\0\0bar, which you probably don't want.

And, your printf in main will only print the first token in the string because it will stop on the first EOS (i.e. '\0').

(i.e.) You probably don't want strcpy/strcat.

More likely, you want to fill an array of char * pointers to the tokens you parse.

So, you'd want to pass down char **argv, then do: argv[argc++] = strtok(...); and then do: return argc

Here's how I would refactor your code:

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

#define ARGMAX  100

int
ReplaceCharactersInString(int argmax,char **argv,char *pcString,
    const char *delim)
{
    char *p;
    int argc;

    // allow space for NULL termination
    --argmax;

    for (argc = 0;  argc < argmax;  ++argc, ++argv) {
        // get next token
        p = strtok(pcString,delim);
        if (p == NULL)
            break;

        // zap the buffer pointer
        pcString = NULL;

        // store the token in the [returned] array
        *argv = p;
    }

    *argv = NULL;

    return argc;
}

int
main(void)
{
    char pcString[] = "I am testing";
    int argc;
    char **av;
    char *argv[ARGMAX];

    argc = ReplaceCharactersInString(ARGMAX,argv,pcString," ");

    printf("argc: %d\n",argc);
    for (av = argv;  *av != NULL;  ++av)
        printf("'%s'\n",*av);

    return 0;
}
</code>```

Here's the output:

```<code>argc: 3
'I'
'am'
'testing'
</code>```

Body:
I really want to change all spaces ' ' in my char array for NULL -

#include <string.h>

void ReplaceCharactersInString(char *pcString, char *cOldChar, char *cNewChar) {
    char *p = strtok(pcString, cOldChar);
    strcpy(pcString, p);
    while (p != NULL) {
        strcat(pcString, p);
        p = strtok(cNewChar, cOldChar);
    }
}

int main() {
    char pcString[] = "I am testing";
    ReplaceCharactersInString(pcString, " ", NULL);
    printf(pcString);
}

OUTPUT: Iamtesting

If I simply put the printf(p) function before:

p = strtok(cNewChar, cOldChar);

In the result I  have what I need - but the problem is how to store it in pcString (directly)?

Or there is maybe a better solution to simply do it?

Body:
While some functions expect a [single] string to be pre-parsed to: I\0am\0testing, that is rare.

And, if you have multiple spaces/delimiters, you'll get (e.g.) foo\0\0bar, which you probably don't want.

And, your printf in main will only print the first token in the string because it will stop on the first EOS (i.e. '\0').

(i.e.) You probably don't want strcpy/strcat.

More likely, you want to fill an array of char * pointers to the tokens you parse.

So, you'd want to pass down char **argv, then do: argv[argc++] = strtok(...); and then do: return argc

Here's how I would refactor your code:

#include <stdio.h>
#include <string.h>

#define ARGMAX  100

int
ReplaceCharactersInString(int argmax,char **argv,char *pcString,
    const char *delim)
{
    char *p;
    int argc;

    // allow space for NULL termination
    --argmax;

    for (argc = 0;  argc < argmax;  ++argc, ++argv) {
        // get next token
        p = strtok(pcString,delim);
        if (p == NULL)
            break;

        // zap the buffer pointer
        pcString = NULL;

        // store the token in the [returned] array
        *argv = p;
    }

    *argv = NULL;

    return argc;
}

int
main(void)
{
    char pcString[] = "I am testing";
    int argc;
    char **av;
    char *argv[ARGMAX];

    argc = ReplaceCharactersInString(ARGMAX,argv,pcString," ");

    printf("argc: %d\n",argc);
    for (av = argv;  *av != NULL;  ++av)
        printf("'%s'\n",*av);

    return 0;
}

Here's the output:

argc: 3
'I'
'am'
'testing'


来源: stackexchange

问:
how to remove Nan Value in python?
```<code>missing_values=['NAN','NaN','Nan',"na",np.nan]

df=pd.read_csv('train.csv',na_values=missing_values )

df.fillna(df['column_name'].mean())

df.isnull().sum(axis = 0)
</code>```

also tried to dropna nothing seems to work df still has missing values

答:
When you do the fillna please assign it back or add inplace

```<code>df.fillna(df['column_name'].mean(),inplace=True)
df=df.fillna(df['column_name'].mean())
</code>```

ContentLicense: CC BY-SA 4.0

Title: how to remove Nan Value in python?

Body:
missing_values=['NAN','NaN','Nan',"na",np.nan]

df=pd.read_csv('train.csv',na_values=missing_values )

df.fillna(df['column_name'].mean())

df.isnull().sum(axis = 0)

also tried to dropna nothing seems to work df still has missing values

Body:
When you do the fillna please assign it back or add inplace

df.fillna(df['column_name'].mean(),inplace=True)
df=df.fillna(df['column_name'].mean())


问:
Reload the page just once if a div is above certain position
I want to reload the page only once if a given div is positioned higher than position:absolute; top:15%.

I think this could be done with jQuery's .css method, something like:

```<code>if ('#mydive').css('top') > '15%' {
    //reload the page
}
</code>```

Could someone suggest a simple solution, preferably jQuery or pure JavaScript?

答:
the above answers point you in the right way, but in order to  "reload the page only once", you need an extra ingredient. you need a way to store a flag that points out whether the page has already been reloaded or not.

Say you follow tradyblix's code.

You should check for that flag before reloading your page :

```<code>if (hasReloaded() && $('#yourdiv').offset().top > ($(document).height() * percent)) {
     reload();
}
</code>```

where hasReloaded is a function that determins if the page has been reloaded, and it can be  either a function that sends an ajax request to a server, that checks a cookie or even the localStorage object:

```<code>function hasReloaded(){
    return !!localStorage['reloaded'];
}
</code>```

In order to set that flag, your reload function needs to access the localStorage (or cookie or ajax server response) :

```<code>function reload(){
    localStorage['reloaded'] = true;
    window.location.reload();
}
</code>```

This is just a sketch of  how you should write this functionality.

ContentLicense: CC BY-SA 3.0

Body:
I want to reload the page only once if a given div is positioned higher than position:absolute; top:15%.

I think this could be done with jQuery's .css method, something like:

if ('#mydive').css('top') > '15%' {
    //reload the page
}

Could someone suggest a simple solution, preferably jQuery or pure JavaScript?

Body:
the above answers point you in the right way, but in order to  "reload the page only once", you need an extra ingredient. you need a way to store a flag that points out whether the page has already been reloaded or not.

Say you follow tradyblix's code.

You should check for that flag before reloading your page :

if (hasReloaded() && $('#yourdiv').offset().top > ($(document).height() * percent)) {
     reload();
}

where hasReloaded is a function that determins if the page has been reloaded, and it can be  either a function that sends an ajax request to a server, that checks a cookie or even the localStorage object:

function hasReloaded(){
    return !!localStorage['reloaded'];
}

In order to set that flag, your reload function needs to access the localStorage (or cookie or ajax server response) :

function reload(){
    localStorage['reloaded'] = true;
    window.location.reload();
}

This is just a sketch of  how you should write this functionality.


问:
Map react data to single array
So I am trying to create a simple array that lists all the items that have been mapped. All other options around here seem much to complex for what I'm trying to do.

The code that gets my data is:

```<code>componentDidMount() {
    fetch('http://localhost:9000/api/get/locations')
      .then(res => res.json())
      .then(res => {
        if (res && res.data) {
          this.setState({ apiResponse: [...this.state.apiResponse, ...res.data] })
        }
      });
  }
</code>```

I can them map it into something like a list using this code:

```<code>getLocations() {
    if (this.state.apiResponse.length <= 0) {
      return <div>Loading...</div>
    } else {
      return this.state.apiResponse.map((val, key) => {
        return <li key={key}> {val.name} </li>
      })
    }
  }
</code>```

However, I want to have an array that such as "locations" So that each value is mapped to an item in an array.

Example (of code that would not work):

```<code>const locations = []

setLocations() {
    if (this.state.apiResponse.length <= 0) {
      return <div>Loading...</div>
    } else {
      return this.state.apiResponse.map((val, key) => {
        return locations = [...locations, ...{id: key, value: val.name, isChecked=false}]
      })
    }
  }

# Output:

locations = [
    {id: 1, value: "val1", isChecked=false},
    {id: 2, value: "val2", isChecked=false},
    {id: 3, value: "val3", isChecked=false},
    {id: 4, value: "val4", isChecked=false}
]
</code>```

Is there a way to do this simply? or another way to go around doing it?

答:
You can take the desired output using a map like this, in fact this the basic usage of map,

```<code>setLocations() {
    if (this.state.apiResponse.length <= 0) {
      locations = [];
    } else {
      locations = this.state.apiResponse.map((val, key) => {id: key, value: val.name, isChecked=false});
    }
  }
</code>```

this will give an output like this:

```<code>locations = [
    {id: 1, value: "val1", isChecked=false},
    {id: 2, value: "val2", isChecked=false},
    {id: 3, value: "val3", isChecked=false},
    {id: 4, value: "val4", isChecked=false}
]
</code>```

please let me know if you need more information.

Title: Map react data to single array

Body:
So I am trying to create a simple array that lists all the items that have been mapped. All other options around here seem much to complex for what I'm trying to do.

The code that gets my data is:

componentDidMount() {
    fetch('http://localhost:9000/api/get/locations')
      .then(res => res.json())
      .then(res => {
        if (res && res.data) {
          this.setState({ apiResponse: [...this.state.apiResponse, ...res.data] })
        }
      });
  }

I can them map it into something like a list using this code:

getLocations() {
    if (this.state.apiResponse.length <= 0) {
      return
Loading...

    } else {
      return this.state.apiResponse.map((val, key) => {
        return
 {val.name}

      })
    }
  }

However, I want to have an array that such as "locations" So that each value is mapped to an item in an array.

Example (of code that would not work):

const locations = []

setLocations() {
    if (this.state.apiResponse.length <= 0) {
      return
Loading...

    } else {
      return this.state.apiResponse.map((val, key) => {
        return locations = [...locations, ...{id: key, value: val.name, isChecked=false}]
      })
    }
  }

# Output:

locations = [
    {id: 1, value: "val1", isChecked=false},
    {id: 2, value: "val2", isChecked=false},
    {id: 3, value: "val3", isChecked=false},
    {id: 4, value: "val4", isChecked=false}
]

Is there a way to do this simply? or another way to go around doing it?

Body:
You can take the desired output using a map like this, in fact this the basic usage of map,

setLocations() {
    if (this.state.apiResponse.length <= 0) {
      locations = [];
    } else {
      locations = this.state.apiResponse.map((val, key) => {id: key, value: val.name, isChecked=false});
    }
  }

this will give an output like this:

locations = [
    {id: 1, value: "val1", isChecked=false},
    {id: 2, value: "val2", isChecked=false},
    {id: 3, value: "val3", isChecked=false},
    {id: 4, value: "val4", isChecked=false}
]

please let me know if you need more information.


问:
Android Simulator not run, become Hyper-V not available in Windows 10 Home
I'm studying React Native.
Unfortunately Windows 10 Home is not Support Hyper-V. Since, i can't use Android Studio Simulator.
Is there any way to run Simulator.</p>

答:
Sorry, mine was AMD Processor, for AMD HAXM no need, instead have to install Hypervision for AMD Processor in Sdk tool.
It worked.</p>


问:
Update global variable by using a interface
I have a async class in my MainActivity.java

```<code>class Register extends AsyncTask<String, String, JSONObject> {
JSONObject json;

     @Override
     protected JSONObject doInBackground(String[] args) {

         String function = args[3];
         String email = args[2];
         String password = args[1];
         String name = args[0];

         ContentValues params = new ContentValues();
         params.put("username", name);
         params.put("password", password);
         params.put("function", function);
         if (email.length() > 0)
             params.put("email", email);

         String URL = "https://lamp.ms.wits.ac.za/home/s2090704/index.php";
         new PhpHandler().makeHttpRequest(act, URL, params, new RequestHandler() {
             @Override
             public void processRequest(String response) throws JSONException {
                json = new JSONObject(response);
                 System.out.println(json); //outputs {response: " ...",message:"..."}

             }
         });
         System.out.println(json); //outputs null
         return json;
     }
}

</code>```

in doInBackground() PhpHandler processes details using OkHttp.

```<code>public class PhpHandler {

    JSONObject json;
    static String responseData = "";

    public void makeHttpRequest(final Activity a, String url,
                                      ContentValues params, final RequestHandler rh) {

        // Making HTTP request
            OkHttpClient client = new OkHttpClient();
            FormBody.Builder builder = new FormBody.Builder();

            for (String key : params.keySet()) {
                builder.add(key, params.getAsString(key));
            }

            final Request request = new Request.Builder()
                    .url(url)
                    .post(builder.build())
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {

                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    responseData = Objects.requireNonNull(response.body()).string();
                    //System.out.println(responseData);
                   a.runOnUiThread(new Runnable() {
                       @Override
                       public void run() {
                           try {
                               rh.processRequest(responseData);
                           } catch (JSONException e) {
                               e.printStackTrace();
                           }
                       }
                   });
                }
            });

    }
}

</code>```

RequestHandler is an interface that processes request on the mainUiThread.

```<code>package com.example.registration;

import org.json.JSONException;

public interface RequestHandler{
   void processRequest(String response) throws JSONException;
}
</code>```

Now json doesn't update out of the processRequest method in doInBackground method of my async class Register.I know that interfaces make variables static and final is there any way to update the value of json?

答:
processRequest method will be executed long after you return json from doInBackground, because makeHttpRequest performs an asynchronous http request.

Knowing this, you will probably want to re-design this class (there is no need to wrap already asynchronous request in AsyncTask), but if you really want to do it this way, you would have to wait for your request to complete before returning the json (for example, by using CountDownLatch).

  CountDownLatch latch = new CountDownLatch(1);
  someField = null;
  AtomicReference<String> someValue = new AtomicReference<>();

  // don't start new threads like this, im just trying to keep this example simple
  new Thread() {
    Thread.sleep(1000); // sleep for 1 second
    someValue.set("abc"); // notice that because when using AtomicReference you assign it's value using `set` method instead of `=` operator, you can keep it as local variable instead of field class
    latch.countDown(); // reduce latch count by one
  }.run();

  System.out.println(someValue.get()); // null - because the assignation will happen in one second

  latch.await(); // this will force current thread to wait until the latch count reaches zero (initial was 1, passed to constructor)

  System.out.println(someValue.get()); // "abc"
```

read more

Body:
I have a async class in my MainActivity.java

class Register extends AsyncTask<String, String, JSONObject> {
JSONObject json;

     @Override
     protected JSONObject doInBackground(String[] args) {

         String function = args[3];
         String email = args[2];
         String password = args[1];
         String name = args[0];

         ContentValues params = new ContentValues();
         params.put("username", name);
         params.put("password", password);
         params.put("function", function);
         if (email.length() > 0)
             params.put("email", email);

         String URL = "https://lamp.ms.wits.ac.za/home/s2090704/index.php";
         new PhpHandler().makeHttpRequest(act, URL, params, new RequestHandler() {
             @Override
             public void processRequest(String response) throws JSONException {
                json = new JSONObject(response);
                 System.out.println(json); //outputs {response: " ...",message:"..."}

             }
         });
         System.out.println(json); //outputs null
         return json;
     }
}

in doInBackground() PhpHandler processes details using OkHttp.

public class PhpHandler {

    JSONObject json;
    static String responseData = "";

    public void makeHttpRequest(final Activity a, String url,
                                      ContentValues params, final RequestHandler rh) {

        // Making HTTP request
            OkHttpClient client = new OkHttpClient();
            FormBody.Builder builder = new FormBody.Builder();

            for (String key : params.keySet()) {
                builder.add(key, params.getAsString(key));
            }

            final Request request = new Request.Builder()
                    .url(url)
                    .post(builder.build())
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {

                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    responseData = Objects.requireNonNull(response.body()).string();
                    //System.out.println(responseData);
                   a.runOnUiThread(new Runnable() {
                       @Override
                       public void run() {
                           try {
                               rh.processRequest(responseData);
                           } catch (JSONException e) {
                               e.printStackTrace();
                           }
                       }
                   });
                }
            });

    }
}

RequestHandler is an interface that processes request on the mainUiThread.

package com.example.registration;

import org.json.JSONException;

public interface RequestHandler{
   void processRequest(String response) throws JSONException;
}

Now json doesn't update out of the processRequest method in doInBackground method of my async class Register.I know that interfaces make variables static and final is there any way to update the value of json?

Body:
processRequest method will be executed long after you return json from doInBackground, because makeHttpRequest performs an asynchronous http request.

Knowing this, you will probably want to re-design this class (there is no need to wrap already asynchronous request in AsyncTask), but if you really want to do it this way, you would have to wait for your request to complete before returning the json (for example, by using CountDownLatch).

  CountDownLatch latch = new CountDownLatch(1);
  someField = null;
  AtomicReference<String> someValue = new AtomicReference<>();

  // don't start new threads like this, im just trying to keep this example simple
  new Thread() {
    Thread.sleep(1000); // sleep for 1 second
    someValue.set("abc"); // notice that because when using AtomicReference you assign it's value using `set` method instead of `=` operator, you can keep it as local variable instead of field class
    latch.countDown(); // reduce latch count by one
  }.run();

  System.out.println(someValue.get()); // null - because the assignation will happen in one second

  latch.await(); // this will force current thread to wait until the latch count reaches zero (initial was 1, passed to constructor)

  System.out.println(someValue.get()); // "abc"

read more


问:
Optional Binding in SwiftUI
I am trying to create an extension on Binding so I can unwrap and bind to the optional Binding.

I have the following code which I got from StackOverFlow.

```<code>extension Binding {

    static func ??<T>(lhs: Binding<Optional<T>>, rhs: T) -> Binding<T> {

        return Binding(
            get: { lhs.wrappedValue ?? rhs },
            set: { lhs.wrappedValue = $0 }
        )

    }
}
</code>```

But I get following error:

答:
When you use the initializer of Binding(...), it infers its type parameter to be Value (remember, Binding is itself a generic, and Value is its type parameter), so in effect it does this:

```<code>Binding<Value>(...)
</code>```

but expects the return to be Binding<T>.

So, you can either explicitly use Binding<T>(...), or just let the compiler infer it based on the return value of the function:

```<code>static func ??<T>(lhs: Binding<Optional<T>>, rhs: T) -> Binding<T> {
   .init(get { lhs.wrappedValue ?? rhs },
         set { lhs.wrappedValue = $0 })
}
</code>```

Or, just use Value instead of T:

```<code>static func ??(lhs: Binding<Optional<Value>>, rhs: Value) -> Binding<Value> {
   Binding(get { lhs.wrappedValue ?? rhs },
           set { lhs.wrappedValue = $0 })
}
</code>```

Title: Optional Binding in SwiftUI

Body:
I am trying to create an extension on Binding so I can unwrap and bind to the optional Binding.

I have the following code which I got from StackOverFlow.

extension Binding {

    static func ??<T>(lhs: Binding<Optional<T>>, rhs: T) -> Binding<T> {

        return Binding(
            get: { lhs.wrappedValue ?? rhs },
            set: { lhs.wrappedValue = $0 }
        )

    }
}

But I get following error:

Body:
When you use the initializer of Binding(...), it infers its type parameter to be Value (remember, Binding is itself a generic, and Value is its type parameter), so in effect it does this:

Binding<Value>(...)

but expects the return to be Binding<T>.

So, you can either explicitly use Binding<T>(...), or just let the compiler infer it based on the return value of the function:

static func ??<T>(lhs: Binding<Optional<T>>, rhs: T) -> Binding<T> {
   .init(get { lhs.wrappedValue ?? rhs },
         set { lhs.wrappedValue = $0 })
}

Or, just use Value instead of T:

static func ??(lhs: Binding<Optional<Value>>, rhs: Value) -> Binding<Value> {
   Binding(get { lhs.wrappedValue ?? rhs },
           set { lhs.wrappedValue = $0 })
}


问:
Convert timestamp to datetime changing format
I have a timestamp 2020-01-08T16:06:00+00:00 format value, I want to convert it to datetime format as 2020-01-08 16:06:00.

I have tried to convert to datetime, but getting error says:

failed when converting date and/or time from character string.

I would like to convert timestamp to datetime.

答:
If you don't care about the timezone, you can use:</p>

```<code>select convert(datetime, left('2020-01-08T16:06:00+00:00', 19))
</code>```

Body:
If you don't care about the timezone, you can use:

select convert(datetime, left('2020-01-08T16:06:00+00:00', 19))


问:
How to resolve dependency in asp.net mvc when can only access Interfaces and don't have access to implementation classes of them
I have injected(AccountAccessInterface) interface in the constructor when I run API I can't resolve its dependency as this interface I am getting from .dll and don't have access to its implementation. So I need some way so that I can resolve dependency   inside controller in any way Please as without having implementation(hidden implementation) class of interface I face error in APIs of dependency resolver

```<code>public class AdminController : ApiController
{
    private readonly AccountAccessInterface _accountAccessInterface;

    public AdminController(AccountAccessInterface accountAccessInterface)
    {
        _accountAccessInterface = accountAccessInterface;
    }

    // to get account if by user id
   [Route("api/admin/ProcessTrsanctionAndSave")]
   [HttpGet]
    public void ProcessTrsanctionAndSave()
    {

        BankDB.BankDB bankDB = new BankDB.BankDB();
        bankDB.ProcessAllTransactions();
        bankDB.SaveToDisk();
    }
}
</code>```

答:
The Dependency service can only resolve services it is provided, it cannot magically create one for you.

If you cannot create an instance of the class you're trying to resolve through the interface then I'm afraid there's nothing you can do.

However, if you can instantiate the class then you can create a wrapper around it and pass that to the dependency service.

Body:
I have injected(AccountAccessInterface) interface in the constructor when I run API I can't resolve its dependency as this interface I am getting from .dll and don't have access to its implementation. So I need some way so that I can resolve dependency   inside controller in any way Please as without having implementation(hidden implementation) class of interface I face error in APIs of dependency resolver

public class AdminController : ApiController
{
    private readonly AccountAccessInterface _accountAccessInterface;

    public AdminController(AccountAccessInterface accountAccessInterface)
    {
        _accountAccessInterface = accountAccessInterface;
    }

    // to get account if by user id
   [Route("api/admin/ProcessTrsanctionAndSave")]
   [HttpGet]
    public void ProcessTrsanctionAndSave()
    {

        BankDB.BankDB bankDB = new BankDB.BankDB();
        bankDB.ProcessAllTransactions();
        bankDB.SaveToDisk();
    }
}


问:
How to resolve the issue regarding Tensorflow and cuda compatibility?
Error :

UnknownError: Failed to get convolution algorithm. This is probably
  because cuDNN failed to initialize, so try looking to see if a warning
  log message was printed above. [Op:Conv2D]

command used for package installation :

```<code>conda install -c anaconda keras-gpu
</code>```

Installed :

tensorflow 2.0.0

cudatoolkit 10.0.130 0

cudnn 7.6.5

cuda10.0_0

keras-gpu 2.2.4 0

tf.test.is_gpu_available()
returns True

答:
UnknownError: Failed to get convolution algorithm. This is probably
  because cuDNN failed to initialize, so try looking to see if a warning
  log message was printed above. [Op:Conv2D]

Generally this problem appears due to incompatibility between CUDA and cuDNN drivers installed. Please refer tested build configuration for Linux an CPU.

If tf.test.is_gpu_available() returns True means, there is nothing wrong with  installation.

So in the next step, you can try GPU memory resources management by allowing GPU memory growth.

It can be done by calling tf.config.experimental.set_memory_growth, which attempts to allocate only as much GPU memory as needed for the runtime allocations: it starts out allocating very little memory, and as the program gets run and more GPU memory is needed, we extend the GPU memory region allocated to the TensorFlow process.

To turn on memory growth for a specific GPU, use the following code prior to allocating any tensors or executing any ops.

```<code>gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  try:
    # Currently, memory growth needs to be the same across GPUs
    for gpu in gpus:
      tf.config.experimental.set_memory_growth(gpu, True)
    logical_gpus = tf.config.experimental.list_logical_devices('GPU')
    print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
  except RuntimeError as e:
    # Memory growth must be set before GPUs have been initialized
    print(e)
</code>```

Another method to enable memory growth is to set the environmental variable TF_FORCE_GPU_ALLOW_GROWTH to true. This configuration is platform specific.

In this method to configure a virtual GPU device with tf.config.experimental.set_virtual_device_configuration and set a hard limit on the total memory to allocate on the GPU.

```<code>gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  # Restrict TensorFlow to only allocate 1GB of memory on the first GPU
  try:
    tf.config.experimental.set_virtual_device_configuration(
        gpus[0],
        [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)])
    logical_gpus = tf.config.experimental.list_logical_devices('GPU')
    print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
  except RuntimeError as e:
    # Virtual devices must be set before GPUs have been initialized
    print(e)
</code>```

For more details please refer here

One suggestion here, you can try installing tensorflow-gpu instead of keras-gpu.

Body:
Error :

UnknownError: Failed to get convolution algorithm. This is probably
  because cuDNN failed to initialize, so try looking to see if a warning
  log message was printed above. [Op:Conv2D]

command used for package installation :

conda install -c anaconda keras-gpu

Installed :

tensorflow 2.0.0

cudatoolkit 10.0.130 0

cudnn 7.6.5

cuda10.0_0

keras-gpu 2.2.4 0

tf.test.is_gpu_available()
returns True

Body:
UnknownError: Failed to get convolution algorithm. This is probably
  because cuDNN failed to initialize, so try looking to see if a warning
  log message was printed above. [Op:Conv2D]

Generally this problem appears due to incompatibility between CUDA and cuDNN drivers installed. Please refer tested build configuration for Linux an CPU.

If tf.test.is_gpu_available() returns True means, there is nothing wrong with  installation.

So in the next step, you can try GPU memory resources management by allowing GPU memory growth.

It can be done by calling tf.config.experimental.set_memory_growth, which attempts to allocate only as much GPU memory as needed for the runtime allocations: it starts out allocating very little memory, and as the program gets run and more GPU memory is needed, we extend the GPU memory region allocated to the TensorFlow process.

To turn on memory growth for a specific GPU, use the following code prior to allocating any tensors or executing any ops.

gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  try:
    # Currently, memory growth needs to be the same across GPUs
    for gpu in gpus:
      tf.config.experimental.set_memory_growth(gpu, True)
    logical_gpus = tf.config.experimental.list_logical_devices('GPU')
    print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
  except RuntimeError as e:
    # Memory growth must be set before GPUs have been initialized
    print(e)

Another method to enable memory growth is to set the environmental variable TF_FORCE_GPU_ALLOW_GROWTH to true. This configuration is platform specific.

In this method to configure a virtual GPU device with tf.config.experimental.set_virtual_device_configuration and set a hard limit on the total memory to allocate on the GPU.

gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  # Restrict TensorFlow to only allocate 1GB of memory on the first GPU
  try:
    tf.config.experimental.set_virtual_device_configuration(
        gpus[0],
        [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)])
    logical_gpus = tf.config.experimental.list_logical_devices('GPU')
    print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
  except RuntimeError as e:
    # Virtual devices must be set before GPUs have been initialized
    print(e)

For more details please refer here

One suggestion here, you can try installing tensorflow-gpu instead of keras-gpu.


问:
How do I solve a function for a given x?
I have been browsing through quite some help pages, but I did not find the solution for my - probably - simple problem.
I defined a function

```<code>funB <- function(x) (0.8042851 +
    ((3.9417843-0.8042851)/(1+((x/0.4039609)^(-3.285016)))))
</code>```

and would like to solve it for a given x (say, x = 0.2).
How do I do that? I have looked at uniroot() and polyroot(), but they did not seem to fit my function.

答:
Well, I guess I must like doing things the hard way. I just rearranged your function to find its inverse:

```<code>funC <- function(y) (((3.137499)/(y - 0.8042851) - 1)^(-1/3.285016)) * 0.4039609
</code>```

So if I want to know when funB(x) == 3.7 I can do:

```<code>funC(3.7)
#> [1] 0.860193
</code>```

and sure enough

```<code>funB(0.860193)
#> [1] 3.7
</code>```

or indeed

```<code>funB(funC(1))
#> [1] 1
</code>```

And as others have pointed out, x doesn't have a real value at funB(x) == 0.2 as you can see in this plot:

```<code>curve(funC, 0, 4)
</code>```

Now, if you really want to know the complex root where funB(x) == 0.2 then you can modify funC like so:

```<code>funC <- function(y) (((3.137499)/(as.complex(y) - 0.8042851) - 1)^(-1/3.285016)) * 0.4039609
</code>```

So now:

```<code>funC(0.2)
#> [1] 0.1336917+0.1894797i
</code>```

And therefore the answer to your question is 0.1336917 +/- 0.1894797i

```<code>funB(complex(real = 0.133691691, imaginary = 0.1894797))
[1] 0.1999996+0i
</code>```

Close enough.

Body:
I have been browsing through quite some help pages, but I did not find the solution for my - probably - simple problem.
I defined a function

funB <- function(x) (0.8042851 +
    ((3.9417843-0.8042851)/(1+((x/0.4039609)^(-3.285016)))))

and would like to solve it for a given x (say, x = 0.2).
How do I do that? I have looked at uniroot() and polyroot(), but they did not seem to fit my function.

Body:
Well, I guess I must like doing things the hard way. I just rearranged your function to find its inverse:

funC <- function(y) (((3.137499)/(y - 0.8042851) - 1)^(-1/3.285016)) * 0.4039609

So if I want to know when funB(x) == 3.7 I can do:

funC(3.7)
#> [1] 0.860193

and sure enough

funB(0.860193)
#> [1] 3.7

or indeed

funB(funC(1))
#> [1] 1

And as others have pointed out, x doesn't have a real value at funB(x) == 0.2 as you can see in this plot:

curve(funC, 0, 4)

Now, if you really want to know the complex root where funB(x) == 0.2 then you can modify funC like so:

funC <- function(y) (((3.137499)/(as.complex(y) - 0.8042851) - 1)^(-1/3.285016)) * 0.4039609

So now:

funC(0.2)
#> [1] 0.1336917+0.1894797i

And therefore the answer to your question is 0.1336917 +/- 0.1894797i

funB(complex(real = 0.133691691, imaginary = 0.1894797))
[1] 0.1999996+0i

Close enough.


答:
Try this instead:</p>

```<code>this.state.apiResponse.map((val, key) => {
        return locations = [...locations, ...[{id: key, value: val.name, isChecked=false}]]
})
</code>```

Title: Map react data to single array

Body:
Try this instead:

this.state.apiResponse.map((val, key) => {
        return locations = [...locations, ...[{id: key, value: val.name, isChecked=false}]]
})


问:
reload vue component from outside
I have a laravel vue project that displays a list of items in a component. The component when mounted makes an ajax call to populate the data element. However, there's other items on the page (not in vue) that can add elements to the database, and I'd like to make sure the list is reactive in the component.

```<code>mounted() {
    this.getTasks();
},
methods: {
    getTasks() {
        let self = this;
        axios.get('/tasks').then(response => {
            self.tasks = response.data;
        })
        .catch(function (error) {
            console.log(error);
        });
    },
}
</code>```

When the user does an action that would add a task to the list, is there a way to fire the getTasks method on the component from outside the component?

答:
You should use vuex actions.

Here's an example:

```<code>Vue.component('ChildB',{
  template:`
    <div class="child childB">
      <h1> Score: {{ score }} </h1>
      <button @click="changeScore">Change Score</button>
    </div>`,
  computed: {
    score () {
      return this.$store.getters.score
    }
  },
  methods: {
    changeScore () {
      this.$store.dispatch('incrementScore', 3000)
    }
  }
})
</code>```

full source:

https://codepen.io/tutsplus/pen/MXpPLz

Title: reload vue component from outside

Body:
I have a laravel vue project that displays a list of items in a component. The component when mounted makes an ajax call to populate the data element. However, there's other items on the page (not in vue) that can add elements to the database, and I'd like to make sure the list is reactive in the component.

mounted() {
    this.getTasks();
},
methods: {
    getTasks() {
        let self = this;
        axios.get('/tasks').then(response => {
            self.tasks = response.data;
        })
        .catch(function (error) {
            console.log(error);
        });
    },
}

When the user does an action that would add a task to the list, is there a way to fire the getTasks method on the component from outside the component?

Body:
You should use vuex actions.

Here's an example:

Vue.component('ChildB',{
  template:`
    <div class="child childB">
      <h1> Score: {{ score }} </h1>
      <button @click="changeScore">Change Score</button>
    </div>`,
  computed: {
    score () {
      return this.$store.getters.score
    }
  },
  methods: {
    changeScore () {
      this.$store.dispatch('incrementScore', 3000)
    }
  }
})

full source:

https://codepen.io/tutsplus/pen/MXpPLz


问:
How to Change name of the NetConnectionProfile Using Set-NetConnectionProfile in PowerShell
I Tried Using  How to Change name of the NetConnectionProfile Using Set-NetConnectionProfile

```<code>$Profile=Get-NetConnectionProfile -InterfaceIndex 35
$Profile.Name = "Network1"
</code>```

The Error is

```<code>"Name" is a ReadOnly property.
 At line:1 char:1
+ $Profile.Name = "Network1"
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) []
+ FullyQualifiedErrorId : ReadOnlyCIMProperty
</code>```

How to Change the Read only Property of the name?? Help Me

答: This attribute could be manually changed using secpol. So, I don't think this couldn't be changed. I only have to know HOW. :-)</p>

Body:
I Tried Using  How to Change name of the NetConnectionProfile Using Set-NetConnectionProfile

$Profile=Get-NetConnectionProfile -InterfaceIndex 35
$Profile.Name = "Network1"

The Error is

"Name" is a ReadOnly property.
 At line:1 char:1
+ $Profile.Name = "Network1"
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) []
+ FullyQualifiedErrorId : ReadOnlyCIMProperty

How to Change the Read only Property of the name?? Help Me


问:
Entity Framework Core Error: An error occurred using the connection to database '' on server 'localhost'
I have made an ASP.NET Core 3.1 Web-based application and want to use MySQL as the database.

I have been following along with some YouTube tutorials on creating MySQL database with ASP.NET Core 3.1 [code first approach] including a tutorial from this site:

https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-3.1&tabs=visual-studio

I have created a DataModel Class, added a service to UseMySQL to the Startup.cs Class and created an AppDBContext Class that implements DbContext Class.

When I run this command in the Package Manager Console: Add-Migration InitialDatabase the application is creating a migration successfully.

When I run update-database it is throwing this exception:

```<code>fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
      An error occurred using the connection to database '' on server 'localhost'.
An error occurred using the connection to database '' on server 'localhost'.
System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseMySQL' call.
</code>```

When I call the EnableRetryOnFailure(); function as required, I am facing this exception:

fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
        An error occurred using the connection to database '' on server 'localhost'. An error occurred using the connection to database '' on
  server 'localhost'.

What could be the issue?
Where am I getting it wrong?

If you have links to useful articles about using MySQL Database with ASP.NET Core I would appreciate or your help on this particular issue.

I am using Visual Studio IDE 2019 and ASP.NET Core 3.1.1

Additional Code:

This is the Startup.cs Class:

```<code>private IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
    _configuration = configuration;
}

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    // database connection string configuration
    services.AddDbContextPool<AppDBContext>(options => options.UseMySql(_configuration.GetConnectionString("DatabaseConnectionString"),
        mySqlOptionsAction: options => { options.EnableRetryOnFailure(); }
        ));

    services.AddMvc();
}
</code>```

This is the connection string in appsettings.json:

```<code>  "ConnectionStrings": {
    "DatabaseConnectionString": "Server=localhost;Database=MyAppDB;user=root;Password=123;"
  }
</code>```

答: I think I found the root of the problem. This error also occurs when the connection to the database couldn't have been established. Make sure the information in your connection string is correct. This error message is very misleading, I spent couple of hours figuring this out because of it.</p>

Body:
I have made an ASP.NET Core 3.1 Web-based application and want to use MySQL as the database.

I have been following along with some YouTube tutorials on creating MySQL database with ASP.NET Core 3.1 [code first approach] including a tutorial from this site:

https://learn.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-3.1&tabs=visual-studio

I have created a DataModel Class, added a service to UseMySQL to the Startup.cs Class and created an AppDBContext Class that implements DbContext Class.

When I run this command in the Package Manager Console: Add-Migration InitialDatabase the application is creating a migration successfully.

When I run update-database it is throwing this exception:

fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
      An error occurred using the connection to database '' on server 'localhost'.
An error occurred using the connection to database '' on server 'localhost'.
System.InvalidOperationException: An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding 'EnableRetryOnFailure()' to the 'UseMySQL' call.

When I call the EnableRetryOnFailure(); function as required, I am facing this exception:

fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]
        An error occurred using the connection to database '' on server 'localhost'. An error occurred using the connection to database '' on
  server 'localhost'.

What could be the issue?
Where am I getting it wrong?

If you have links to useful articles about using MySQL Database with ASP.NET Core I would appreciate or your help on this particular issue.

I am using Visual Studio IDE 2019 and ASP.NET Core 3.1.1

Additional Code:

This is the Startup.cs Class:

private IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
    _configuration = configuration;
}

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    // database connection string configuration
    services.AddDbContextPool<AppDBContext>(options => options.UseMySql(_configuration.GetConnectionString("DatabaseConnectionString"),
        mySqlOptionsAction: options => { options.EnableRetryOnFailure(); }
        ));

    services.AddMvc();
}

This is the connection string in appsettings.json:

  "ConnectionStrings": {
    "DatabaseConnectionString": "Server=localhost;Database=MyAppDB;user=root;Password=123;"
  }


问:
Fix coin change brute force solution
I am starting to write and understand coin change problem and couldn't get intuition so I have started to write a brute force solution. I want to understand the brute force solution before moving to memoization.

```<code>coins = [2, 3, 7]
change = 12

def coin_change(c):
    print(c)
    if c <= 0:
        return 0
    else:
        for i in coins:
            if c - i >= 0:
                coin_change(c - i)

coin_change(change)
</code>```

It prints out couple of changes left but I don't know how to store each path in an array.

I also want to understand how recursion can be used to track path. I can think of adding an extra argument in coin_change but maybe there is an alternate way.

I am confused about its complexity. It has a number of coins call at every step but many online resources mention it's 2n.

Edit: Please note that the coin supply is unlimited, The answer is 4

```<code>[2, 2, 2, 2, 2, 2]
[3, 3, 3, 3]
[2, 2, 2, 3, 3]
[2, 3, 7]
</code>```

答:
Another possible approach is to use a recursive generator function with yield and yield from. This removes the need to save the discovered combinations in a list, which then has to be returned:

```<code>coins = [2, 3, 7]
change = 12
def coin_change(c = []):
  if sum(c) == change:
     yield tuple(sorted(c))
  else:
     for i in coins:
        if sum(c+[i]) <= change:
           yield from coin_change(c+[i])

print(list(map(list, set(coin_change()))))
</code>```

Output:

```<code>[[3, 3, 3, 3], [2, 2, 2, 3, 3], [2, 3, 7], [2, 2, 2, 2, 2, 2]]
</code>```

Title: Fix coin change brute force solution

Body:
I am starting to write and understand coin change problem and couldn't get intuition so I have started to write a brute force solution. I want to understand the brute force solution before moving to memoization.

coins = [2, 3, 7]
change = 12

def coin_change(c):
    print(c)
    if c <= 0:
        return 0
    else:
        for i in coins:
            if c - i >= 0:
                coin_change(c - i)

coin_change(change)

It prints out couple of changes left but I don't know how to store each path in an array.

I also want to understand how recursion can be used to track path. I can think of adding an extra argument in coin_change but maybe there is an alternate way.

I am confused about its complexity. It has a number of coins call at every step but many online resources mention it's 2n.

Edit: Please note that the coin supply is unlimited, The answer is 4

[2, 2, 2, 2, 2, 2]
[3, 3, 3, 3]
[2, 2, 2, 3, 3]
[2, 3, 7]

Body:
Another possible approach is to use a recursive generator function with yield and yield from. This removes the need to save the discovered combinations in a list, which then has to be returned:

coins = [2, 3, 7]
change = 12
def coin_change(c = []):
  if sum(c) == change:
     yield tuple(sorted(c))
  else:
     for i in coins:
        if sum(c+[i]) <= change:
           yield from coin_change(c+[i])

print(list(map(list, set(coin_change()))))

Output:

[[3, 3, 3, 3], [2, 2, 2, 3, 3], [2, 3, 7], [2, 2, 2, 2, 2, 2]]


问:
Accessing data that was saved with jquery .data()
I have a iframe and I used the jquery .data() function to save some element from the iframe.

I attached them to the body like this $('body').data('clicksData', myClicksData);

Now i need to access that information from out of the iframe, I tried just doing this var allData = $('body').data('clicksData')[0]; but it didnt work.

any ideas how to do this?

答:
Use this :

assign some id to your iframe like this :

```<code><iframe id="frameId"></iframe>
</code>```

and use this jquery code to access that iframe

```<code>$("#frameId").contents().find("body").data("clicksData");
</code>```

Body:
Use this :

assign some id to your iframe like this :

<iframe id="frameId"></iframe>

and use this jquery code to access that iframe

$("#frameId").contents().find("body").data("clicksData");


问:
How to cast an object to Type?
I want to cast an object to a type that a System.Type object defines. I only know the object and the Type as inputs, I can't add type parameters.

```<code>void Test()
{
    object obj = 3;
    Type type = typeof(int);

    int number = Cast(obj, type);

    Console.WriteLine($"{number}, {number.GetType()}"); // Should output "3, System.Int32"
}

// I can't change the inputs
??? Cast(object obj, Type type)
{
    // return the obj casted to type, but how?
}
</code>```

I guess there's a way to solve it using reflection but I couldn't find anything like this.

答:
It is possible to do it without changing the Cast method into a template. It needs to return dynamic type. To cast, you should use the method Convert.ChangeType.

//I can't change the inputs
dynamic Cast(object obj, Type type)
{
    // return the obj casted to type, but how?
    return Convert.ChangeType(obj, type);
}
```

Title: How to cast an object to Type?

Body:
I want to cast an object to a type that a System.Type object defines. I only know the object and the Type as inputs, I can't add type parameters.

void Test()
{
    object obj = 3;
    Type type = typeof(int);

    int number = Cast(obj, type);

    Console.WriteLine($"{number}, {number.GetType()}"); // Should output "3, System.Int32"
}

// I can't change the inputs
??? Cast(object obj, Type type)
{
    // return the obj casted to type, but how?
}

I guess there's a way to solve it using reflection but I couldn't find anything like this.


问:
Need to have image and text on same line
I am not very good at CSS, I am just learning. I need to have the div with the class "profile_picture" on the same lines as the div with class "text". Can I get some guidance. </p>

```<code>    <div class="card">
<div class="cardimage">
  <img src="./images/desert.jpg" alt="Desert Picture" height="194">
</div>
<div class="text">
  <h2 class="card_title">Title goes here</h2>
  <div class="sec_text"> Secondary text </div>
</div>
<div class="profile_picture">
  <img alt="Profile Picture" src="./images/person-avatar.jpg" width="40">
</div>
<div class="bodytext">
  <p class="card_text">Greyhound divisively hello coldly wonderfully marginally far upon excluding.</p>
</div>
</div>
</body>
</code>```

<p>Below is my CSS </p>

```<code>.card {
    width: 344px;
    background: red;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.15);

}
* {
     box-sizing: border-box;
     margin: 0px;
     padding: 0px;

 }
 .bodytext {
     padding: 16px;
 }

 .cardimage {
    text-align:center;
 }
 .card_title {
     color: #000;
     font-size: 22px;
 }
 .sec_text, .card_text {
     color: #232F34
 }
 .card_text {
     font-size: 11px;
 }
</code>```

答:
You can set both the profile picture and the text classes to display: inline-block;

Adding this:

```<code>.profile_picture{
   display: inline-block;
 }

 .text {
   display: inline-block;
 }
</code>```

Here's a working example:

.card {
    width: 344px;
    background: red;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.15);

}
* {
     box-sizing: border-box;
     margin: 0px;
     padding: 0px;

 }
 .bodytext {
     padding: 16px;
 }

 .cardimage {
    text-align:center;
 }
 .card_title {
     color: #000;
     font-size: 22px;
 }
 .sec_text, .card_text {
     color: #232F34
 }
 .card_text {
     font-size: 11px;
 }

 .profile_picture{
   display: inline-block;
   float: left;
 }

 .text {
   display: inline-block;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card">
<div class="cardimage">
  <img src="https://www.w3schools.com/html/img_girl.jpg" alt="Desert Picture" height="194">
</div>
<div class="text">
  <h2 class="card_title">Title goes here</h2>
  <div class="sec_text"> Secondary text </div>
</div>
<div class="profile_picture">
  <img alt="Profile Picture" src="https://www.w3schools.com/html/img_girl.jpg" width="40">
</div>
<div class="bodytext">
  <p class="card_text">Greyhound divisively hello coldly wonderfully marginally far upon excluding.</p>
</div>
</div></code>```

Body:
I am not very good at CSS, I am just learning. I need to have the div with the class "profile_picture" on the same lines as the div with class "text". Can I get some guidance.

Title goes here

 Secondary text

Greyhound divisively hello coldly wonderfully marginally far upon excluding.

Below is my CSS

.card {
    width: 344px;
    background: red;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.15);

}
* {
     box-sizing: border-box;
     margin: 0px;
     padding: 0px;

 }
 .bodytext {
     padding: 16px;
 }

 .cardimage {
    text-align:center;
 }
 .card_title {
     color: #000;
     font-size: 22px;
 }
 .sec_text, .card_text {
     color: #232F34
 }
 .card_text {
     font-size: 11px;
 }

Body:
You can set both the profile picture and the text classes to display: inline-block;

Adding this:

.profile_picture{
   display: inline-block;
 }

 .text {
   display: inline-block;
 }

Here's a working example:

.card {
    width: 344px;
    background: red;
    box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.15);

}
* {
     box-sizing: border-box;
     margin: 0px;
     padding: 0px;

 }
 .bodytext {
     padding: 16px;
 }

 .cardimage {
    text-align:center;
 }
 .card_title {
     color: #000;
     font-size: 22px;
 }
 .sec_text, .card_text {
     color: #232F34
 }
 .card_text {
     font-size: 11px;
 }

 .profile_picture{
   display: inline-block;
   float: left;
 }

 .text {
   display: inline-block;
 }

<div class="card">
<div class="cardimage">
  <img src="https://www.w3schools.com/html/img_girl.jpg" alt="Desert Picture" height="194">
</div>
<div class="text">
  <h2 class="card_title">Title goes here</h2>
  <div class="sec_text"> Secondary text </div>
</div>
<div class="profile_picture">
  <img alt="Profile Picture" src="https://www.w3schools.com/html/img_girl.jpg" width="40">
</div>
<div class="bodytext">
  <p class="card_text">Greyhound divisively hello coldly wonderfully marginally far upon excluding.</p>
</div>
</div>


问:
How can i extract month and year from a string in python?
Input text:

```<code>text = "Wipro Limited | Hyderabad, IN                Dec 2017 – Present
Project Analyst

Infosys | Delhi, IN                Apr 2017 – Nov 2017
Software Developer

HCL Technologies | Hyderabad, IN                Jun 2016 – Mar 2017
Software Engineer
"
</code>```

I have written a code for this but it displays in list for each extracted word and unable to do anything of it.

```<code>regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s+\–\s+(?P<month1>[a-zA-Z]+)\s+(?P<year1>\d{4})')
mat = re.findall(regex, text)
mat
</code>```

Check out the code : https://regex101.com/r/mMlgYp/1.
I want the output like below to preview the dates and make difference of it then calculate total experience:
Here Present or Till date should consider current month and year.

```<code>import time
Present = time.strftime("%m-%Y")
Present
# output: '05-2020'
</code>```

```<code>#Desired output
Extracted dates:
[('Dec 2017 - Present'),
 ('Apr 2017 - Nov 2017'),
 ('Jun 2016 - Mar 2017')]# and so on ...should display all the search results

First experience: 1.9 years
second experience: 8 months
third experience: 7 months
# and so on ...should display all the search results
Total experience: 3.4 years
</code>```

Please help me with this I'm new to programming lang and NLP, regex stuff.

答:
```<code>import re
import numpy as np
import pandas as pd

text = '''Wipro Limited | Hyderabad, IN                Dec 2017 – Present
Project Analyst

Infosys | Delhi, IN                Apr 2017 – Nov 2017
Software Developer

HCL Technologies | Hyderabad, IN                Jun 2016 – Mar 2017
Software Engineer
'''

def pretty_format(monthts):
    return f'{monthts/12:.1f} years' if monthts > 11 else f'{monthts:.1f} months'

data = []
for employer, d1, d2 in re.findall(r'(.*?)\s*\|.*([A-Z][a-z]{2} [12]\d{3}) – (?:([A-Z][a-z]{2} [12]\d{3})|Present)', text):
    data.append({'Employer': employer, 'Begin': d1, 'End': d2 or np.nan})

df = pd.DataFrame(data)
df['Begin'] = pd.to_datetime(df['Begin'])
df['End'] = pd.to_datetime(df['End'])

df['Experience'] = ((df['End'].fillna(pd.to_datetime('now')) - df['Begin']) / np.timedelta64(1, 'M')).apply(pretty_format)
print(df)

total = np.sum(df['End'].fillna(pd.to_datetime('now')) - df['Begin']) / np.timedelta64(1, 'M')
print()
print(f'Total experience = {pretty_format(total)}')
</code>```

Prints:

```<code>           Employer      Begin        End  Experience
0     Wipro Limited 2017-12-01        NaT   2.5 years
1           Infosys 2017-04-01 2017-11-01  7.0 months
2  HCL Technologies 2016-06-01 2017-03-01  9.0 months

Total experience = 3.8 years
</code>```

Body:
Input text:

text = "Wipro Limited | Hyderabad, IN                Dec 2017 – Present
Project Analyst

Infosys | Delhi, IN                Apr 2017 – Nov 2017
Software Developer

HCL Technologies | Hyderabad, IN                Jun 2016 – Mar 2017
Software Engineer
"

I have written a code for this but it displays in list for each extracted word and unable to do anything of it.

regex = re.compile('(?P<month>[a-zA-Z]+)\s+(?P<year>\d{4})\s+\–\s+(?P<month1>[a-zA-Z]+)\s+(?P<year1>\d{4})')
mat = re.findall(regex, text)
mat

Check out the code : https://regex101.com/r/mMlgYp/1.
I want the output like below to preview the dates and make difference of it then calculate total experience:
Here Present or Till date should consider current month and year.

import time
Present = time.strftime("%m-%Y")
Present
# output: '05-2020'

#Desired output
Extracted dates:
[('Dec 2017 - Present'),
 ('Apr 2017 - Nov 2017'),
 ('Jun 2016 - Mar 2017')]# and so on ...should display all the search results

First experience: 1.9 years
second experience: 8 months
third experience: 7 months
# and so on ...should display all the search results
Total experience: 3.4 years

Please help me with this I'm new to programming lang and NLP, regex stuff.

Body:
import re
import numpy as np
import pandas as pd

text = '''Wipro Limited | Hyderabad, IN                Dec 2017 – Present
Project Analyst

Infosys | Delhi, IN                Apr 2017 – Nov 2017
Software Developer

HCL Technologies | Hyderabad, IN                Jun 2016 – Mar 2017
Software Engineer
'''

def pretty_format(monthts):
    return f'{monthts/12:.1f} years' if monthts > 11 else f'{monthts:.1f} months'

data = []
for employer, d1, d2 in re.findall(r'(.*?)\s*\|.*([A-Z][a-z]{2} [12]\d{3}) – (?:([A-Z][a-z]{2} [12]\d{3})|Present)', text):
    data.append({'Employer': employer, 'Begin': d1, 'End': d2 or np.nan})

df = pd.DataFrame(data)
df['Begin'] = pd.to_datetime(df['Begin'])
df['End'] = pd.to_datetime(df['End'])

df['Experience'] = ((df['End'].fillna(pd.to_datetime('now')) - df['Begin']) / np.timedelta64(1, 'M')).apply(pretty_format)
print(df)

total = np.sum(df['End'].fillna(pd.to_datetime('now')) - df['Begin']) / np.timedelta64(1, 'M')
print()
print(f'Total experience = {pretty_format(total)}')

Prints:

           Employer      Begin        End  Experience
0     Wipro Limited 2017-12-01        NaT   2.5 years
1           Infosys 2017-04-01 2017-11-01  7.0 months
2  HCL Technologies 2016-06-01 2017-03-01  9.0 months

Total experience = 3.8 years


问:
How do you work out the average of a sum function within a temp table?
I have created a temp table that lists each client's invoice(s), plus the number of days it took to pay the invoice. A client can have more than one invoice.

Instead of this, I would just like the temp table to list each client once, along with the AVERAGE number of days it took to pay all of their invoices.

Any tips on how to do this would be much appreciated.

Thanks

```<code>select
c.client_code,
b.bill_num,
b.bill_date,
ba.TRAN_DATE,
sum(datediff(Day,b.BILL_DATE, ba.TRAN_DATE)) as Days_To_Pay

into #tempG1

from blt_bill b
left outer join blt_billm bm on b.tran_uno = bm.bill_tran_uno
left outer join BLT_BILL_AMT ba on bm.BILLM_UNO = ba.BILLM_UNO
left outer join hbm_matter m on bm.matter_uno = m.matter_uno
left outer join hbm_client c on m.client_uno = c.client_uno

where b.total_bill_amt > 0.0
and bm.ar_status NOT IN ('P','X')
and ba.TRAN_TYPE in ('CR','crx')

group by c.client_code,b.bill_num,b.bill_date,ba.TRAN_DATE

select * from #tempG1

Drop Table #tempG1
</code>```

答:
This sounds like a simple aggregation:

```<code>select c.client_code, avg(datediff(Day, b.BILL_DATE, ba.TRAN_DATE)) as Days_To_Pay
from blt_bill b join
     blt_billm bm
     on b.tran_uno = bm.bill_tran_uno join
     BLT_BILL_AMT ba
     on bm.BILLM_UNO = ba.BILLM_UNO join
     hbm_matter m on bm.matter_uno = m.matter_uno join
     hbm_client c
     on m.client_uno = c.client_uno
where b.total_bill_amt > 0.0 and
      bm.ar_status not in ('P', 'X') and
      ba.TRAN_TYPE in ('CR', 'crx')
group by c.client_code;
</code>```

Note that you do not need outer joins.  The where clause is turning most of them into inner joins anyway.  Plus, if you are aggregating by the client code, then presumably you want a non-NULL value.

Body:
I have created a temp table that lists each client's invoice(s), plus the number of days it took to pay the invoice. A client can have more than one invoice.

Instead of this, I would just like the temp table to list each client once, along with the AVERAGE number of days it took to pay all of their invoices.

Any tips on how to do this would be much appreciated.

Thanks

select
c.client_code,
b.bill_num,
b.bill_date,
ba.TRAN_DATE,
sum(datediff(Day,b.BILL_DATE, ba.TRAN_DATE)) as Days_To_Pay

into #tempG1

from blt_bill b
left outer join blt_billm bm on b.tran_uno = bm.bill_tran_uno
left outer join BLT_BILL_AMT ba on bm.BILLM_UNO = ba.BILLM_UNO
left outer join hbm_matter m on bm.matter_uno = m.matter_uno
left outer join hbm_client c on m.client_uno = c.client_uno

where b.total_bill_amt > 0.0
and bm.ar_status NOT IN ('P','X')
and ba.TRAN_TYPE in ('CR','crx')

group by c.client_code,b.bill_num,b.bill_date,ba.TRAN_DATE

select * from #tempG1

Drop Table #tempG1

Body:
This sounds like a simple aggregation:

select c.client_code, avg(datediff(Day, b.BILL_DATE, ba.TRAN_DATE)) as Days_To_Pay
from blt_bill b join
     blt_billm bm
     on b.tran_uno = bm.bill_tran_uno join
     BLT_BILL_AMT ba
     on bm.BILLM_UNO = ba.BILLM_UNO join
     hbm_matter m on bm.matter_uno = m.matter_uno join
     hbm_client c
     on m.client_uno = c.client_uno
where b.total_bill_amt > 0.0 and
      bm.ar_status not in ('P', 'X') and
      ba.TRAN_TYPE in ('CR', 'crx')
group by c.client_code;

Note that you do not need outer joins.  The where clause is turning most of them into inner joins anyway.  Plus, if you are aggregating by the client code, then presumably you want a non-NULL value.


问:
ios: import a pod as framework into aswift ios project without using cocoapods
Is there a way that I can import a framework that is available as a pod into my swift ios project without using cocoapods?</p>

答:
Yes.

You should read through the framework's documentation since the specific steps may vary.

Typically you'll just need to

Clone or download the source/repo

Then from within Xcode:

Drag the framework's .xcodeproj into your project

In the Build Phases Tab, drag the framework's .framework into Link Binary with Libraries

Hope this helps someone!


问:
How do I open instagram from flutter app?
I want to transite to Instagram profile, when I am tapping on button. I use this library url_launcher. But there I can use only Web Browser for this. What will I do, in order to reach my goal?</p>

答:
Well, I don't know if it's too late, but this works for me using the url_launcher library (tested on android only):</p>

```<code>var url = 'https://www.instagram.com/<INSTAGRAM_PROFILE>/';

if (await canLaunch(url)) {
  await launch(
    url,
    universalLinksOnly: true,
  );
} else {
  throw 'There was a problem to open the url: $url';
}
</code>```

Body:
Well, I don't know if it's too late, but this works for me using the url_launcher library (tested on android only):

var url = 'https://www.instagram.com/<INSTAGRAM_PROFILE>/';

if (await canLaunch(url)) {
  await launch(
    url,
    universalLinksOnly: true,
  );
} else {
  throw 'There was a problem to open the url: $url';
}


问:
Trouble adding font awesome to scene builder(Missing classes)
I recently started my school project containing graphics with JavaFX. I added Font Awsome to maven dependencies and classes are fine loaded in the IntelliJ but when I am added its JAR file to scene builder there are only: 1. GlyphCheckBox and 2. GlyphStack and there isn't any FontAwsomeIconView in it.
How should I fix this problem? (I'm using JDK 13, JavaFX 14 and scene builder 11)</p>

```<code><dependency>
            <groupId>de.jensd</groupId>
            <artifactId>fontawesomefx</artifactId>
            <version>8.9</version>
</dependency>
</code>```

答:
The latest version of FontAwesomeFX (11) is hosted at bintray; the one in maven central (8.9) is not compatible with the the latest JDK because of some old com.sun references in the code.

Open the JAR/FXML Manager in SceneBuilder (dropdown menu in the Library pane)

Add a repository with the URL - https://dl.bintray.com/jerady/maven/

Then you have to add de.jensd:fontawesomefx-commons:11.0 as well as de.jensd.fontawesomefx-fontawesome:4.7.0-11 to get FontAwesomeIconView to show up in the controls list.

Body:
I recently started my school project containing graphics with JavaFX. I added Font Awsome to maven dependencies and classes are fine loaded in the IntelliJ but when I am added its JAR file to scene builder there are only: 1. GlyphCheckBox and 2. GlyphStack and there isn't any FontAwsomeIconView in it.
How should I fix this problem? (I'm using JDK 13, JavaFX 14 and scene builder 11)

<dependency>
            <groupId>de.jensd</groupId>
            <artifactId>fontawesomefx</artifactId>
            <version>8.9</version>
</dependency>


问:
d3v4 scatterplot - fixing the domain adding animations
I'm trying to upgrade an old scatterplot chart -- but mapping the domain has become an issue where its not rendering the positions for the dots correctly.

//version 4 attempt
https://jsfiddle.net/z16u8j4c/1/

//old version 3
https://jsfiddle.net/oj2sg38z/2/

I tried to refactor the dataset so it could contain label information - for possible future legend generation.

```<code>        var x = d3.scale.linear()
                  .domain([0, d3.max(data, function(d) { return d[0]; })])
                  .range([ 0, width ]);

        var y = d3.scale.linear()
                  .domain([0, d3.max(data, function(d) { return d[1]; })])
                  .range([ height, 0 ]);
</code>```

I've tried to fix it in my version by using d3v4 standards

```<code>        var x = d3.scaleLinear()
                  .domain([0, d3.max(data, function(d) { return d.value[0]; })])
                  .range([ 0, width ]);

        var y = d3.scaleLinear()
                  .domain([0, d3.max(data, function(d) { return d.value[1]; })])
                  .range([ height, 0 ]);
</code>```

答:
The problem is with your d3.max. Your data is an array of object with values for different series. If you want to find the max for all values, you have to iterate over all data.values, so one way to do it is to get all values and flat it on array, then find its max.

var x = d3
  .scaleLinear()
  .domain([0, d3.max(data.map(s => s.value).flat(), d => d[0])])
  .range([0, width])

var y = d3
  .scaleLinear()
  .domain([0, d3.max(data.map(s => s.value).flat(), d => d[1])])
  .range([0, height])
```

Body:
I'm trying to upgrade an old scatterplot chart -- but mapping the domain has become an issue where its not rendering the positions for the dots correctly.

//version 4 attempt
https://jsfiddle.net/z16u8j4c/1/

//old version 3
https://jsfiddle.net/oj2sg38z/2/

I tried to refactor the dataset so it could contain label information - for possible future legend generation.

        var x = d3.scale.linear()
                  .domain([0, d3.max(data, function(d) { return d[0]; })])
                  .range([ 0, width ]);

        var y = d3.scale.linear()
                  .domain([0, d3.max(data, function(d) { return d[1]; })])
                  .range([ height, 0 ]);

I've tried to fix it in my version by using d3v4 standards

        var x = d3.scaleLinear()
                  .domain([0, d3.max(data, function(d) { return d.value[0]; })])
                  .range([ 0, width ]);

        var y = d3.scaleLinear()
                  .domain([0, d3.max(data, function(d) { return d.value[1]; })])
                  .range([ height, 0 ]);


问:
Best way to group filename based on filename in Bash?
I have a folder with the following files:

```<code>DA-001-car.jpg
DA-001-dog.jpg
DA-001-coffee.jpg
DA-002-house.jpg
DA-003-coffee.jpg
DA-003-cat.jpg
...
</code>```

I want to generate this (CSV) output:

```<code>SKU, IMAGE
DA-001, "DA-001-car.jpg, DA-001-dog.jpg, DA-001-coffee.jpg"
DA-002, "DA-001-house.jpg"
DA-003, "DA-001-coffee.jpg, DA-001-cat.jpg"
</code>```

I tried to program this in Bash:

```<code>#!/bin/bash
echo "SKU, FILE" >> tmp.csv
for file in /home/calvin/test/*.jpg
do
    SKU_NAME="${file##*/}"
    echo ${SKU_NAME:0:6}, \"inner for-loop?, ?, ?\" >> tmp.csv
done
uniq tmp.csv output.csv
</code>```

As you can see I'm a noob as for programming :)
Please help me out, thanks in advance!

答:
If the filenames don't contain spaces, you can use sed instead of an inner loop:

```<code>printf '%s\n' *.jpg \
| cut -f1,2 -d- \
| sort -u \
| while IFS= read -r sku ; do
    echo "$sku",\"$(echo "$sku"* | sed 's/ /, /')\"
done
</code>```

With the inner loop, you can switch to printf from echo. Sed is used to remove the trailing comma.

```<code>printf '%s\n' *.jpg \
| cut -f1,2 -d- \
| sort -u \
| while IFS= read -r sku ; do
    printf %s "$sku, \""
    for f in "$sku"* ; do
        printf '%s, ' "$f"
    done | sed 's/, $//'
    printf '"\n'
done
</code>```

If you don't want to parse the output of ls and run sort, you can store the prefixes in an associative array:

```<code>#!/bin/bash
declare -A prefix
for jpg in *.jpg ; do
    p1=${jpg%%-*}
    jpg=${jpg#*-}
    p2=${jpg%%-*}
    prefix[$p1-$p2]=1
done

for sku in "${!prefix[@]}" ; do
    printf '%s, "' "$sku"
    for f in "$sku"* ; do
        printf '%s, ' "$f"
    done | sed 's/, $//'
    printf '"\n'
done
</code>```

Body:
I have a folder with the following files:

DA-001-car.jpg
DA-001-dog.jpg
DA-001-coffee.jpg
DA-002-house.jpg
DA-003-coffee.jpg
DA-003-cat.jpg
...

I want to generate this (CSV) output:

SKU, IMAGE
DA-001, "DA-001-car.jpg, DA-001-dog.jpg, DA-001-coffee.jpg"
DA-002, "DA-001-house.jpg"
DA-003, "DA-001-coffee.jpg, DA-001-cat.jpg"

I tried to program this in Bash:

#!/bin/bash
echo "SKU, FILE" >> tmp.csv
for file in /home/calvin/test/*.jpg
do
    SKU_NAME="${file##*/}"
    echo ${SKU_NAME:0:6}, \"inner for-loop?, ?, ?\" >> tmp.csv
done
uniq tmp.csv output.csv

As you can see I'm a noob as for programming :)
Please help me out, thanks in advance!

Body:
If the filenames don't contain spaces, you can use sed instead of an inner loop:

printf '%s\n' *.jpg \
| cut -f1,2 -d- \
| sort -u \
| while IFS= read -r sku ; do
    echo "$sku",\"$(echo "$sku"* | sed 's/ /, /')\"
done

With the inner loop, you can switch to printf from echo. Sed is used to remove the trailing comma.

printf '%s\n' *.jpg \
| cut -f1,2 -d- \
| sort -u \
| while IFS= read -r sku ; do
    printf %s "$sku, \""
    for f in "$sku"* ; do
        printf '%s, ' "$f"
    done | sed 's/, $//'
    printf '"\n'
done

If you don't want to parse the output of ls and run sort, you can store the prefixes in an associative array:

#!/bin/bash
declare -A prefix
for jpg in *.jpg ; do
    p1=${jpg%%-*}
    jpg=${jpg#*-}
    p2=${jpg%%-*}
    prefix[$p1-$p2]=1
done

for sku in "${!prefix[@]}" ; do
    printf '%s, "' "$sku"
    for f in "$sku"* ; do
        printf '%s, ' "$f"
    done | sed 's/, $//'
    printf '"\n'
done


问:
What happened to the changes that I made using git filter-branch?
For the first time, I tried to rewrite my git history using git filter-branch. I did this by writing a (Python) script (let's call it edit_file) that makes an edit to a file (let's call it target_file). Then, I ran this command:

```<code>git filter-branch --tree-filter "path/to/edit_file" HEAD
</code>```

I got a nice stream of output which seemed to indicate that I'd gotten the effect that I wanted, but when viewed target_file, I did not see any changes. When I run edit_file directly, target_file in my working copy successfully receives the edits that I intended.

It sounds like my changes exist within some deep, dark, and dank recess in git's twisted mind, and I just need a magical incantation to summon forth my changes. I have no idea whether this is correct, nor do I understand where to begin looking, because all the material that I've read (including the official git book) indicates that once git filter-branch finishes, the branch that I am working on should have the changes that edit_file would perform on every version of target_file...

Halp?

Sorry if this is a bit long winded, but I don't know what details are necessary (because that is a core feature of being confused).

More details:

The reasons I say that it looked like filter-branch did what I wanted are:

I could see the output of edit_file running on each commit, and it indicated success on all of them. The output of edit_file changes as it operates on different versions of target_file, and I was able to see the different output from edit_file as git filter-branch moved through history.

At the end, I saw this:

```<code>Ref 'refs/heads/my-branch' was rewritten
</code>```

PS: Before doing git filter-branch, I ran

```<code>git checkout -b my-branch
</code>```

to create a new branch named my-branch (and check it out), in case git filter-branch went horribly wrong.

After seeing that git filter-branch ... left target_file unchanged, I ran git checkout -b my-branch, but I guess that did nothing. I thought it might do something, because the last line from git filter-branch seems to be saying that the branch my-branch has been changed, but I honestly do not understand what that line means.

答:
It sounds like my changes exist within some deep, dark, and dank recess in git's twisted mind, and I just need a magical incantation to summon forth my changes.

That is why you don't use git filter-branch anymore (it is obsolete, along with BFG)

You use git filter-repo with

path-base filtering to limit the filter to a specific file

blob callback in order to call your script and edit that file.

Body:
For the first time, I tried to rewrite my git history using git filter-branch. I did this by writing a (Python) script (let's call it edit_file) that makes an edit to a file (let's call it target_file). Then, I ran this command:

git filter-branch --tree-filter "path/to/edit_file" HEAD

I got a nice stream of output which seemed to indicate that I'd gotten the effect that I wanted, but when viewed target_file, I did not see any changes. When I run edit_file directly, target_file in my working copy successfully receives the edits that I intended.

It sounds like my changes exist within some deep, dark, and dank recess in git's twisted mind, and I just need a magical incantation to summon forth my changes. I have no idea whether this is correct, nor do I understand where to begin looking, because all the material that I've read (including the official git book) indicates that once git filter-branch finishes, the branch that I am working on should have the changes that edit_file would perform on every version of target_file...

Halp?

Sorry if this is a bit long winded, but I don't know what details are necessary (because that is a core feature of being confused).

More details:

The reasons I say that it looked like filter-branch did what I wanted are:

I could see the output of edit_file running on each commit, and it indicated success on all of them. The output of edit_file changes as it operates on different versions of target_file, and I was able to see the different output from edit_file as git filter-branch moved through history.

At the end, I saw this:

Ref 'refs/heads/my-branch' was rewritten

PS: Before doing git filter-branch, I ran

git checkout -b my-branch

to create a new branch named my-branch (and check it out), in case git filter-branch went horribly wrong.

After seeing that git filter-branch ... left target_file unchanged, I ran git checkout -b my-branch, but I guess that did nothing. I thought it might do something, because the last line from git filter-branch seems to be saying that the branch my-branch has been changed, but I honestly do not understand what that line means.


问:
i want to write a python code that calculates time
If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?

This is what I have tried:

```<code>>>> import datetime
>>> t=datetime.time(6,52)
>>> print (t)
06:52:00
>>> b=t+datetime.timedelta (8 hours,15 minutes)
  File "<stdin>", line 1
    b=t+datetime.timedelta (8 hours,15 minutes)
                              ^
SyntaxError: invalid syntax
````````````````````````````````````````````````````
```

答:
So let's walk it back a few steps. When you tried b=t+datetime.timedelta (8 hours,15 minutes), what you were trying to do was increment your time object by 8 minutes and 15 seconds, using the timedelta function. In Python, functions take arguments, and timedelta, like any other function, has specific kinds of values you can pass for arguments. You can find them here, because since datetime is a library, it has nice documentation for everything. It looks like you were using IDLE which also gives you a peek at type hints:

So now we know that timedelta takes any one of days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0.

In our case, we want to add 8 minutes and 15 seconds to our original datetime object.

That would mean setting minutes=8 and seconds=15.

So when we call the timedelta function, to avoid that syntax error, we want to invoke the function like such:

b=t+datetime.timedelta(minutes=8, seconds=15)
```

And there you have it! Just remember what is and is not valid syntax in Python. Python doesn't know a thing about what you mean when you give it plain English.

Body:
If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast?

This is what I have tried:

>>> import datetime
>>> t=datetime.time(6,52)
>>> print (t)
06:52:00
>>> b=t+datetime.timedelta (8 hours,15 minutes)
  File "<stdin>", line 1
    b=t+datetime.timedelta (8 hours,15 minutes)
                              ^
SyntaxError: invalid syntax
````````````````````````````````````````````````````

Body:
So let's walk it back a few steps. When you tried b=t+datetime.timedelta (8 hours,15 minutes), what you were trying to do was increment your time object by 8 minutes and 15 seconds, using the timedelta function. In Python, functions take arguments, and timedelta, like any other function, has specific kinds of values you can pass for arguments. You can find them here, because since datetime is a library, it has nice documentation for everything. It looks like you were using IDLE which also gives you a peek at type hints:

So now we know that timedelta takes any one of days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0.

In our case, we want to add 8 minutes and 15 seconds to our original datetime object.

That would mean setting minutes=8 and seconds=15.

So when we call the timedelta function, to avoid that syntax error, we want to invoke the function like such:

b=t+datetime.timedelta(minutes=8, seconds=15)

And there you have it! Just remember what is and is not valid syntax in Python. Python doesn't know a thing about what you mean when you give it plain English.


问:
How to read a portion of a line in a text file?
So, I have a text file with thousands of lines formatted similarly to this:

123456:0.8525000:1590882780:91011

These files are almost always a different length, and I only need to read the first two parts of the line, being 123456:0.8525000.

I know that I can split each line using C#, but I'm unsure how to only read the first 2 parts. Anyone have any idea on how to do this? Sorry if my question doesn't make sense, I can restate it if needed.

答:
Some bare bones code:</p>

```<code>string fileName = @"c:\some folder\path\file.txt";
using (StreamReader sr = new StreamReader(fileName))
{
    while (!sr.EndOfStream)
    {
        String[] values = sr.ReadLine().Split(":".ToCharArray());
        if (values.Length >= 2)
        {
            // ... do something with values[0] and values[1] ...
            Console.WriteLine(values[0] + ", " + values[1]);
        }
    }
}
</code>```

Body:
Some bare bones code:

string fileName = @"c:\some folder\path\file.txt";
using (StreamReader sr = new StreamReader(fileName))
{
    while (!sr.EndOfStream)
    {
        String[] values = sr.ReadLine().Split(":".ToCharArray());
        if (values.Length >= 2)
        {
            // ... do something with values[0] and values[1] ...
            Console.WriteLine(values[0] + ", " + values[1]);
        }
    }
}


问:
concatenate numpy 1D array in columns
I have two numpy arrays:

```<code>a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
</code>```

and I want to concatenate them into two columns like,

```<code>1 4
2 5
3 6
</code>```

is there any way to do this without transposing or reshaping the arrays?

答:
You can try:

```<code>a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.concatenate((a[np.newaxis, :], b[np.newaxis, :]), axis = 0).T
</code>```

And you get :

c = array([[1, 4],
            [2, 5],
            [3, 6]])

Best,

Title: concatenate numpy 1D array in columns

Body:
I have two numpy arrays:

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

and I want to concatenate them into two columns like,

1 4
2 5
3 6

is there any way to do this without transposing or reshaping the arrays?

Body:
You can try:

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.concatenate((a[np.newaxis, :], b[np.newaxis, :]), axis = 0).T

And you get :

c = array([[1, 4],
            [2, 5],
            [3, 6]])

Best,


问:
What is the difference between passing"this" and "activity!!" as a ViewModelStoreOwner while creating ViewModelProvider instance
Hi I am a Kotlin learner, wanted to understand the difference between passing"this" and "activity!!" as a ViewModelStoreOwner while creating ViewModelProvider instance in a fragment for ex

```<code> viewModel = ViewModelProvider(
        this,
        InventoryDetailsFragmentViewModelFactory.getInstance(activity!!.application)
    )
        .get(InventoryDetailsFragmentViewModel::class.java)
</code>```

when I am using this as owner sometimes observer is not working
Please help me to understand difference in using this and activity!!

答:
"this" means "Context", which is the Fragment you are Instantiated the viewModel.

From the code you provided i can understand "this" = "InventoryDetailsFragment", which is >the class you instantiated the viewModel.

Your code should look like this

```<code>val application = requireNotNull(activity).application
viewModelFactory = InventoryDetailsFragmentViewModelFactory(application)
viewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(InventoryDetailsFragmentViewModel::class.java)
</code>```

If you want to see an example where ViewModel and ViewModelFactory are used in a project visit this link sample

Body:
Hi I am a Kotlin learner, wanted to understand the difference between passing"this" and "activity!!" as a ViewModelStoreOwner while creating ViewModelProvider instance in a fragment for ex

 viewModel = ViewModelProvider(
        this,
        InventoryDetailsFragmentViewModelFactory.getInstance(activity!!.application)
    )
        .get(InventoryDetailsFragmentViewModel::class.java)

when I am using this as owner sometimes observer is not working
Please help me to understand difference in using this and activity!!

Body:
"this" means "Context", which is the Fragment you are Instantiated the viewModel.

From the code you provided i can understand "this" = "InventoryDetailsFragment", which is >the class you instantiated the viewModel.

Your code should look like this

val application = requireNotNull(activity).application
viewModelFactory = InventoryDetailsFragmentViewModelFactory(application)
viewModel = ViewModelProviders.of(this, viewModelFactory)
            .get(InventoryDetailsFragmentViewModel::class.java)

If you want to see an example where ViewModel and ViewModelFactory are used in a project visit this link sample


问:
Automate the Boring Stuff With Python Madlibs Project With Shelve Module
I've been learning python as my first coding language with the book 'Automate the Boring Stuff With Python', and after the chapter about reading/writing files and using the shelve module I managed to create the madlibs program. The only problem is I am sure I was suppose to use the shelve module, but I am still not sure how that works. Here is the code:

```<code>import re

basemadlibs = open('C:\\Users\\Username\\Desktop\\MADLIBS.txt', 'r')
#creates a string out of the contents of the madlibs file
newmadlibslist = list(basemadlibs.read())
newtext = ''.join(newmadlibslist)
#regex for finding placeholders(VERB, ADJECTIVE, ect.) in the  madlibs file content
placeholders = re.compile(r'[A-Z]{2,10}')
#replaces the placeholders with a %s
emptytext = placeholders.sub('%s', newtext)
#creates a list of inputs to substitute the %s in the emptystring
replacements = []
for i in range(len(placeholders.findall(newtext))):
    print('type a\\an: ' + placeholders.findall(newtext)[i])
    replacement = input()
    replacements.append(replacement)
#string formats the %s placeholders with the replacements
madlibcompleted = emptytext % tuple(replacements)
#prints the completed mad lib
print(madlibcompleted)
#saves a copy of the completed madlib to the desktop called 'alterdMADLIBS.txt'
alteredmadlibs = open('C:\\users\\Username\\Desktop\\alteredMADLIBS.txt', 'w')
alteredmadlibs.write(madlibcompleted)
alteredmadlibs.close()
basemadlibs.close()
</code>```

Can someone explain to me how the shelve module would make this more efficient? Thanks!

答:
```<code>import re

# Open text file and save string to variable.
file_name = input("Enter the full name of the text file: ")
text_file = open(file_name, "r")
text = text_file.read()
text_file.close
# Create regex to find ADJECTIVE, NOUN, ADVERB, or VERB.
mad_libs_regex = re.compile(r"(ADJECTIVE|NOUN|ADVERB|VERB)")
# For each match, prompt user for word and update string.
while mad_libs_regex.search(text) != None:
    word = input(f"Enter a(n) {mad_libs_regex.search(text).group().lower()}: ")
    text = mad_libs_regex.sub(word, text, 1)
# Save updated string to new text file.
mad_libs_file = open(f"{file_name.split('.')[0]}_madlibs.txt", "w")
mad_libs_file.write(text)
mad_libs_file.close
# Print updated string.
print(text)
</code>```

Body:
I've been learning python as my first coding language with the book 'Automate the Boring Stuff With Python', and after the chapter about reading/writing files and using the shelve module I managed to create the madlibs program. The only problem is I am sure I was suppose to use the shelve module, but I am still not sure how that works. Here is the code:

import re

basemadlibs = open('C:\\Users\\Username\\Desktop\\MADLIBS.txt', 'r')
#creates a string out of the contents of the madlibs file
newmadlibslist = list(basemadlibs.read())
newtext = ''.join(newmadlibslist)
#regex for finding placeholders(VERB, ADJECTIVE, ect.) in the  madlibs file content
placeholders = re.compile(r'[A-Z]{2,10}')
#replaces the placeholders with a %s
emptytext = placeholders.sub('%s', newtext)
#creates a list of inputs to substitute the %s in the emptystring
replacements = []
for i in range(len(placeholders.findall(newtext))):
    print('type a\\an: ' + placeholders.findall(newtext)[i])
    replacement = input()
    replacements.append(replacement)
#string formats the %s placeholders with the replacements
madlibcompleted = emptytext % tuple(replacements)
#prints the completed mad lib
print(madlibcompleted)
#saves a copy of the completed madlib to the desktop called 'alterdMADLIBS.txt'
alteredmadlibs = open('C:\\users\\Username\\Desktop\\alteredMADLIBS.txt', 'w')
alteredmadlibs.write(madlibcompleted)
alteredmadlibs.close()
basemadlibs.close()

Can someone explain to me how the shelve module would make this more efficient? Thanks!


问:
how to send push notification without apple device
is it possible to send push notification for apple without apple device? I would like to send push notification using any page or service from apple, but not using an app created in xcode for example. My app that will get the push is ready and working, but I would like to send the push from a normal page, not from mac or iphone app.</p>

答:
Yes, you can do that for free with using a push notification API, such as Spontit.

See the API docs here: https://api.spontit.com/

See the Python wrapper here: https://github.com/spontit/spontit-api-python-wrapper


问:
How to have nested ngfor with dynamic calls to api
I have an array of object that I get back at once from my API and I display them in .component.html like this:

```<code><div *ngFor="let obj of ObjectArray">
    <div>{{obj.name}}</div>
</div>
</code>```

I need to make second call to API with each one of the objects where I will populate second object array and will need to display it underneath obj.name and I tried to do that like this:

```<code><div *ngFor="let obj of ObjectArray">
    <div data-dummy="{{populateAnotherObjectArray(obj.id)}}"></div>
    <div>{{obj.name}}</div>
    <div *ngFor="let anotherObj of AnotherObjArray">
        {{anotherObj.name}}
    </div>
</div>
</code>```

populateAnotherObjectArray(obj.id) is a function in component.ts file where I populate AnotherObjArray.

Now I only get endless calls to second API.

I tried to user Directive and EventEmitter but I don't get anything there.

Is there a simple way to do this?

Update:

Lets say 1st call to API I get in ObjectArray:

```<code>[obj1From1stArray, obj2From1stArray]
</code>```

now I call API again this.api.populate2ndArray(obj1From1stArray.id) and get in AnotherObjecArray:

```<code>[obj1From2ndArray]
</code>```

and after that this.api.populate2ndArray(obj2From1stArray.id) and get in AnotherObjecArray:

```<code>[obj2From2ndArray]
</code>```

What I get on my .html page with current answer:

```<code>obj1From1stArray name
    obj1From2ndArray
    obj2From2ndArray
obj2From1stArray name
    obj1From2ndArray
    obj2From2ndArray
</code>```

What I want:

```<code>obj1From1stArray name
    obj1From2ndArray
obj2From1stArray name
    obj2From2ndArray
</code>```

答:
Try to avoid calling functions inside directives and interpolations as much as possible. If you aren't controlling the change detection strategy, they will be called too many times. You could trigger the call in the controller before displaying the data. Try the following

Controller

import { forkJoin, of } from 'rxjs';
import { catchError, switchMap } from 'rxjs/operators';

ngOnInit() {
  this.apiService.getObjectArray().pipe(
    switchMap(arr1 => {
      this.ObjectArray = arr1;
      return forkJoin(arr1.map(item => this.apiService.getAnotherObjArray(item['id'])));
    }),
    catchError(err1 => {
      // handle error
      return of(err1);
    })
  ).subscribe(
    arr2 => {
      this.ObjectArray.forEach(obj, index => this.ObjectArray['AnotherObjArray'] = arr2[index]);
    },
    err2 => {
      // handle error
    }
  );
}
```

<p>Template</p>

<pre class="lang-html prettyprint-override"><code><div *ngFor="let obj of ObjectArray">
  <div>{{obj.name}}</div>
  <div *ngFor="let anotherObj of obj.AnotherObjArray">
    {{anotherObj.name}}
  </div>
</div>
</code>```

Body:
I have an array of object that I get back at once from my API and I display them in .component.html like this:

{{obj.name}}

I need to make second call to API with each one of the objects where I will populate second object array and will need to display it underneath obj.name and I tried to do that like this:

{{obj.name}}

        {{anotherObj.name}}

populateAnotherObjectArray(obj.id) is a function in component.ts file where I populate AnotherObjArray.

Now I only get endless calls to second API.

I tried to user Directive and EventEmitter but I don't get anything there.

Is there a simple way to do this?

Update:

Lets say 1st call to API I get in ObjectArray:

[obj1From1stArray, obj2From1stArray]

now I call API again this.api.populate2ndArray(obj1From1stArray.id) and get in AnotherObjecArray:

[obj1From2ndArray]

and after that this.api.populate2ndArray(obj2From1stArray.id) and get in AnotherObjecArray:

[obj2From2ndArray]

What I get on my .html page with current answer:

obj1From1stArray name
    obj1From2ndArray
    obj2From2ndArray
obj2From1stArray name
    obj1From2ndArray
    obj2From2ndArray

What I want:

obj1From1stArray name
    obj1From2ndArray
obj2From1stArray name
    obj2From2ndArray

Body:
Try to avoid calling functions inside directives and interpolations as much as possible. If you aren't controlling the change detection strategy, they will be called too many times. You could trigger the call in the controller before displaying the data. Try the following

Controller

import { forkJoin, of } from 'rxjs';
import { catchError, switchMap } from 'rxjs/operators';

ngOnInit() {
  this.apiService.getObjectArray().pipe(
    switchMap(arr1 => {
      this.ObjectArray = arr1;
      return forkJoin(arr1.map(item => this.apiService.getAnotherObjArray(item['id'])));
    }),
    catchError(err1 => {
      // handle error
      return of(err1);
    })
  ).subscribe(
    arr2 => {
      this.ObjectArray.forEach(obj, index => this.ObjectArray['AnotherObjArray'] = arr2[index]);
    },
    err2 => {
      // handle error
    }
  );
}

Template

<div *ngFor="let obj of ObjectArray">
  <div>{{obj.name}}</div>
  <div *ngFor="let anotherObj of obj.AnotherObjArray">
    {{anotherObj.name}}
  </div>
</div>


问:
Does sourcetree provide any tool or screen for editing gitignore file?
Recently I put some extension to global gitignore file by sourcetree.

But I found out it was wrong decision.

So I want to change it.

But I do not know which .gitignore file the sourcetree uses for saveing global ignore list. (I have so many .gitignore file in my computer)

So, I want to know sourcetree provide any good tool or screen for edit global gitignore file list.

I found some articles for doing by command line, but it is kind of hard to do it for me.

Thanks

答:
The following steps fixed the problem for me on my Windows 7 box:

1) Open regedit.exe

2) Search for "gitignore_auto_file"

3) Replace the program parameter in the registry setting with your desired edit tool, using the exact path and program name, make sure to enclosed this in quotes as illustrated below:

```<code> a) e.g.: "C:\MyFolder\MyUniqueEditor.exe" "%1"
</code>```

4) When SourceTree executes the GUI, and looks up this entry in the Windows registry, then

```<code>      1) the "%1" is the parameter that is past to your choosen editor
</code>```

It is acknowledged that it would be helpful if SourceTree provided the functionality to undo/re-do the edit tool selection, if a mistake is made.

Body:
The following steps fixed the problem for me on my Windows 7 box:

1) Open regedit.exe

2) Search for "gitignore_auto_file"

3) Replace the program parameter in the registry setting with your desired edit tool, using the exact path and program name, make sure to enclosed this in quotes as illustrated below:

 a) e.g.: "C:\MyFolder\MyUniqueEditor.exe" "%1"

4) When SourceTree executes the GUI, and looks up this entry in the Windows registry, then

      1) the "%1" is the parameter that is past to your choosen editor

It is acknowledged that it would be helpful if SourceTree provided the functionality to undo/re-do the edit tool selection, if a mistake is made.