问:
how to store numpy arrays as tfrecord?
I am trying to create a dataset in tfrecord format from numpy arrays. I am trying to store 2d and 3d coordinates.

2d coordinates are numpy array of shape (2,10) of type float64
3d coordinates are numpy array of shape (3,10) of type float64

this is my code:

```<code>def _floats_feature(value):
    return tf.train.Feature(float_list=tf.train.FloatList(value=value))

train_filename = 'train.tfrecords'  # address to save the TFRecords file
writer = tf.python_io.TFRecordWriter(train_filename)

for c in range(0,1000):

    #get 2d and 3d coordinates and save in c2d and c3d

    feature = {'train/coord2d': _floats_feature(c2d),
                   'train/coord3d': _floats_feature(c3d)}
    sample = tf.train.Example(features=tf.train.Features(feature=feature))
    writer.write(sample.SerializeToString())

writer.close()
</code>```

when i run this i get the error:

```<code>  feature = {'train/coord2d': _floats_feature(c2d),
  File "genData.py", line 19, in _floats_feature
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\internal\python_message.py", line 510, in init
copy.extend(field_value)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\internal\containers.py", line 275, in extend
new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter]
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\internal\containers.py", line 275, in <listcomp>
new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter]
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\internal\type_checkers.py", line 109, in CheckValue
raise TypeError(message)
TypeError: array([-163.685,  240.818, -114.05 , -518.554,  107.968,  427.184,
    157.418, -161.798,   87.102,  406.318]) has type <class 'numpy.ndarray'>, but expected one of: ((<class 'numbers.Real'>,),)
</code>```

I dont know how to fix this. should i store the features as int64 or bytes? I have no clue how to go about this since i am completely new to tensorflow. any help would be great! thanks

答:
The function _floats_feature described in the Tensorflow-Guide expects a scalar (either float32 or float64) as input.

```<code>def _float_feature(value):
  """Returns a float_list from a float / double."""
  return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
</code>```

As you can see the inputted scalar is written into a list (value=[value]) which is subsequently given to tf.train.FloatList as input. tf.train.FloatList expects an iterator that outputs a float in each iteration (as the list does).

If your feature is not a scalar but a vectur, _float_feature can be rewritten to pass the iterator directly to tf.train.FloatList (instead of putting it into a list first).

```<code>def _float_array_feature(value):
  return tf.train.Feature(float_list=tf.train.FloatList(value=value))
</code>```

However if your feature has two or more dimensions this solution does not work anymore. Like @mmry described in his answer in this case flattening your feature or splitting it into several one-dimensional features would be a solution. The disadvantage of these two approaches is that the information about the actual shape of the feature is lost if no further effort is invested.

Another possibility to write an example message for a higher dimensional array is to convert the array into a byte string and then use the _bytes_feature function described in the Tensorflow-Guide to write the example message for it. The example message is then serialized and written into a TFRecord file.

```<code>import tensorflow as tf
import numpy as np

def _bytes_feature(value):
    """Returns a bytes_list from a string / byte."""
    if isinstance(value, type(tf.constant(0))): # if value ist tensor
        value = value.numpy() # get value of tensor
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def serialize_array(array):
  array = tf.io.serialize_tensor(array)
  return array

#----------------------------------------------------------------------------------
# Create example data
array_blueprint = np.arange(4, dtype='float64').reshape(2,2)
arrays = [array_blueprint+1, array_blueprint+2, array_blueprint+3]

#----------------------------------------------------------------------------------
# Write TFrecord file
file_path = 'data.tfrecords'
with tf.io.TFRecordWriter(file_path) as writer:
  for array in arrays:
    serialized_array = serialize_array(array)
    feature = {'b_feature': _bytes_feature(serialized_array)}
    example_message = tf.train.Example(features=tf.train.Features(feature=feature))
    writer.write(example_message.SerializeToString())
</code>```

The serialized example messages stored in the TFRecord file can be accessed via tf.data.TFRecordDataset. After the example messages have been parsed, the original array needs to be restored from the byte string it was converted to. This is possible via tf.io.parse_tensor.

```<code># Read TFRecord file
def _parse_tfr_element(element):
  parse_dic = {
    'b_feature': tf.io.FixedLenFeature([], tf.string), # Note that it is tf.string, not tf.float32
    }
  example_message = tf.io.parse_single_example(element, parse_dic)

  b_feature = example_message['b_feature'] # get byte string
  feature = tf.io.parse_tensor(b_feature, out_type=tf.float64) # restore 2D array from byte string
  return feature

tfr_dataset = tf.data.TFRecordDataset('data.tfrecords')
for serialized_instance in tfr_dataset:
  print(serialized_instance) # print serialized example messages

dataset = tfr_dataset.map(_parse_tfr_element)
for instance in dataset:
  print()
  print(instance) # print parsed example messages with restored arrays
</code>```

Title: how to store numpy arrays as tfrecord?

Body:
I am trying to create a dataset in tfrecord format from numpy arrays. I am trying to store 2d and 3d coordinates.

2d coordinates are numpy array of shape (2,10) of type float64
3d coordinates are numpy array of shape (3,10) of type float64

this is my code:

def _floats_feature(value):
    return tf.train.Feature(float_list=tf.train.FloatList(value=value))

train_filename = 'train.tfrecords'  # address to save the TFRecords file
writer = tf.python_io.TFRecordWriter(train_filename)

for c in range(0,1000):

    #get 2d and 3d coordinates and save in c2d and c3d

    feature = {'train/coord2d': _floats_feature(c2d),
                   'train/coord3d': _floats_feature(c3d)}
    sample = tf.train.Example(features=tf.train.Features(feature=feature))
    writer.write(sample.SerializeToString())

writer.close()

when i run this i get the error:

  feature = {'train/coord2d': _floats_feature(c2d),
  File "genData.py", line 19, in _floats_feature
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\internal\python_message.py", line 510, in init
copy.extend(field_value)
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\internal\containers.py", line 275, in extend
new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter]
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\internal\containers.py", line 275, in <listcomp>
new_values = [self._type_checker.CheckValue(elem) for elem in elem_seq_iter]
  File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\google\protobuf\internal\type_checkers.py", line 109, in CheckValue
raise TypeError(message)
TypeError: array([-163.685,  240.818, -114.05 , -518.554,  107.968,  427.184,
    157.418, -161.798,   87.102,  406.318]) has type <class 'numpy.ndarray'>, but expected one of: ((<class 'numbers.Real'>,),)

I dont know how to fix this. should i store the features as int64 or bytes? I have no clue how to go about this since i am completely new to tensorflow. any help would be great! thanks

Body:
The function _floats_feature described in the Tensorflow-Guide expects a scalar (either float32 or float64) as input.

def _float_feature(value):
  """Returns a float_list from a float / double."""
  return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))

As you can see the inputted scalar is written into a list (value=[value]) which is subsequently given to tf.train.FloatList as input. tf.train.FloatList expects an iterator that outputs a float in each iteration (as the list does).

If your feature is not a scalar but a vectur, _float_feature can be rewritten to pass the iterator directly to tf.train.FloatList (instead of putting it into a list first).

def _float_array_feature(value):
  return tf.train.Feature(float_list=tf.train.FloatList(value=value))

However if your feature has two or more dimensions this solution does not work anymore. Like @mmry described in his answer in this case flattening your feature or splitting it into several one-dimensional features would be a solution. The disadvantage of these two approaches is that the information about the actual shape of the feature is lost if no further effort is invested.

Another possibility to write an example message for a higher dimensional array is to convert the array into a byte string and then use the _bytes_feature function described in the Tensorflow-Guide to write the example message for it. The example message is then serialized and written into a TFRecord file.

import tensorflow as tf
import numpy as np

def _bytes_feature(value):
    """Returns a bytes_list from a string / byte."""
    if isinstance(value, type(tf.constant(0))): # if value ist tensor
        value = value.numpy() # get value of tensor
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

def serialize_array(array):
  array = tf.io.serialize_tensor(array)
  return array

#----------------------------------------------------------------------------------
# Create example data
array_blueprint = np.arange(4, dtype='float64').reshape(2,2)
arrays = [array_blueprint+1, array_blueprint+2, array_blueprint+3]

#----------------------------------------------------------------------------------
# Write TFrecord file
file_path = 'data.tfrecords'
with tf.io.TFRecordWriter(file_path) as writer:
  for array in arrays:
    serialized_array = serialize_array(array)
    feature = {'b_feature': _bytes_feature(serialized_array)}
    example_message = tf.train.Example(features=tf.train.Features(feature=feature))
    writer.write(example_message.SerializeToString())

The serialized example messages stored in the TFRecord file can be accessed via tf.data.TFRecordDataset. After the example messages have been parsed, the original array needs to be restored from the byte string it was converted to. This is possible via tf.io.parse_tensor.

# Read TFRecord file
def _parse_tfr_element(element):
  parse_dic = {
    'b_feature': tf.io.FixedLenFeature([], tf.string), # Note that it is tf.string, not tf.float32
    }
  example_message = tf.io.parse_single_example(element, parse_dic)

  b_feature = example_message['b_feature'] # get byte string
  feature = tf.io.parse_tensor(b_feature, out_type=tf.float64) # restore 2D array from byte string
  return feature

tfr_dataset = tf.data.TFRecordDataset('data.tfrecords')
for serialized_instance in tfr_dataset:
  print(serialized_instance) # print serialized example messages

dataset = tfr_dataset.map(_parse_tfr_element)
for instance in dataset:
  print()
  print(instance) # print parsed example messages with restored arrays


来源: stackexchange

问:
How can I get input from multiple entry widgets created in a loop?
I've hunted through some of the previous answers and got a step closer, but my problem is still that I can not get the value from multiple entry boxes.

```<code>import tkinter as tk
from tkinter import ttk
window = tk.Tk()
my_list = []

def get_info():
    for each_player in my_list:
        tk.Label(window, text=temp_entry.get()).grid()

#number of players is determined by the user.
#In this example, lets say there are 3 players
tk.Label(window, text="Number of Players: ").grid()
num_of_players = ttk.Combobox(window, values=[1, 2, 3])
num_of_players.current(2)
num_of_players.grid(row=0, column=1)
#The code above is only the recreate the user selecting the amount of players from a combobox

#create number of entry boxes for user-determined number of players
for each_player in range(1, int(num_of_players.get()) + 1):
    temp_label = tk.Label(window, text="Player {}: ".format(each_player))
    temp_entry = tk.Entry(window)
    my_list.append(temp_entry)

    temp_label.grid(row=each_player, column=0, pady=10)
    temp_entry.grid(row=each_player, column=1, pady=10)
button = tk.Button(window, text="Save", command=get_info)
button.grid()

window.mainloop()
</code>```

It's at the end of the code where I struggle to find out how I could possibly get information from the entry boxes. How can I use the get() method but only after the user has input text?

答:
Use a button that triggers a method that gets the text for u like:</p>

```<code>play = Button(window, text="get_button", command=that_getter_method)
.....
.....
def that_getter_method():
    var = field.get()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've hunted through some of the previous answers and got a step closer, but my problem is still that I can not get the value from multiple entry boxes.

import tkinter as tk
from tkinter import ttk
window = tk.Tk()
my_list = []

def get_info():
    for each_player in my_list:
        tk.Label(window, text=temp_entry.get()).grid()

#number of players is determined by the user.
#In this example, lets say there are 3 players
tk.Label(window, text="Number of Players: ").grid()
num_of_players = ttk.Combobox(window, values=[1, 2, 3])
num_of_players.current(2)
num_of_players.grid(row=0, column=1)
#The code above is only the recreate the user selecting the amount of players from a combobox

#create number of entry boxes for user-determined number of players
for each_player in range(1, int(num_of_players.get()) + 1):
    temp_label = tk.Label(window, text="Player {}: ".format(each_player))
    temp_entry = tk.Entry(window)
    my_list.append(temp_entry)

    temp_label.grid(row=each_player, column=0, pady=10)
    temp_entry.grid(row=each_player, column=1, pady=10)
button = tk.Button(window, text="Save", command=get_info)
button.grid()

window.mainloop()

It's at the end of the code where I struggle to find out how I could possibly get information from the entry boxes. How can I use the get() method but only after the user has input text?

Body:
Use a button that triggers a method that gets the text for u like:

play = Button(window, text="get_button", command=that_getter_method)
.....
.....
def that_getter_method():
    var = field.get()


问:
I've commited and pushed a new feature_branch on git but it doesn't show the changes on that branch after commit/push in central repository on github
So at first I just created the new branch in IntelliJ on the fly, made the adjustments to the code, push/commit the file. immediately after that I checked the central repository on github and there was no such branch. So I created the same branch directly on the github page, and when I tried to commit and push the changes this time using gitBash (even though I don't know if there is a difference) I got this message: "On branch feature_branch
nothing to commit, working tree clean"

I checked the central repository and my changes still weren't there. I've lost a whole day going back and forth I even reinstalled intelliJ.

Also I think it's important to note that the file I commit had several errors (it's like the class that I was working on had no Idea of other Classes in the same package), and intelliJ wasn't showing compiler errors when I wrote the code... I tried checking the Build Project Automatically checkbox in settings and it still doesn't work... I tried changing the project SDK, still doesn't work.

Could the problem be in IntelliJ, and if so, where and what should I look for? I'm completely lost and need some help. Any ideas on what should I try are welcome.

答:
Check git log if there is your change comitted, check git status if there is anything left to commit.
Try to check also your current branch git branch if you are on feature branch.


问:
How to sum data from multiple rows, based on a condition in Teradata?
I am trying to sum the data, based on two columns, where the values in 2 of the rows are equal.
This is the table I have:

```<code>Country   | System     | Money
 AAA      | A          | 10
 AAA      | A          | 200
 AAA      | B          | 60
 BBB      | B          | 600
 BBB      | A          | 150
 BBB      | B          | 140
</code>```

This is what I want to achieve:

```<code>Country   | System     | Money  | SystemSum
 AAA      | A          | 10     |  210
 AAA      | A          | 200    |  210
 AAA      | B          | 60     |  60
 BBB      | B          | 600    |  740
 BBB      | A          | 150    |  150
 BBB      | B          | 140    |  740
</code>```

This is what I have tried:

```<code>SUM(Money) OVER (ORDER BY Country, System ROWS UNBOUNDED PRECEDING)
</code>```

but it returns the values cumulatively. How to do it correctly?

答:
You seem to want the sum over the combination of Country and System.  A window function is the way to go, but with partition by and not order by:

```<code>SELECT t.*,
       SUM(Money) OVER (PARTITION BY Country, System)
FROM t;
</code>```

Body:
I am trying to sum the data, based on two columns, where the values in 2 of the rows are equal.
This is the table I have:

Country   | System     | Money
 AAA      | A          | 10
 AAA      | A          | 200
 AAA      | B          | 60
 BBB      | B          | 600
 BBB      | A          | 150
 BBB      | B          | 140

This is what I want to achieve:

Country   | System     | Money  | SystemSum
 AAA      | A          | 10     |  210
 AAA      | A          | 200    |  210
 AAA      | B          | 60     |  60
 BBB      | B          | 600    |  740
 BBB      | A          | 150    |  150
 BBB      | B          | 140    |  740

This is what I have tried:

SUM(Money) OVER (ORDER BY Country, System ROWS UNBOUNDED PRECEDING)

but it returns the values cumulatively. How to do it correctly?

Body:
You seem to want the sum over the combination of Country and System.  A window function is the way to go, but with partition by and not order by:

SELECT t.*,
       SUM(Money) OVER (PARTITION BY Country, System)
FROM t;


问:
Can't get jQuery script to run after page has been loaded
I have tried to get some jQuery code to execute when a page has been fully loaded and rendered. I have read that I should use the .on("pageshow") event to trigger the code to be executed.

The code below is a test that I can't get to work properly. It loads a "box" that is colored cyan from the beginning. I want the color to be changed to yellow via jQuery after the page has been loaded. I also added a click-trigger to make sure that the color can be changed if I manually click on the text in the box. But the auto execution won't work... I have also tried to define an event for .on("load").

So... I simply want to find a way to execute jQuery code after the page has been loaded (in my real code I will use it to scroll down to a specific element and highlight it)

    <!DOCTYPE html>

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

                    My header!

    ```

答:
As mentioned in some of the comments I have now modified the code to a working solution. I would like to present it if someone needs it in the future:</p>

```<code><!DOCTYPE html>
<html lang="sv">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

  <script>
    // the event is now defined outside the $(document).ready-part
    $(window).on('pageshow', function() {
        $("#box").css("background-color", "yellow"); // This happens after page is loaded
    });

    $(document).ready(function(){
        $("#titletext").click(function(){
            $("#box").css("background-color", "green");
        });
    });
  </script>

</head>
<body>
        <div id="box" class="d-flex p-2" style="background-color: cyan">
            <div id="titletext" class="p-2 w-100">
                My header!
            </div>
        </div>
</body>
</html>
</code>```

Body:
As mentioned in some of the comments I have now modified the code to a working solution. I would like to present it if someone needs it in the future:

<!DOCTYPE html>
<html lang="sv">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

  <script>
    // the event is now defined outside the $(document).ready-part
    $(window).on('pageshow', function() {
        $("#box").css("background-color", "yellow"); // This happens after page is loaded
    });

    $(document).ready(function(){
        $("#titletext").click(function(){
            $("#box").css("background-color", "green");
        });
    });
  </script>

</head>
<body>
        <div id="box" class="d-flex p-2" style="background-color: cyan">
            <div id="titletext" class="p-2 w-100">
                My header!
            </div>
        </div>
</body>
</html>


问:
parsing string with respect to string format |how
I have ;

```<code> string  str = "";
</code>```

in str, I store data is in following form "_ : _, _ "
"_" can be just a word like "X" or a composition of words like "a sds 23 dsds 1"

I want them parse it to three different string ;

```<code>in str       : X:y dfj kd kk,sdd 12 89 ++
string parsed[i] ;
in parsed[0] : X
in parsed[1] : y dfj kd kk
in parsed[2] : sdd 12 89 ++
</code>```

How can I do that over using c++ std::string features ?

答:
You can split your string using the following std:string methods for example:</p>

```<code>size_t index1 = str.find( ":" ) + 1;
size_t index2 = str.find( ",", index1 ) + 1;

std::string sub1 = str.substr (0, index1-1);
std::string sub2 = str.substr (index1, index2-index1-1);
std::string sub3 = str.substr (index2, str.length()-index2);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have ;

 string  str = "";

in str, I store data is in following form "_ : _, _ "
"_" can be just a word like "X" or a composition of words like "a sds 23 dsds 1"

I want them parse it to three different string ;

in str       : X:y dfj kd kk,sdd 12 89 ++
string parsed[i] ;
in parsed[0] : X
in parsed[1] : y dfj kd kk
in parsed[2] : sdd 12 89 ++

How can I do that over using c++ std::string features ?

Body:
You can split your string using the following std:string methods for example:

size_t index1 = str.find( ":" ) + 1;
size_t index2 = str.find( ",", index1 ) + 1;

std::string sub1 = str.substr (0, index1-1);
std::string sub2 = str.substr (index1, index2-index1-1);
std::string sub3 = str.substr (index2, str.length()-index2);


问:
Removing unused materialize-css and js code from React App for efficiency
Materialize-css brings lots of already-baked components for you.
But If you wanna use only 1 component (date-picker) of materialize-css in your react app. Will react gonna remove rest of the un-used components from production build? Or will my react app gonna carry whole materialzie css and js code along the way?

suggest a way if react doesn't remove unused materialize code automatically in production build.

答:
The best way is to bring in only what you need, rather than purge out what you don't afterwards.

https://medium.com/@mattdlockyer/youre-using-materialize-css-wrong-470b593e78e9

For Wordpress builds, I use sass to compile a custom materialize.css as I'm building the site, and the same with js - I use grunt to include only the components that the project needs. This is a more manual approach.

In your use case, you can follow Matt's article to bring in materialize components at component level in React.


答:
It looks like you are just grouping by (country, system).  Give this a try:

SELECT
  Country, System, Money,
  SUM(Money) OVER(PARTITION BY Country, System) AS SystemSum
FROM MyTable
```

This will give you your SUM based on the groups, but also return all the detailed row data.

Title: How to sum data from multiple rows, based on a condition in Teradata?

Body:
It looks like you are just grouping by (country, system).  Give this a try:

SELECT
  Country, System, Money,
  SUM(Money) OVER(PARTITION BY Country, System) AS SystemSum
FROM MyTable

This will give you your SUM based on the groups, but also return all the detailed row data.


问:
JsonTransformation using Jolt
I'm using jolt + java(https://github.com/bazaarvoice/jolt) to transform an external JSON in a format that I can understand.

My problem is the structure keeps changing and this is making my spec more and more complex.

I want to extract all the fields which are called "path" no matter the structure.

does someone have an idea how can I do that?

Example of structure:

```<code>{
    "groups": {
        "rows": {
            "fieldSets": {
                "fields": [{
                    "path": "example"
                }]
            }
        }
    }
}

or

{
    "groups": {
        "rows": {
            "rowsets": {
                "fieldSets": {
                    "fields": [{
                        "path": "example"
                    }]
                }
            }
        }
    }
}

or
{
    "groups": {
        "fieldSets": {
            "fields": [{
                "path": "example"
            }]
        }
    }
}

</code>```

in the end, I just want an array with plain "path" values.

答:
I am also new to the JOLT. Anyway I tried with what I understood from your question. Just try the below spec:

```<code>[
  {
    "operation": "shift",
    "spec": {
      "groups": {
        "rows": {
          "fieldSets": {
            "fields": {
              "*": {
                "path": "path"
              }
            }
          }
        }
      }
    }
  }
]
</code>```

If it is not what you are expecting, then please give an output json, so that i can understood what you want.

Title: JsonTransformation using Jolt

Body:
I'm using jolt + java(https://github.com/bazaarvoice/jolt) to transform an external JSON in a format that I can understand.

My problem is the structure keeps changing and this is making my spec more and more complex.

I want to extract all the fields which are called "path" no matter the structure.

does someone have an idea how can I do that?

Example of structure:

{
    "groups": {
        "rows": {
            "fieldSets": {
                "fields": [{
                    "path": "example"
                }]
            }
        }
    }
}

or

{
    "groups": {
        "rows": {
            "rowsets": {
                "fieldSets": {
                    "fields": [{
                        "path": "example"
                    }]
                }
            }
        }
    }
}

or
{
    "groups": {
        "fieldSets": {
            "fields": [{
                "path": "example"
            }]
        }
    }
}

in the end, I just want an array with plain "path" values.

Body:
I am also new to the JOLT. Anyway I tried with what I understood from your question. Just try the below spec:

[
  {
    "operation": "shift",
    "spec": {
      "groups": {
        "rows": {
          "fieldSets": {
            "fields": {
              "*": {
                "path": "path"
              }
            }
          }
        }
      }
    }
  }
]

If it is not what you are expecting, then please give an output json, so that i can understood what you want.


问:
C# how to check exact time difference in if condition
I have this if condition where I need to do some stuff if the difference is 15 min or so

```<code>if (DateTime.UtcNow - x.Timestamp == TimeSpan.FromMinutes(15))
{
    //Do something
}
</code>```

The above condition never satisfies when I check with == but when I do >= it gets into the condition but that's not what I need, I want 15 min or so difference.

Can someone explain this behavior?

Sample Data:

x = 2/17/2020 8:45:17 PM

答:
```<code>//I cannot comment on the above answer i dont have enough Rep
</code>```

I think a better solution for a time trigger to do something would be like so:

```<code>static System.Timers.Timer _t = new System.Timers.Timer();

void Init()
{
    //Start a timer trigger every 300000 milliseconds = 5 minutes
     _t.Interval = 300000;
     _t.Elapsed += fiveMinutesElapsed;
     _t.Enabled = true;
}
public void fiveMinutesElapsed()
{
    t.Enabled = false;
    //Do Something
    t.Enabled = true;
}
</code>```

Body:
I have this if condition where I need to do some stuff if the difference is 15 min or so

if (DateTime.UtcNow - x.Timestamp == TimeSpan.FromMinutes(15))
{
    //Do something
}

The above condition never satisfies when I check with == but when I do >= it gets into the condition but that's not what I need, I want 15 min or so difference.

Can someone explain this behavior?

Sample Data:

x = 2/17/2020 8:45:17 PM

Body:
//I cannot comment on the above answer i dont have enough Rep

I think a better solution for a time trigger to do something would be like so:

static System.Timers.Timer _t = new System.Timers.Timer();

void Init()
{
    //Start a timer trigger every 300000 milliseconds = 5 minutes
     _t.Interval = 300000;
     _t.Elapsed += fiveMinutesElapsed;
     _t.Enabled = true;
}
public void fiveMinutesElapsed()
{
    t.Enabled = false;
    //Do Something
    t.Enabled = true;
}


问:
Google APi + Passport + React : Authentication flow
I'm using passport to authenticate using Google API, I'm sending a token by URL to the client (React app) which saves it in the localStorage.

I want to use that token : With every API call (get, post, put) I want to send that token to the server , but I didn't know how to verify that token on the server side.

Passport Startegy :

```<code>app.use(passport.initialize()); // Used to initialize passport
app.use(passport.session()); // Used to persist login sessions

passport.use(new GoogleStrategy({
    clientID: 'IDxxxxx',
    clientSecret: 'SecreXXX',
    callbackURL: 'http://localhost:3000/callback'
},
(accessToken, refreshToken, profile, done) => {

    // Directory API here

    var userData = {
        name: profile.displayName,
        token: accessToken
       };

    done(null, userData);
</code>```

Authentication :

```<code>app.get('/auth/google', passport.authenticate('google', {
    scope: ['profile'] // Used to specify the required data
}));

// The middleware receives the data from Google and runs the function on Strategy config
app.get('/callback', passport.authenticate('google'), (req, res) => {
    var token = req.user.token;
    res.redirect("http://localhost:8000?token=" + token);
});
</code>```

API in express (which contains CRUD methods) :

```<code>app.use('/api', movieRouter)
</code>```

In react side : Getting the token

```<code>  componentWillMount() {
    var query = queryString.parse(this.props.location.search);
    if (query.token) {
      window.localStorage.setItem("jwt", query.token);
      // appel a directory api (avec token) puis sauvergarder dans redux puis redirection vers liste demandes
      this.props.history.push("/");
    }
  }
</code>```

Doing API calls :

```<code>import axios from 'axios'

const api = axios.create({
    baseURL: 'http://localhost:3000/api',
})

export const insertMovie = payload => api.post(`/movie`, payload)
</code>```

I just need to send the token in every call and check it in the server side.

Thanks

答:
You want to set the token in a header most likely, try changing your axios client to something like

```<code>const api = axios.create({
  baseURL: 'http://localhost:3000/api',
  headers: {
    Authorization: `Bearer ${your_token_here}`
  }
})
</code>```

I'm not 100% sure if this is the correct header form that passport will be expecting, but it's the general idea you need to do.

Body:
I'm using passport to authenticate using Google API, I'm sending a token by URL to the client (React app) which saves it in the localStorage.

I want to use that token : With every API call (get, post, put) I want to send that token to the server , but I didn't know how to verify that token on the server side.

Passport Startegy :

app.use(passport.initialize()); // Used to initialize passport
app.use(passport.session()); // Used to persist login sessions

passport.use(new GoogleStrategy({
    clientID: 'IDxxxxx',
    clientSecret: 'SecreXXX',
    callbackURL: 'http://localhost:3000/callback'
},
(accessToken, refreshToken, profile, done) => {

    // Directory API here

    var userData = {
        name: profile.displayName,
        token: accessToken
       };

    done(null, userData);

Authentication :

app.get('/auth/google', passport.authenticate('google', {
    scope: ['profile'] // Used to specify the required data
}));

// The middleware receives the data from Google and runs the function on Strategy config
app.get('/callback', passport.authenticate('google'), (req, res) => {
    var token = req.user.token;
    res.redirect("http://localhost:8000?token=" + token);
});

API in express (which contains CRUD methods) :

app.use('/api', movieRouter)

In react side : Getting the token

  componentWillMount() {
    var query = queryString.parse(this.props.location.search);
    if (query.token) {
      window.localStorage.setItem("jwt", query.token);
      // appel a directory api (avec token) puis sauvergarder dans redux puis redirection vers liste demandes
      this.props.history.push("/");
    }
  }

Doing API calls :

import axios from 'axios'

const api = axios.create({
    baseURL: 'http://localhost:3000/api',
})

export const insertMovie = payload => api.post(`/movie`, payload)

I just need to send the token in every call and check it in the server side.

Thanks

Body:
You want to set the token in a header most likely, try changing your axios client to something like

const api = axios.create({
  baseURL: 'http://localhost:3000/api',
  headers: {
    Authorization: `Bearer ${your_token_here}`
  }
})

I'm not 100% sure if this is the correct header form that passport will be expecting, but it's the general idea you need to do.


问:
Problem Creating a struct within my script in Matlab
I am trying to write a variable into a structure and read it from another existing structure:

struct1.vector = struct2.matrix(:,1);

when I run this line in my script it will create a double variable struct1. Thats why I will get the error:

Unable to perform assignment because dot indexing is not supported for variables of this type.

When I just run the same line in my Command Window it will create a struct variable struct1 just as I want to. Also there are multiple lines, where I try to write into struct1 and some times the first 4 lines work and the 5th doesn't.
I don't understand why the script is creating a double, can anybody help me with this?

Help is much appreciated, thank you.

答:
That probably means that you already have a variable named struct1 in your workspace, either leftover from some previous activity, or assigned earlier in the script.

You can make sure you have a fresh workspace by calling clear before running your script. Better yet, turn your script into a function, and it will have its own workspace.

You can also replace the whole struct1 variable with a new empty struct, to make sure it's of the right type, before assigning to its fields.

```<code>struct1 = struct;
struct1.vector = struct2.matrix(:,1);
</code>```

Body:
That probably means that you already have a variable named struct1 in your workspace, either leftover from some previous activity, or assigned earlier in the script.

You can make sure you have a fresh workspace by calling clear before running your script. Better yet, turn your script into a function, and it will have its own workspace.

You can also replace the whole struct1 variable with a new empty struct, to make sure it's of the right type, before assigning to its fields.

struct1 = struct;
struct1.vector = struct2.matrix(:,1);


问:
Bayes Factor in R with Jaggs
I am trying to decide between linear regression models using the Bayes Factor in Jaggs through R.
For simplicity's sake, I am working on the mtcars dataset and the models are:

(1) mpg on only intercept
(2) mpg on wt
(3) mpg on disp
(4) mpg on wt and disp

I am utilizing flat priors and try to implement the model comparison with the following code, but run into some problems and errors:

```<code>reg.bf.model <- "model{
    M ~ dcat(model.p[])
    model.p[1] <- 0.25
    model.p[2] <- 0.25
    model.p[3] <- 0.25
    model.p[4] <- 0.25

  # Likelihood
  for (i in 1:n){
      y[i] ~ dnorm(mu[i,M],tau[M])
        mu[i,1] <- alpha[1]
        mu[i,2] <- alpha[2] + beta1[1] * wt[i]
        mu[i,3] <- alpha[3] + beta1[2] * disp[i]
        mu[i,4] <- alpha[4] + beta1[3] * disp[i]+ beta2* wt[i]
  }

  for (m in 1:4){
      alpha[m] ~ dnorm(0,0.0001)
      sigma2[m] <- (1/tau[m])
  }

  for (j in 1:3) {
      beta1[j] ~ dnorm(0,0.0001)
  }

    beta2 ~ dnorm(0,0.0001)

    tau[1] ~ dgamma(prior.shape1[M],prior.rate1[M])
    tau[2] ~ dgamma(prior.shape2[M],prior.rate2[M])
    tau[3] ~ dgamma(prior.shape3[M],prior.rate3[M])
    tau[4] ~ dgamma(prior.shape4[M],prior.rate4[M])
}"

jags.data <- list(y=mtcars$mpg,n=nrow(mtcars),
                  wt = mtcars$wt, disp = mtcars$disp,
                  prior.shape1=c(0.0001,1),prior.rate1=c(0.0001,1),
                  prior.shape2=c(1,0.0001),prior.rate2=c(1,0.0001),
                  prior.shape3=c(1,0.0001),prior.rate3=c(1,0.0001),
                  prior.shape4=c(1,0.0001),prior.rate4=c(1,0.0001))

jags.bf <- jags.model(file=textConnection(reg.bf.model),
                      #                      inits=jags.inits,
                      data=jags.data, n.chains=3)

update(jags.bf, 100)
jags.bf.out <- coda.samples(jags.bf,
                            variable.names=c("alpha","beta1","beta2"
                                             ,"sigma2","M"),
                            n.iter=50000, thin=400)
</code>```

But I get the following error messages:

"Error in update.jags(jags.bf, 100) : LOGIC ERROR:
SimpleRange::leftOffset. Index outside of allowed range
Please send a bug report to martyn_plummer@users.sourceenter code hereforge.net"

and

"Error in jags.samples(model, variable.names, n.iter, thin, type = "trace",  :
  No valid monitors set
In addition: Warning messages:
1: In FUN(X[[i]], ...) : Can't set monitor. No model!

2: In FUN(X[[i]], ...) : Can't set monitor. No model!

3: In FUN(X[[i]], ...) : Can't set monitor. No model!

4: In FUN(X[[i]], ...) : Can't set monitor. No model!

5: In FUN(X[[i]], ...) : Can't set monitor. No model!"

Any ideas or nudges in the right direction are greatly appreciated!

答:
As an update, apparently the Bayes factor needs to be used as an alternative to the frequentist's hypothesis test between two models. Therefore the following code adjustment got things to work.

```<code>reg.bf.model <- "model{
  M ~ dcat(model.p[])
  model.p[1] <- prior1
  model.p[2] <- 1-prior1

  # Likelihood
  for (i in 1:n){
    y[i] ~ dnorm(mu[i,M],tau[M])
    mu[i,1] <- alpha[1]
    mu[i,2] <- alpha[2] + beta1[1] * wt[i]
  }

  for (m in 1:2){
      alpha[m] ~ dnorm(0,0.0001)
      sigma2[m] <- (1/tau[m])
  }

  for (j in 1:1) {
    beta1[j] ~ dnorm(0,0.0001)
  }

  beta2 ~ dnorm(0,0.0001)

  tau[1] ~ dgamma(prior.shape1[M],prior.rate1[M])
  tau[2] ~ dgamma(prior.shape2[M],prior.rate2[M])

}"
prior1 = 0.5
jags.data <- list(y=mtcars$mpg,n=nrow(mtcars), prior1 = prior1,
                  wt = mtcars$wt, disp = mtcars$disp,
                  prior.shape1=c(0.0001,1),prior.rate1=c(0.0001,1),
                  prior.shape2=c(1,0.0001),prior.rate2=c(1,0.0001))

jags.bf <- jags.model(file=textConnection(reg.bf.model),
                      #                      inits=jags.inits,
                      data=jags.data, n.chains=3)

update(jags.bf, 100)
jags.bf.out <- coda.samples(jags.bf,
                            variable.names=c("alpha","beta1","beta2"
                                             ,"sigma2","M"),
                            n.iter=50000, thin=400)

# calculating bayes factor
posterior.M <- unlist(jags.bf.out[,"M"])
posterior.odds <- mean(posterior.M==1)/mean(posterior.M==2)
prior.odds <- prior1/(1-prior1)
bayes.factor <- posterior.odds/prior.odds
bayes.factor
</code>```

Title: Bayes Factor in R with Jaggs

Body:
I am trying to decide between linear regression models using the Bayes Factor in Jaggs through R.
For simplicity's sake, I am working on the mtcars dataset and the models are:

(1) mpg on only intercept
(2) mpg on wt
(3) mpg on disp
(4) mpg on wt and disp

I am utilizing flat priors and try to implement the model comparison with the following code, but run into some problems and errors:

reg.bf.model <- "model{
    M ~ dcat(model.p[])
    model.p[1] <- 0.25
    model.p[2] <- 0.25
    model.p[3] <- 0.25
    model.p[4] <- 0.25

  # Likelihood
  for (i in 1:n){
      y[i] ~ dnorm(mu[i,M],tau[M])
        mu[i,1] <- alpha[1]
        mu[i,2] <- alpha[2] + beta1[1] * wt[i]
        mu[i,3] <- alpha[3] + beta1[2] * disp[i]
        mu[i,4] <- alpha[4] + beta1[3] * disp[i]+ beta2* wt[i]
  }

  for (m in 1:4){
      alpha[m] ~ dnorm(0,0.0001)
      sigma2[m] <- (1/tau[m])
  }

  for (j in 1:3) {
      beta1[j] ~ dnorm(0,0.0001)
  }

    beta2 ~ dnorm(0,0.0001)

    tau[1] ~ dgamma(prior.shape1[M],prior.rate1[M])
    tau[2] ~ dgamma(prior.shape2[M],prior.rate2[M])
    tau[3] ~ dgamma(prior.shape3[M],prior.rate3[M])
    tau[4] ~ dgamma(prior.shape4[M],prior.rate4[M])
}"

jags.data <- list(y=mtcars$mpg,n=nrow(mtcars),
                  wt = mtcars$wt, disp = mtcars$disp,
                  prior.shape1=c(0.0001,1),prior.rate1=c(0.0001,1),
                  prior.shape2=c(1,0.0001),prior.rate2=c(1,0.0001),
                  prior.shape3=c(1,0.0001),prior.rate3=c(1,0.0001),
                  prior.shape4=c(1,0.0001),prior.rate4=c(1,0.0001))

jags.bf <- jags.model(file=textConnection(reg.bf.model),
                      #                      inits=jags.inits,
                      data=jags.data, n.chains=3)

update(jags.bf, 100)
jags.bf.out <- coda.samples(jags.bf,
                            variable.names=c("alpha","beta1","beta2"
                                             ,"sigma2","M"),
                            n.iter=50000, thin=400)

But I get the following error messages:

"Error in update.jags(jags.bf, 100) : LOGIC ERROR:
SimpleRange::leftOffset. Index outside of allowed range
Please send a bug report to martyn_plummer@users.sourceenter code hereforge.net"

and

"Error in jags.samples(model, variable.names, n.iter, thin, type = "trace",  :
  No valid monitors set
In addition: Warning messages:
1: In FUN(X[[i]], ...) : Can't set monitor. No model!

2: In FUN(X[[i]], ...) : Can't set monitor. No model!

3: In FUN(X[[i]], ...) : Can't set monitor. No model!

4: In FUN(X[[i]], ...) : Can't set monitor. No model!

5: In FUN(X[[i]], ...) : Can't set monitor. No model!"

Any ideas or nudges in the right direction are greatly appreciated!

Body:
As an update, apparently the Bayes factor needs to be used as an alternative to the frequentist's hypothesis test between two models. Therefore the following code adjustment got things to work.

reg.bf.model <- "model{
  M ~ dcat(model.p[])
  model.p[1] <- prior1
  model.p[2] <- 1-prior1

  # Likelihood
  for (i in 1:n){
    y[i] ~ dnorm(mu[i,M],tau[M])
    mu[i,1] <- alpha[1]
    mu[i,2] <- alpha[2] + beta1[1] * wt[i]
  }

  for (m in 1:2){
      alpha[m] ~ dnorm(0,0.0001)
      sigma2[m] <- (1/tau[m])
  }

  for (j in 1:1) {
    beta1[j] ~ dnorm(0,0.0001)
  }

  beta2 ~ dnorm(0,0.0001)

  tau[1] ~ dgamma(prior.shape1[M],prior.rate1[M])
  tau[2] ~ dgamma(prior.shape2[M],prior.rate2[M])

}"
prior1 = 0.5
jags.data <- list(y=mtcars$mpg,n=nrow(mtcars), prior1 = prior1,
                  wt = mtcars$wt, disp = mtcars$disp,
                  prior.shape1=c(0.0001,1),prior.rate1=c(0.0001,1),
                  prior.shape2=c(1,0.0001),prior.rate2=c(1,0.0001))

jags.bf <- jags.model(file=textConnection(reg.bf.model),
                      #                      inits=jags.inits,
                      data=jags.data, n.chains=3)

update(jags.bf, 100)
jags.bf.out <- coda.samples(jags.bf,
                            variable.names=c("alpha","beta1","beta2"
                                             ,"sigma2","M"),
                            n.iter=50000, thin=400)

# calculating bayes factor
posterior.M <- unlist(jags.bf.out[,"M"])
posterior.odds <- mean(posterior.M==1)/mean(posterior.M==2)
prior.odds <- prior1/(1-prior1)
bayes.factor <- posterior.odds/prior.odds
bayes.factor


问:
Problem with storing german words into the MySql DB....?
I am facing an small issue in my project When I am trying to store some German words into the MYSQL Database. When this German words contains umlauts i.e. characters ä, ö, ß, ü etc., they are not stored as they are.....?

I want to store them as it is into the Database.To do so I tried to change the COLLATION to UTF8-general-ci, and others in the list using PHP myAdmin. But none of them is working for me.

Am I in the right way or I have to do something else.

Please suggest some help.

Thanks In Advance......

答:
Try to use utf8_encode($string) to encode your text into UTF8 first, before saving it into the database. In order for characters to display correctly in a certain language, you have to (1) set the text into the right charset and then also (2) set a database to the right charset (as you did).

Also, for example, file display.php will output the German text, you can open the file in any editors (EmEditor?) and then "save as", choose a right encoding scheme. After that, the display file, when outputting the text, will take care of the charset.


问:
How to set a listview column header to bold, in code
I have a list view, which is used as a calendar display, with each column representing a day.
How can I set the column header to bold, in code?  Is it possible to do it directly, without bothering with defining styles, static resources, triggers etc?

I tried:

```<code>If TheDate.DayOfWeek = DayOfWeek.Saturday Or TheDate.DayOfWeek = DayOfWeek.Sunday Then Day01Column.SetValue(GridViewColumnHeader.FontWeightProperty, FontWeights.Bold) Else Day01Column.SetValue(GridViewColumnHeader.FontWeightProperty, FontWeights.Normal)
If TheDate.AddDays(1).DayOfWeek = DayOfWeek.Saturday Or TheDate.AddDays(1).DayOfWeek = DayOfWeek.Sunday Then Day02Column.SetValue(GridViewColumnHeader.FontWeightProperty, FontWeights.Bold) Else Day02Column.SetValue(GridViewColumnHeader.FontWeightProperty, FontWeights.Normal)
If TheDate.AddDays(2).DayOfWeek = DayOfWeek.Saturday Or TheDate.AddDays(2).DayOfWeek = DayOfWeek.Sunday Then Day03Column.SetValue(GridViewColumnHeader.FontWeightProperty, FontWeights.Bold) Else Day03Column.SetValue(GridViewColumnHeader.FontWeightProperty, FontWeights.Normal)
</code>```

(and so on, for the whole month)
and then I tried:

```<code>Dim BoldStyle As New Style
BoldStyle.Setters.Add(New Setter(Control.FontWeightProperty, FontWeights.Bold))
Dim NormalStyle As New Style
NormalStyle.Setters.Add(New Setter(Control.FontWeightProperty, FontWeights.Normal))

If TheDate.DayOfWeek = DayOfWeek.Saturday Or TheDate.DayOfWeek = DayOfWeek.Sunday Then Day01Column.SetValue(GridView.ColumnHeaderContainerStyleProperty, BoldStyle) Else Day01Column.SetValue(GridView.ColumnHeaderContainerStyleProperty, NormalStyle)
If TheDate.AddDays(1).DayOfWeek = DayOfWeek.Saturday Or TheDate.AddDays(1).DayOfWeek = DayOfWeek.Sunday Then Day02Column.SetValue(GridView.ColumnHeaderContainerStyleProperty, BoldStyle) Else Day02Column.SetValue(GridView.ColumnHeaderContainerStyleProperty, NormalStyle)
If TheDate.AddDays(2).DayOfWeek = DayOfWeek.Saturday Or TheDate.AddDays(2).DayOfWeek = DayOfWeek.Sunday Then Day03Column.SetValue(GridView.ColumnHeaderContainerStyleProperty, BoldStyle) Else Day03Column.SetValue(GridView.ColumnHeaderContainerStyleProperty, NormalStyle)
</code>```

Neither worked - the column headers seem resolutely non-bold.
Any ideas what I'm doing wrong?

I'm so fed up with WPF.  Everything is an order of magnitude more complicated.  Previously with WinForms, I could knock out little apps for myself in no time at all.  Now I spend weeks wrestling with XAML, databinding, commands, etc.  When things don't work, there are no error messages, Intellisense is only of minor help in the XAML, and the only benefit I get from all this is resolution-independent apps.

Edit:- I should add that I know this works:

```<code><Window.Resources>
    <Style x:Key="ColumnHeaderBoldStyle" TargetType="{x:Type GridViewColumnHeader}">
        <Setter Property="FontWeight" Value="Bold"/>
    </Style>
    <Style x:Key="ColumnHeaderNormalStyle" TargetType="{x:Type GridViewColumnHeader}">
        <Setter Property="FontWeight" Value="Normal"/>
    </Style>

If TheDate.DayOfWeek = DayOfWeek.Saturday Or TheDate.DayOfWeek = DayOfWeek.Sunday Then Day01Column.SetValue(GridViewColumn.HeaderContainerStyleProperty, Application.Current.MainWindow.FindResource("ColumnHeaderBoldStyle"))
</code>```

But I believe I can only apply one style to an element, and since I also want to be able apply grey background to certain column headers, I think that would mean styles for grey only, bold only, grey + bold and neither.  And if I then wanted to set, say, the font colour, that would need 8 styles.  It doesn't scale well.
Surely there is a way to reach into the listview element from code and adjust individual bits of chrome?

Many thanks

Nick

答:
In C#, I can do this from XAML as preparation:

```<code><ListView.View>
   <GridView>
     <GridViewColumn DisplayMemberBinding="{Binding Name}" Width="160">
     <GridViewColumn.Header>
       <GridViewColumnHeader Tag="Name" Click="SortInterfaces_Click">Name</GridViewColumnHeader>
     </GridViewColumn.Header>
    </GridViewColumn>
</code>```

and then in C# I switch font weights:

```<code>private void SortInterfaces_Click(object sender, RoutedEventArgs e)
{
  GridViewColumnHeader column = (sender as GridViewColumnHeader);
  if (column.Tag == null) return;
  column.FontWeight = FontWeights.Bold;
  InterfaceSortChangeTo(column);
}
</code>```

If WPF gives you pain, try not to stray from the default built-in functionality. For the functions that are in there, it's actually quite ok.

Body:
I have a list view, which is used as a calendar display, with each column representing a day.
How can I set the column header to bold, in code?  Is it possible to do it directly, without bothering with defining styles, static resources, triggers etc?

I tried:

If TheDate.DayOfWeek = DayOfWeek.Saturday Or TheDate.DayOfWeek = DayOfWeek.Sunday Then Day01Column.SetValue(GridViewColumnHeader.FontWeightProperty, FontWeights.Bold) Else Day01Column.SetValue(GridViewColumnHeader.FontWeightProperty, FontWeights.Normal)
If TheDate.AddDays(1).DayOfWeek = DayOfWeek.Saturday Or TheDate.AddDays(1).DayOfWeek = DayOfWeek.Sunday Then Day02Column.SetValue(GridViewColumnHeader.FontWeightProperty, FontWeights.Bold) Else Day02Column.SetValue(GridViewColumnHeader.FontWeightProperty, FontWeights.Normal)
If TheDate.AddDays(2).DayOfWeek = DayOfWeek.Saturday Or TheDate.AddDays(2).DayOfWeek = DayOfWeek.Sunday Then Day03Column.SetValue(GridViewColumnHeader.FontWeightProperty, FontWeights.Bold) Else Day03Column.SetValue(GridViewColumnHeader.FontWeightProperty, FontWeights.Normal)

(and so on, for the whole month)
and then I tried:

Dim BoldStyle As New Style
BoldStyle.Setters.Add(New Setter(Control.FontWeightProperty, FontWeights.Bold))
Dim NormalStyle As New Style
NormalStyle.Setters.Add(New Setter(Control.FontWeightProperty, FontWeights.Normal))

If TheDate.DayOfWeek = DayOfWeek.Saturday Or TheDate.DayOfWeek = DayOfWeek.Sunday Then Day01Column.SetValue(GridView.ColumnHeaderContainerStyleProperty, BoldStyle) Else Day01Column.SetValue(GridView.ColumnHeaderContainerStyleProperty, NormalStyle)
If TheDate.AddDays(1).DayOfWeek = DayOfWeek.Saturday Or TheDate.AddDays(1).DayOfWeek = DayOfWeek.Sunday Then Day02Column.SetValue(GridView.ColumnHeaderContainerStyleProperty, BoldStyle) Else Day02Column.SetValue(GridView.ColumnHeaderContainerStyleProperty, NormalStyle)
If TheDate.AddDays(2).DayOfWeek = DayOfWeek.Saturday Or TheDate.AddDays(2).DayOfWeek = DayOfWeek.Sunday Then Day03Column.SetValue(GridView.ColumnHeaderContainerStyleProperty, BoldStyle) Else Day03Column.SetValue(GridView.ColumnHeaderContainerStyleProperty, NormalStyle)

Neither worked - the column headers seem resolutely non-bold.
Any ideas what I'm doing wrong?

I'm so fed up with WPF.  Everything is an order of magnitude more complicated.  Previously with WinForms, I could knock out little apps for myself in no time at all.  Now I spend weeks wrestling with XAML, databinding, commands, etc.  When things don't work, there are no error messages, Intellisense is only of minor help in the XAML, and the only benefit I get from all this is resolution-independent apps.

Edit:- I should add that I know this works:

<Window.Resources>

If TheDate.DayOfWeek = DayOfWeek.Saturday Or TheDate.DayOfWeek = DayOfWeek.Sunday Then Day01Column.SetValue(GridViewColumn.HeaderContainerStyleProperty, Application.Current.MainWindow.FindResource("ColumnHeaderBoldStyle"))

But I believe I can only apply one style to an element, and since I also want to be able apply grey background to certain column headers, I think that would mean styles for grey only, bold only, grey + bold and neither.  And if I then wanted to set, say, the font colour, that would need 8 styles.  It doesn't scale well.
Surely there is a way to reach into the listview element from code and adjust individual bits of chrome?

Many thanks

Nick

Body:
In C#, I can do this from XAML as preparation:

<ListView.View>
   <GridView>
     <GridViewColumn DisplayMemberBinding="{Binding Name}" Width="160">
     <GridViewColumn.Header>
       <GridViewColumnHeader Tag="Name" Click="SortInterfaces_Click">Name</GridViewColumnHeader>
     </GridViewColumn.Header>
    </GridViewColumn>

and then in C# I switch font weights:

private void SortInterfaces_Click(object sender, RoutedEventArgs e)
{
  GridViewColumnHeader column = (sender as GridViewColumnHeader);
  if (column.Tag == null) return;
  column.FontWeight = FontWeights.Bold;
  InterfaceSortChangeTo(column);
}

If WPF gives you pain, try not to stray from the default built-in functionality. For the functions that are in there, it's actually quite ok.


问:
Per-Pixel operation with conditonals in Python without slowy loops
I'm trying to apply a treshold to an image, but not a regular simple treshold.

I need to set to black pixels if they fit the conditonal, and if not, set them to white.

I could just loop over pixels, but on a 1080p image, it's far too long.

I'm using HSV for the comparisons I need to make.

Here is the conditional (this example is how I would use it if it was in a loop):

```<code>if abs(input_pixel_color.hue - reference.hue) < 2 and input_pixel_color.saturation >= 0.25 and input_pixel_color.brightness >= 0.42:
    set_to_black
else:
    set_to_white
</code>```

input_pixel is the HSV value of the pixel in the loop.

reference is a variable to be compared to.

I thought about using numpy, but I really don't know how to write this :/

Thanks in advance

答:
Updated

Now that your actual intended processing has become clearer, you would probably be better served by OpenCV inRange() function. Like this:

```<code>#!/usr/local/bin/python3

import cv2 as cv
import numpy as np

# Load the image and convert to HLS
image = cv.imread("image.jpg")
hls   = cv.cvtColor(image,cv.COLOR_BGR2HLS)

# Define lower and uppper limits for each component
lo = np.array([50,0,0])
hi = np.array([70,255,255])

# Mask image to only select filtered pixels
mask = cv.inRange(hls,lo,hi)

# Change image to white where we found our colour
image[mask>0]=(255,255,255)

cv.imwrite("result.png",image)
</code>```

So, if we use this image:

We are selecting Hues in the range 50-70, and making them white:

If you go here to a colour converter, you can see that "Green" is Hue=120, but OpenCV divides Hues by 2 so that 360 degrees becomes 180 and still fits in a uint8. So, our 60 in the code means 120 in online colour converters.

The ranges OpenCV uses for uint8 images are:

Hue 0..180

Lightness 0..255

Saturation 0..255

As I said before, you should get in the habit of looking at your data types, shapes and ranges in your debugger. To see the shape, dtype, and maximum Hue, Lightness and Saturation, use:

```<code>print(hls.dtype, hls.shape)
print(hls[...,0].max())
print(hls[...,1].max())
print(hls[...,2].max())
</code>```

Original Answer

There are several ways to do that. The most performant is probably with the OpenCV function cv2.inRange() and there are plenty of answers on StackOverflow about that.

Here is a Numpy way. If you read the comments and look at the printed values, you can see how to combine logical AND with logical OR and so on, as well as how to address specific channels.

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

from random import randint, seed
import numpy as np

# Generate a repeatable random HSV image
np.random.seed(42)
h, w = 4, 5
HSV = np.random.randint(1,100,(h,w,3),dtype=np.uint8)
print('Initial HSV\n',HSV)

# Create mask of all pixels with acceptable Hue, i.e. H > 50
HueOK = HSV[...,0] > 50
print('HueOK\n',HueOK)

# Create mask of all pixels with acceptable Saturation, i.e. S > 20 AND S < 80
SatOK = np.logical_and(HSV[...,1]>20, HSV[...,1]<80)
print('SatOK\n',SatOK)

# Create mask of all pixels with acceptable value, i.e. V < 20 OR V > 60
ValOK = np.logical_or(HSV[...,2]<20, HSV[...,2]>60)
print('ValOK\n',ValOK)

# Combine masks
combinedMask = HueOK & SatOK & ValOK
print('Combined\n',combinedMask)

# Now, if you just want to set the masked pixels to 255
HSV[combinedMask] = 255
print('Result1\n',HSV)

# Or, if you want to set the masked pixels to one value and the others to another value
HSV = np.where(combinedMask,255,0)
print('Result2\n',HSV)
</code>```

Sample Output

```<code>Initial HSV
 [[[93 98 96]
  [52 62 76]
  [93  4 99]
  [15 22 47]
  [60 72 85]]

 [[26 72 61]
  [47 66 26]
  [21 45 76]
  [25 87 40]
  [25 35 83]]

 [[66 40 87]
  [24 26 75]
  [18 95 15]
  [75 86 18]
  [88 57 62]]

 [[94 86 45]
  [99 26 19]
  [37 24 63]
  [69 54  3]
  [33 33 39]]]
HueOK
 [[ True  True  True False  True]
 [False False False False False]
 [ True False False  True  True]
 [ True  True False  True False]]
SatOK
 [[False  True False  True  True]
 [ True  True  True False  True]
 [ True  True False False  True]
 [False  True  True  True  True]]
ValOK
 [[ True  True  True False  True]
 [ True False  True False  True]
 [ True  True  True  True  True]
 [False  True  True  True False]]
Combined
 [[False  True False False  True]
 [False False False False False]
 [ True False False False  True]
 [False  True False  True False]]
Result1
 [[[ 93  98  96]
  [255 255 255]
  [ 93   4  99]
  [ 15  22  47]
  [255 255 255]]

 [[ 26  72  61]
  [ 47  66  26]
  [ 21  45  76]
  [ 25  87  40]
  [ 25  35  83]]

 [[255 255 255]
  [ 24  26  75]
  [ 18  95  15]
  [ 75  86  18]
  [255 255 255]]

 [[ 94  86  45]
  [255 255 255]
  [ 37  24  63]
  [255 255 255]
  [ 33  33  39]]]
Result2
 [[  0 255   0   0 255]
 [  0   0   0   0   0]
 [255   0   0   0 255]
 [  0 255   0 255   0]]
</code>```

Notes:

1) You can also access pixels not selected by the mask, using negation:

```<code># All unmasked pixels become 3
HSV[~combinedMask] = 3
</code>```

2) The ellipsis (...) is just a shortcut meaning "all other dimensions I didn't bother listing", so HSV[...,1] is the same as HSV[:,:,1]

3) If you don't like writing HSV[...,0] for Hue, and HSV[...,1] for Saturation, you can split the channels

```<code>H, S, V = cv2.split(HSV)
</code>```

Then you can just use H instead of HSV[...,0]. When you are finished, if you want to re-assemble the channels back into a 3-channel image, you can do:

```<code>HSV = cv2.merge((H,S,V))
</code>```

or

```<code>HSV = np.dstack((H,S,V))
</code>```

Body:
I'm trying to apply a treshold to an image, but not a regular simple treshold.

I need to set to black pixels if they fit the conditonal, and if not, set them to white.

I could just loop over pixels, but on a 1080p image, it's far too long.

I'm using HSV for the comparisons I need to make.

Here is the conditional (this example is how I would use it if it was in a loop):

if abs(input_pixel_color.hue - reference.hue) < 2 and input_pixel_color.saturation >= 0.25 and input_pixel_color.brightness >= 0.42:
    set_to_black
else:
    set_to_white

input_pixel is the HSV value of the pixel in the loop.

reference is a variable to be compared to.

I thought about using numpy, but I really don't know how to write this :/

Thanks in advance

Body:
Updated

Now that your actual intended processing has become clearer, you would probably be better served by OpenCV inRange() function. Like this:

#!/usr/local/bin/python3

import cv2 as cv
import numpy as np

# Load the image and convert to HLS
image = cv.imread("image.jpg")
hls   = cv.cvtColor(image,cv.COLOR_BGR2HLS)

# Define lower and uppper limits for each component
lo = np.array([50,0,0])
hi = np.array([70,255,255])

# Mask image to only select filtered pixels
mask = cv.inRange(hls,lo,hi)

# Change image to white where we found our colour
image[mask>0]=(255,255,255)

cv.imwrite("result.png",image)

So, if we use this image:

We are selecting Hues in the range 50-70, and making them white:

If you go here to a colour converter, you can see that "Green" is Hue=120, but OpenCV divides Hues by 2 so that 360 degrees becomes 180 and still fits in a uint8. So, our 60 in the code means 120 in online colour converters.

The ranges OpenCV uses for uint8 images are:

Hue 0..180

Lightness 0..255

Saturation 0..255

As I said before, you should get in the habit of looking at your data types, shapes and ranges in your debugger. To see the shape, dtype, and maximum Hue, Lightness and Saturation, use:

print(hls.dtype, hls.shape)
print(hls[...,0].max())
print(hls[...,1].max())
print(hls[...,2].max())

Original Answer

There are several ways to do that. The most performant is probably with the OpenCV function cv2.inRange() and there are plenty of answers on StackOverflow about that.

Here is a Numpy way. If you read the comments and look at the printed values, you can see how to combine logical AND with logical OR and so on, as well as how to address specific channels.

#!/usr/bin/env python3

from random import randint, seed
import numpy as np

# Generate a repeatable random HSV image
np.random.seed(42)
h, w = 4, 5
HSV = np.random.randint(1,100,(h,w,3),dtype=np.uint8)
print('Initial HSV\n',HSV)

# Create mask of all pixels with acceptable Hue, i.e. H > 50
HueOK = HSV[...,0] > 50
print('HueOK\n',HueOK)

# Create mask of all pixels with acceptable Saturation, i.e. S > 20 AND S < 80
SatOK = np.logical_and(HSV[...,1]>20, HSV[...,1]<80)
print('SatOK\n',SatOK)

# Create mask of all pixels with acceptable value, i.e. V < 20 OR V > 60
ValOK = np.logical_or(HSV[...,2]<20, HSV[...,2]>60)
print('ValOK\n',ValOK)

# Combine masks
combinedMask = HueOK & SatOK & ValOK
print('Combined\n',combinedMask)

# Now, if you just want to set the masked pixels to 255
HSV[combinedMask] = 255
print('Result1\n',HSV)

# Or, if you want to set the masked pixels to one value and the others to another value
HSV = np.where(combinedMask,255,0)
print('Result2\n',HSV)

Sample Output

Initial HSV
 [[[93 98 96]
  [52 62 76]
  [93  4 99]
  [15 22 47]
  [60 72 85]]

 [[26 72 61]
  [47 66 26]
  [21 45 76]
  [25 87 40]
  [25 35 83]]

 [[66 40 87]
  [24 26 75]
  [18 95 15]
  [75 86 18]
  [88 57 62]]

 [[94 86 45]
  [99 26 19]
  [37 24 63]
  [69 54  3]
  [33 33 39]]]
HueOK
 [[ True  True  True False  True]
 [False False False False False]
 [ True False False  True  True]
 [ True  True False  True False]]
SatOK
 [[False  True False  True  True]
 [ True  True  True False  True]
 [ True  True False False  True]
 [False  True  True  True  True]]
ValOK
 [[ True  True  True False  True]
 [ True False  True False  True]
 [ True  True  True  True  True]
 [False  True  True  True False]]
Combined
 [[False  True False False  True]
 [False False False False False]
 [ True False False False  True]
 [False  True False  True False]]
Result1
 [[[ 93  98  96]
  [255 255 255]
  [ 93   4  99]
  [ 15  22  47]
  [255 255 255]]

 [[ 26  72  61]
  [ 47  66  26]
  [ 21  45  76]
  [ 25  87  40]
  [ 25  35  83]]

 [[255 255 255]
  [ 24  26  75]
  [ 18  95  15]
  [ 75  86  18]
  [255 255 255]]

 [[ 94  86  45]
  [255 255 255]
  [ 37  24  63]
  [255 255 255]
  [ 33  33  39]]]
Result2
 [[  0 255   0   0 255]
 [  0   0   0   0   0]
 [255   0   0   0 255]
 [  0 255   0 255   0]]

Notes:

1) You can also access pixels not selected by the mask, using negation:

# All unmasked pixels become 3
HSV[~combinedMask] = 3

2) The ellipsis (...) is just a shortcut meaning "all other dimensions I didn't bother listing", so HSV[...,1] is the same as HSV[:,:,1]

3) If you don't like writing HSV[...,0] for Hue, and HSV[...,1] for Saturation, you can split the channels

H, S, V = cv2.split(HSV)

Then you can just use H instead of HSV[...,0]. When you are finished, if you want to re-assemble the channels back into a 3-channel image, you can do:

HSV = cv2.merge((H,S,V))

or

HSV = np.dstack((H,S,V))


问:
Limiting Network Traffic in Flink with Kinesis
I have a Flink application running in Amazon's Kinesis Data Analytics Service (managed Flink cluster). In the app, I read in user data from a Kinesis stream, keyBy userId, and then aggregate some user information. After asking this question, I learned that Flink will split the reading of a stream across physical hosts in a cluster. Flink will then forward incoming events to the host that has the aggregator task assigned to the key space that corresponds to the given event.

With this in mind, I am trying to decide what to use as a partition key for the Kinesis stream that my Flink application reads from. My goal is to limit network traffic between hosts in the Flink cluster in order to optimize performance of my Flink application. I can either partition randomly, so the events are evenly distributed across the shards, or I can partition my shards by userId.

The decision depends on how Flink works internally. Is Flink smart enough to assign the local aggregator tasks on a host a key space that will correspond to the key space of the shard(s) the Kinesis consumer task on the same host is reading from? If this is the case, then sharding by userId would result in ZERO network traffic, since each event is streamed by the host that will aggregate it. It seems like Flink would not have a clear way of doing this, since it does not know how the Kinesis streams are sharded.

OR, does Flink randomly assign each Flink consumer task a subset of shards to read and randomly assign aggregator tasks a portion of the key space? If this is the case, then it seems a random partitioning of shards would result in the least amount of network traffic since at least some events will be read by a Flink consumer that is on the same host as the event's aggregator task. This would be better than partitioning by userId and then having to forward all events over the network because the keySpace of the shards did not align with the assigned key spaces of the local aggregators.

答:
10 years ago, it was really important that as little data as possible is shipped over the network. Since 5 years, network has become so incredible fast that you notice little difference between accessing a chunk of data over network or memory (random access is of course still much faster), such that I wouldn't sweat to much about the additional traffic (unless you have to pay for it). Anecdotally, Google Datastream started to stream all data to a central shuffle server between two tasks, effectively doubling the traffic; but they still experience tremendous speedups on their Petabyte network.

So with that in mind, let's move to Flink. Flink currently has no way to dynamically adjust to shards as they can come and go over time. In half a year with FLIP-27, it could be different.

For now, there is a workaround, currently mostly used in Kafka-land (static partition). DataStreamUtils#reinterpretAsKeyedStream allows you to specify a logical keyby without a physical shuffle. Of course, you are responsible that the provided partitioning corresponds to the reality or else you would get incorrect results.


问:
Merging distinct results SQL
So my problem is the following:
I have a MariaDB database that I am trying to query.
I am looking at experiment data. What I would like, is to summarize several experiments into one results row of an SQL query.

This is what the data looks like:

```<code>Experiment_ID | Antibiotic | Strain | Medium    | ...
1               Ampicillin   E. coli  TBauto      ...
2               Ampicillin   E. coli  TB + IPTG
</code>```

What I would like to get:

```<code>Experiment_ID | Antibiotic | Strain | Medium               | ...
1               Ampicillin   E. coli  TBauto, TB + IPTG      ...
</code>```

I don't care about the Experiment_ID, that is just there to make clear the I am talking about two distinct entries.

I already tried

```<code>Select
    tmp.*
From
    ((Select * from my_tbl Where ExperimentID = 1)
Union
    (Select * from my_tbl Where ExperimentID = 2)) as tmp
</code>```

There I still end up with 2 rows of results. I could also do it in my Python code. But I would like to not have to modify results that I grab from the DB.

I guess I must have just been looking for the wrong word, to merge those two entries. So please kindly guide me in the right direction.

答:
You seem to want aggregation:</p>

```<code>select min(Experiment_ID) as Experiment_ID, Antibiotic, Strain,
       group_concat(Medium order by Experiment_ID separator ', ')
from t
where Experiment_ID in (1, 2)
group by Antibiotic, Strain;
</code>```

Title: Merging distinct results SQL

Body:
So my problem is the following:
I have a MariaDB database that I am trying to query.
I am looking at experiment data. What I would like, is to summarize several experiments into one results row of an SQL query.

This is what the data looks like:

Experiment_ID | Antibiotic | Strain | Medium    | ...
1               Ampicillin   E. coli  TBauto      ...
2               Ampicillin   E. coli  TB + IPTG

What I would like to get:

Experiment_ID | Antibiotic | Strain | Medium               | ...
1               Ampicillin   E. coli  TBauto, TB + IPTG      ...

I don't care about the Experiment_ID, that is just there to make clear the I am talking about two distinct entries.

I already tried

Select
    tmp.*
From
    ((Select * from my_tbl Where ExperimentID = 1)
Union
    (Select * from my_tbl Where ExperimentID = 2)) as tmp

There I still end up with 2 rows of results. I could also do it in my Python code. But I would like to not have to modify results that I grab from the DB.

I guess I must have just been looking for the wrong word, to merge those two entries. So please kindly guide me in the right direction.

Body:
You seem to want aggregation:

select min(Experiment_ID) as Experiment_ID, Antibiotic, Strain,
       group_concat(Medium order by Experiment_ID separator ', ')
from t
where Experiment_ID in (1, 2)
group by Antibiotic, Strain;


问:
WebSocket TLS certificate setup fun
I'm trying to setup a WebSocket over TLS.

For that end I'm going by the directions on page 81 in the following book.

https://www.amazon.com/WebSocket-Client-Server-Communications-Andrew-Lombardi/dp/1449369278/ref=sr_1_1?keywords=websocket&qid=1581782142&sr=8-1

I setup the server code as they say in the book.
All good there, but there is some problem with the certificates.

According to the book I am supposed to take four steps in setting up the certificates

```<code>1. Generate a 2048 bit key.
openssl genrsa -des -passout pass:x -out server.pass.key 2048

2. Generate a passphrase free key.
openssl rsa -passin pass:x -in server.pass.key -out server.key

3. Generate csr from the private key.
openssl req -new -key server.key -out server.csr

4. Generate the certificate
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
</code>```

When I run step 1 I get error

```<code>"UI_set_result:result too small .."
</code>```

For which the fix is here.

He basically says to run the following snipped instead of step 1.

```<code>openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out server.key
</code>```

It looks like he is skipping the .pass part. For which step 2 is taken. So I am unsure if I should take that step or not, after the fix.

I run those four steps, then in server.js i have:

```<code>var connection={
    ssl:true,
    port:port_number_here,
    ssl_key:'server.key',
    ssl_cert:'server.crt'
    }

//..
var processRequest=function(req,res){
    res.writeHead(200);
    res.end("Hi!\n");
    //console.log('connecting');
    };

var app=null;
app = httpsServ.createServer({
    key: fs.readFileSync(connection.ssl_key),
    cert:fs.readFileSync(connection.ssl_cert)
    },processRequest).listen(connection.port);

var wss = new WebSocketServer({server:app});

var clients=[];
var client_number=0;
wss.on('connection', function(cclient_socket){
    console.log('Estabished Connection with client.');
    }
</code>```

Then I start the server with:

```<code>node server.js
</code>```

But when I run the client code via Firefox I get error:

```<code>Firefox can’t establish a connection to the server at wss://somedomain:someportnumber/.
</code>```

And in Chromium I get error:

```<code>(index):9 WebSocket connection to 'wss://thedomain.org:theportnumber/'
failed: Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID
</code>```

I am unsure how to proceed from here.
I would guess I somehow didn't make the certificates correctly but the error doesn't give me much to work with.

Any help would be appreciated.

p.s. I tried implementing the following directions, to no avail.

https://stackoverflow.com/a/41366949/322537

Also, I have a suspicion the Chromium error "ERR_CERT_AUTHORITY_INVALID" is a key thing here. I googled it and found
https://www.guildcafe.com/fix-net-err_cert_authority_invalid-error.html
it has to do with the certificate authority. which is just me. I'm still stranded though for I don't know how to fix it.

答: The solution was to not create the certificates as the book described but instead simply refer to the ssl certificates that had already been created for the given website.</p>

Title: WebSocket TLS certificate setup fun

Body:
I'm trying to setup a WebSocket over TLS.

For that end I'm going by the directions on page 81 in the following book.

https://www.amazon.com/WebSocket-Client-Server-Communications-Andrew-Lombardi/dp/1449369278/ref=sr_1_1?keywords=websocket&qid=1581782142&sr=8-1

I setup the server code as they say in the book.
All good there, but there is some problem with the certificates.

According to the book I am supposed to take four steps in setting up the certificates

1. Generate a 2048 bit key.
openssl genrsa -des -passout pass:x -out server.pass.key 2048

2. Generate a passphrase free key.
openssl rsa -passin pass:x -in server.pass.key -out server.key

3. Generate csr from the private key.
openssl req -new -key server.key -out server.csr

4. Generate the certificate
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

When I run step 1 I get error

"UI_set_result:result too small .."

For which the fix is here.

He basically says to run the following snipped instead of step 1.

openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out server.key

It looks like he is skipping the .pass part. For which step 2 is taken. So I am unsure if I should take that step or not, after the fix.

I run those four steps, then in server.js i have:

var connection={
    ssl:true,
    port:port_number_here,
    ssl_key:'server.key',
    ssl_cert:'server.crt'
    }

//..
var processRequest=function(req,res){
    res.writeHead(200);
    res.end("Hi!\n");
    //console.log('connecting');
    };

var app=null;
app = httpsServ.createServer({
    key: fs.readFileSync(connection.ssl_key),
    cert:fs.readFileSync(connection.ssl_cert)
    },processRequest).listen(connection.port);

var wss = new WebSocketServer({server:app});

var clients=[];
var client_number=0;
wss.on('connection', function(cclient_socket){
    console.log('Estabished Connection with client.');
    }

Then I start the server with:

node server.js

But when I run the client code via Firefox I get error:

Firefox can’t establish a connection to the server at wss://somedomain:someportnumber/.

And in Chromium I get error:

(index):9 WebSocket connection to 'wss://thedomain.org:theportnumber/'
failed: Error in connection establishment: net::ERR_CERT_AUTHORITY_INVALID

I am unsure how to proceed from here.
I would guess I somehow didn't make the certificates correctly but the error doesn't give me much to work with.

Any help would be appreciated.

p.s. I tried implementing the following directions, to no avail.

https://stackoverflow.com/a/41366949/322537

Also, I have a suspicion the Chromium error "ERR_CERT_AUTHORITY_INVALID" is a key thing here. I googled it and found
https://www.guildcafe.com/fix-net-err_cert_authority_invalid-error.html
it has to do with the certificate authority. which is just me. I'm still stranded though for I don't know how to fix it.


问:
How do I resolve error Installing Twilio NUGET
Good day Guys,

I have used Twilio on a project before and working fine. But i am trying to use it on another project on the same development machine. It keeps throwing the error below.

Any one with help

```<code>Install-Package Twilio
Attempting to gather dependencies information for package 'Twilio.5.37.4' with respect to project 'Newzone_CreditFacility', targeting '.NETFramework,Version=v4.5.2'
Attempting to resolve dependencies for package 'Twilio.5.37.4' with DependencyBehavior 'Lowest'
Resolving actions to install package 'Twilio.5.37.4'
Resolved actions to install package 'Twilio.5.37.4'
Adding package 'Microsoft.IdentityModel.Logging.1.1.2' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'Microsoft.IdentityModel.Logging.1.1.2' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'Microsoft.IdentityModel.Logging.1.1.2' to 'packages.config'
Successfully installed 'Microsoft.IdentityModel.Logging 1.1.2' to Newzone_CreditFacility
Adding package 'Newtonsoft.Json.10.0.1' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'Newtonsoft.Json.10.0.1' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'Newtonsoft.Json.10.0.1' to 'packages.config'
Executing script file 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages\Newtonsoft.Json.10.0.1\tools\install.ps1'
Successfully installed 'Newtonsoft.Json 10.0.1' to Newzone_CreditFacility
Adding package 'Microsoft.IdentityModel.Tokens.5.1.2' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'Microsoft.IdentityModel.Tokens.5.1.2' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'Microsoft.IdentityModel.Tokens.5.1.2' to 'packages.config'
Successfully installed 'Microsoft.IdentityModel.Tokens 5.1.2' to Newzone_CreditFacility
Adding package 'System.IdentityModel.Tokens.Jwt.5.1.2' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'System.IdentityModel.Tokens.Jwt.5.1.2' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'System.IdentityModel.Tokens.Jwt.5.1.2' to 'packages.config'
Successfully installed 'System.IdentityModel.Tokens.Jwt 5.1.2' to Newzone_CreditFacility
Install failed. Rolling back...
Package 'Twilio 5.37.4' does not exist in project 'Newzone_CreditFacility'
Removed package 'System.IdentityModel.Tokens.Jwt 5.1.2' from 'packages.config'
Removed package 'Microsoft.IdentityModel.Tokens 5.1.2' from 'packages.config'
Removed package 'Newtonsoft.Json 10.0.1' from 'packages.config'
Removed package 'Microsoft.IdentityModel.Logging 1.1.2' from 'packages.config'
Package 'Twilio 5.37.4' does not exist in folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removing package 'System.IdentityModel.Tokens.Jwt 5.1.2' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removed package 'System.IdentityModel.Tokens.Jwt 5.1.2' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removing package 'Microsoft.IdentityModel.Tokens 5.1.2' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removed package 'Microsoft.IdentityModel.Tokens 5.1.2' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removing package 'Newtonsoft.Json 10.0.1' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removed package 'Newtonsoft.Json 10.0.1' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removing package 'Microsoft.IdentityModel.Logging 1.1.2' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removed package 'Microsoft.IdentityModel.Logging 1.1.2' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Install-Package : Object reference not set to an instance of an object.
At line:1 char:1
+ Install-Package Twilio
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
+ FullyQualifiedErrorId :
 NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand
</code>```

答:
Here are some of steps you can try to fix this issue: You check for resolution after each of the step

Restart Visual Studio

Rename the folder Nuget to Nuget.old present in %appdata% > Roaming

Launch VS as admin

Check for updates under Tools > Extensions and Updates

Rename the folder cache to cache.old under AppData\Local\NuGet\

If nothing works you can try to re-install package manager see reference

Body:
Good day Guys,

I have used Twilio on a project before and working fine. But i am trying to use it on another project on the same development machine. It keeps throwing the error below.

Any one with help

Install-Package Twilio
Attempting to gather dependencies information for package 'Twilio.5.37.4' with respect to project 'Newzone_CreditFacility', targeting '.NETFramework,Version=v4.5.2'
Attempting to resolve dependencies for package 'Twilio.5.37.4' with DependencyBehavior 'Lowest'
Resolving actions to install package 'Twilio.5.37.4'
Resolved actions to install package 'Twilio.5.37.4'
Adding package 'Microsoft.IdentityModel.Logging.1.1.2' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'Microsoft.IdentityModel.Logging.1.1.2' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'Microsoft.IdentityModel.Logging.1.1.2' to 'packages.config'
Successfully installed 'Microsoft.IdentityModel.Logging 1.1.2' to Newzone_CreditFacility
Adding package 'Newtonsoft.Json.10.0.1' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'Newtonsoft.Json.10.0.1' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'Newtonsoft.Json.10.0.1' to 'packages.config'
Executing script file 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages\Newtonsoft.Json.10.0.1\tools\install.ps1'
Successfully installed 'Newtonsoft.Json 10.0.1' to Newzone_CreditFacility
Adding package 'Microsoft.IdentityModel.Tokens.5.1.2' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'Microsoft.IdentityModel.Tokens.5.1.2' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'Microsoft.IdentityModel.Tokens.5.1.2' to 'packages.config'
Successfully installed 'Microsoft.IdentityModel.Tokens 5.1.2' to Newzone_CreditFacility
Adding package 'System.IdentityModel.Tokens.Jwt.5.1.2' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'System.IdentityModel.Tokens.Jwt.5.1.2' to folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Added package 'System.IdentityModel.Tokens.Jwt.5.1.2' to 'packages.config'
Successfully installed 'System.IdentityModel.Tokens.Jwt 5.1.2' to Newzone_CreditFacility
Install failed. Rolling back...
Package 'Twilio 5.37.4' does not exist in project 'Newzone_CreditFacility'
Removed package 'System.IdentityModel.Tokens.Jwt 5.1.2' from 'packages.config'
Removed package 'Microsoft.IdentityModel.Tokens 5.1.2' from 'packages.config'
Removed package 'Newtonsoft.Json 10.0.1' from 'packages.config'
Removed package 'Microsoft.IdentityModel.Logging 1.1.2' from 'packages.config'
Package 'Twilio 5.37.4' does not exist in folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removing package 'System.IdentityModel.Tokens.Jwt 5.1.2' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removed package 'System.IdentityModel.Tokens.Jwt 5.1.2' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removing package 'Microsoft.IdentityModel.Tokens 5.1.2' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removed package 'Microsoft.IdentityModel.Tokens 5.1.2' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removing package 'Newtonsoft.Json 10.0.1' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removed package 'Newtonsoft.Json 10.0.1' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removing package 'Microsoft.IdentityModel.Logging 1.1.2' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Removed package 'Microsoft.IdentityModel.Logging 1.1.2' from folder 'c:\users\owner\documents\visual studio 2015\Projects\Newzone_CreditFacility\packages'
Install-Package : Object reference not set to an instance of an object.
At line:1 char:1
+ Install-Package Twilio
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Install-Package], Exception
+ FullyQualifiedErrorId :
 NuGetCmdletUnhandledException,NuGet.PackageManagement.PowerShellCmdlets.InstallPackageCommand


问:
How can i go .xib ViewController to storyboard ViewController and again storyboard to .xib ViewController
Here is my first .xib ViewController how can I go this ViewController to storyboard ViewController

```<code>class FirstViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

}
</code>```

Here is storyboard secondViewController and I would like to go again this ViewController to .xib ViewController

```<code>class SecondViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

}
</code>```

答:
From .xib to .storyboard:

```<code>let sb = UIStoryboard(name: "the-name-of-the-storyboard", bundle: nil)
let ctrl = sb.instantiateViewController(withIdentifier: "SecondViewControllerIdentifier")
self.present(ctrl, animated: true, completion: nil)
</code>```

Keep in mind that SecondViewControllerIdentifier is the identifier of the storyboard scene; it is not the class name of your controller

From .storyboard to .xib:

```<code>let ctrl = FirstViewController()
self.present(ctrl, animated: true, completion: nil)
</code>```

Assuming that either FirstViewController.xib or First.xib exists

Body:
Here is my first .xib ViewController how can I go this ViewController to storyboard ViewController

class FirstViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

}

Here is storyboard secondViewController and I would like to go again this ViewController to .xib ViewController

class SecondViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

}

Body:
From .xib to .storyboard:

let sb = UIStoryboard(name: "the-name-of-the-storyboard", bundle: nil)
let ctrl = sb.instantiateViewController(withIdentifier: "SecondViewControllerIdentifier")
self.present(ctrl, animated: true, completion: nil)

Keep in mind that SecondViewControllerIdentifier is the identifier of the storyboard scene; it is not the class name of your controller

From .storyboard to .xib:

let ctrl = FirstViewController()
self.present(ctrl, animated: true, completion: nil)

Assuming that either FirstViewController.xib or First.xib exists


问:
Cannot pass the props value?
Im new to react, and now is going to pass the id from one page to another page by props. But I'm not sure is it the correct way to pass it.

Consider the code below:

```<code><div  className="submit-button">
    <input type="submit"
        value="Purchase"
        className="btn btn-primary mt-2 text-capitalize "
        onClick={this.handleClickPurchase}
    />
</div>
</code>```

```<code>        handleClickPurchase(){
            window.location.href='/PurchaseInformation'
            return(
                <PurchaseInformation value={this.state.data.id}/>
            )
        }
</code>```

On my Purchase Information page

```<code>render(props){
    console.log(this.props.value)
    return (
      <div>
        <Header />
        <div>
          <h1> {this.props.value}</h1>
          <h2> Purchase Information Page is under development </h2>
        </div>
      </div>
    );
  }
</code>```

答:
As @Ido mentioned return <PurchaseInformation value={this.state.data.id}/> doesn't do anything.

Are you rendering PurchaseInformation in your parent component?
If so just use <PurchaseInformation value={this.state.data.id}/> in your render function.

I would use destructing syntax, makes it easier to use props/object.

```<code>render(){
   const {value} = this.props;
    console.log(value)
    return (
      <div>
        <Header />
        <div>
          <h1>{value}</h1>
          <h2>Purchase Information Page is under development</h2>
        </div>
      </div>
    );
  }
</code>```

Title: Cannot pass the props value?

Body:
Im new to react, and now is going to pass the id from one page to another page by props. But I'm not sure is it the correct way to pass it.

Consider the code below:

    <input type="submit"
        value="Purchase"
        className="btn btn-primary mt-2 text-capitalize "
        onClick={this.handleClickPurchase}
    />

        handleClickPurchase(){
            window.location.href='/PurchaseInformation'
            return(
                <PurchaseInformation value={this.state.data.id}/>
            )
        }

On my Purchase Information page

render(props){
    console.log(this.props.value)
    return (

 {this.props.value}

 Purchase Information Page is under development

    );
  }

Body:
As @Ido mentioned return <PurchaseInformation value={this.state.data.id}/> doesn't do anything.

Are you rendering PurchaseInformation in your parent component?
If so just use <PurchaseInformation value={this.state.data.id}/> in your render function.

I would use destructing syntax, makes it easier to use props/object.

render(){
   const {value} = this.props;
    console.log(value)
    return (
      <div>
        <Header />
        <div>
          <h1>{value}</h1>
          <h2>Purchase Information Page is under development</h2>
        </div>
      </div>
    );
  }


问:
pip/python: normal site-packages is not writeable
I have a new Macbook - a user installed it, and then I installed a new user (mine), granted admin privileges and deleted the old one. I am on OS Catalina.

Since the installation I've been having several permission problems.
VSCode can't find Jupyter Notebook, pip installs packages at ~/Library/Python/3.7/site-packages.

When I do which python3 I get usr/bin/python3.
When I do pip3 install <package> I get: Defaulting to user installation because normal site-packages is not writeable And then it says it has already been installed, even though I can't access it when I do import <package>.

It's seems clear that this is a permission problem, pip can't install to the "base" python, and them python can't find what I've installed into ~/Library/Python/3.7/site-packages.

I've tried reinstalling the OS, but since I haven't done a clean install, it didn't change anything.
What am I missing?
How exactly can I fix permissions? Where do I want packages to be installed (venv sure, but some packages I want global (like jupyter).

答:
It's best to not use the system-provided Python directly. Leave that one alone since the OS can change it in undesired ways, as you experienced.

The best practice is to configure your own Python version(s) and manage them on a per-project basis using virtualenv (for Python 2) or venv, possibly via poetry, (for Python 3). This eliminates all dependency on the system-provided Python version, and also isolates each project from other projects on the machine.

Each project can have a different Python point version if needed, and gets its own site_packages directory so pip-installed libraries can also have different versions by project. This approach is a major problem-avoider.


问:
Sort array of days in javascript
I have an array. The array can contain 1 to 7 unique strings of day names. The day names will be in order from Mon to Sun. - eg:

["Tue", "Thu", "Sun"]

I want to use javascript to sort that array so that the order will be beginning with today.

ie: if today is Friday, then the sorted array should be

["Sun", "Tue", "Thu"]

if today is Thursday then the sorted array should be

["Thu", "Sun", "Tue"]

Can anyone help?

答:
Here's an interesting way of solving the problem - wouldn't be suprised if this was fairly performant too (i.e. no complex objects, etc)</p>

```<code>const sortDays = days => {
    let arr = ['', '', '', '', '', '', '']
    days.forEach(day => {
        if (day === 'Sun') arr[0] = 'Sun'
        if (day === 'Mon') arr[1] = 'Mon'
        if (day === 'Tue') arr[2] = 'Tue'
        if (day === 'Wed') arr[3] = 'Wed'
        if (day === 'Thu') arr[4] = 'Thu'
        if (day === 'Fri') arr[5] = 'Fri'
        if (day === 'Sat') arr[6] = 'Sat'
    })
    return arr.filter(str => str !== '')
}
</code>```

Title: Sort array of days in javascript

Body:
Here's an interesting way of solving the problem - wouldn't be suprised if this was fairly performant too (i.e. no complex objects, etc)

const sortDays = days => {
    let arr = ['', '', '', '', '', '', '']
    days.forEach(day => {
        if (day === 'Sun') arr[0] = 'Sun'
        if (day === 'Mon') arr[1] = 'Mon'
        if (day === 'Tue') arr[2] = 'Tue'
        if (day === 'Wed') arr[3] = 'Wed'
        if (day === 'Thu') arr[4] = 'Thu'
        if (day === 'Fri') arr[5] = 'Fri'
        if (day === 'Sat') arr[6] = 'Sat'
    })
    return arr.filter(str => str !== '')
}