问:
Remove words from pandas series that are not found in list
I have a list of strings and a series with sentences for which all punctuation has been removed:

series = test_data["reviews']

words = [ 'great', 'awesome', 'ok', 'sucky']

I need do remove all words from the series that are not in the list[words]  and assign to new series.
I did an online search plus tried but unable to find a solution.

Can someone please assist?

Here is what I have:

```<code>new_series= []
for word in words:
    if  word in significant_words:
         new_series.append(word)
print (new_series)
</code>```

Much appreciated.

答:
If data contains sentences and need new columns filled by lists use:</p>

```<code>words = [ 'great', 'awesome', 'ok', 'sucky']
test_data = pd.DataFrame({'reviews':['great it is', 'ok good well awesome']})

words = [ 'great', 'awesome', 'ok', 'sucky']

def func(x):
    a, b = [], []
    for word in x.split():
        if word not in words:
            a.append(word)
        else:
            b.append(word)

    return pd.Series([a, b])

test_data[['out','in']]  = test_data["reviews"].apply(func)
print (test_data)
                reviews           out             in
0           great it is      [it, is]        [great]
1  ok good well awesome  [good, well]  [ok, awesome]
</code>```

Body:
I have a list of strings and a series with sentences for which all punctuation has been removed:

series = test_data["reviews']

words = [ 'great', 'awesome', 'ok', 'sucky']

I need do remove all words from the series that are not in the list[words]  and assign to new series.
I did an online search plus tried but unable to find a solution.

Can someone please assist?

Here is what I have:

new_series= []
for word in words:
    if  word in significant_words:
         new_series.append(word)
print (new_series)

Much appreciated.

Body:
If data contains sentences and need new columns filled by lists use:

words = [ 'great', 'awesome', 'ok', 'sucky']
test_data = pd.DataFrame({'reviews':['great it is', 'ok good well awesome']})

words = [ 'great', 'awesome', 'ok', 'sucky']

def func(x):
    a, b = [], []
    for word in x.split():
        if word not in words:
            a.append(word)
        else:
            b.append(word)

    return pd.Series([a, b])

test_data[['out','in']]  = test_data["reviews"].apply(func)
print (test_data)
                reviews           out             in
0           great it is      [it, is]        [great]
1  ok good well awesome  [good, well]  [ok, awesome]


来源: stackexchange

问:
Deleting a row in datagrid view
I want to Delete a row in the Gridview which is in the update panel . But instead of the command button ., i took a link button to get a confirmation message. Now if I press ok then the record should be deleted (both from db and frm girdview). I know how to delete from db but not when linkbutton is pressed, and deleting the record. And also the gridview is in update panel.so it should be reflected.

A sample code is appreciated.

Thanks

答:
you can use RowCommand event of gridview, like...

```<code>protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        e.CommandArgument  -- this return Data Key Value
//Deletion Code goes here.....
var brochureToDelete = (from b in dataContext.ArticleBrochures where b.ArticleId == ArticleId select b).FirstOrDefault();
if (brochureToDelete != null)
{
dataContext.ArticleBrochures.DeleteOnSubmit(brochureToDelete);
dataContext.SubmitChanges();
bindBrochureGridView(ArticleId);
// if your gridview in updatepanel
//Call update method of UpdatePanel
//UpdatePanel.Update();
 }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Deleting a row in datagrid view

Body:
you can use RowCommand event of gridview, like...

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        e.CommandArgument  -- this return Data Key Value
//Deletion Code goes here.....
var brochureToDelete = (from b in dataContext.ArticleBrochures where b.ArticleId == ArticleId select b).FirstOrDefault();
if (brochureToDelete != null)
{
dataContext.ArticleBrochures.DeleteOnSubmit(brochureToDelete);
dataContext.SubmitChanges();
bindBrochureGridView(ArticleId);
// if your gridview in updatepanel
//Call update method of UpdatePanel
//UpdatePanel.Update();
 }
}


问:
Can't create backup mongodump with --db. Authentication failed
When I create backup of all databases in MongoDB (version 3):

```<code>mongodump --username bacUser --password 12345
</code>```

It's OK. But when I try to create backup of a selected db:

```<code>mongodump --username bacUser --password 12345 --db test
</code>```

It gives me this error:

Failed: error connecting to db server: server returned error on SASL authentication step: Authentication failed.

答:
```<code>mongodump --host <host-ip> --port 27017 --db <database>  --authenticationDatabase admin --username <username> --password <password> --out ./Documents/
</code>```

After all the trail, I found above working command to dump from mongdb.

Body:
When I create backup of all databases in MongoDB (version 3):

mongodump --username bacUser --password 12345

It's OK. But when I try to create backup of a selected db:

mongodump --username bacUser --password 12345 --db test

It gives me this error:

Failed: error connecting to db server: server returned error on SASL authentication step: Authentication failed.

Body:
mongodump --host <host-ip> --port 27017 --db <database>  --authenticationDatabase admin --username <username> --password <password> --out ./Documents/

After all the trail, I found above working command to dump from mongdb.

ContentLicense: CC BY-SA 4.0


问:
Print ONNXRUNTIME::Graph without having Model
I'm working on new optimizer that inherits from GraphTransformer in c++

How can I view the changes that I made, just after ApplyImpl ends
I tried graph.ToGraphProto() but I cannot save it
And I need to make a new Model to be able to save it and view it in Netron or something

答:
Found it
Need to make new model and versions
need to get SchemaRegistry:</p>

```<code>ModelProto model_proto1;
model_proto1.set_ir_version(IR_VERSION);
OperatorSetIdProto* op_set_id = model_proto1.add_opset_import();
op_set_id->set_domain("");
op_set_id->set_version(12);
model_proto1.set_allocated_graph(new GraphProto(graph.ToGraphProto()));
IOnnxRuntimeOpSchemaRegistryList local_registries{graph.GetSchemaRegistry()};

Model model(model_proto1, &local_registries, logger);
onnxruntime::Model::Save(model, "/tmp/new_g.onnx");
</code>```

Body:
Found it
Need to make new model and versions
need to get SchemaRegistry:

ModelProto model_proto1;
model_proto1.set_ir_version(IR_VERSION);
OperatorSetIdProto* op_set_id = model_proto1.add_opset_import();
op_set_id->set_domain("");
op_set_id->set_version(12);
model_proto1.set_allocated_graph(new GraphProto(graph.ToGraphProto()));
IOnnxRuntimeOpSchemaRegistryList local_registries{graph.GetSchemaRegistry()};

Model model(model_proto1, &local_registries, logger);
onnxruntime::Model::Save(model, "/tmp/new_g.onnx");


问:
Why introduce a new array in a method? Why not reuse the parameter?
In the method normalize I input an array say, {1, 2, 3, 4}, and the return is a normalized array, {0.1, 0.2, 0.3, 0.4}.
I know I should introduce a new array in the method (b in the following), but why actually?

```<code>public static double[] normalize(double[] a) {
    double[] b = new double[a.length];
    double sum = 0;
        for (int i = 0; i < b.length; i++) {
            sum += a[i];
        }
        for (int i = 0; i < b.length; i++) {
            b[i] = a[i]/sum;
        }
    return b;
}
Input: 1 2 3 4
Output: 0.1 0.2 0.3 0.4
</code>```

Why is the following wrong:

```<code>public static double[] normalize(double[] a) {
    double sum = 0;
        for (int i = 0; i < a.length; i++) {
            sum += a[i];
        }
        for (int i = 0; i < a.length; i++) {
            a[i] = a[i]/sum;
        }
    return a;
}
Input: 1 2 3 4
Output: 0.1 0.2 0.3 0.4
</code>```

答:
In the first case, the original array will stay unmodified when the method returns.

In the second case, the original array will be modified (even when it returns to where it was called), irregardless to whatever array you set the return value to afterward.

Both options can be viable, but it depends on the case and what is expected to happen.  However, typically I would expect when you pass a parameter to a method, the parameter will not be modified when the method returns.

Documentation can make it clear that the original array will be modified or if it will not be.

Side Note:

This will not work the same way if you modify a directly, instead of modifying the values contained within:

```<code>public static void normalize(double[] a) {
    a = new double[5];
}
</code>```

a will remain unchanged in this case when the method returns.

Body:
In the method normalize I input an array say, {1, 2, 3, 4}, and the return is a normalized array, {0.1, 0.2, 0.3, 0.4}.
I know I should introduce a new array in the method (b in the following), but why actually?

public static double[] normalize(double[] a) {
    double[] b = new double[a.length];
    double sum = 0;
        for (int i = 0; i < b.length; i++) {
            sum += a[i];
        }
        for (int i = 0; i < b.length; i++) {
            b[i] = a[i]/sum;
        }
    return b;
}
Input: 1 2 3 4
Output: 0.1 0.2 0.3 0.4

Why is the following wrong:

public static double[] normalize(double[] a) {
    double sum = 0;
        for (int i = 0; i < a.length; i++) {
            sum += a[i];
        }
        for (int i = 0; i < a.length; i++) {
            a[i] = a[i]/sum;
        }
    return a;
}
Input: 1 2 3 4
Output: 0.1 0.2 0.3 0.4

Body:
In the first case, the original array will stay unmodified when the method returns.

In the second case, the original array will be modified (even when it returns to where it was called), irregardless to whatever array you set the return value to afterward.

Both options can be viable, but it depends on the case and what is expected to happen.  However, typically I would expect when you pass a parameter to a method, the parameter will not be modified when the method returns.

Documentation can make it clear that the original array will be modified or if it will not be.

Side Note:

This will not work the same way if you modify a directly, instead of modifying the values contained within:

public static void normalize(double[] a) {
    a = new double[5];
}

a will remain unchanged in this case when the method returns.


答:
The difference is that one method updates the input array in place, whereas the other one keeps the array intact and returns a copy.

Neither is wrong(*), both ways have their place, you just need to make sure to the caller knows what is happening.

If you update in-place, you can make that clearer by making the method void instead of returning a (redundant) reference to the same array.

(*) In modern practice, prefer immutable data structures. So unless performance is a real issue, go with the "safer" variant.

Title: Why introduce a new array in a method? Why not reuse the parameter?


问:
Error using Flickr photos search api: Invalid API Key (Key has invalid format)
In my app I'm doing some work to construct a query string to call through Flickr API, the result is something like this:

```<code>https://api.flickr.com/services/rest/?format=json&api_key={MY API KEY}&method=flickr.photos.search&tags=happy%2Cdog
</code>```

Requesting that in the browser works just fine, however, requesting the same query with curl returns an error:

```<code>jsonFlickrApi({"stat":"fail","code":100,"message":"Invalid API Key (Key has invalid format)"})
</code>```

Here's my curl code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $this->query);
$result = curl_exec($ch);
curl_close($ch);
```

答:
If it works when the URL generated by your system gets copy&pasted into the browser, then something must be different.

Your debug output likely got interpreted as HTML, so if there is an erroneous & in there somewhere instead of just an &, it still looks like an &, and also gets copy&pasted as &.

htmlspecialchars is always helpful in cases like this, to see the actual value, and not what the browser has interpreted it as.

Body:
In my app I'm doing some work to construct a query string to call through Flickr API, the result is something like this:

https://api.flickr.com/services/rest/?format=json&api_key={MY API KEY}&method=flickr.photos.search&tags=happy%2Cdog

Requesting that in the browser works just fine, however, requesting the same query with curl returns an error:

jsonFlickrApi({"stat":"fail","code":100,"message":"Invalid API Key (Key has invalid format)"})

Here's my curl code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, $this->query);
$result = curl_exec($ch);
curl_close($ch);

Body:
If it works when the URL generated by your system gets copy&pasted into the browser, then something must be different.

Your debug output likely got interpreted as HTML, so if there is an erroneous &amp; in there somewhere instead of just an &, it still looks like an &, and also gets copy&pasted as &.

htmlspecialchars is always helpful in cases like this, to see the actual value, and not what the browser has interpreted it as.


问:
Question on threading in C#
I have a Windows Forms application at the moment, and I want to create a new thread and run a method on another class that accepts an input.

For example

```<code>public partial class Form1: Form {
    SerialPort serialInput;
    // I want to create a new thread that will pass the parameter serialInput into the method
    // SMSListener on another class and run the method contionously on the background.
}

class SMS
{
    public void SMSListener(SerialPort serial1)
    {
        serial1.DataReceived += port_DataRecieved;
    }

    private void port_DataRecieved(object sender, SerialDataReceivedEventArgs e)
    {
        // Other codes
    }
}
</code>```

How do I perform this in C#? I have seen numerous examples on the web, and most of them run the method on the same class with no parameters, but none that suits my requirements.

答:
Perhaps a Background Worker could help you?

It is a bit hard to understand what you are aiming at.

```<code>public class Runner
{
    private readonly BackgroundWorker _worker = new BackgroundWorker();

    public Runner()
    {
        _worker.DoWork += WorkerDoWork;
    }

    public void RunMe(int payload)
    {
        _worker.RunWorkerAsync(payload);
    }

    static void WorkerDoWork(object sender, DoWorkEventArgs e)
    {
        var worker = sender as BackgroundWorker;

        while (true)
        {
            if (worker.CancellationPending)
            {
                e.Cancel = true;
                break;
            }

            // Work
            System.Threading.Thread.Sleep((int)e.Argument);
        }
    }
}
</code>```

Title: Question on threading in C#

Body:
I have a Windows Forms application at the moment, and I want to create a new thread and run a method on another class that accepts an input.

For example

public partial class Form1: Form {
    SerialPort serialInput;
    // I want to create a new thread that will pass the parameter serialInput into the method
    // SMSListener on another class and run the method contionously on the background.
}

class SMS
{
    public void SMSListener(SerialPort serial1)
    {
        serial1.DataReceived += port_DataRecieved;
    }

    private void port_DataRecieved(object sender, SerialDataReceivedEventArgs e)
    {
        // Other codes
    }
}

How do I perform this in C#? I have seen numerous examples on the web, and most of them run the method on the same class with no parameters, but none that suits my requirements.

Body:
Perhaps a Background Worker could help you?

It is a bit hard to understand what you are aiming at.

public class Runner
{
    private readonly BackgroundWorker _worker = new BackgroundWorker();

    public Runner()
    {
        _worker.DoWork += WorkerDoWork;
    }

    public void RunMe(int payload)
    {
        _worker.RunWorkerAsync(payload);
    }

    static void WorkerDoWork(object sender, DoWorkEventArgs e)
    {
        var worker = sender as BackgroundWorker;

        while (true)
        {
            if (worker.CancellationPending)
            {
                e.Cancel = true;
                break;
            }

            // Work
            System.Threading.Thread.Sleep((int)e.Argument);
        }
    }
}


问:
Problem with declaring a protected pointer to a vector
I'm trying to declare a pointer to a std::vector<int> in a derived class in C++. That class is a base class for other classes again.

My attempt was as follows

```<code>protected:
   std::vector<CustomClass> *mypointer;
</code>```

However, when I compile it, I get the following error:

```<code>error: no match for ‘operator=’ (operand types are ‘std::vector<int>’ and ‘std::vector<int>*’)
error: no match for ‘operator*’ (operand type is ‘std::vector<int>’)
</code>```

and some other operands are missing.

I'm pretty clueless, where the problem lies at all. Do I have to implement all those functions in the current class? If so, why do I have to do so?

For anyone needing more context, I want to implement that pointer in the class CbmStsSensor (found here), which derives from CbmStsElement.

Edit: Some relevant classes can be found here CbmStsElement.h and here enter link description here.

Edit2: The whole compilation error log can be found here.

答:
The problem wasn't the c++ code itself, but the framework it used, in this case ROOT. If you define a pointer in a ROOT class, you have to tell the program what to do with that pointer in the case of the class being written to file. Even though the class might never be written to a file (like in my case).
In this specific case (class never being written to a file), you can simply tell ROOT to ignore the given pointer by adding //! after the declaration, e.g. write

```<code>protected:
   std::vector<CustomClass> *mypointer; //!
</code>```

Thanks to everyone for helping in this helpless case!

Body:
I'm trying to declare a pointer to a std::vector<int> in a derived class in C++. That class is a base class for other classes again.

My attempt was as follows

protected:
   std::vector<CustomClass> *mypointer;

However, when I compile it, I get the following error:

error: no match for ‘operator=’ (operand types are ‘std::vector<int>’ and ‘std::vector<int>*’)
error: no match for ‘operator*’ (operand type is ‘std::vector<int>’)

and some other operands are missing.

I'm pretty clueless, where the problem lies at all. Do I have to implement all those functions in the current class? If so, why do I have to do so?

For anyone needing more context, I want to implement that pointer in the class CbmStsSensor (found here), which derives from CbmStsElement.

Edit: Some relevant classes can be found here CbmStsElement.h and here enter link description here.

Edit2: The whole compilation error log can be found here.

Body:
The problem wasn't the c++ code itself, but the framework it used, in this case ROOT. If you define a pointer in a ROOT class, you have to tell the program what to do with that pointer in the case of the class being written to file. Even though the class might never be written to a file (like in my case).
In this specific case (class never being written to a file), you can simply tell ROOT to ignore the given pointer by adding //! after the declaration, e.g. write

protected:
   std::vector<CustomClass> *mypointer; //!

Thanks to everyone for helping in this helpless case!


问:
How to fix error "ANCM In-Process Handler Load Failure"?
I'm setting up the first site in IIS on Windows Server 2016 Standard.
This is a NET Core 2.2 application. I cannot get the site to show.

I am getting this error:

HTTP Error 500.0 - ANCM In-Process Handler Load Failure

What can I change to clear this error and get my site to display?

My application is a dll.

I tested my application on the server through the Command Prompt with

```<code>dotnet ./MyApp.dll
</code>```

it displays in the browser but only on the server itself with (localhost:5001/).

Using this method the site cannot be accessed from any other server.
When I set up the site through IIS, I get the In-Process error both on the server and from servers attempting to access the site.

At first I was receiving the Out-Process error. Something I read said to add this (hostingModel="inprocess") to my web.config
so I did but now I receive the In-Process error.

The site works fine when installed on my development server.

The Event Viewer shows this error for "IIS AspNetCore Module V2":

Failed to start application '/LM/W3SVC/2/ROOT', ErrorCode '0x8000ffff'.

This is my web.config:

<?xml version="1.0" encoding="utf-8"?>
    <configuration>
  <system.web>
    <customErrors mode="RemoteOnly"></customErrors>
        <identity impersonate="false" password="****" userName="****" />
  </system.web>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="dotnet" arguments=".\MyApp.dll" stdoutLogEnabled="false" hostingModel="inprocess" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false">
      <environmentVariables />
    </aspNetCore>
  </system.webServer>
</configuration>
```

答:
Sometimes this is because multiple applications may be using same Application Pool

In such cases first application will work and other won't work

Solution is to create new application pool for each application.

Body:
I'm setting up the first site in IIS on Windows Server 2016 Standard.
This is a NET Core 2.2 application. I cannot get the site to show.

I am getting this error:

HTTP Error 500.0 - ANCM In-Process Handler Load Failure

What can I change to clear this error and get my site to display?

My application is a dll.

I tested my application on the server through the Command Prompt with

dotnet ./MyApp.dll

it displays in the browser but only on the server itself with (localhost:5001/).

Using this method the site cannot be accessed from any other server.
When I set up the site through IIS, I get the In-Process error both on the server and from servers attempting to access the site.

At first I was receiving the Out-Process error. Something I read said to add this (hostingModel="inprocess") to my web.config
so I did but now I receive the In-Process error.

The site works fine when installed on my development server.

The Event Viewer shows this error for "IIS AspNetCore Module V2":

Failed to start application '/LM/W3SVC/2/ROOT', ErrorCode '0x8000ffff'.

This is my web.config:

<?xml version="1.0" encoding="utf-8"?>
    <configuration>
  <system.web>
    <customErrors mode="RemoteOnly"></customErrors>
        <identity impersonate="false" password="****" userName="****" />
  </system.web>
  <system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="dotnet" arguments=".\MyApp.dll" stdoutLogEnabled="false" hostingModel="inprocess" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false">
      <environmentVariables />
    </aspNetCore>
  </system.webServer>
</configuration>


问:
What does the "!!" operator mean in Kotlin?
I'm reading this guide from Google for Android and they have the snippet bellow.

What does the !! do in userDao.save(response.body()!!)?

```<code>private fun refreshUser(userId: String) {
   // Runs in a background thread.
   executor.execute {
       // Check if user data was fetched recently.
       val userExists = userDao.hasUser(FRESH_TIMEOUT)
       if (!userExists) {
           // Refreshes the data.
           val response = webservice.getUser(userId).execute()

           // Check for errors here.

           // Updates the database. The LiveData object automatically
           // refreshes, so we don't need to do anything else here.
           userDao.save(response.body()!!)
       }
   }
}
</code>```

答:
This is used to convert an expression to non-null and throw a KotlinNullPointerException if the result is null. So in this usage, it will only save the response's body was not null, otherwise an exception will be thrown.

See here for more information.

Body:
I'm reading this guide from Google for Android and they have the snippet bellow.

What does the !! do in userDao.save(response.body()!!)?

private fun refreshUser(userId: String) {
   // Runs in a background thread.
   executor.execute {
       // Check if user data was fetched recently.
       val userExists = userDao.hasUser(FRESH_TIMEOUT)
       if (!userExists) {
           // Refreshes the data.
           val response = webservice.getUser(userId).execute()

           // Check for errors here.

           // Updates the database. The LiveData object automatically
           // refreshes, so we don't need to do anything else here.
           userDao.save(response.body()!!)
       }
   }
}


问:
Is apache flink TimerService callback and KeyedProcessFunction.processElement thread safe
I have a KeyedProcessFunction implementation that override "processElement()" and "onTimer()" methods.
Are they threads safe to each other?

Seems that the onTimer() method is called by a TimerService thead pool. So it looks like to me they could be executed in the same time.

答:
processElement and onTimer are never executed in parallel.

Prior to Flink 1.10, both methods would be invoked after acquiring the checkpoint lock.

Since Flink 1.10, they are only invoked through the same task thread, so it's even safe to access fields in a non-synchronized fashion (even if using non-managed fields is discouraged to begin with).


问:
How to send fcm notification when app is not running
I have tried many solutions but none of them are worked. I am able receive FCM notification when app is active, but not getting notification when app is background or killed.</p>

答:
If you want to get notification when app is background or killed your json object has to be this like:

{
  "data":{
    "title" : "your_title",
    "body" : "your_body"
  },
  "to": "device_token",
  "priority": "high"
}

You can catch notification onMessageReceived


问:
Looking for a more pythonic way of converting list of lists to string
I have python (3.7) code that works, but it's ugly, and I'm sure there's a more elegant way of doing what I want to do.  I have 9 3x3 grids that I want to print out (plus some line separators) for a tic-tac-toe game.

I basically want the output to look like this (sample of the first row)

```<code>█ █│   │███
 █ │ 2 │█ █
█ █│   │███
</code>```

The code below does this, but it seems like there's a better way, and I'm not sure how to do this in an elegant for loop.

Thanks in advance!

```<code>choice_x = [
    ['█', ' ', '█'],
    [' ', '█', ' '],
    ['█', ' ', '█']
]

choice_o = [
    ['█', '█', '█'],
    ['█', ' ', '█'],
    ['█', '█', '█']
]

v_grid = [
    ['│'],
    ['│'],
    ['│']
]

empty_grid = [
    [' ',' ',' '],
    [' ','2',' '],
    [' ',' ',' ']
]

row1 = [
    choice_x, v_grid, empty_grid, v_grid, choice_o
]

#for n in range(0,4):
slice1 = [sublist[0][:3] for sublist in row1]
result = ''.join([''.join(item) for item in slice1])
print(result)

slice2 = [sublist[1][:3] for sublist in row1]
result = ''.join([''.join(item) for item in slice2])
print(result)

slice3 = [sublist[2][:3] for sublist in row1]
result = ''.join([''.join(item) for item in slice3])
print(result)
#end for loop
</code>```

Body:
I have python (3.7) code that works, but it's ugly, and I'm sure there's a more elegant way of doing what I want to do.  I have 9 3x3 grids that I want to print out (plus some line separators) for a tic-tac-toe game.

I basically want the output to look like this (sample of the first row)

█ █│   │███
 █ │ 2 │█ █
█ █│   │███

The code below does this, but it seems like there's a better way, and I'm not sure how to do this in an elegant for loop.

Thanks in advance!

choice_x = [
    ['█', ' ', '█'],
    [' ', '█', ' '],
    ['█', ' ', '█']
]

choice_o = [
    ['█', '█', '█'],
    ['█', ' ', '█'],
    ['█', '█', '█']
]

v_grid = [
    ['│'],
    ['│'],
    ['│']
]

empty_grid = [
    [' ',' ',' '],
    [' ','2',' '],
    [' ',' ',' ']
]

row1 = [
    choice_x, v_grid, empty_grid, v_grid, choice_o
]

#for n in range(0,4):
slice1 = [sublist[0][:3] for sublist in row1]
result = ''.join([''.join(item) for item in slice1])
print(result)

slice2 = [sublist[1][:3] for sublist in row1]
result = ''.join([''.join(item) for item in slice2])
print(result)

slice3 = [sublist[2][:3] for sublist in row1]
result = ''.join([''.join(item) for item in slice3])
print(result)
#end for loop

Body:
Try this:

class Printer:
    def __init__(self):
        self.grid = [[[[" " for y in range(3)] for x in range(3)] for i in range(3)] for j in range(3)]

    def render(self):
        print("-" * 13)
        for y in range(3):
            for j in range(3):
                print("|",end="")
                for x in range(3):
                    print("".join(self.grid[y][x][j]), end="|")
                print()
            print("-" * 13)

    def set_char(self, x, y, char):
        self.grid[y][x] = char

choice_x = [
    ['█', ' ', '█'],
    [' ', '█', ' '],
    ['█', ' ', '█']
]

choice_o = [
    ['█', '█', '█'],
    ['█', ' ', '█'],
    ['█', '█', '█']
]

empty_grid = [
    [' ',' ',' '],
    [' ','2',' '],
    [' ',' ',' ']
]

board = Printer()
board.set_char(0,1,choice_x)
board.set_char(1,1,empty_grid)
board.set_char(2,1,choice_o)
board.render()

print("\n" * 2)

board.set_char(2, 0, choice_o)
board.render()

Output:

-------------
|   |   |   |
|   |   |   |
|   |   |   |
-------------
|█ █|   |███|
| █ | 2 |█ █|
|█ █|   |███|
-------------
|   |   |   |
|   |   |   |
|   |   |   |
-------------

-------------
|   |   |███|
|   |   |█ █|
|   |   |███|
-------------
|█ █|   |███|
| █ | 2 |█ █|
|█ █|   |███|
-------------
|   |   |   |
|   |   |   |
|   |   |   |
-------------

Board x/y explaination:

   0 1 2
  -------
0 | | | |
  -------
1 | | | |
  -------
2 | | | |
  -------

As you can see, both start at 0, and top-left.

Hope this helps :)


问:
How can an ES6 module be run as a script in Node?
How can an ES6 module be run as a script in Node?

When I try this shebang I get an error:

```<code>#!/usr/bin/env node --experimental-modules
</code>```

/usr/bin/env: ‘node --experimental-modules’: No such file or directory

If I use this shebang it has syntax errors (of course):

```<code>#!/usr/bin/env node
</code>```

SyntaxError: Unexpected token import

The work around I'm using is to use a shell script to call the module:

```<code>#!/usr/bin/env sh

BASEDIR=$( dirname "$0" )
node --experimental-modules $BASEDIR/script.mjs "$@"
</code>```

Is it possible to get this working without a second file?

答:
I've patched Ishan Thilina Somasiri solution to work with Node 13 without the .mjs extension:

#!/usr/bin/env bash
":" //# comment; exec /usr/bin/env node --input-type=module - "$@" < "$0"

import { hostname } from 'os';

console.log(hostname());
```

The trick is pretty much the same, but using stdin, which is the only documented way when you don't have a package.json nor the .mjs extension. Thus, a standalone extensionless script.

However, global variables like __dirname or __filename won't be available.

Body:
How can an ES6 module be run as a script in Node?

When I try this shebang I get an error:

#!/usr/bin/env node --experimental-modules

/usr/bin/env: ‘node --experimental-modules’: No such file or directory

If I use this shebang it has syntax errors (of course):

#!/usr/bin/env node

SyntaxError: Unexpected token import

The work around I'm using is to use a shell script to call the module:

#!/usr/bin/env sh

BASEDIR=$( dirname "$0" )
node --experimental-modules $BASEDIR/script.mjs "$@"

Is it possible to get this working without a second file?

Body:
I've patched Ishan Thilina Somasiri solution to work with Node 13 without the .mjs extension:

#!/usr/bin/env bash
":" //# comment; exec /usr/bin/env node --input-type=module - "$@" < "$0"

import { hostname } from 'os';

console.log(hostname());

The trick is pretty much the same, but using stdin, which is the only documented way when you don't have a package.json nor the .mjs extension. Thus, a standalone extensionless script.

However, global variables like __dirname or __filename won't be available.


问:
Can't create dbConnect to Postgres with SSL
I'm running a Postgres-9.4 server that I would like to require SSL for.  When I connect to the Postgres server from my laptop with either pgadmin or windows odbc connection, it works with SSL.  However when I try to connect with R using SSL it fails.

```<code>library(RPostgreSQL)
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv,
                 user = "postgres",
                 password = mypasswd,
                 dbname = "dbname=postgres sslmode=prefer",
                 host = "192.168.1.179")
</code>```

If I set my pg_hba.conf to allow non-ssl connections then this will work.  When I set it to only allow SSL connections then this will fail.  Unfortunately dbConnect doesn't have a verbose option so I don't get anything more than could not connect postgres@192.168.1.179 on dbname "postgres"

I found this question which seems to suggest I'm doing the right thing but, no go.

Edit:

I did some more digging and found this discussion which suggests that this won't work on windows due to various library/dll issues.  That discussion is a few years old at this point so perhaps it has been resolved.  I can confirm that doing the above from linux does work.

答:
My understanding of the problem is that RPostgreSQL uses a client that doesn't support SSL.

I switched to the package RPostgres and got it to work. I first installed RPostgres with install.packages('RPostgres')  then used this package to connect with sslmode="require".

```<code>library('RPostgres') #Instead of library('RPostgreSQL')
con <- dbConnect(RPostgres::Postgres(),
                 user = "postgres",
                 password = mypasswd,
                 dbname = "postgres",
                 host = "192.168.1.179",
                 sslmode = "require")
)
</code>```

Body:
I'm running a Postgres-9.4 server that I would like to require SSL for.  When I connect to the Postgres server from my laptop with either pgadmin or windows odbc connection, it works with SSL.  However when I try to connect with R using SSL it fails.

library(RPostgreSQL)
drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv,
                 user = "postgres",
                 password = mypasswd,
                 dbname = "dbname=postgres sslmode=prefer",
                 host = "192.168.1.179")

If I set my pg_hba.conf to allow non-ssl connections then this will work.  When I set it to only allow SSL connections then this will fail.  Unfortunately dbConnect doesn't have a verbose option so I don't get anything more than could not connect postgres@192.168.1.179 on dbname "postgres"

I found this question which seems to suggest I'm doing the right thing but, no go.

Edit:

I did some more digging and found this discussion which suggests that this won't work on windows due to various library/dll issues.  That discussion is a few years old at this point so perhaps it has been resolved.  I can confirm that doing the above from linux does work.

Body:
My understanding of the problem is that RPostgreSQL uses a client that doesn't support SSL.

I switched to the package RPostgres and got it to work. I first installed RPostgres with install.packages('RPostgres')  then used this package to connect with sslmode="require".

library('RPostgres') #Instead of library('RPostgreSQL')
con <- dbConnect(RPostgres::Postgres(),
                 user = "postgres",
                 password = mypasswd,
                 dbname = "postgres",
                 host = "192.168.1.179",
                 sslmode = "require")
)


问:
Remove BOM (ï»¿) from imported .csv file
I want to delete the BOM from my imported file, but it just doesn't seem to work.

I tried to preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $file); and a str_replace.

I hope anybody sees what I'm doing wrong.

```<code>$filepath = get_bloginfo('template_directory')."/testing.csv";
            setlocale(LC_ALL, 'nl_NL');
            ini_set('auto_detect_line_endings',TRUE);
            $file = fopen($filepath, "r") or die("Error opening file");
            $i = 0;
            while(($line = fgetcsv($file, 1000, ";")) !== FALSE) {
                if($i == 0) {
                    $c = 0;
                    foreach($line as $col) {
                        $cols[$c] = utf8_encode($col);
                        $c++;
                    }
                } else if($i > 0) {
                    $c = 0;
                    foreach($line as $col) {
                        $data[$i][$cols[$c]] = utf8_encode($col);
                        $c++;
                    }
                }
                $i++;
            }
</code>```

-----------

SOLVED VERSION:

```<code>setlocale(LC_ALL, 'nl_NL');
ini_set('auto_detect_line_endings',TRUE);
require_once(ABSPATH.'wp-admin/includes/file.php' );

$path = get_home_path();
$filepath = $path .'wp-content/themes/pon/testing.csv';
$content = file_get_contents($filepath);
file_put_contents($filepath, str_replace("\xEF\xBB\xBF",'', $content));

// FILE_PUT_CONTENTS AUTOMATICCALY CLOSES THE FILE
$file = fopen($filepath, "r") or die("Error opening file");

$i = 0;
while(($line = fgetcsv($file, 1000, ";")) !== FALSE) {
    if($i == 0) {
        $c = 0;
        foreach($line as $col) {
            $cols[$c] = $col;
            $c++;
        }
    } else if($i > 0) {
        $c = 0;
        foreach($line as $col) {
            $data[$i][$cols[$c]] = $col;
            $c++;
        }
    }
    $i++;
}
</code>```

I found that it removes the BOM and adjusts the file by overwriting it with the new data. The problem is that the rest of my script doesn't work anymore and I can't see why. It is a new .csv file

答:
Correct way is to skip BOM if present in file (https://www.php.net/manual/en/function.fgetcsv.php#122696):</p>

```<code>ini_set('auto_detect_line_endings',TRUE);
$file = fopen($filepath, "r") or die("Error opening file");
if (fgets($file, 4) !== "\xef\xbb\xbf") //Skip BOM if present
        rewind($file); //Or rewind pointer to start of file

$i = 0;
while(($line = fgetcsv($file, 1000, ";")) !== FALSE) {
    ...
}
</code>```

Body:
I want to delete the BOM from my imported file, but it just doesn't seem to work.

I tried to preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $file); and a str_replace.

I hope anybody sees what I'm doing wrong.

$filepath = get_bloginfo('template_directory')."/testing.csv";
            setlocale(LC_ALL, 'nl_NL');
            ini_set('auto_detect_line_endings',TRUE);
            $file = fopen($filepath, "r") or die("Error opening file");
            $i = 0;
            while(($line = fgetcsv($file, 1000, ";")) !== FALSE) {
                if($i == 0) {
                    $c = 0;
                    foreach($line as $col) {
                        $cols[$c] = utf8_encode($col);
                        $c++;
                    }
                } else if($i > 0) {
                    $c = 0;
                    foreach($line as $col) {
                        $data[$i][$cols[$c]] = utf8_encode($col);
                        $c++;
                    }
                }
                $i++;
            }

-----------

SOLVED VERSION:

setlocale(LC_ALL, 'nl_NL');
ini_set('auto_detect_line_endings',TRUE);
require_once(ABSPATH.'wp-admin/includes/file.php' );

$path = get_home_path();
$filepath = $path .'wp-content/themes/pon/testing.csv';
$content = file_get_contents($filepath);
file_put_contents($filepath, str_replace("\xEF\xBB\xBF",'', $content));

// FILE_PUT_CONTENTS AUTOMATICCALY CLOSES THE FILE
$file = fopen($filepath, "r") or die("Error opening file");

$i = 0;
while(($line = fgetcsv($file, 1000, ";")) !== FALSE) {
    if($i == 0) {
        $c = 0;
        foreach($line as $col) {
            $cols[$c] = $col;
            $c++;
        }
    } else if($i > 0) {
        $c = 0;
        foreach($line as $col) {
            $data[$i][$cols[$c]] = $col;
            $c++;
        }
    }
    $i++;
}

I found that it removes the BOM and adjusts the file by overwriting it with the new data. The problem is that the rest of my script doesn't work anymore and I can't see why. It is a new .csv file

Body:
Correct way is to skip BOM if present in file (https://www.php.net/manual/en/function.fgetcsv.php#122696):

ini_set('auto_detect_line_endings',TRUE);
$file = fopen($filepath, "r") or die("Error opening file");
if (fgets($file, 4) !== "\xef\xbb\xbf") //Skip BOM if present
        rewind($file); //Or rewind pointer to start of file

$i = 0;
while(($line = fgetcsv($file, 1000, ";")) !== FALSE) {
    ...
}


问:
Mongodb,find results from array and move to another array
for example：

```<code>{
  "groups": [
    ...,
    {
      "id": 1,
      "name": "g1",
      "items": [
        {
          "id": 11,
          "name": "item-11"
        },
        {
          "id": 12,
          "name": "item-12"
        }
      ]
    },
    {
      "_id": 2,
      "name": "g2",
      "items": []
    }
  ]
}
</code>```

Use ‘update’, groups[0].items search results, move to groups[1].items.

Expected result:

```<code>{
  "groups": [
    {
      "_id": 2,
      "name": "g2",
      "items": [
        {
          "id": 11,
          "name": "item-11"
        },
        {
          "id": 12,
          "name": "item-12"
        }
      ]
    }
  ]
}
</code>```

答:
Based on answers to this question it looks like the only way to use value of another field in an update is to create a script. You haven't specified what is the expected for groups[0].items so I set it to empty array:

```<code>var requests = [];
var cursor = db.getCollection('collection_name').find({});
cursor.forEach(document => {
    requests.push( {
        'updateOne': {
            'filter': { '_id': document._id },
            'update': { '$set': {
                'groups.1.items': document.groups[0].items,
                'groups.0.items': []
                 }
            }
        }
    });
    if (requests.length === 500) {
        //Execute per 500 operations and re-init
        db.getCollection("collection_name").bulkWrite(requests);
        requests = [];
    }
});

if(requests.length > 0) {
     db.getCollection("collection_name").bulkWrite(requests);
}
</code>```

Body:
for example：

{
  "groups": [
    ...,
    {
      "id": 1,
      "name": "g1",
      "items": [
        {
          "id": 11,
          "name": "item-11"
        },
        {
          "id": 12,
          "name": "item-12"
        }
      ]
    },
    {
      "_id": 2,
      "name": "g2",
      "items": []
    }
  ]
}

Use ‘update’, groups[0].items search results, move to groups[1].items.

Expected result:

{
  "groups": [
    {
      "_id": 2,
      "name": "g2",
      "items": [
        {
          "id": 11,
          "name": "item-11"
        },
        {
          "id": 12,
          "name": "item-12"
        }
      ]
    }
  ]
}

Body:
Based on answers to this question it looks like the only way to use value of another field in an update is to create a script. You haven't specified what is the expected for groups[0].items so I set it to empty array:

var requests = [];
var cursor = db.getCollection('collection_name').find({});
cursor.forEach(document => {
    requests.push( {
        'updateOne': {
            'filter': { '_id': document._id },
            'update': { '$set': {
                'groups.1.items': document.groups[0].items,
                'groups.0.items': []
                 }
            }
        }
    });
    if (requests.length === 500) {
        //Execute per 500 operations and re-init
        db.getCollection("collection_name").bulkWrite(requests);
        requests = [];
    }
});

if(requests.length > 0) {
     db.getCollection("collection_name").bulkWrite(requests);
}


问:
vector resizing - portable way to detect
I have a vector that I am loading with a know amount of elements (N).

The processing dynamically creates new elements, which are appended to the vector.

I am expecting about 2 * N additional elements to be created,
so I resize the vector to 3 * N.

If the additional elements exceed that, I would like a program abort, rather than a dynamic expansion of the vector.

Is there a way to detect that, that is portable between AIX/TRU64/Linux?

答:
std classes use an allocator called everytime you insert an element. You can write a new allocator inheriting from the std::alocator, and add all kind of checks/traces you need. </p>

<p>(I did this before but it took me a while to make working code.)</p>

OwnerDisplayName: EvilTeach

ContentLicense: CC BY-SA 2.5

Body:
std classes use an allocator called everytime you insert an element. You can write a new allocator inheriting from the std::alocator, and add all kind of checks/traces you need.

(I did this before but it took me a while to make working code.)

OwnerDisplayName: Ben


问:
Deactivate function with decorator
Is it possible to "deactivate" a function with a python decorator? Here an example:

```<code>cond = False

class C:

    if cond:
        def x(self): print "hi"

    def y(self): print "ho"
</code>```

Is it possible to rewrite this code with a decorator, like this?:

```<code>class C:

    @cond
    def x(self): print "hi"

    def y(self): print "ho"
</code>```

Background: In our library are some dependencies (like matplotlib) optional, and these are only needed by a few functions (for debug or fronted). This means on some systems matplotlib is installed on other systems not, but on both should run the (core) code. Therefor I'd like to disable some functions if matplotlib is not installed. Is there such elegant way?

答:
removing methods from a class seems strange to me. Why not use try / except

```<code>plot_avail = True
try:
    import matplotlib
except:
    plot_avail = False
</code>```

then in your function(s)

```<code>def x(self):
    if not plot_avail: return
</code>```

So no call ends up in: class has not attribute X

Title: Deactivate function with decorator

Body:
Is it possible to "deactivate" a function with a python decorator? Here an example:

cond = False

class C:

    if cond:
        def x(self): print "hi"

    def y(self): print "ho"

Is it possible to rewrite this code with a decorator, like this?:

class C:

    @cond
    def x(self): print "hi"

    def y(self): print "ho"

Background: In our library are some dependencies (like matplotlib) optional, and these are only needed by a few functions (for debug or fronted). This means on some systems matplotlib is installed on other systems not, but on both should run the (core) code. Therefor I'd like to disable some functions if matplotlib is not installed. Is there such elegant way?

Body:
removing methods from a class seems strange to me. Why not use try / except

plot_avail = True
try:
    import matplotlib
except:
    plot_avail = False

then in your function(s)

def x(self):
    if not plot_avail: return

So no call ends up in: class has not attribute X


问:
How do I add multiple users for keycloak clients
I'm trying to make an applications with single sign on with keycloak. I generate realm, clients as per the documentation given by keycloak. But I have to add users for my clients. I have more than 5000 users for each client (application). So I want to know is there any way to add multiple users at a time.
If there is any please guide.
Thanks</p>

答:
You could write Java tool that will do the import. Keycloak provides Java libs to work with API.
Add dependency:

```<code><dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-admin-client</artifactId>
    <version>8.0.2</version>
</dependency>
</code>```

And then you can create a user like this:

```<code>Keycloak keycloak = Keycloak.getInstance("http://localhost:8080/auth",
            "master",
            "admin",
            "admin",
            "admin-cli",
            "password");

UserRepresentation user = new UserRepresentation();
user.setUsername("username1");
user.setFirstName("John");
user.setLastName("Doe");
user.setEnabled(true);
Response response = keycloak.realm("master").users().create(user);
</code>```

So it is quite simple and Java tool will give you flexibility to read from different sources types and preprocess/adjust data if needed.

Body:
You could write Java tool that will do the import. Keycloak provides Java libs to work with API.
Add dependency:

<dependency>
    <groupId>org.keycloak</groupId>
    <artifactId>keycloak-admin-client</artifactId>
    <version>8.0.2</version>
</dependency>

And then you can create a user like this:

Keycloak keycloak = Keycloak.getInstance("http://localhost:8080/auth",
            "master",
            "admin",
            "admin",
            "admin-cli",
            "password");

UserRepresentation user = new UserRepresentation();
user.setUsername("username1");
user.setFirstName("John");
user.setLastName("Doe");
user.setEnabled(true);
Response response = keycloak.realm("master").users().create(user);

So it is quite simple and Java tool will give you flexibility to read from different sources types and preprocess/adjust data if needed.


问:
Change order of blocks for mobile and desktop both vertically and horizontally
I am trying to create a layout which allows me change the order of elements between mobile and desktop as demonstrated by the diagram bellow:

I have ordered them in the DOM within a single container in the order as they are numbered. I'm trying to get the second item to display to the left as shown. I tried with flex but couldn't get it right. I also tried floating the second div to the left and the rest to the right, but this is messy, especially if the 4th element in right column overlaps the 3rd.

Can somebody help me with this?

Thanks

答:
Example using CSS grid:

section {
  display: grid;
  grid-template-areas: "block1" "block2" "block3" "block4"
}

.block-1 {
  grid-area: block1;
  background-color: red;
}

.block-2 {
  grid-area: block2;
  background-color: blue;
}

.block-3 {
  grid-area: block3;
  background-color: green;
}

.block-4 {
  grid-area: block4;
  background-color: yellow;
}

@media screen and (min-width: 767px) {
  section {
    grid-template-areas: "block2 block1" "block2 block3" "block2 block4"
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <div class="block-1">
    Block 1
  </div>
  <div class="block-2">
    Block 2
  </div>
  <div class="block-3">
    Block 3
  </div>
  <div class="block-4">
    Block 4
  </div>
</section></code>```

Body:
Example using CSS grid:

section {
  display: grid;
  grid-template-areas: "block1" "block2" "block3" "block4"
}

.block-1 {
  grid-area: block1;
  background-color: red;
}

.block-2 {
  grid-area: block2;
  background-color: blue;
}

.block-3 {
  grid-area: block3;
  background-color: green;
}

.block-4 {
  grid-area: block4;
  background-color: yellow;
}

@media screen and (min-width: 767px) {
  section {
    grid-template-areas: "block2 block1" "block2 block3" "block2 block4"
  }
}

<section>
  <div class="block-1">
    Block 1
  </div>
  <div class="block-2">
    Block 2
  </div>
  <div class="block-3">
    Block 3
  </div>
  <div class="block-4">
    Block 4
  </div>
</section>


问:
Is `__shfl_sync` broken for 64-bit?
I have implemented a warp-wide and block-wide reduction using shuffle instructions. Everything works fine when I use 32-bit types, but for 64-bit I always get 0 as a result. To my knowledge, shuffling supports 64-bit arguments. What am I missing?

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

template<typename T>
inline __device__ T warpRegSumTest(T val) {
  T result = val;
  static constexpr unsigned mask = 0xffffffff;
#pragma unroll
  for (int delta = 16; delta > 0; delta /= 2) {
    result = result + __shfl_down_sync(mask, result, delta);
  }
  return result;
}

template<int numWarpsInBlock, typename T>
inline __device__ T blockRegSumTest(T val) {
  __shared__ T part[numWarpsInBlock];
  T warppart = warpRegSumTest(val);
  if (threadIdx.x % 32 == 0) {
    part[threadIdx.x / 32] = warppart;
  }
  __syncthreads();
  if (threadIdx.x < 32) {
    int tid = threadIdx.x;
    T solution = warpRegSumTest(tid < numWarpsInBlock ? part[tid] : T(0));
    __syncwarp();
    part[0] = solution;
  }

  __syncthreads();
  T result = part[0];
  __syncthreads();
  return result;
}

__global__ void testKernel() {
  float float_result = blockRegSumTest<256 / 32>(float(threadIdx.x));
  if (threadIdx.x == 0) {
    printf("Float sum: %f\n", float_result);
  }
  double double_result = blockRegSumTest<256 / 32>(double(threadIdx.x));
  if (threadIdx.x == 0) {
    printf("Double sum: %f\n", double_result);
  }
  int int_result = blockRegSumTest<256 / 32>(int(threadIdx.x));
  if (threadIdx.x == 0) {
    printf("Int sum: %d\n", int_result);
  }
  long long longlong_result = blockRegSumTest<256 / 32>(long long(threadIdx.x));
  if (threadIdx.x == 0) {
    printf("Long long sum: %lld\n", longlong_result);
  }
}

int main()
{
  testKernel << <1, 256 >> > ();
}
</code>```

I am compiling this with compute_70,sm_70 and running on GTX 2070 SUPER.
It outputs:

```<code>Float sum: 32640.000000
Double sum: 0.000000
Int sum: 32640
Long long sum: 0
</code>```

I expected to see 32640 (the sum 0+1+2+...+255) in all 4 cases.

答:
You've got an error here:

```<code>part[0] = solution;
</code>```

it should be:

```<code>if (!threadIdx.x) part[0] = solution;
</code>```

You only want thread 0 to execute that line.

Title: Is `__shfl_sync` broken for 64-bit?

Body:
I have implemented a warp-wide and block-wide reduction using shuffle instructions. Everything works fine when I use 32-bit types, but for 64-bit I always get 0 as a result. To my knowledge, shuffling supports 64-bit arguments. What am I missing?

#include <stdio.h>

template<typename T>
inline __device__ T warpRegSumTest(T val) {
  T result = val;
  static constexpr unsigned mask = 0xffffffff;
#pragma unroll
  for (int delta = 16; delta > 0; delta /= 2) {
    result = result + __shfl_down_sync(mask, result, delta);
  }
  return result;
}

template<int numWarpsInBlock, typename T>
inline __device__ T blockRegSumTest(T val) {
  __shared__ T part[numWarpsInBlock];
  T warppart = warpRegSumTest(val);
  if (threadIdx.x % 32 == 0) {
    part[threadIdx.x / 32] = warppart;
  }
  __syncthreads();
  if (threadIdx.x < 32) {
    int tid = threadIdx.x;
    T solution = warpRegSumTest(tid < numWarpsInBlock ? part[tid] : T(0));
    __syncwarp();
    part[0] = solution;
  }

  __syncthreads();
  T result = part[0];
  __syncthreads();
  return result;
}

__global__ void testKernel() {
  float float_result = blockRegSumTest<256 / 32>(float(threadIdx.x));
  if (threadIdx.x == 0) {
    printf("Float sum: %f\n", float_result);
  }
  double double_result = blockRegSumTest<256 / 32>(double(threadIdx.x));
  if (threadIdx.x == 0) {
    printf("Double sum: %f\n", double_result);
  }
  int int_result = blockRegSumTest<256 / 32>(int(threadIdx.x));
  if (threadIdx.x == 0) {
    printf("Int sum: %d\n", int_result);
  }
  long long longlong_result = blockRegSumTest<256 / 32>(long long(threadIdx.x));
  if (threadIdx.x == 0) {
    printf("Long long sum: %lld\n", longlong_result);
  }
}

int main()
{
  testKernel << <1, 256 >> > ();
}

I am compiling this with compute_70,sm_70 and running on GTX 2070 SUPER.
It outputs:

Float sum: 32640.000000
Double sum: 0.000000
Int sum: 32640
Long long sum: 0

I expected to see 32640 (the sum 0+1+2+...+255) in all 4 cases.

Body:
You've got an error here:

part[0] = solution;

it should be:

if (!threadIdx.x) part[0] = solution;

You only want thread 0 to execute that line.


问:
Python regex - difference between search and find all
I am trying to use python regex on a URL string.

```<code>id= 'edu.vt.lib.scholar:http/ejournals/VALib/v48_n4/newsome.html'
>>> re.search('news|ejournals|theses',id).group()
'ejournals'
>>> re.findall('news|ejournals|theses',id)
['ejournals', 'news']
</code>```

Based on the docs at http://docs.python.org/2/library/re.html#finding-all-adverbs, it says search() matches the first one and find all matches all the possible ones in the string.

I am wondering why 'news' is not captured with search even though it is declared first in the pattern.

Did i use the wrong pattern ? I want to search if any of those keywords occur in the string.

答:
`id= 'edu.vt.lib.scholar:http/ejournals/VALib/v48_n4/newsome.html'

re.search('news|ejournals|theses',id).group()
      'ejournals'

re.search -> search for first appearance in string and then exit.

re.findall('news|ejournals|theses',id)
      ['ejournals', 'news']

re.findall -> search for all occurrences of match in string and return in list form.

Body:
I am trying to use python regex on a URL string.

id= 'edu.vt.lib.scholar:http/ejournals/VALib/v48_n4/newsome.html'
>>> re.search('news|ejournals|theses',id).group()
'ejournals'
>>> re.findall('news|ejournals|theses',id)
['ejournals', 'news']

Based on the docs at http://docs.python.org/2/library/re.html#finding-all-adverbs, it says search() matches the first one and find all matches all the possible ones in the string.

I am wondering why 'news' is not captured with search even though it is declared first in the pattern.

Did i use the wrong pattern ? I want to search if any of those keywords occur in the string.


问:
How to instanciate indexed block in pyomo abstract model with parameters indexed with an index foreign from the block?
I am writing an extensive problem in pyomo in which i need to activate and deactivate assets in projects. I think the easiest way to model this is to write an abstract model and then put each asset into a block. Then every time a model would be instanciated it would be possible to activate only certain type of blocks and a certain number of each blocks (ie 3 block wind turbine). Therefore the block will be indexed. Inside these blocks I define parameters that are time dependent but the time will be a shared index between all so it won't be local set but a general set.

Here is a short example of the typical situation I am running into:

```<code>import pyomo.environ as pm

model=pm.AbstractModel()

model.A=pm.Set()
model.T=pm.Set(ordered=True) #the set of Time

def Ablock(b,g):
    b.A_param=pm.Param(model.T)
model.A_block=pm.Block(model.A,rule=Ablock)

Amodel_dict = \
    {None : dict(
        A = {None:[1,2,3]},
        T = {None:[4,12,23]},
        A_block = { 1: dict(A_param = { 4:3, 12:4, 23:5}),
                    2: dict(A_param = { 4:5, 12:6, 23:7}),
                    3: dict(A_param = { 4:8, 12:9, 23:10})}
                )
    }

instance=model.create_instance(data=Amodel_dict)
</code>```

This gives the error:

```<code>RuntimeError: Failed to set value for param=A_block[1].A_param, index=4, value=3.
    source error message="Index '4' is not valid for indexed component 'A_block[1].A_param'"
</code>```

Intuitively i feel it is wrong to call for model.T inside the function Ablock as it is not supposed to know what it refers to but if i give it as an argument of the function, it modifies the block creation to block indexed on time as well. Do you have any idea how to solve this ?

答:
I found the solution that was quite simple but very practical. Instead of calling model.T one should navigate in the hierarchical structure by using the functions model() or parent_block().

A solution for my problem is to call:

b.model().T or b.parent_block().T

Body:
I am writing an extensive problem in pyomo in which i need to activate and deactivate assets in projects. I think the easiest way to model this is to write an abstract model and then put each asset into a block. Then every time a model would be instanciated it would be possible to activate only certain type of blocks and a certain number of each blocks (ie 3 block wind turbine). Therefore the block will be indexed. Inside these blocks I define parameters that are time dependent but the time will be a shared index between all so it won't be local set but a general set.

Here is a short example of the typical situation I am running into:

import pyomo.environ as pm

model=pm.AbstractModel()

model.A=pm.Set()
model.T=pm.Set(ordered=True) #the set of Time

def Ablock(b,g):
    b.A_param=pm.Param(model.T)
model.A_block=pm.Block(model.A,rule=Ablock)

Amodel_dict = \
    {None : dict(
        A = {None:[1,2,3]},
        T = {None:[4,12,23]},
        A_block = { 1: dict(A_param = { 4:3, 12:4, 23:5}),
                    2: dict(A_param = { 4:5, 12:6, 23:7}),
                    3: dict(A_param = { 4:8, 12:9, 23:10})}
                )
    }

instance=model.create_instance(data=Amodel_dict)

This gives the error:

RuntimeError: Failed to set value for param=A_block[1].A_param, index=4, value=3.
    source error message="Index '4' is not valid for indexed component 'A_block[1].A_param'"

Intuitively i feel it is wrong to call for model.T inside the function Ablock as it is not supposed to know what it refers to but if i give it as an argument of the function, it modifies the block creation to block indexed on time as well. Do you have any idea how to solve this ?


问:
Flutter - CupertinoActionSheet / CupertinoActionSheetAction background color different on-device than in simulator
My Scaffold has a dark background color.

I'm using showCupertinoModalPopup, with the CupertinoActionSheet and using CupertinoActionSheetAction as the children.

In the simulator the actionsheet looks like this:

.

When I run the app on my actual iphone, it looks like this:

The actionsheet items look correct in the sim. Very white in appearance.

On-device though, are way more transparent on-device and therefore are harder to see.

Both CupertinoActionSheet and CupertinoActionSheetAction do not have color or transparency level properties

Any ideas on what's going on here?

Flutter doctor:

```<code>Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v0.11.7, on Mac OS X 10.13.6 17G65, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
[✓] iOS toolchain - develop for iOS devices (Xcode 10.1)
[✓] Android Studio (version 3.2)
[✓] VS Code (version 1.29.0)
[✓] Connected device (3 available)
</code>```

答:
This is still an issue in:

Flutter (Channel stable, v1.12.13+hotfix.8)

Mac OS X 10.15.3

Xcode 11.2.1

I guess it's a bug in Flutter. Or it might be a feature, which I concluded based on this PR (GitHub link).
If You really need to fix it, You will need to modify the code in flutter directly, in the /flutter/packages/flutter/lib/src/cupertino/action_sheet.dart, inside the build method of CupertinoActionSheetAction:

```<code>
    return GestureDetector(
      // ...
      child: ConstrainedBox(
        // ...
        child: Semantics(
          button: true,
          child: Container(
            // add decoration property
            decoration: BoxDecoration(
              color: CupertinoDynamicColor.resolve(CupertinoColors.secondarySystemGroupedBackground, context),
              borderRadius: BorderRadius.circular(_kCornerRadius),
            ),
            // ...
</code>```

Note1: This will work in both light and dark mode on iOS.

Note2: I don't advise You to do this. :)

Body:
My Scaffold has a dark background color.

I'm using showCupertinoModalPopup, with the CupertinoActionSheet and using CupertinoActionSheetAction as the children.

In the simulator the actionsheet looks like this:

.

When I run the app on my actual iphone, it looks like this:

The actionsheet items look correct in the sim. Very white in appearance.

On-device though, are way more transparent on-device and therefore are harder to see.

Both CupertinoActionSheet and CupertinoActionSheetAction do not have color or transparency level properties

Any ideas on what's going on here?

Flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v0.11.7, on Mac OS X 10.13.6 17G65, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
[✓] iOS toolchain - develop for iOS devices (Xcode 10.1)
[✓] Android Studio (version 3.2)
[✓] VS Code (version 1.29.0)
[✓] Connected device (3 available)

Body:
This is still an issue in:

Flutter (Channel stable, v1.12.13+hotfix.8)

Mac OS X 10.15.3

Xcode 11.2.1

I guess it's a bug in Flutter. Or it might be a feature, which I concluded based on this PR (GitHub link).
If You really need to fix it, You will need to modify the code in flutter directly, in the /flutter/packages/flutter/lib/src/cupertino/action_sheet.dart, inside the build method of CupertinoActionSheetAction:

    return GestureDetector(
      // ...
      child: ConstrainedBox(
        // ...
        child: Semantics(
          button: true,
          child: Container(
            // add decoration property
            decoration: BoxDecoration(
              color: CupertinoDynamicColor.resolve(CupertinoColors.secondarySystemGroupedBackground, context),
              borderRadius: BorderRadius.circular(_kCornerRadius),
            ),
            // ...

Note1: This will work in both light and dark mode on iOS.

Note2: I don't advise You to do this. :)


问:
Report issue in odoo 12
I have developed a new report for account.invoice in odoo 12 but when i suppose to print this, it gives me a warning like this in 12.0 branch :

The report's template 'Template name' is wrong, please contact your administrator.

Can not separate file to save as attachment because the report's template does not contains the attributes 'data-oe-model' and 'data-oe-id' on the div with 'article' classname.

In master branch it says data-model instead of data-oe-model, data-id instead of data-oe-id and 'page' classname instead of 'article' classname

If anyone has faced the same issue and find a solution then please let me know.

Thanks

答:
This error could happen if there is no report_type="qweb-html" for the report_type="qweb-pdf".
To solve this issue just had both... something like this :

```<code><report
        id="report_invoice_html"
        model="MY_MODEL_NAME"
        string="Invoice HTML"
        name="MODULE.report_invoice_view"
        file="MODULE.report_invoice"
        report_type="qweb-html" />

<report
        id="report_invoice_pdf"
        model="MY_MODEL_NAME"
        string="Invoice PDF"
        name="MODULE.report_invoice_view"
        file="MODULE.report_invoice"
        report_type="qweb-pdf" />
</code>```

If you look at the Odoo code source at ir_actions_report.py, you will see a statement comparing set(res_ids) != set(html_ids), if HTML template doesn't exist it return True, and then raise the Error

Title: Report issue in odoo 12

Body:
This error could happen if there is no report_type="qweb-html" for the report_type="qweb-pdf".
To solve this issue just had both... something like this :

<report
        id="report_invoice_html"
        model="MY_MODEL_NAME"
        string="Invoice HTML"
        name="MODULE.report_invoice_view"
        file="MODULE.report_invoice"
        report_type="qweb-html" />

<report
        id="report_invoice_pdf"
        model="MY_MODEL_NAME"
        string="Invoice PDF"
        name="MODULE.report_invoice_view"
        file="MODULE.report_invoice"
        report_type="qweb-pdf" />

If you look at the Odoo code source at ir_actions_report.py, you will see a statement comparing set(res_ids) != set(html_ids), if HTML template doesn't exist it return True, and then raise the Error


问:
How to count the number of rows containing a specific number in it's column
I would like to echo a count how many rows are containing the same specific number.

I have a column called "member_group_id" in my db.

For example, the leader group id is "4" some members have this number assigned in the db, so I would like to do something like:

```<code>$countLeaders = count($row['member_group_id'] == 4);
</code>```

How could I do that?

Here is my db query:

```<code>$result = mysqli_query($con,"SELECT * FROM core_members WHERE member_group_id IN (4, 7, 8, 6, 11) ORDER BY
    CASE member_group_id
        WHEN '4' THEN 1
        WHEN '7' THEN 2
        WHEN '8' THEN 3
        WHEN '6' THEN 4
        WHEN '11' THEN 5
    END ASC, name ASC");
</code>```

Here's my actual loop and desired result:

```<code>while($row = mysqli_fetch_array($result)){
    $group = $row['member_group_id'];
    $countLeaders = count($group == 4);
}

echo "<span>" . $countLeaders . " Leaders</span>";
</code>```

答:
You will just need to test the $row['member_group_id'] for the value you are interested in, and then add to an accumulator if it is the right value

```<code>$countLeaders = 0;
while($row = mysqli_fetch_assoc($result)){
    if ($row['member_group_id'] == '4') {
        $countLeaders++;
    }

    // other code if you have it
}

echo "<span>" . $countLeaders . " Leaders</span>";
</code>```

Body:
I would like to echo a count how many rows are containing the same specific number.

I have a column called "member_group_id" in my db.

For example, the leader group id is "4" some members have this number assigned in the db, so I would like to do something like:

$countLeaders = count($row['member_group_id'] == 4);

How could I do that?

Here is my db query:

$result = mysqli_query($con,"SELECT * FROM core_members WHERE member_group_id IN (4, 7, 8, 6, 11) ORDER BY
    CASE member_group_id
        WHEN '4' THEN 1
        WHEN '7' THEN 2
        WHEN '8' THEN 3
        WHEN '6' THEN 4
        WHEN '11' THEN 5
    END ASC, name ASC");

Here's my actual loop and desired result:

while($row = mysqli_fetch_array($result)){
    $group = $row['member_group_id'];
    $countLeaders = count($group == 4);
}

echo "" . $countLeaders . " Leaders";

Body:
You will just need to test the $row['member_group_id'] for the value you are interested in, and then add to an accumulator if it is the right value

$countLeaders = 0;
while($row = mysqli_fetch_assoc($result)){
    if ($row['member_group_id'] == '4') {
        $countLeaders++;
    }

    // other code if you have it
}

echo "<span>" . $countLeaders . " Leaders</span>";


问:
Checksum/Hash Column in a Many to Many Relation table
I am currently developing a web project using JSF, Hibernate and Spring with Spring Security and for data integrity i am currently using an extra column in domain tables and generating that column related to the other columns of that tables so i can later check it if any of the data changed externally. I save or update that column according to operation made. My problem is i have it working on simple plain tables but the situation arises when its about many to many midtables. They are generated and updated by hibernate automatically with only composite key on the midtable with no hash column of course. So I have problem about checking if the data changed externally or can not detect deleted rows. I have logs on main object save for example but no logs for midtable entries. Is it possible that i can add a column in those many to many tables by hibernate and save their entry logs so i can check up later on?</p>

答: Perhaps you could use SQL triggers, although this would log all actions of course, not just the external changes...</p>


问:
SFTP in Node.js uploading empty files
I'm having an issue with a project I'm working on whereby I'm downloading files from my FTP server using a node module called sftp-ssh2-client and then trying to pass the stream back into my FTP server but into a different directory.

The code looks like this:

```<code>const stream = sftp.get(`path/to/file.csv.gz`).then(() => {

}).catch((err) => {

});

sftp.put(stream, 'path/to/new/file.csv.gz').then(() => {

}).catch((err) => {

})
</code>```

However, when I dial into my FTP server to the location where the file has been PUT to, the file size is 0 and when downloaded is corrupted. Can anyone tell me what I'm doing wrong here?

Many thanks,

G

答:
```<code> function uploadFile(req, res) {
    req.pipe(req.busboy);
    req.busboy.on('file', function(fieldname, file, filename) {
        // debug("Uploading: " + filename);
        filename = (new Date()).getTime() + '-' + filename;

        //Path where file will be uploaded
        var fstream = fs.createWriteStream(FILE_STORE + filename);

        file.pipe(fstream);

        fstream.on('close', function() {
            //   debug("Upload Finished of " + filename);
            var newFileName = FILE_STORE + filename;
            if (!fs.existsSync(newFileName)) {

                res.status(404).json({ 'message': 'file not found' })
                return;
            }
            res.status(200).json({ file: filename });
        })
    })

}
</code>```

Title: SFTP in Node.js uploading empty files

Body:
I'm having an issue with a project I'm working on whereby I'm downloading files from my FTP server using a node module called sftp-ssh2-client and then trying to pass the stream back into my FTP server but into a different directory.

The code looks like this:

const stream = sftp.get(`path/to/file.csv.gz`).then(() => {

}).catch((err) => {

});

sftp.put(stream, 'path/to/new/file.csv.gz').then(() => {

}).catch((err) => {

})

However, when I dial into my FTP server to the location where the file has been PUT to, the file size is 0 and when downloaded is corrupted. Can anyone tell me what I'm doing wrong here?

Many thanks,

G


问:
Is view.leadingAnchor.constraint higher precedence than view.trailingAnchor.constraint?
I have my ViewController code as below

```<code>class ViewController: UIViewController {

    override func viewDidLoad() {
    super.viewDidLoad()
        view.backgroundColor = .white
        let titleLabel = UILabel()
        titleLabel.text = "Hello World!"

        view.addSubview(titleLabel)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            titleLabel.topAnchor.constraint(equalTo: view.topAnchor),
            titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            titleLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])
    }
}
</code>```

I'm expecting my "Hello World!" to be center aligned. Why wasn't it center aligned? (Vertically it is centered, but horizontally it is aligned to left as shown below.)

p/s: If I remove itleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor), then it is aligned right.

答:
Do you want your label to cover the entire view with the text centered? If so, keep your constraints as they are and set .textAlignment = .center.

I've set the background color of the label to cyan so you can see what's happening:

However, I suspect you just want your label centered in the view. In that case, change your constraints to this:

```<code>    NSLayoutConstraint.activate([
        titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        titleLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    ])
</code>```

Result:

Body:
I have my ViewController code as below

class ViewController: UIViewController {

    override func viewDidLoad() {
    super.viewDidLoad()
        view.backgroundColor = .white
        let titleLabel = UILabel()
        titleLabel.text = "Hello World!"

        view.addSubview(titleLabel)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            titleLabel.topAnchor.constraint(equalTo: view.topAnchor),
            titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            titleLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        ])
    }
}

I'm expecting my "Hello World!" to be center aligned. Why wasn't it center aligned? (Vertically it is centered, but horizontally it is aligned to left as shown below.)

p/s: If I remove itleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor), then it is aligned right.

Body:
Do you want your label to cover the entire view with the text centered? If so, keep your constraints as they are and set .textAlignment = .center.

I've set the background color of the label to cyan so you can see what's happening:

However, I suspect you just want your label centered in the view. In that case, change your constraints to this:

    NSLayoutConstraint.activate([
        titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
        titleLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
    ])

Result:


问:
How to stop single node kubernetes cluster gracefully
I've set up single node kubernetes  according to [official tutorial][1].

In addition to official documentation I've set-up single node cluster:

```<code>kubectl taint nodes --all node-role.kubernetes.io/master-
</code>```

Disabled eviction limit:

```<code>cat << EOF >> /var/lib/kubelet/config.yaml
evictionHard:
  imagefs.available: 1%
  memory.available: 100Mi
  nodefs.available: 1%
  nodefs.inodesFree: 1%
EOF

systemctl daemon-reload
systemctl restart kubelet
</code>```

And set systemd driver for Docker:

```<code>cat << EOF > /etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2"
}
EOF

systemctl daemon-reload
systemctl restart docker
</code>```

How can I temporary stop Kubernetes cluster (including all it's services, podd, etc)? I've issued systemctl stop kubelet but I stil see some kubernetes stuff among processes

```<code>$ ps -elf | grep kube
4 S root       6032   5914  1  80   0 - 2653148 -    Feb17 ?        00:35:10 etcd --advertise-client-urls=https://192.168.1.111:2379 --cert-file=/etc/kubernetes/pki/etcd/server.crt --client-cert-auth=true --data-dir=/var/lib/etcd --initial-advertise-peer-urls=https://192.168.1.111:2380 --initial-cluster=ubuntu=https://192.168.1.111:2380 --key-file=/etc/kubernetes/pki/etcd/server.key --listen-client-urls=https://127.0.0.1:2379,https://192.168.1.111:2379 --listen-metrics-urls=http://127.0.0.1:2381 --listen-peer-urls=https://192.168.1.111:2380 --name=ubuntu --peer-cert-file=/etc/kubernetes/pki/etcd/peer.crt --peer-client-cert-auth=true --peer-key-file=/etc/kubernetes/pki/etcd/peer.key --peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt --snapshot-count=10000 --trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
4 S root       7536   7495  0  80   0 - 35026 -      Feb17 ?        00:01:04 /usr/local/bin/kube-proxy --config=/var/lib/kube-proxy/config.conf --hostname-override=ubuntu
4 S root       9868   9839  0  80   0 - 34463 -      Feb17 ?        00:00:59 /usr/bin/kube-controllers
4 S root      48394  48375  2  80   0 - 36076 -      13:41 ?        00:01:09 kube-scheduler --authentication-kubeconfig=/etc/kubernetes/scheduler.conf --authorization-kubeconfig=/etc/kubernetes/scheduler.conf --bind-address=127.0.0.1 --kubeconfig=/etc/kubernetes/scheduler.conf --leader-elect=true
4 S root      48461  48436  3  80   0 - 52484 -      13:41 ?        00:01:53 kube-controller-manager --allocate-node-cidrs=true --authentication-kubeconfig=/etc/kubernetes/controller-manager.conf --authorization-kubeconfig=/etc/kubernetes/controller-manager.conf --bind-address=127.0.0.1 --client-ca-file=/etc/kubernetes/pki/ca.crt --cluster-cidr=10.244.0.0/16 --cluster-signing-cert-file=/etc/kubernetes/pki/ca.crt --cluster-signing-key-file=/etc/kubernetes/pki/ca.key --controllers=*,bootstrapsigner,tokencleaner --kubeconfig=/etc/kubernetes/controller-manager.conf --leader-elect=true --node-cidr-mask-size=24 --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt --root-ca-file=/etc/kubernetes/pki/ca.crt --service-account-private-key-file=/etc/kubernetes/pki/sa.key --service-cluster-ip-range=10.96.0.0/12 --use-service-account-credentials=true
4 S root      52675  52586  7  80   0 - 123895 -     14:00 ?        00:02:01 kube-apiserver --advertise-address=192.168.1.111 --allow-privileged=true --authorization-mode=Node,RBAC --client-ca-file=/etc/kubernetes/pki/ca.crt --enable-admission-plugins=NodeRestriction --enable-bootstrap-token-auth=true --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt --etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt --etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.key --etcd-servers=https://127.0.0.1:2379 --insecure-port=0 --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key --requestheader-allowed-names=front-proxy-client --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt --requestheader-extra-headers-prefix=X-Remote-Extra- --requestheader-group-headers=X-Remote-Group --requestheader-username-headers=X-Remote-User --secure-port=6443 --service-account-key-file=/etc/kubernetes/pki/sa.pub --service-cluster-ip-range=10.96.0.0/12 --tls-cert-file=/etc/kubernetes/pki/apiserver.crt --tls-private-key-file=/etc/kubernetes/pki/apiserver.key
</code>```

答:
You should use kubectl drain <node name>

When kubectl drain returns successfully, that indicates that all of the pods have been safely evicted respecting the desired graceful termination period.

Once it returns (without giving an error), you can power down the node (or equivalently, if on a cloud platform, delete the virtual machine backing the node). If you leave the node in the cluster during the maintenance operation, you need to run

```<code>kubectl uncordon <node name>
</code>```

afterwards to tell Kubernetes that it can resume scheduling new pods onto the node

Body:
I've set up single node kubernetes  according to [official tutorial][1].

In addition to official documentation I've set-up single node cluster:

kubectl taint nodes --all node-role.kubernetes.io/master-

Disabled eviction limit:

cat << EOF >> /var/lib/kubelet/config.yaml
evictionHard:
  imagefs.available: 1%
  memory.available: 100Mi
  nodefs.available: 1%
  nodefs.inodesFree: 1%
EOF

systemctl daemon-reload
systemctl restart kubelet

And set systemd driver for Docker:

cat << EOF > /etc/docker/daemon.json
{
  "exec-opts": ["native.cgroupdriver=systemd"],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "100m"
  },
  "storage-driver": "overlay2"
}
EOF

systemctl daemon-reload
systemctl restart docker

How can I temporary stop Kubernetes cluster (including all it's services, podd, etc)? I've issued systemctl stop kubelet but I stil see some kubernetes stuff among processes

$ ps -elf | grep kube
4 S root       6032   5914  1  80   0 - 2653148 -    Feb17 ?        00:35:10 etcd --advertise-client-urls=https://192.168.1.111:2379 --cert-file=/etc/kubernetes/pki/etcd/server.crt --client-cert-auth=true --data-dir=/var/lib/etcd --initial-advertise-peer-urls=https://192.168.1.111:2380 --initial-cluster=ubuntu=https://192.168.1.111:2380 --key-file=/etc/kubernetes/pki/etcd/server.key --listen-client-urls=https://127.0.0.1:2379,https://192.168.1.111:2379 --listen-metrics-urls=http://127.0.0.1:2381 --listen-peer-urls=https://192.168.1.111:2380 --name=ubuntu --peer-cert-file=/etc/kubernetes/pki/etcd/peer.crt --peer-client-cert-auth=true --peer-key-file=/etc/kubernetes/pki/etcd/peer.key --peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt --snapshot-count=10000 --trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
4 S root       7536   7495  0  80   0 - 35026 -      Feb17 ?        00:01:04 /usr/local/bin/kube-proxy --config=/var/lib/kube-proxy/config.conf --hostname-override=ubuntu
4 S root       9868   9839  0  80   0 - 34463 -      Feb17 ?        00:00:59 /usr/bin/kube-controllers
4 S root      48394  48375  2  80   0 - 36076 -      13:41 ?        00:01:09 kube-scheduler --authentication-kubeconfig=/etc/kubernetes/scheduler.conf --authorization-kubeconfig=/etc/kubernetes/scheduler.conf --bind-address=127.0.0.1 --kubeconfig=/etc/kubernetes/scheduler.conf --leader-elect=true
4 S root      48461  48436  3  80   0 - 52484 -      13:41 ?        00:01:53 kube-controller-manager --allocate-node-cidrs=true --authentication-kubeconfig=/etc/kubernetes/controller-manager.conf --authorization-kubeconfig=/etc/kubernetes/controller-manager.conf --bind-address=127.0.0.1 --client-ca-file=/etc/kubernetes/pki/ca.crt --cluster-cidr=10.244.0.0/16 --cluster-signing-cert-file=/etc/kubernetes/pki/ca.crt --cluster-signing-key-file=/etc/kubernetes/pki/ca.key --controllers=*,bootstrapsigner,tokencleaner --kubeconfig=/etc/kubernetes/controller-manager.conf --leader-elect=true --node-cidr-mask-size=24 --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt --root-ca-file=/etc/kubernetes/pki/ca.crt --service-account-private-key-file=/etc/kubernetes/pki/sa.key --service-cluster-ip-range=10.96.0.0/12 --use-service-account-credentials=true
4 S root      52675  52586  7  80   0 - 123895 -     14:00 ?        00:02:01 kube-apiserver --advertise-address=192.168.1.111 --allow-privileged=true --authorization-mode=Node,RBAC --client-ca-file=/etc/kubernetes/pki/ca.crt --enable-admission-plugins=NodeRestriction --enable-bootstrap-token-auth=true --etcd-cafile=/etc/kubernetes/pki/etcd/ca.crt --etcd-certfile=/etc/kubernetes/pki/apiserver-etcd-client.crt --etcd-keyfile=/etc/kubernetes/pki/apiserver-etcd-client.key --etcd-servers=https://127.0.0.1:2379 --insecure-port=0 --kubelet-client-certificate=/etc/kubernetes/pki/apiserver-kubelet-client.crt --kubelet-client-key=/etc/kubernetes/pki/apiserver-kubelet-client.key --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname --proxy-client-cert-file=/etc/kubernetes/pki/front-proxy-client.crt --proxy-client-key-file=/etc/kubernetes/pki/front-proxy-client.key --requestheader-allowed-names=front-proxy-client --requestheader-client-ca-file=/etc/kubernetes/pki/front-proxy-ca.crt --requestheader-extra-headers-prefix=X-Remote-Extra- --requestheader-group-headers=X-Remote-Group --requestheader-username-headers=X-Remote-User --secure-port=6443 --service-account-key-file=/etc/kubernetes/pki/sa.pub --service-cluster-ip-range=10.96.0.0/12 --tls-cert-file=/etc/kubernetes/pki/apiserver.crt --tls-private-key-file=/etc/kubernetes/pki/apiserver.key

Body:
You should use kubectl drain <node name>

When kubectl drain returns successfully, that indicates that all of the pods have been safely evicted respecting the desired graceful termination period.

Once it returns (without giving an error), you can power down the node (or equivalently, if on a cloud platform, delete the virtual machine backing the node). If you leave the node in the cluster during the maintenance operation, you need to run

kubectl uncordon <node name>

afterwards to tell Kubernetes that it can resume scheduling new pods onto the node


问:
version `GLIBCXX_3.4.21' not found on PowerPC (ppc64le) architecture
I am on rhel7.6 ppc64le, trying to build a package. I have devtoolset-8 installed on my system. However when I try to test it, it gives the following error:

/lib64/libstdc++.so.6: version 'GLIBCXX_3.4.21' not found (required by /tmp/snappy7148417400130025252.tmp)

I have tried the command strings /usr/lib64/libstdc++.so.6 | grep GLIB which gives the following output:

GLIBCXX_3.4
GLIBCXX_3.4.1
GLIBCXX_3.4.2
GLIBCXX_3.4.3
GLIBCXX_3.4.4
GLIBCXX_3.4.5
GLIBCXX_3.4.6
GLIBCXX_3.4.7
GLIBCXX_3.4.8
GLIBCXX_3.4.9
GLIBCXX_3.4.10
GLIBCXX_3.4.11
GLIBCXX_3.4.12
GLIBCXX_3.4.13
GLIBCXX_3.4.14
GLIBCXX_3.4.15
GLIBCXX_3.4.16
GLIBCXX_3.4.17
GLIBCXX_3.4.18
GLIBCXX_3.4.19
GLIBCXX_LDBL_3.4
GLIBCXX_LDBL_3.4.7
GLIBCXX_LDBL_3.4.10
GLIBC_2.17
GLIBCXX_FORCE_NEW
GLIBCXX_DEBUG_MESSAGE_LENGTH

my LD_LIBRARY_PATH is set to /opt/rh/devtoolset-8/root/lib. I have also tried changing it to /opt/rh/devtoolset-8/root/usr/lib/gcc/ppc64le-redhat-linux/8.

Would like some help. I am running it on a High end VM with good connectivity.

答:
It might help to see full the link command.

Why are you using LD_LIBRARY_PATH?

Also, confirm you have devtoolset-8-libstdc++-devel installed.

LD_DEBUG can be used to produce a raft of related (and unrelated) debugging information.

```<code>LD_DEBUG=help /bin/true
</code>```

... will show brief help text.

Body:
It might help to see full the link command.

Why are you using LD_LIBRARY_PATH?

Also, confirm you have devtoolset-8-libstdc++-devel installed.

LD_DEBUG can be used to produce a raft of related (and unrelated) debugging information.

LD_DEBUG=help /bin/true

... will show brief help text.


问:
Locate patterns
I am trying to locate all files on a linux server that fit this profile:

sfvhebviweuiber9.html

  sfvhebviweuiber11.html

  jdjhwn2jjsfy2q10.html

Where the first 10-15 characters are a-z, followed by [1-15], then .html.

How can I use locate (or any other method) to find all files that fit this profile?

The differences are basically the first 10-15 characters as they are made up of random alphabet characters.

答:
I don't quite get the "[1-15]" part of your description, but I think this would do.  You can refine the .* part in the regex

```<code>locate -r '[a-z]\{10,15\}.*html'
</code>```

Title: Locate patterns

Body:
I don't quite get the "[1-15]" part of your description, but I think this would do.  You can refine the .* part in the regex

locate -r '[a-z]\{10,15\}.*html'


问:
Change locale in react-datepicker
I am using react-datepicker NPM package,

I tried to follow documentation but I was unable to import

```<code>registerLocale
</code>```

and

```<code>setDefaultLocale
</code>```

from react-datepicker

Do you see where I make mistake?

```<code> import DatePicker from 'react-datepicker';

...
    <DatePicker
            { ...this.props }
            dateFormat={ this.dateFormat }
            ref={ (node) => { this.ref = node; } }
            onClickOutside={ this.clickOutside }
          />
...
</code>```

this is code where I want to import locale.

答:
For those who don't want to depend on date-fns module you can define your own localization.

Here's a working demo on CodeSandbox.

```<code>const days = ['Pt', 'Sa', 'Ça', 'Pe', 'Cu', 'Ct', 'Pz']
const months = ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık']

const locale = {
  localize: {
    day: n => days[n],
    month: n => months[n]
  },
  formatLong: {
    date: () => 'mm/dd/yyyy'
  }
}

<DatePicker locale={locale} />
</code>```

Title: Change locale in react-datepicker

Body:
I am using react-datepicker NPM package,

I tried to follow documentation but I was unable to import

registerLocale

and

setDefaultLocale

from react-datepicker

Do you see where I make mistake?

 import DatePicker from 'react-datepicker';

...
    <DatePicker
            { ...this.props }
            dateFormat={ this.dateFormat }
            ref={ (node) => { this.ref = node; } }
            onClickOutside={ this.clickOutside }
          />
...

this is code where I want to import locale.

Body:
For those who don't want to depend on date-fns module you can define your own localization.

Here's a working demo on CodeSandbox.

const days = ['Pt', 'Sa', 'Ça', 'Pe', 'Cu', 'Ct', 'Pz']
const months = ['Ocak', 'Şubat', 'Mart', 'Nisan', 'Mayıs', 'Haziran', 'Temmuz', 'Ağustos', 'Eylül', 'Ekim', 'Kasım', 'Aralık']

const locale = {
  localize: {
    day: n => days[n],
    month: n => months[n]
  },
  formatLong: {
    date: () => 'mm/dd/yyyy'
  }
}

<DatePicker locale={locale} />


问:
Alert about bounced emails using Spring Boot
I have a Spring Boot application that sends emails. For any action that requires notification, a Mail instance is created with status PENDING in the database and a job is run to send the pending emails every minute. The status of the Mail instances are set as PENDING, SENT or FAILED.

```<code>try {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.from", myEmailAddress);
    props.put("mail.smtp.timeout", 2000);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    MimeMessage message = new MimeMessage(session);
    MimeMultipart content = getContent(mail, message, username);
    message.setContent(content);
    Transport.send(message);
    mail.setStatus(MailStatus.SENT);
    mailService.save(mail);
} catch (MailConnectException mce) {
    mail.setStatus(MailStatus.FAILED);
    mailService.save(mail);
} catch (Exception e) {
    // other actions
}
</code>```

Now, this works fine if a valid email id is provided. But when the receiving email address is a non-existent one like somerandomname@gmail.com, there are no exceptions thrown. From what I read from similar questions in SO and elsewhere, I understand that mail sending is an asynchronous process and hence there is no way to determine that a given email is existing or not (or other issues like Inbox full). That is why after the Transport.send(message); statement, the mail.setStatus(MailStatus.SENT); statement will always be executed irrespective of the email address being present. Later the mail will actually be attempted to be sent and I get an email in myEmailAddress with content like the following:

The response from the remote server was: 550 5.1.1
  somerandomname@gmail.com User unknown

Okay, accepted until this point. But now I need a way to alert the user that the email couldn't be sent because they entered an invalid email so that they can update their email. More specifically, I need to set the status of the Mail instance to FAILED. What is the best way to achieve this?

答: If you use a service like AWS SES to send your mail, you can receive notifications about bounces (and complaints) either simply as notifications for a human to read, or as programmatic triggers that could be used to call an alert endpoint on your spring boot server, for example through AWS Lambda. There are other services that may be able to do the same, such as SendGrid.</p>

Body:
I have a Spring Boot application that sends emails. For any action that requires notification, a Mail instance is created with status PENDING in the database and a job is run to send the pending emails every minute. The status of the Mail instances are set as PENDING, SENT or FAILED.

try {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.from", myEmailAddress);
    props.put("mail.smtp.timeout", 2000);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    MimeMessage message = new MimeMessage(session);
    MimeMultipart content = getContent(mail, message, username);
    message.setContent(content);
    Transport.send(message);
    mail.setStatus(MailStatus.SENT);
    mailService.save(mail);
} catch (MailConnectException mce) {
    mail.setStatus(MailStatus.FAILED);
    mailService.save(mail);
} catch (Exception e) {
    // other actions
}

Now, this works fine if a valid email id is provided. But when the receiving email address is a non-existent one like somerandomname@gmail.com, there are no exceptions thrown. From what I read from similar questions in SO and elsewhere, I understand that mail sending is an asynchronous process and hence there is no way to determine that a given email is existing or not (or other issues like Inbox full). That is why after the Transport.send(message); statement, the mail.setStatus(MailStatus.SENT); statement will always be executed irrespective of the email address being present. Later the mail will actually be attempted to be sent and I get an email in myEmailAddress with content like the following:

The response from the remote server was: 550 5.1.1
  somerandomname@gmail.com User unknown

Okay, accepted until this point. But now I need a way to alert the user that the email couldn't be sent because they entered an invalid email so that they can update their email. More specifically, I need to set the status of the Mail instance to FAILED. What is the best way to achieve this?