问:
Logic Apps liquid template ask
I am a complete newcomer to Liquid, started playing with it a few hours ago.

i am trying to parse a JSON and extract certain key value pairs out of it, yet i am not successful at all. the JSON is outputed from Azure Form Recognizer, and i am trying to do a Liquid json 2 json in Logic Apps.

the JSON looks like this

```<code>{
  "status": "success",
  "pages": [
    {
      "number": 1,
      "keyValuePairs": [
        {
          "key": [
            {
              "text": "Page No:",
              "boundingBox": [
                507.4
               ]
            }
          ],
          "value": [
            {
              "text": "1",
              "boundingBox": [
                586.8
              ],
              "confidence": 1.0
            }
          ]
        },
....
...
</code>```

what i am looking for is to loop through the keyValuePairs array, and then pull the "text" element from the "key" array, and the "text"+"confidence" element from the "value"array.

Could you please help me in understanding the approach here? I tried something like this, but the array comes back empty

```<code>{
"results":[
{% for kvp in content.keyValuePairs  %}

{% for mykey in kvp.key  %}

"thiskey":"{{mykey.text}}
{%- endfor -%}
{% for myval in kvp.value  %}

"thisvalue":{{myval.text}}
"thisconfidence":{{myval.confidence}}
{%- endfor -%}
{%- endfor -%}
]
}
</code>```

And second question: what's the best approach for debugging Liquid, so i can see where i am getting it wrong and adjust?

Thank you!

答:
I have tried to design workflow using your sample JSON payload.

I have parsed the JSON schema and extracted the required values from it.

Since your JSON payload is a bit complex, we need to use Logic App Expressions to extract the value out of it.

Payload I used:

```<code>{
"status": "success",
"pages": [{
    "number": 1,
    "keyValuePairs": [{
            "key": [{
                "text": "Page No:",
                "boundingBox": [
                    507.4
                ]
            }],
            "value": [{
                "text": "1",
                "boundingBox": [
                    586.8
                ],
                "confidence": 1.0
            }]
        },
        "null"
    ]
}]
</code>```

}

Once you get the JSON output from the upstream actions, you have to parse it.

Now, Initialize a couple of variables to get the required value from the parsed JSON.

Expression to be used in the first variable: concat(body('Parse_JSON')?['pages'][0]?['keyValuePairs'][0]?['key'][0]?['text'],body('Parse_JSON')?['pages'][0]?['keyValuePairs'][0]?['value'][0]?['text'])

Expression to be used in the second variable: body('Parse_JSON')?['pages'][0]?['keyValuePairs'][0]?['value'][0]?['confidence']

Finally, the logic apps after your Form Recognizor will look something like this:

I hope it helps!

Title: Logic Apps liquid template ask

Body:
I am a complete newcomer to Liquid, started playing with it a few hours ago.

i am trying to parse a JSON and extract certain key value pairs out of it, yet i am not successful at all. the JSON is outputed from Azure Form Recognizer, and i am trying to do a Liquid json 2 json in Logic Apps.

the JSON looks like this

{
  "status": "success",
  "pages": [
    {
      "number": 1,
      "keyValuePairs": [
        {
          "key": [
            {
              "text": "Page No:",
              "boundingBox": [
                507.4
               ]
            }
          ],
          "value": [
            {
              "text": "1",
              "boundingBox": [
                586.8
              ],
              "confidence": 1.0
            }
          ]
        },
....
...

what i am looking for is to loop through the keyValuePairs array, and then pull the "text" element from the "key" array, and the "text"+"confidence" element from the "value"array.

Could you please help me in understanding the approach here? I tried something like this, but the array comes back empty

{
"results":[
{% for kvp in content.keyValuePairs  %}

{% for mykey in kvp.key  %}

"thiskey":"{{mykey.text}}
{%- endfor -%}
{% for myval in kvp.value  %}

"thisvalue":{{myval.text}}
"thisconfidence":{{myval.confidence}}
{%- endfor -%}
{%- endfor -%}
]
}

And second question: what's the best approach for debugging Liquid, so i can see where i am getting it wrong and adjust?

Thank you!

Body:
I have tried to design workflow using your sample JSON payload.

I have parsed the JSON schema and extracted the required values from it.

Since your JSON payload is a bit complex, we need to use Logic App Expressions to extract the value out of it.

Payload I used:

{
"status": "success",
"pages": [{
    "number": 1,
    "keyValuePairs": [{
            "key": [{
                "text": "Page No:",
                "boundingBox": [
                    507.4
                ]
            }],
            "value": [{
                "text": "1",
                "boundingBox": [
                    586.8
                ],
                "confidence": 1.0
            }]
        },
        "null"
    ]
}]

}

Once you get the JSON output from the upstream actions, you have to parse it.

Now, Initialize a couple of variables to get the required value from the parsed JSON.

Expression to be used in the first variable: concat(body('Parse_JSON')?['pages'][0]?['keyValuePairs'][0]?['key'][0]?['text'],body('Parse_JSON')?['pages'][0]?['keyValuePairs'][0]?['value'][0]?['text'])

Expression to be used in the second variable: body('Parse_JSON')?['pages'][0]?['keyValuePairs'][0]?['value'][0]?['confidence']

Finally, the logic apps after your Form Recognizor will look something like this:

I hope it helps!


来源: stackexchange

问:
Difference between Spring TestContext Framework and Jboss Arquillian
My company developed in the last 7 years a medium/large web application. The application make use of Spring Framework (3.0), Hibernate(3.x) and Struts (1.x) among the others. Unfortunately we didn't use any kind of automatic tests. Now we need to add them to avoid regression bug and to start a better development lifecycle.
Following best practice for this hard job, I read we could start with smoke gui test, followed by integration testing before adding unit test.
So my question is: about integration test (in container) which are the difference between Spring TestContextFramework and JBoss Arquillian? I read Arquillian will support Spring in it's final release (http://community.jboss.org/message/563768). Will I have some kind of benefits using it once stable?

Thanks,
Stefano.

答:
I'm an Arquillian user myself, but I recommend you to stick with Spring's solution. While eventually it will be container agnostic, right now the effort is focused on Java EE. Your job seems hard enough and I wouldn't recommend Aquillian for now.

However, to clear up some confusion, you can run embedded tests on Arquillian. It can bootstrap an embedded Glassfish or JBoss AS servers and run test using the "real thing" instead of mock or alternate implementations. JPA, Interceptors, JTA, XA Datasources, JMS, JSF, Servlet. All available - batteries included ;)

Alternatively, you could fire up an JBoss instance on the background and run the test remotely. Arquillian takes care of the deploy/test/undeploy cycle - and it's blazing fast!

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Set NOW() as Default Value for datetime datatype?
I have two columns in table users namely registerDate and lastVisitDate which consist of datetime data type. I would like to do the following.

Set registerDate defaults value to MySQL NOW()

Set lastVisitDate default value to 0000-00-00 00:00:00 Instead of null which it uses by default.

Because the table already exists and has existing records, I would like to use Modify table.  I've tried using the two piece of code below, but neither works.

```<code>ALTER TABLE users MODIFY registerDate datetime DEFAULT NOW()
ALTER TABLE users MODIFY registerDate datetime DEFAULT CURRENT_TIMESTAMP;
</code>```

It gives me Error : ERROR 1067 (42000): Invalid default value for 'registerDate'

Is it possible for me to set the default datetime value to NOW() in MySQL?

答:
```<code>CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
  `dateUpdated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `mobile_UNIQUE` (`mobile`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
</code>```

Body:
I have two columns in table users namely registerDate and lastVisitDate which consist of datetime data type. I would like to do the following.

Set registerDate defaults value to MySQL NOW()

Set lastVisitDate default value to 0000-00-00 00:00:00 Instead of null which it uses by default.

Because the table already exists and has existing records, I would like to use Modify table.  I've tried using the two piece of code below, but neither works.

ALTER TABLE users MODIFY registerDate datetime DEFAULT NOW()
ALTER TABLE users MODIFY registerDate datetime DEFAULT CURRENT_TIMESTAMP;

It gives me Error : ERROR 1067 (42000): Invalid default value for 'registerDate'

Is it possible for me to set the default datetime value to NOW() in MySQL?

ContentLicense: CC BY-SA 4.0


问:
SystemC cannot use "+" "-" operators in visual studio 2019
enter image description here
I am trying to build the counter, when the "dec1" signal is high, the 8-bit unsign integer counter will decrese by 1. I am using visual sidio 2019 to complie the counter.cpp file, and "Hello worlds" .cpp is successful to run. </p>

答:
A SystemC signal does not provide access to all member functions of its internal value type, only an implicit conversion. You'll need to write the long form of

  counter1 = counter1 + 1;
```


问:
using berkshelf programmatically
i am managing my cookbooks with berkshelf.
i would like to play a little bit with the cookbook dependency graph. for instance:

given a cookbook, get its dependencies (the same as the resolver does it)

given a cookbook, get depended cookbooks (same as berks contingent)

i tried

```<code>require 'berkshelf'
Berkshelf::Lockfile.new(file_path: './Berksfile.lock')
</code>```

but it did not work.

how can berkshelf be invoked programmatically under ruby and achieve the above?

答:
If you have Berksfile, It might be helpful for you.</p>

```<code>
require 'berkshelf'

# initializing berksfile
s = Berkshelf::Berksfile.from_file('./find_versions/Berksfile')

#install dependencies to create Berksfile.lock
s.install()

# parse lockfile
s.lockfile().parse()

# find dependencies
puts s.find('cookbook_name').locked_version

</code>```

Title: using berkshelf programmatically

Body:
i am managing my cookbooks with berkshelf.
i would like to play a little bit with the cookbook dependency graph. for instance:

given a cookbook, get its dependencies (the same as the resolver does it)

given a cookbook, get depended cookbooks (same as berks contingent)

i tried

require 'berkshelf'
Berkshelf::Lockfile.new(file_path: './Berksfile.lock')

but it did not work.

how can berkshelf be invoked programmatically under ruby and achieve the above?

Body:
If you have Berksfile, It might be helpful for you.

require 'berkshelf'

# initializing berksfile
s = Berkshelf::Berksfile.from_file('./find_versions/Berksfile')

#install dependencies to create Berksfile.lock
s.install()

# parse lockfile
s.lockfile().parse()

# find dependencies
puts s.find('cookbook_name').locked_version


问:
How to get the number of columns in a dataset in python
A rookie question here.
I am trying to get the number of instances and the number of features in a dataset.
I am using pycharm
But I am getting an error:
(569, 31)
[Problem 0-B]: Value should be 32, found 31

```<code>def dimensions(dataset_id , dataset):
    dim = None
    num_inst = len(dataset)
    num_feat = len(dataset.columns)
    dim = (num_inst , num_feat)
    print(dim)

    return dim
</code>```

答:
use dataset.shape instead

```<code>def dimensions(dataset_id , dataset):
    return dataset.shape
</code>```

Body:
A rookie question here.
I am trying to get the number of instances and the number of features in a dataset.
I am using pycharm
But I am getting an error:
(569, 31)
[Problem 0-B]: Value should be 32, found 31

def dimensions(dataset_id , dataset):
    dim = None
    num_inst = len(dataset)
    num_feat = len(dataset.columns)
    dim = (num_inst , num_feat)
    print(dim)

    return dim

Body:
use dataset.shape instead

def dimensions(dataset_id , dataset):
    return dataset.shape


问:
Why can't I cast DateTime[] to object[]?
It seems that I can cast DateTime to object, so why can't I cast array DateTime[] to object[]?  I know this has something to do with value/reference types, but doesn't boxing allow me to do this?</p>

答:
Because DateTime is an object, but an array of DateTime isn't an array of object.

Arrays of value types are different than arrays of reference types so these two types of arrays are fundamentally incompatible.  The value type array actually contains the values and the reference type array contains, well, only references.


问:
Python regex that match column with non-uniform space separation between any 2 column?

I have a text file that contain some numerical line of data that I need to match. The data are put into column separate by some space. For example, consider the third line:

```<code>101     NUC-A       21.600 1  1.0200 1.3450  450.00  -66.03 0.9894  49.64 0.2681 0.4167
</code>```

We see that 101 in column 1 and NUC-A in column 2 is separated by 5 spaces. However column 2 and column 3 between the words NUC-A and 21.600 is separated by 7 spaces.

All the line that need to be match are marked by the red downward arrow.

There are a total of 12 columns, how can I extract all of these line that contain 12 columns out ? I still cannot think of any good pattern in the case

Thank you very much

答:
You don't want "a regex that matches columns with non-uniform space separation", you want to split at \s+.

```<code>import re

with open('filename', encoding='utf8') as file:
    for line in file:
        fields = re.split(r'\s+', line)
        if len(fields) == 12:
            print(fields)
</code>```

You can do the same thing without regex, by splitting at the space and filtering out any empty strings.

```<code>        fields = list(filter(None, line.split(' ')))
        if len(fields) == 12:
            print(fields)
</code>```

Body:
I have a text file that contain some numerical line of data that I need to match. The data are put into column separate by some space. For example, consider the third line:

101     NUC-A       21.600 1  1.0200 1.3450  450.00  -66.03 0.9894  49.64 0.2681 0.4167

We see that 101 in column 1 and NUC-A in column 2 is separated by 5 spaces. However column 2 and column 3 between the words NUC-A and 21.600 is separated by 7 spaces.

All the line that need to be match are marked by the red downward arrow.

There are a total of 12 columns, how can I extract all of these line that contain 12 columns out ? I still cannot think of any good pattern in the case

Thank you very much

Body:
You don't want "a regex that matches columns with non-uniform space separation", you want to split at \s+.

import re

with open('filename', encoding='utf8') as file:
    for line in file:
        fields = re.split(r'\s+', line)
        if len(fields) == 12:
            print(fields)

You can do the same thing without regex, by splitting at the space and filtering out any empty strings.

        fields = list(filter(None, line.split(' ')))
        if len(fields) == 12:
            print(fields)


问:
saving userType in ReactJs thorughout the session
I am using ReactJs and Nodejs with mysql as my backend, I am maintaining user session via express-session and setting cookie header in my browser. The problem is that I want to display components based on role (eg.admin or user). I am sending the userType from database to React app,in response to the successful login.
How can I maintain and store this userType througout the session so that I can manage my roles.
I dont think local Storage is a good option.

P.S: I have also key:value pair of userType inside the cookie which I am receiving in my browser.but I dont know how to extract userType from the cookie

答: Storing in a cookie/local storage is fine you just have to make sure the user is authenticated server-side for a certain privilege.</p>


问:
Slow iteration through elements in WatiN
I'm writing an application with Watin. Its great, but running a performance analysis on my program, over 50% of execution time is spent looping through lists of elements.

For example:
    foreach (TextField bT in browser.TextFields)
    {

Is very slow.

I seem to remember seeing somewhere there is a faster way of doing this in WatiN, but unfortunately I can't find the page again.

Accessing the number of elements also seems to be slow, eg;
    browser.CheckBoxes.Count

Thanks for any tips,
Chris

答:
I think I could answer you better if I had a better idea of what you were trying to do, but I can share some observations on what I've learned with WatiN so far.

The more specific your selectors are, the faster things will go. Avoid using "browser.Elements" as that is really generic. I'm not sure that it saves much, but doing something like browser.Body.Elements throws the header elements out of the scope of things to check and may save a few calculations.

When I say "scope", consider that WatiN always starts with the entire DOM. Can you think of ways to limit the scope of elements perhaps to the text fields within the main div on your page? WatiN returns Elements and ElementCollections, each of which may have its own ElementCollection. That div probably has a specific ID, so you can do something like

```<code>var textFields = ie.Div("divId").TextFields;
</code>```

Look for opportunities to be more specific, and you can use LINQ to describe what you want more clearly. For example, can you write something like:

```<code>ie.Body.TextFields.
  Where(tf => !string.IsNullOrWhiteSpace(tf.ClassName) && tf.ClassName.Contains("classname")).ToList().
  Foreach(tf => tf.Value = "Your Text");
</code>```

I would refine that further by reducing the number of times I scan the collection by doing something like:

```<code>ie.Body.TextFields.ToList().
  Foreach(tf => {
    if(!string.IsNullOrWhiteSpace(tf.ClassName) && tf.ClassName.Contains("classname")) {
      tf => tf.Value = "Your Text"
    }
  });
</code>```

The "Find.By*" specifiers also help WatiN operate on the collections you want faster and are a more elegant short-hand for what I wrote above:

```<code>ie.Body.TextFields.Filter(Find.ByClass("class")).ToList().ForEach(tf => tf.Value = "Your Text");
</code>```

And as a last piece of advice, this project lets you find elements using jQuery/CSS style selectors.

So, tl;dr: Narrow down the scope of what you're looking for, and be specific.

Hope that helps. I'm looking for ways to speed up my own tests.

Body:
I think I could answer you better if I had a better idea of what you were trying to do, but I can share some observations on what I've learned with WatiN so far.

The more specific your selectors are, the faster things will go. Avoid using "browser.Elements" as that is really generic. I'm not sure that it saves much, but doing something like browser.Body.Elements throws the header elements out of the scope of things to check and may save a few calculations.

When I say "scope", consider that WatiN always starts with the entire DOM. Can you think of ways to limit the scope of elements perhaps to the text fields within the main div on your page? WatiN returns Elements and ElementCollections, each of which may have its own ElementCollection. That div probably has a specific ID, so you can do something like

var textFields = ie.Div("divId").TextFields;

Look for opportunities to be more specific, and you can use LINQ to describe what you want more clearly. For example, can you write something like:

ie.Body.TextFields.
  Where(tf => !string.IsNullOrWhiteSpace(tf.ClassName) && tf.ClassName.Contains("classname")).ToList().
  Foreach(tf => tf.Value = "Your Text");

I would refine that further by reducing the number of times I scan the collection by doing something like:

ie.Body.TextFields.ToList().
  Foreach(tf => {
    if(!string.IsNullOrWhiteSpace(tf.ClassName) && tf.ClassName.Contains("classname")) {
      tf => tf.Value = "Your Text"
    }
  });

The "Find.By*" specifiers also help WatiN operate on the collections you want faster and are a more elegant short-hand for what I wrote above:

ie.Body.TextFields.Filter(Find.ByClass("class")).ToList().ForEach(tf => tf.Value = "Your Text");

And as a last piece of advice, this project lets you find elements using jQuery/CSS style selectors.

So, tl;dr: Narrow down the scope of what you're looking for, and be specific.

Hope that helps. I'm looking for ways to speed up my own tests.


问:
React Native - iOS - Invalid `Podfile` file: undefined method `[]' for nil:NilClass
I have just started out with React Native. I was following the React Native CLI Quickstart from the official documentation. That does also mean I am up to date with React Native version 0.61.2.

Since then I have done some basic UI, checking with the result in the iPhone simulator. It works when running react-native run-ios, not really touching the ios/Podfile too much.

My problem is running pod install inside my ios/ folder always results in an error! This becomes a problem now where I need to install additional packages. But it is already failing with default Podfile!

Error message:

```<code>[!] Invalid `Podfile` file: undefined method `[]' for nil:NilClass.

 #  from /Users/marcel/Projekte/WerBinIch/ios/Podfile:43
 #  -------------------------------------------
 #
 >    use_native_modules!
 #  end
 #  -------------------------------------------
</code>```

ios/Podfile

```<code>platform :ios, '9.0'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

target 'WerBinIch' do
  # Pods for WerBinIch
  pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
  pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"
  pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"
  pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"
  pod 'React', :path => '../node_modules/react-native/'
  pod 'React-Core', :path => '../node_modules/react-native/'
  pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'
  pod 'React-Core/DevSupport', :path => '../node_modules/react-native/'
  pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
  pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
  pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
  pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
  pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
  pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
  pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
  pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
  pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
  pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native/'

  pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
  pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
  pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
  pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
  pod 'ReactCommon/jscallinvoker', :path => "../node_modules/react-native/ReactCommon"
  pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"
  pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga'

  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'

  target 'WerBinIchTests' do
    inherit! :search_paths
    # Pods for testing
  end

  use_native_modules!
end
</code>```

I have no idea how to deal with this! I have no idea how the Podfile and the thing with the xcode files really work! I was trying to delete folders accomplishing a reset. More than that I have no idea what the error message could mean.

答:
This error happens when you cd to ios folder and run "pod install"
and is because you added a new react native module by

npm -i package

instead of using yarn

yarn add package

To solve this problem, just go to the main react native project folder where package.json is and run the command below again

yarn cache clean

yarn add package

Then try cd to the ios folder and run "pod install" and there will no more errors. Hope this can help the other people who are also facing the same problem.

Body:
I have just started out with React Native. I was following the React Native CLI Quickstart from the official documentation. That does also mean I am up to date with React Native version 0.61.2.

Since then I have done some basic UI, checking with the result in the iPhone simulator. It works when running react-native run-ios, not really touching the ios/Podfile too much.

My problem is running pod install inside my ios/ folder always results in an error! This becomes a problem now where I need to install additional packages. But it is already failing with default Podfile!

Error message:

[!] Invalid `Podfile` file: undefined method `[]' for nil:NilClass.

 #  from /Users/marcel/Projekte/WerBinIch/ios/Podfile:43
 #  -------------------------------------------
 #
 >    use_native_modules!
 #  end
 #  -------------------------------------------

ios/Podfile

platform :ios, '9.0'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

target 'WerBinIch' do
  # Pods for WerBinIch
  pod 'FBLazyVector', :path => "../node_modules/react-native/Libraries/FBLazyVector"
  pod 'FBReactNativeSpec', :path => "../node_modules/react-native/Libraries/FBReactNativeSpec"
  pod 'RCTRequired', :path => "../node_modules/react-native/Libraries/RCTRequired"
  pod 'RCTTypeSafety', :path => "../node_modules/react-native/Libraries/TypeSafety"
  pod 'React', :path => '../node_modules/react-native/'
  pod 'React-Core', :path => '../node_modules/react-native/'
  pod 'React-CoreModules', :path => '../node_modules/react-native/React/CoreModules'
  pod 'React-Core/DevSupport', :path => '../node_modules/react-native/'
  pod 'React-RCTActionSheet', :path => '../node_modules/react-native/Libraries/ActionSheetIOS'
  pod 'React-RCTAnimation', :path => '../node_modules/react-native/Libraries/NativeAnimation'
  pod 'React-RCTBlob', :path => '../node_modules/react-native/Libraries/Blob'
  pod 'React-RCTImage', :path => '../node_modules/react-native/Libraries/Image'
  pod 'React-RCTLinking', :path => '../node_modules/react-native/Libraries/LinkingIOS'
  pod 'React-RCTNetwork', :path => '../node_modules/react-native/Libraries/Network'
  pod 'React-RCTSettings', :path => '../node_modules/react-native/Libraries/Settings'
  pod 'React-RCTText', :path => '../node_modules/react-native/Libraries/Text'
  pod 'React-RCTVibration', :path => '../node_modules/react-native/Libraries/Vibration'
  pod 'React-Core/RCTWebSocket', :path => '../node_modules/react-native/'

  pod 'React-cxxreact', :path => '../node_modules/react-native/ReactCommon/cxxreact'
  pod 'React-jsi', :path => '../node_modules/react-native/ReactCommon/jsi'
  pod 'React-jsiexecutor', :path => '../node_modules/react-native/ReactCommon/jsiexecutor'
  pod 'React-jsinspector', :path => '../node_modules/react-native/ReactCommon/jsinspector'
  pod 'ReactCommon/jscallinvoker', :path => "../node_modules/react-native/ReactCommon"
  pod 'ReactCommon/turbomodule/core', :path => "../node_modules/react-native/ReactCommon"
  pod 'Yoga', :path => '../node_modules/react-native/ReactCommon/yoga'

  pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
  pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
  pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'

  target 'WerBinIchTests' do
    inherit! :search_paths
    # Pods for testing
  end

  use_native_modules!
end

I have no idea how to deal with this! I have no idea how the Podfile and the thing with the xcode files really work! I was trying to delete folders accomplishing a reset. More than that I have no idea what the error message could mean.


答:
See the other answers for why you cannot do so.

The alternative is to perform a deep copy of the array. Example using LINQ:

```<code>DateTime[] dates = ...;
object[] objects = dates.Select(d => (object)d).ToArray();
</code>```

Title: Why can't I cast DateTime[] to object[]?

Body: It seems that I can cast DateTime to object, so why can't I cast array DateTime[] to object[]?  I know this has something to do with value/reference types, but doesn't boxing allow me to do this?

Body:
See the other answers for why you cannot do so.

The alternative is to perform a deep copy of the array. Example using LINQ:

DateTime[] dates = ...;
object[] objects = dates.Select(d => (object)d).ToArray();


问:
High-performance replacement for multiprocessing.Queue
My distributed application consists of many producers that push tasks into several FIFO queues, and multiple consumers for every one of these queues. All these components live on a single node, so no networking involved.

This pattern is perfectly supported by Python's built-in multiprocessing.Queue, however when I am scaling up my application the queue implementation seems to be a bottleneck. I am not sending large amounts of data, so memory sharing does not solve the problem. What I need is fast guaranteed delivery of 10^4-10^5 small messages per second. Each message is about 100 bytes.

I am new to the world of fast distributed computing and I am very confused by the sheer amount of options. There is RabbitMQ, Redis, Kafka, etc.

ZeroMQ is a more focused and compact alternative, which also has successors such as nanomsg and nng. Also, implementing something like a many-to-many queue with a guaranteed delivery seems nontrivial without a broker.

I would really appreciate if someone could point me to a "standard" way of doing something like this with one of the faster frameworks.

答:
I think that a lot of it depends partly on what sort of importance you place on individual messages.

If each and every one is vital, and you have to consider what happens to them in the event of some failure somewhere, then frameworks like RabbitMQ can be useful. RabbitMQ has a broker, and it's possible to configure this for some sort of high availability, high reliability mode. With the right queue settings, RabbitMQ will look after your messages up until some part of your system consumes them.

To do all this, RabbitMQ needs a broker. This makes it fairly slow. Though at one point there was talk about reimplementing RabbitMQ on top of ZeroMQ's underlying protocols (zmtp) and doing away with the broker, implementing all the functionality in the endpoints instead.

In contrast, ZeroMQ does far less to guarantee that, in the event of failures, your messages will actually, eventually, get through to the intended destination. If a process dies, or a network connection fails, then there's a high chance that messages have got lost. More recent versions can be set up to actively monitor connections, so that if a network cable breaks or a process dies somewhere, the endpoints at the other end of the sockets can be informed about this pretty quickly. If one then implements a communicating sequential processes framework on top of ZMQ's actor framework (think: message acknowledgements, etc. This will slow it down) you can end up with a system whereby endpoints can know for sure that messages have been transfered to intended destinations.

Being brokerless allows zmq to be pretty fast. And it's efficient across a number of different transports, ranging from inproc to tcp, all of which can be blended together. If you're not worried about processes crashing or network connections failing, ZMQ gives you a guarantee to deliver messages right out of the box.

So, deciding what it is that's important in your application helps choose what technology you're doing to use as part of it - RabbitMQ, ZeroMQ, etc. Once you've decided that, then the problem of "how to get the patterns I need" is reduced to "what patterns does that technology support". RabbitMQ is, AFAIK, purely pub/sub (there can be a lot of each), whereas ZeroMQ has many more.


问:
NestJs dependency injection with task scheduling is not working
I am trying to implement task scheduling as described in Nest documentation, but there is no example with dependency injection for a service that uses scheduling. What I want is to use injected services in recurring tasks, but when I do something like this:

```<code>@Injectable()
export class MyWorkerService {

    constructor(private readonly injectedService: MyInjectedService) {}

    @Timeout(5000)
    async doSomething():  {
     console.log(this.injectedService); // undefined
     this.injectedService.doStuff(); // TypeError: cannot read property 'doStuff' of undefined
    }
}
</code>```

...dependency injection just does not work. Both services are registered as providers in the same module.

Why would this happen? How else can I access my other services from scheduled methods?

答:
Here I am answering my own question 2 hours later :)

So basically one of the services that I injected into service that I injected into my scheduled service had REQUEST scope:

@Injectable({ scope: Scope.REQUEST })

After removing it from injected service constructor dependency injection began working as expected.

Body:
I am trying to implement task scheduling as described in Nest documentation, but there is no example with dependency injection for a service that uses scheduling. What I want is to use injected services in recurring tasks, but when I do something like this:

@Injectable()
export class MyWorkerService {

    constructor(private readonly injectedService: MyInjectedService) {}

    @Timeout(5000)
    async doSomething():  {
     console.log(this.injectedService); // undefined
     this.injectedService.doStuff(); // TypeError: cannot read property 'doStuff' of undefined
    }
}

...dependency injection just does not work. Both services are registered as providers in the same module.

Why would this happen? How else can I access my other services from scheduled methods?


问:
Reuse an operator<< for several classes
I have two classes (this is a, extract from my actual more complex case)

```<code>class ClUInt {
public:
    ClUInt() : _i(2), _arr{1,2,3} {};
    ClUInt(const unsigned int ui) : _i(ui) {};
private:
    unsigned int _i;
    double _arr[3];
};

class ClInt {
public:
    ClInt() : _i(-2), _arr{-1,-2,-3} {};
    ClInt(const int i) : ClInt() { _i = i; };
private:
    int _i;
    double _arr[3];
};
</code>```

They are very similar, but one uses int and the other unsigned int for member _i.

I want to overload operator<< with, e.g.,

```<code>std::ostream& operator<<(std::ostream& os, const ClInt & ci)
{
    cout << ci._i << endl;
    cout << ci._arr[0] << endl;
    return os;
}
</code>```

Assume I want the "same" overload for both classes.

How can I write it only once, so it is easier to maintain?
I thought of defining my own cast, but I am not sure it is the way to go...

Notes:

I think I have no chance of making the two classes share any part of an inheritance tree.

They could actually be structs, so if privacy affects the answer, one can assume _i and _arr are public.

In the actual case, the two structs have a larger number of "common" members which are signed/unsigned, respectively.

答:
You could try creating a templated operator<< which works for only those two types using SFINAE. E.g.:

```<code>template <class T,
  std::enable_if_t<
      std::is_same<ClInt, std::decay_t<T>>::value
      or std::is_same<ClUInt, std::decay_t<T>>::value
    , int> = 0>
std::ostream & operator<< (std::ostream & out, T const & obj) {
  out << obj._i << '\n';
  out << obj._arr[0] << '\n';
  return out;
}
</code>```

The above example is for C++14, but can be made to work with C++11 if you replace things like std::decay_t<T> with typename std::decay<T>::type.

Note: I replaced std::endl with '\n', since you probably don't want to be flushing your output stream every time. See C++: "std::endl" vs "\n".

Title: Reuse an operator<< for several classes

Body:
I have two classes (this is a, extract from my actual more complex case)

class ClUInt {
public:
    ClUInt() : _i(2), _arr{1,2,3} {};
    ClUInt(const unsigned int ui) : _i(ui) {};
private:
    unsigned int _i;
    double _arr[3];
};

class ClInt {
public:
    ClInt() : _i(-2), _arr{-1,-2,-3} {};
    ClInt(const int i) : ClInt() { _i = i; };
private:
    int _i;
    double _arr[3];
};

They are very similar, but one uses int and the other unsigned int for member _i.

I want to overload operator<< with, e.g.,

std::ostream& operator<<(std::ostream& os, const ClInt & ci)
{
    cout << ci._i << endl;
    cout << ci._arr[0] << endl;
    return os;
}

Assume I want the "same" overload for both classes.

How can I write it only once, so it is easier to maintain?
I thought of defining my own cast, but I am not sure it is the way to go...

Notes:

I think I have no chance of making the two classes share any part of an inheritance tree.

They could actually be structs, so if privacy affects the answer, one can assume _i and _arr are public.

In the actual case, the two structs have a larger number of "common" members which are signed/unsigned, respectively.

Body:
You could try creating a templated operator<< which works for only those two types using SFINAE. E.g.:

template <class T,
  std::enable_if_t<
      std::is_same<ClInt, std::decay_t<T>>::value
      or std::is_same<ClUInt, std::decay_t<T>>::value
    , int> = 0>
std::ostream & operator<< (std::ostream & out, T const & obj) {
  out << obj._i << '\n';
  out << obj._arr[0] << '\n';
  return out;
}

The above example is for C++14, but can be made to work with C++11 if you replace things like std::decay_t<T> with typename std::decay<T>::type.

Note: I replaced std::endl with '\n', since you probably don't want to be flushing your output stream every time. See C++: "std::endl" vs "\n".


问:
Symbolicated iOS crash report from Apple review still not readable
I got a crash report from Apple and symbolicated it following this document, but I still didn't understand the report.

First, I tried below "XCode approach" to symbolicate the report:

Connect an iOS device to your Mac

Choose "Devices" from the "Window" menu

Under the "DEVICES" section in the left column, choose a device

Click the "View Device Logs" button under the "Device Information" section on the right hand panel

Drag your crash report onto the left column of the presented panel

Xcode will automatically symbolicate the crash report and display the results

Before that, I downloaded dSYM files from App Store by 'Organizer' and copied them into a separated folder. But all the symbolicated names looked like this:

```<code>5   Recycling                       0x10103b464 fb1UCM8vZCiE + 355
6   Recycling                       0x1010431d4 fbkUVUzGnhkS + 1655
7   Recycling                       0x101038a78 fbIiaWxkoUb6 + 307
</code>```

And then, I tried the approach from this blog, but the problem remained:

```<code>{"app_name":"Recycling","timestamp":"2020-02-08 00:00:51.02 +0800","app_version":"1.7.3","slice_uuid":"20cdeb29-1f14-3298-9649-503635ded968","adam_id":1406292831,"build_version":"3","bundleID":"com.qdjzd.Recycling","share_with_app_devs":true,"is_first_party":false,"bug_type":"109","os_version":"iPhone OS 13.3.1 (17D50)","incident_id":"36AEED5C-F4AD-4711-926E-783D4783039E","name":"Recycling"}
Incident Identifier: 36AEED5C-F4AD-4711-926E-783D4783039E
CrashReporter Key:   665569f89a7cca0567f04077cd6e5757ddeffea5
Hardware Model:      xxx1
Process:             Recycling [6029]
Path:                /private/var/containers/Bundle/Application/0A62AE5B-BE91-4A30-8CB5-A6137DE9DCC1/Recycling.app/Recycling
Identifier:          com.qdjzd.Recycling
Version:             3 (1.7.3)
AppStoreTools:       11C29
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           com.qdjzd.Recycling [1787]

Date/Time:           2020-02-08 00:00:50.8368 +0800
Launch Time:         2020-02-08 00:00:22.0052 +0800
OS Version:          iPhone OS 13.3.1 (17D50)
Release Type:        User
Baseband Version:    n/a
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  11

Last Exception Backtrace:
0   CoreFoundation                  0x1abab8a48 0x1ab98d000 + 1227336
1   libobjc.A.dylib                 0x1ab7dffa4 0x1ab7da000 + 24484
2   CoreFoundation                  0x1ab9c0e34 0x1ab98d000 + 212532
3   CoreServices                    0x1ac1232d8 0x1ac056000 + 840408
4   Foundation                      0x1abd736f8 0x1abd69000 + 42744
5   Recycling                       0x10103b464 fb1UCM8vZCiE + 355
6   Recycling                       0x1010431d4 fbkUVUzGnhkS + 1655
7   Recycling                       0x101038a78 fbIiaWxkoUb6 + 307
8   libsystem_pthread.dylib         0x1ab7d3d8c 0x1ab7c9000 + 44428
9   libsystem_pthread.dylib         0x1ab7d776c 0x1ab7c9000 + 59244
</code>```

Can anyone help me?

答:
Thanks for everyone! I finally resolved this problem by myself.

The reason is that I used a 3rd-party library named UMCCommon with version 1.5.3, and all of its symbols are obfuscated, so I can not understand.

Body:
I got a crash report from Apple and symbolicated it following this document, but I still didn't understand the report.

First, I tried below "XCode approach" to symbolicate the report:

Connect an iOS device to your Mac

Choose "Devices" from the "Window" menu

Under the "DEVICES" section in the left column, choose a device

Click the "View Device Logs" button under the "Device Information" section on the right hand panel

Drag your crash report onto the left column of the presented panel

Xcode will automatically symbolicate the crash report and display the results

Before that, I downloaded dSYM files from App Store by 'Organizer' and copied them into a separated folder. But all the symbolicated names looked like this:

5   Recycling                       0x10103b464 fb1UCM8vZCiE + 355
6   Recycling                       0x1010431d4 fbkUVUzGnhkS + 1655
7   Recycling                       0x101038a78 fbIiaWxkoUb6 + 307

And then, I tried the approach from this blog, but the problem remained:

{"app_name":"Recycling","timestamp":"2020-02-08 00:00:51.02 +0800","app_version":"1.7.3","slice_uuid":"20cdeb29-1f14-3298-9649-503635ded968","adam_id":1406292831,"build_version":"3","bundleID":"com.qdjzd.Recycling","share_with_app_devs":true,"is_first_party":false,"bug_type":"109","os_version":"iPhone OS 13.3.1 (17D50)","incident_id":"36AEED5C-F4AD-4711-926E-783D4783039E","name":"Recycling"}
Incident Identifier: 36AEED5C-F4AD-4711-926E-783D4783039E
CrashReporter Key:   665569f89a7cca0567f04077cd6e5757ddeffea5
Hardware Model:      xxx1
Process:             Recycling [6029]
Path:                /private/var/containers/Bundle/Application/0A62AE5B-BE91-4A30-8CB5-A6137DE9DCC1/Recycling.app/Recycling
Identifier:          com.qdjzd.Recycling
Version:             3 (1.7.3)
AppStoreTools:       11C29
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           com.qdjzd.Recycling [1787]

Date/Time:           2020-02-08 00:00:50.8368 +0800
Launch Time:         2020-02-08 00:00:22.0052 +0800
OS Version:          iPhone OS 13.3.1 (17D50)
Release Type:        User
Baseband Version:    n/a
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  11

Last Exception Backtrace:
0   CoreFoundation                  0x1abab8a48 0x1ab98d000 + 1227336
1   libobjc.A.dylib                 0x1ab7dffa4 0x1ab7da000 + 24484
2   CoreFoundation                  0x1ab9c0e34 0x1ab98d000 + 212532
3   CoreServices                    0x1ac1232d8 0x1ac056000 + 840408
4   Foundation                      0x1abd736f8 0x1abd69000 + 42744
5   Recycling                       0x10103b464 fb1UCM8vZCiE + 355
6   Recycling                       0x1010431d4 fbkUVUzGnhkS + 1655
7   Recycling                       0x101038a78 fbIiaWxkoUb6 + 307
8   libsystem_pthread.dylib         0x1ab7d3d8c 0x1ab7c9000 + 44428
9   libsystem_pthread.dylib         0x1ab7d776c 0x1ab7c9000 + 59244

Can anyone help me?


问:
how do i create a prompt in javascript with 3 checkboxes/radio buttons as choices?
How do I create a javascript prompt box where you have to select 1 of 3 choices? I'm looking to do something similar to a html form's radio buttons except within a javascript prompt.</p>

答:
This can't be achieved natively as .prompt(). This functionality requires more advanced JS. Here are some libs to mess with:

jQuery UI (dialog)

jQuery Tools - Overlay

Could be more adequate ones out there. Been a while using such stuff


问:
Microfrontends React/Component based splitting
Background:
I am confronted with the task to modernize a tool and convert it to microservices with a react frontend. My idea was to have a general top-level component containing e.g. the Nav and a component for each microservice that contains the functionality.

Approaches:

bundle the components locally so that it becomes effectively a monolithic frontend and the the forntend code is seperated just in the repo.

I think that would give up on the advantage of not having to redeploy your entire app for every change

lazy-load a minified bundle of each of the components from the microservice by defining them in a config file

With this approach I could just webpack each component on their own and async import it from the Main Page but maybe there would be a huge overhead

I read about component based splitting with react-loadable and bundling react-router or webpack, but I can't find information on how to load small bundles form different URL-Endpoints.

Question:
Is it possible to bundle react components on their own and import them from different Resource-URL's and how would one approach that ?(Or is React even suitable for that)

答:
Take a look at the below link:

https://www.martinfowler.com/articles/micro-frontends.html

I've recently made a project based on that article and I think that it might be what You are looking for.
I made the wrapper app which is rendering the microfrontends dynamically on the runtime based on the URL and routings.  In the article above, there is a demo app showing the idea.
Every microfrontend is the separate project with it's own code repo.
https://demo.microfrontends.com/

Each app is hosted and js chunks are getting loaded on the runtime. This code might make it a little bit more clear what's going on there.

componentDidMount() {
    const { name, host } = this.props;
    const scriptId =micro-frontend-script-${name}`;

```<code>if (document.getElementById(scriptId)) {
  this.renderMicroFrontend();
  return;
}

fetch(`${host}/asset-manifest.json`)
  .then(res => res.json())
  .then(manifest => {
    const script = document.createElement('script');
    script.id = scriptId;
    script.src = `${host}${manifest['main.js']}`;
    script.onload = this.renderMicroFrontend;
    document.head.appendChild(script);
  });
</code>```

}`

I hope You'll find that helpful :)
Good luck!

Body:
Take a look at the below link:

https://www.martinfowler.com/articles/micro-frontends.html

I've recently made a project based on that article and I think that it might be what You are looking for.
I made the wrapper app which is rendering the microfrontends dynamically on the runtime based on the URL and routings.  In the article above, there is a demo app showing the idea.
Every microfrontend is the separate project with it's own code repo.
https://demo.microfrontends.com/

Each app is hosted and js chunks are getting loaded on the runtime. This code might make it a little bit more clear what's going on there.

componentDidMount() {
    const { name, host } = this.props;
    const scriptId =micro-frontend-script-${name}`;

if (document.getElementById(scriptId)) {
  this.renderMicroFrontend();
  return;
}

fetch(`${host}/asset-manifest.json`)
  .then(res => res.json())
  .then(manifest => {
    const script = document.createElement('script');
    script.id = scriptId;
    script.src = `${host}${manifest['main.js']}`;
    script.onload = this.renderMicroFrontend;
    document.head.appendChild(script);
  });

}`

I hope You'll find that helpful :)
Good luck!


问:
No such operator torchvision::nms
When I try to run yoloV3 detect,it happend the error

```<code>op = torch._C._jit_get_operation(qualified_op_name)

RuntimeError: No such operator torchvision::nms
</code>```

Though this code is the source code of torchvision ,I try sevaral time to correct the code by the tips  with failure.

答:
As I met lot of hurdles to install torch and torchvison ,I'm not reluctant to reinstall the enviroment.Running 'conda list' the version of torch and torchvison ,I found they are not incompitable,the versions of two packages installed are:

```<code> torchvision-0.5.0+cu92-cp37-cp37m-win_amd64.whl
 torch-1.4.0+cpu-cp37-cp37m-win_amd64.whl
</code>```

I change the version of torchvison to

```<code> torchvision-0.5.0+cpu-cp37-cp37m-win_amd64.whl
</code>```

I have dealt with my proplem until now.
note： the enviroment of my os and python are fellowing：

```<code>  Windows_X64
  python3.7
</code>```

Title: No such operator torchvision::nms

Body:
When I try to run yoloV3 detect,it happend the error

op = torch._C._jit_get_operation(qualified_op_name)

RuntimeError: No such operator torchvision::nms

Though this code is the source code of torchvision ,I try sevaral time to correct the code by the tips  with failure.

Body:
As I met lot of hurdles to install torch and torchvison ,I'm not reluctant to reinstall the enviroment.Running 'conda list' the version of torch and torchvison ,I found they are not incompitable,the versions of two packages installed are:

 torchvision-0.5.0+cu92-cp37-cp37m-win_amd64.whl
 torch-1.4.0+cpu-cp37-cp37m-win_amd64.whl

I change the version of torchvison to

 torchvision-0.5.0+cpu-cp37-cp37m-win_amd64.whl

I have dealt with my proplem until now.
note： the enviroment of my os and python are fellowing：

  Windows_X64
  python3.7


问:
Grandchild process has PID 1 in C
I am trying to pass input from parent to child and then from child to grandchild with pipes. After that, the grandchild sends the result to the parent back and the parent will kill both processes.

I can do data passing with pipes but I guess I cannot kill processes because PID of the grandchild is seen as 1 by the parent.

Here is my code:

```<code>int main(){

    if (pipe(fd) == -1) {
        fprintf(stderr,"Pipe failed fd");
        return 1;
    }

    if (pipe(sd) == -1) {
        fprintf(stderr,"Pipe failed sd");
        return 1;
    }

    if (pipe(td) == -1) {
        fprintf(stderr,"Pipe failed sd");
        return 1;
    }

    printf("Enter a number: ");
    scanf("%s", write_msg);

    pid_child = fork();

    if (pid_child < 0) {
        fprintf(stderr, "Fork failed child");
        return 1;
    }

    if(pid_child > 0){ // parent

        //pass data to child

        close(fd[READ_END]);
        write(fd[WRITE_END], write_msg, strlen(write_msg)+1);
        close(fd[WRITE_END]);

        wait(NULL);

        close(td[WRITE_END]);
        read(td[READ_END], read_msg_parent, strlen(read_msg_parent)+1);
        printf("final output is: %s\n", read_msg_parent);
        fflush(stdout);
        close(td[READ_END]);

        kill(pid_child);
        printf("killed child with pid: %d\n" , pid_child);

        kill(pid_grandc);
        printf("killed grandchild with pid: %d\n" , pid_grandc);

    } else { // child + grandchild

        pid_grandc = fork();

        if (pid_grandc < 0) {
            fprintf(stderr, "Fork failed grand child");
            return 1;
        }

        if(pid_grandc > 0){ // child

            // get data from parent

            close(fd[WRITE_END]);
            read(fd[READ_END], read_msg_child, BUFFER_SIZE);
            sscanf(read_msg_child, "%d", &x);
            printf("Child: input %d and output %d\n", x, x*2);
            fflush(stdout);
            close(fd[READ_END]);

            // pass data to grandchild

            close(sd[READ_END]);
            x *= 2;
            sprintf(write_msg2, "%d", x);
            write(sd[WRITE_END], write_msg2, strlen(write_msg2)+1);
            close(sd[WRITE_END]);

            wait(NULL);
            exit(0);

        } else { // grandchild

            // get data from child

            close(sd[WRITE_END]);
            read(sd[READ_END], read_msg_grandchild, strlen(read_msg_grandchild)+1);
            close(sd[READ_END]);

            sscanf(read_msg_grandchild, "%d", &z);
            printf("Grandchild: input %d, output: %d\n",z, z*2);
            fflush(stdout);
            z *= 2;

            // pass data to child back
            close(td[READ_END]);
            sprintf(write_msg3, "%d",z);
            write(td[WRITE_END], write_msg3, strlen(write_msg3) + 1);
            close(td[WRITE_END]);

            exit(0);

        }

    }
    return 0;
}
</code>```

And the sample output is:

```<code>> Enter a number: 12
> Child: input 12 and output 24
> Grandchild: input 24,output: 48
> final output is: 48
> killed child with pid: 7321
> killed grandchild with pid: 1
</code>```

答:
In your code, since the child is the one that creates grandchild process, the parent doesn't know the grandchild's pid.

I think you can pass the grandchild's pid by using an extra pipe.

after you check:

```<code>    if(pid_grandc > 0){ // child
    passGrandchildPid(newpipename, pid_grandc);  // function to write pid to pipe

    }
    // ...

void passGrandchildPid(int newpipename[2], int pid_grandc){
        int pid = grand_child_pid;
         close(newpipename[0]);          /* Close unused read end */
             write(newpipename[1], &pid , sizeof(pid));
             close(newpipename[1]);
             fflush(stdout);
    }
</code>```

Then in the parent process, you can read the grandchild's process id from this new pipe and kill it.

Title: Grandchild process has PID 1 in C

Body:
I am trying to pass input from parent to child and then from child to grandchild with pipes. After that, the grandchild sends the result to the parent back and the parent will kill both processes.

I can do data passing with pipes but I guess I cannot kill processes because PID of the grandchild is seen as 1 by the parent.

Here is my code:

int main(){

    if (pipe(fd) == -1) {
        fprintf(stderr,"Pipe failed fd");
        return 1;
    }

    if (pipe(sd) == -1) {
        fprintf(stderr,"Pipe failed sd");
        return 1;
    }

    if (pipe(td) == -1) {
        fprintf(stderr,"Pipe failed sd");
        return 1;
    }

    printf("Enter a number: ");
    scanf("%s", write_msg);

    pid_child = fork();

    if (pid_child < 0) {
        fprintf(stderr, "Fork failed child");
        return 1;
    }

    if(pid_child > 0){ // parent

        //pass data to child

        close(fd[READ_END]);
        write(fd[WRITE_END], write_msg, strlen(write_msg)+1);
        close(fd[WRITE_END]);

        wait(NULL);

        close(td[WRITE_END]);
        read(td[READ_END], read_msg_parent, strlen(read_msg_parent)+1);
        printf("final output is: %s\n", read_msg_parent);
        fflush(stdout);
        close(td[READ_END]);

        kill(pid_child);
        printf("killed child with pid: %d\n" , pid_child);

        kill(pid_grandc);
        printf("killed grandchild with pid: %d\n" , pid_grandc);

    } else { // child + grandchild

        pid_grandc = fork();

        if (pid_grandc < 0) {
            fprintf(stderr, "Fork failed grand child");
            return 1;
        }

        if(pid_grandc > 0){ // child

            // get data from parent

            close(fd[WRITE_END]);
            read(fd[READ_END], read_msg_child, BUFFER_SIZE);
            sscanf(read_msg_child, "%d", &x);
            printf("Child: input %d and output %d\n", x, x*2);
            fflush(stdout);
            close(fd[READ_END]);

            // pass data to grandchild

            close(sd[READ_END]);
            x *= 2;
            sprintf(write_msg2, "%d", x);
            write(sd[WRITE_END], write_msg2, strlen(write_msg2)+1);
            close(sd[WRITE_END]);

            wait(NULL);
            exit(0);

        } else { // grandchild

            // get data from child

            close(sd[WRITE_END]);
            read(sd[READ_END], read_msg_grandchild, strlen(read_msg_grandchild)+1);
            close(sd[READ_END]);

            sscanf(read_msg_grandchild, "%d", &z);
            printf("Grandchild: input %d, output: %d\n",z, z*2);
            fflush(stdout);
            z *= 2;

            // pass data to child back
            close(td[READ_END]);
            sprintf(write_msg3, "%d",z);
            write(td[WRITE_END], write_msg3, strlen(write_msg3) + 1);
            close(td[WRITE_END]);

            exit(0);

        }

    }
    return 0;
}

And the sample output is:

> Enter a number: 12
> Child: input 12 and output 24
> Grandchild: input 24,output: 48
> final output is: 48
> killed child with pid: 7321
> killed grandchild with pid: 1

Body:
In your code, since the child is the one that creates grandchild process, the parent doesn't know the grandchild's pid.

I think you can pass the grandchild's pid by using an extra pipe.

after you check:

    if(pid_grandc > 0){ // child
    passGrandchildPid(newpipename, pid_grandc);  // function to write pid to pipe

    }
    // ...

void passGrandchildPid(int newpipename[2], int pid_grandc){
        int pid = grand_child_pid;
         close(newpipename[0]);          /* Close unused read end */
             write(newpipename[1], &pid , sizeof(pid));
             close(newpipename[1]);
             fflush(stdout);
    }

Then in the parent process, you can read the grandchild's process id from this new pipe and kill it.


问:
Laravel (1/1) NotFoundHttpException in RouteCollection.php line 179
I've encountered a problem submitting my form in laravel.  My form structure looks this.

```<code><form  class="form-group" action="{{ route('writepoem') }}"
method="post" name="publish" enctype="multipart/form-data"
onsubmit="return validateForm();">
   <input type="hidden" name="_token" value="{{ Session::token() }}">
   <input type="text" name="user">
   <textarea name="poem"></textarea>
   <input type="submit" value="save">
</form>
</code>```

My web.php file has this route.

```<code>Route::post('/writepoem', ['uses'=>'PoemController@postCreatePoem','as'=>'writepoem']);
</code>```

My PoemController.

```<code>namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Poem;

class PoemController extends Controller
{
    public function postCreatePoem(Request $request)
    {
        //validation
        $poem=new Poem();
        $poem->poem=$request['poem'];
        $poem->user=$request['user'];

        //save poem
        $request->user()->poems()->save($poem);
        return redirect()->route('feed');
    }
}
</code>```

On submitting my form I get this Exception.

(1/1) NotFoundHttpException

in RouteCollection.php line 179.

What could be the issue with routing?

答:
I had the same problem but now I fixed my problem.

You need to follow these steps. If you have written the right code and then you get this error, then you need to follow steps.

Clear cache php artisan route:clear & php artisan route:cache run command one by one. If your problem not fixed yet then you need to follow the second step also

Run this command to reload composer composer dump-autoload

Body:
I've encountered a problem submitting my form in laravel.  My form structure looks this.

<form  class="form-group" action="{{ route('writepoem') }}"
method="post" name="publish" enctype="multipart/form-data"
onsubmit="return validateForm();">
   <input type="hidden" name="_token" value="{{ Session::token() }}">
   <input type="text" name="user">
   <textarea name="poem"></textarea>
   <input type="submit" value="save">
</form>

My web.php file has this route.

Route::post('/writepoem', ['uses'=>'PoemController@postCreatePoem','as'=>'writepoem']);

My PoemController.

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Poem;

class PoemController extends Controller
{
    public function postCreatePoem(Request $request)
    {
        //validation
        $poem=new Poem();
        $poem->poem=$request['poem'];
        $poem->user=$request['user'];

        //save poem
        $request->user()->poems()->save($poem);
        return redirect()->route('feed');
    }
}

On submitting my form I get this Exception.

(1/1) NotFoundHttpException

in RouteCollection.php line 179.

What could be the issue with routing?


问:
Express handlerbars node js question with
I have succesfully parsed my shopify product items into mongodb database using a model and i am trying to output them using express-handlebars package to show them into the user.

I have a small problem though.

I use {{this.title}}

To show a link with product title so user can click on it and go to the product on the request page.

When i put the link it goes to localhost:5000/www.shop.myshopify.com/products/....

instead of www.shop.myshopify.com/products/... and therefore i am getting a cannot get request back.

What i am doing wrong?

答:
Guys i found the answer and it's pretty simple.

Because i had the link as www.shop.myshopify.com/products/.... instead of https://www.shop.myshopify.com/products/.... wasn't rendering it properly so it was going to get / from node.js server and what was getting from there.

Title: Express handlerbars node js question with <a href=>


问:
How to make protractor press the ESCAPE key?
I've tried this:

```<code>browser.actions().sendKeys(protractor.Key.ESCAPE).perform();
</code>```

but nothing happens.

I'm using this with SPACE Key and this works fine.

```<code>browser.actions().sendKeys(protractor.Key.SPACE).perform();
</code>```

答:
   basically what you have done is correct. try to write it like method and call this method because it is working fine for me.

selectEscapeKey: function () { return
browser.actions().sendKeys(protractor.Key.ESCAPE).perform();},

Body:
I've tried this:

browser.actions().sendKeys(protractor.Key.ESCAPE).perform();

but nothing happens.

I'm using this with SPACE Key and this works fine.

browser.actions().sendKeys(protractor.Key.SPACE).perform();


问:
ASP.NET 4.6 SPA, Publish entire wwwroot content dynamically via MsBuild
I have an ASP.NET 4.6 application which is hosting React.
All published content goes into wwwroot with an MsBuild step as below:

```<code>  <Target Name="BeforeBuild">
    <!-- Call npm build -->
    <Exec Condition="$(Configuration) == 'Release'" Command="npm install" WorkingDirectory="ClientApp">
    </Exec>
    <Exec Condition="$(Configuration) == 'Release'" Command="npm run build" WorkingDirectory="ClientApp">
    </Exec>
    <Exec Condition="$(Configuration) == 'Release'" Command="xcopy.exe  $(SourceDirectory) $(DestinationDirectory) /Y /E">
    </Exec>
  </Target>
</code>```

The problem I have is when I publish via Azure DevOps.
Inside the project I have included this ItemGroup:

```<code>  </ItemGroup>
    <Content Include="Views\_ViewStart.cshtml" />
    <Content Include="Views\Home\Index.cshtml" />
    <Content Include="Views\Shared\Error.cshtml" />
    <Content Include="Views\Shared\_Layout.cshtml" />
    <Content Include="wwwroot\**\*" CopyToPublishDirectory="Always" />
  </ItemGroup>
</code>```

When I build, in Release mode, I can see the content available inside wwwroot, provided by Webpack but when the website is published, the folder wwwroot is there but empty. Of course I can't add the files to the solution because webpack produces dynamic content, so I have to use <Content Include="wwwroot\**\*" CopyToPublishDirectory="Always" />

答:
Found an old post. Actually because the files are generated at build time, the only way to include inside the output is to use this Pre-Deployment script:

```<code>  <Target Name="BeforeBuild">
    <!-- Call npm build -->
    <Exec Condition="$(Configuration) == 'Release'" Command="npm install" WorkingDirectory="ClientApp">
    </Exec>
    <Exec Condition="$(Configuration) == 'Release'" Command="npm run build" WorkingDirectory="ClientApp">
    </Exec>
    <Exec Condition="$(Configuration) == 'Release'" Command="xcopy.exe  $(SourceDirectory) $(DestinationDirectory) /Y /E">
    </Exec>
  </Target>
  <Target Name="SpaBeforeBuild" AfterTargets="BeforeBuild">
    <ItemGroup>
      <Content Include="wwwroot\**" />
    </ItemGroup>
  </Target>
</code>```

The order is:

Compile webpack and move from build folder into wwwroot

During publish, set all compiled files to "Content" which will allow MsBuild to put them into the PublishedWebsite folder

Body:
I have an ASP.NET 4.6 application which is hosting React.
All published content goes into wwwroot with an MsBuild step as below:

  <Target Name="BeforeBuild">

    <Exec Condition="$(Configuration) == 'Release'" Command="npm install" WorkingDirectory="ClientApp">
    </Exec>
    <Exec Condition="$(Configuration) == 'Release'" Command="npm run build" WorkingDirectory="ClientApp">
    </Exec>
    <Exec Condition="$(Configuration) == 'Release'" Command="xcopy.exe  $(SourceDirectory) $(DestinationDirectory) /Y /E">
    </Exec>
  </Target>

The problem I have is when I publish via Azure DevOps.
Inside the project I have included this ItemGroup:

  </ItemGroup>
    <Content Include="Views\_ViewStart.cshtml" />
    <Content Include="Views\Home\Index.cshtml" />
    <Content Include="Views\Shared\Error.cshtml" />
    <Content Include="Views\Shared\_Layout.cshtml" />
    <Content Include="wwwroot\**\*" CopyToPublishDirectory="Always" />
  </ItemGroup>

When I build, in Release mode, I can see the content available inside wwwroot, provided by Webpack but when the website is published, the folder wwwroot is there but empty. Of course I can't add the files to the solution because webpack produces dynamic content, so I have to use <Content Include="wwwroot\**\*" CopyToPublishDirectory="Always" />

Body:
Found an old post. Actually because the files are generated at build time, the only way to include inside the output is to use this Pre-Deployment script:

  <Target Name="BeforeBuild">
    <!-- Call npm build -->
    <Exec Condition="$(Configuration) == 'Release'" Command="npm install" WorkingDirectory="ClientApp">
    </Exec>
    <Exec Condition="$(Configuration) == 'Release'" Command="npm run build" WorkingDirectory="ClientApp">
    </Exec>
    <Exec Condition="$(Configuration) == 'Release'" Command="xcopy.exe  $(SourceDirectory) $(DestinationDirectory) /Y /E">
    </Exec>
  </Target>
  <Target Name="SpaBeforeBuild" AfterTargets="BeforeBuild">
    <ItemGroup>
      <Content Include="wwwroot\**" />
    </ItemGroup>
  </Target>

The order is:

Compile webpack and move from build folder into wwwroot

During publish, set all compiled files to "Content" which will allow MsBuild to put them into the PublishedWebsite folder


问:
MVVM binding viewmodel property child to viewmodel property
not sure if my title explains well the issue im having.

In my application i make a service calls to
-retrieve a list of customers.
-retrieve a list of organisations.

Then i bind this list of customers to a listbox on my view.

In my viewmodel i have the following properties:

```<code>IEnumerable<Organisation> Organisations
ObservableCollection<Customer> Customers
</code>```

Organisation properties: OrganisationId, OrganisationName

Customer properties: CustomerId, OrganisationId, CustomerFirstName, CustomerLastName

Inside the Listbox on my view i want to show the organisationname for each customer in the list.

how can i go about binding this in my view? I just want a textblock to show the organisationname for the customer.

答:
I'd flatten the Model in a customer ViewModel:

class CustomerViewModel : INotifyPropertyChanged
{
    public string OrgName { get; }
    public string FirstName {get; }
    public string LastName { get; }
}
```

<p>Then the owning ViewModel returns the collection of Customers:</p>

<pre class="lang-cs prettyprint-override"><code>public class StoreViewModel : INotifyPropertyChanged
{
    public ObservableCollection<CustomerViewModel> Customers { get; }
}
</code>```

Bind the ListBox to the OrgName property on the CustomerViewModel:

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding FirstName}"/>
                <TextBlock Text="{Binding OrgName}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
```

Body:
not sure if my title explains well the issue im having.

In my application i make a service calls to
-retrieve a list of customers.
-retrieve a list of organisations.

Then i bind this list of customers to a listbox on my view.

In my viewmodel i have the following properties:

IEnumerable<Organisation> Organisations
ObservableCollection<Customer> Customers

Organisation properties: OrganisationId, OrganisationName

Customer properties: CustomerId, OrganisationId, CustomerFirstName, CustomerLastName

Inside the Listbox on my view i want to show the organisationname for each customer in the list.

how can i go about binding this in my view? I just want a textblock to show the organisationname for the customer.

Body:
I'd flatten the Model in a customer ViewModel:

class CustomerViewModel : INotifyPropertyChanged
{
    public string OrgName { get; }
    public string FirstName {get; }
    public string LastName { get; }
}

Then the owning ViewModel returns the collection of Customers:

public class StoreViewModel : INotifyPropertyChanged
{
    public ObservableCollection<CustomerViewModel> Customers { get; }
}

Bind the ListBox to the OrgName property on the CustomerViewModel:

<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding FirstName}"/>
                <TextBlock Text="{Binding OrgName}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


问:
TypeError: opendirSync is not a function
I am writing an electron application and I want to use the opendirSync function of the fs module in order to count the number of files in a directory. However, I get the following error:

```<code>(node:12944) UnhandledPromiseRejectionWarning: TypeError: fs.opendirSync is not a function
    at DataImporter.CountFiles (C:\Users\v\Documents\Projects\Electron\asts\server\data_importer.js:18:8)
    at new DataImporter (C:\Users\v\Documents\Projects\Electron\asts\server\data_importer.js:5:26)
    at C:\Users\v\Documents\Projects\Electron\asts\main.js:32:19
(node:12944) UnhandledPromiseRejectionWarning: TypeError: fs.opendir is not a function
    at DataImporter.CountFiles (C:\Users\v\Documents\Projects\Electron\asts\server\data_importer.js:18:8)
    at new DataImporter (C:\Users\v\Documents\Projects\Electron\asts\server\data_importer.js:5:26)
    at C:\Users\v\Documents\Projects\Electron\asts\main.js:32:19
(node:12944) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12944) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12944) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:12944) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code>```

The code I am using is as follows:

let fs = require('fs');
let path_mod = require('path');

function CountFiles(path) {
    let dir_end = null;
    let count = 0;
    let directory = fs.opendirSync(path);
    while(1) {
      let ret = directory.readSync();
      if(!ret) {
        break;
      } else if(ret.isDirectory()) {
        console.log(path_mod.join(path, ret.name));
        count += CountFiles(path_mod.join(path, ret.name));
      } else {
        count++;
      }
    }
    directory.closeSync();
    return count;
  }
```

Node Version: 12.6.0

Electron Version: 7.1.12

I cannot understand what causes this error and how to fix it. I know that the path is correct and that I have access to the target directory (since I also used the fs module to read a file from that directory).

Thank you for you help.

答:
The opendirSync method was added in node version: v12.12.0, You have to upgrade the node version.

History:

```<code>Version Changes
v13.1.0  The bufferSize option was introduced.

v12.12.0 Added in: v12.12.0

</code>```

You can read more about this here

Body:
I am writing an electron application and I want to use the opendirSync function of the fs module in order to count the number of files in a directory. However, I get the following error:

(node:12944) UnhandledPromiseRejectionWarning: TypeError: fs.opendirSync is not a function
    at DataImporter.CountFiles (C:\Users\v\Documents\Projects\Electron\asts\server\data_importer.js:18:8)
    at new DataImporter (C:\Users\v\Documents\Projects\Electron\asts\server\data_importer.js:5:26)
    at C:\Users\v\Documents\Projects\Electron\asts\main.js:32:19
(node:12944) UnhandledPromiseRejectionWarning: TypeError: fs.opendir is not a function
    at DataImporter.CountFiles (C:\Users\v\Documents\Projects\Electron\asts\server\data_importer.js:18:8)
    at new DataImporter (C:\Users\v\Documents\Projects\Electron\asts\server\data_importer.js:5:26)
    at C:\Users\v\Documents\Projects\Electron\asts\main.js:32:19
(node:12944) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12944) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:12944) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:12944) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

The code I am using is as follows:

let fs = require('fs');
let path_mod = require('path');

function CountFiles(path) {
    let dir_end = null;
    let count = 0;
    let directory = fs.opendirSync(path);
    while(1) {
      let ret = directory.readSync();
      if(!ret) {
        break;
      } else if(ret.isDirectory()) {
        console.log(path_mod.join(path, ret.name));
        count += CountFiles(path_mod.join(path, ret.name));
      } else {
        count++;
      }
    }
    directory.closeSync();
    return count;
  }

Node Version: 12.6.0

Electron Version: 7.1.12

I cannot understand what causes this error and how to fix it. I know that the path is correct and that I have access to the target directory (since I also used the fs module to read a file from that directory).

Thank you for you help.

Body:
The opendirSync method was added in node version: v12.12.0, You have to upgrade the node version.

History:

Version Changes
v13.1.0  The bufferSize option was introduced.

v12.12.0 Added in: v12.12.0

You can read more about this here


问:
NullInjectorError: No provider for FirebaseX in Ionic 4 FirebaseX
I'm working with FirebaseX in an Ionic 4 project and i get this error.

```<code>NullInjectorError: No provider for FirebaseX
</code>```

How do I load this service in the appModule.ts?
If i just put FirebaseX in the provider section i get this error

```<code>Invalid provider for the NgModule 'AppModule'
</code>```

Please help.

FirebaseX - https://github.com/dpa99c/cordova-plugin-firebasex

Thanks.

答:
It works the same way as StatusBar and SplashScreen, on app.module import module and declare it as provider:

```<code>import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { FirebaseX } from '@ionic-native/firebase-x/ngx';

@NgModule({
...
  providers: [
    InAppBrowser,
    SplashScreen,
    StatusBar,
    FirebaseX,
  ],
...
})
</code>```

Body:
I'm working with FirebaseX in an Ionic 4 project and i get this error.

NullInjectorError: No provider for FirebaseX

How do I load this service in the appModule.ts?
If i just put FirebaseX in the provider section i get this error

Invalid provider for the NgModule 'AppModule'

Please help.

FirebaseX - https://github.com/dpa99c/cordova-plugin-firebasex

Thanks.

Body:
It works the same way as StatusBar and SplashScreen, on app.module import module and declare it as provider:

import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { FirebaseX } from '@ionic-native/firebase-x/ngx';

@NgModule({
...
  providers: [
    InAppBrowser,
    SplashScreen,
    StatusBar,
    FirebaseX,
  ],
...
})


问:
JWT payload encryption without any JS access to token
i want to encrypt JWT payload with current methods like symmetric or asymmetric encryption method.
my question is that if i use these methods, javascript needs to do any action on my data on client side? or still all parts of encryption and validation will be done on server side?
in this article, they say that if you need to encrypt payload, you must to store public key(due to encryption algorithm like RSA or ...). WHY?
if i wnat to encrypt payload, why we need to store public key (or any keys) in jwt token?
is there any way to encrypt payload symmetricly only on server side? and no javascript needs to access them and manipulate the token?</p>

答:
You are misinterpreting the article

To encrypt a JWT for a given recipient you need to know their public RSA key.

This would probably be more clear if it read

To encrypt a JWT for a given recipient so that they can decrypt it you need to know their public RSA key.

This means that if the client wanted to encrypt something to send to you, that you could decrypt, they would only need to know your public key, and you would only need to know your private key.  If you wanted to encrypt something that the client could decrypt, you would need the clients public key.

It sounds like you want to encrypt something to send to the client, that they can then send back to you for you to decrypt.  Since you are both encrypting and decrypting, no keys need to be sent to the client (unless you use a different key  per client, in which case you would need to send them the public key you used so you could figure out which private key to decrypt with).


问:
rabbitmq not working with java
I have rabbitmq setup on my machine and it has 3 different queues. One java code is listening to a queue and other queues are sending messages to python codes. Now python codes are working fine but java code seems to have a problem with AMQ. Following error is coming:

```<code>Exception in thread "main" com.rabbitmq.client.PossibleAuthenticationFailureException: Possibly caused by authentication failure
    at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:341)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:590)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:612)
    at com.elki.test.Worker.main(Worker.java:73)
Caused by: com.rabbitmq.client.ShutdownSignalException: connection error
    at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:67)
    at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:33)
    at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:343)
    at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:216)
    at com.rabbitmq.client.impl.AMQChannel.rpc(AMQChannel.java:202)
    at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:326)
    ... 3 more
Caused by: java.io.EOFException
    at java.io.DataInputStream.readUnsignedByte(DataInputStream.java:290)
    at com.rabbitmq.client.impl.Frame.readFrom(Frame.java:95)
    at com.rabbitmq.client.impl.SocketFrameHandler.readFrame(SocketFrameHandler.java:139)
    at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:532)
    at java.lang.Thread.run(Thread.java:744)
</code>```

How come there could be an AuthenticationFailure with java but not with python.
Any help appreciated.

CODE:

```<code>public static void main(String[] argv)
                          throws java.io.IOException,
                          java.lang.InterruptedException {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        com.rabbitmq.client.Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        channel.basicQos(1);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(TASK_QUEUE_NAME, false, consumer);

        while (true) {
          QueueingConsumer.Delivery delivery = consumer.nextDelivery();
          String message = new String(delivery.getBody());

          System.out.println(" [x] Received '" + message + "'");

          "do some work"
        System.out.println(" [x] Done" );

          int prefetchCount = 1;
          channel.basicQos(prefetchCount);
          channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
      }
</code>```

答:
I had same error. The problem was that the rabbitmq was started with default config on ipv6 protocol. I don't know why, but it does not work on windows linux subsystem.

Force ipv4 helped for me:

```<code>cat /etc/rabbitmq/rabbitmq.config

[
  {rabbit, [
    {tcp_listeners, [{"127.0.0.1", 5672}]}
  ]}
].
</code>```

By default rabbitmq uses ipv6 address ::1.

PS^ You need to create config file if there are not exists.

Title: rabbitmq not working with java

Body:
I have rabbitmq setup on my machine and it has 3 different queues. One java code is listening to a queue and other queues are sending messages to python codes. Now python codes are working fine but java code seems to have a problem with AMQ. Following error is coming:

Exception in thread "main" com.rabbitmq.client.PossibleAuthenticationFailureException: Possibly caused by authentication failure
    at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:341)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:590)
    at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:612)
    at com.elki.test.Worker.main(Worker.java:73)
Caused by: com.rabbitmq.client.ShutdownSignalException: connection error
    at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:67)
    at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:33)
    at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:343)
    at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:216)
    at com.rabbitmq.client.impl.AMQChannel.rpc(AMQChannel.java:202)
    at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:326)
    ... 3 more
Caused by: java.io.EOFException
    at java.io.DataInputStream.readUnsignedByte(DataInputStream.java:290)
    at com.rabbitmq.client.impl.Frame.readFrom(Frame.java:95)
    at com.rabbitmq.client.impl.SocketFrameHandler.readFrame(SocketFrameHandler.java:139)
    at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:532)
    at java.lang.Thread.run(Thread.java:744)

How come there could be an AuthenticationFailure with java but not with python.
Any help appreciated.

CODE:

public static void main(String[] argv)
                          throws java.io.IOException,
                          java.lang.InterruptedException {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        com.rabbitmq.client.Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        channel.basicQos(1);

        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(TASK_QUEUE_NAME, false, consumer);

        while (true) {
          QueueingConsumer.Delivery delivery = consumer.nextDelivery();
          String message = new String(delivery.getBody());

          System.out.println(" [x] Received '" + message + "'");

          "do some work"
        System.out.println(" [x] Done" );

          int prefetchCount = 1;
          channel.basicQos(prefetchCount);
          channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }
      }

Body:
I had same error. The problem was that the rabbitmq was started with default config on ipv6 protocol. I don't know why, but it does not work on windows linux subsystem.

Force ipv4 helped for me:

cat /etc/rabbitmq/rabbitmq.config

[
  {rabbit, [
    {tcp_listeners, [{"127.0.0.1", 5672}]}
  ]}
].

By default rabbitmq uses ipv6 address ::1.

PS^ You need to create config file if there are not exists.


问:
Why can't I cast DateTime[] to object[]?
It seems that I can cast DateTime to object, so why can't I cast array DateTime[] to object[]?  I know this has something to do with value/reference types, but doesn't boxing allow me to do this?</p>

答:
If you've got LINQ available (.NET 3.5+) you can do:

```<code>DateTime[] dates = new DateTime[3];

dates[0] = new DateTime(2009, 01, 01);
dates[1] = new DateTime(2010, 01, 01);
dates[2] = new DateTime(2011, 01, 01);

object[] dates2 = Array.ConvertAll(dates, d => (object)d);
</code>```

As Jeff pointed out you can also do a similar thing in .NET 2.0 using delegates:

```<code>object[] dates3 = Array.ConvertAll(dates,
                        delegate(DateTime d) { return (object)d; });
</code>```

Body:
If you've got LINQ available (.NET 3.5+) you can do:

DateTime[] dates = new DateTime[3];

dates[0] = new DateTime(2009, 01, 01);
dates[1] = new DateTime(2010, 01, 01);
dates[2] = new DateTime(2011, 01, 01);

object[] dates2 = Array.ConvertAll(dates, d => (object)d);

As Jeff pointed out you can also do a similar thing in .NET 2.0 using delegates:

object[] dates3 = Array.ConvertAll(dates,
                        delegate(DateTime d) { return (object)d; });


问:
Accessing Anaconda in Gitbash-> bash: conda: command not found, unexpected token '('
Path of my Anaconda3 folder:

```<code>  C:\Users\shail\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)
</code>```

Commands tried in Git bash terminal:

```<code>  conda init bash
  echo '. ${HOME}/.bash_profile' >> ~/.bashrc
  base *c:\Users\shail\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)
</code>```

Error:

```<code>  bash: syntax error near unexpected token '(' #on using the base command
</code>```

I have read many blogs but all the codes are mostly outdated and do not work for me. Pls guide. I have anaconda installed which workd perfectly on cmd terminal and anaconda prompt but I am unable to access anaconda in git bash.

答:
Whenever you set a path for local environment variable, ideally make sure that the path does not have spaces or special characters: (, ), !, $, & etc.

If this cannot be avoided, you can solve this by searching environment in windows search -> Select Environment Variables -> Double click on Path -> Look for the path you have mentioned above and change it whatever folder conda.exe is located in. If in path, this location is not there, add it. Also, add the scripts in Anaconda/scripts to your path.

If this doesn't work, some people have found workarounds here.

Body:
Path of my Anaconda3 folder:

  C:\Users\shail\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)

Commands tried in Git bash terminal:

  conda init bash
  echo '. ${HOME}/.bash_profile' >> ~/.bashrc
  base *c:\Users\shail\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit)

Error:

  bash: syntax error near unexpected token '(' #on using the base command

I have read many blogs but all the codes are mostly outdated and do not work for me. Pls guide. I have anaconda installed which workd perfectly on cmd terminal and anaconda prompt but I am unable to access anaconda in git bash.


问:
Overwriting multiple partitions bigquery
say I have a table t1 which is date partitioned on column sdate

I have another table t2 which is also partitioned on column pdate which has data already in some partitions (20200101 to 20200130)

Now, I want to overwrite few partitions ( 20200105 to  20200110) in t2 from data in t1

and I want to do it in a single query and not one query per partition.

Select Query:

```<code>SELECT sdate,
c1, c2

FROM `dataset.t1` where sdate between "2020-01-05" and "2020-01-10"
</code>```

I have seen examples where we can specify destination table like t2$20200102, but that will overwrite only a single partition.

How can we write insert statement to populate selected partitions

Any ideas of how the insert query would look like?

答:
You can simply use SELECT sdate AS pdate in your INSERT statement:

INSERT dataset.t2 (pdate, c1, c2)
  SELECT sdate AS pdate, c1, c2
  FROM dataset.t1
  WHERE sdate BETWEEN "2020-01-05" and "2020-01-10"
```

<p>Of course, this will append the rows to each target partition so, if you want to overwrite them, you can delete them first with:</p>

<pre class="lang-sql prettyprint-override"><code>DELETE
  dataset.t2
WHERE
  pdate BETWEEN "2020-01-05" AND "2020-01-10"
</code>```

Obviously, you should be careful when deleting partitions. An extra check can be added if you only want to overwrite dates with data in the source table:

DELETE
  dataset.t2
WHERE
  pdate IN (
    SELECT sdate
    FROM dataset.t1
    WHERE sdate BETWEEN "2020-01-05" AND "2020-01-10")
```

<p>You can also consider using <code>MERGE</code> but then you would need to take into account what happens when matching row by row.</p>

<p>I did some tests with this gist.</p>

<p>Another option is to do a piece-wise <code>SELECT</code> query to break the data into three date ranges and <code>UNION ALL</code> to bring them together.</p>

<pre class="lang-sql prettyprint-override"><code>SELECT * FROM dataset.t2
WHERE pdate < "2020-01-05" OR pdate > "2020-01-10"
UNION ALL
SELECT * FROM dataset.t1
WHERE sdate BETWEEN "2020-01-05" AND "2020-01-10"
</code>```

This requires specifying a destination table with WRITE_TRUNCATE and runs in a single job but has to essentially re-write the whole table.

Body:
say I have a table t1 which is date partitioned on column sdate

I have another table t2 which is also partitioned on column pdate which has data already in some partitions (20200101 to 20200130)

Now, I want to overwrite few partitions ( 20200105 to  20200110) in t2 from data in t1

and I want to do it in a single query and not one query per partition.

Select Query:

SELECT sdate,
c1, c2

FROM `dataset.t1` where sdate between "2020-01-05" and "2020-01-10"

I have seen examples where we can specify destination table like t2$20200102, but that will overwrite only a single partition.

How can we write insert statement to populate selected partitions

Any ideas of how the insert query would look like?

Body:
You can simply use SELECT sdate AS pdate in your INSERT statement:

INSERT dataset.t2 (pdate, c1, c2)
  SELECT sdate AS pdate, c1, c2
  FROM dataset.t1
  WHERE sdate BETWEEN "2020-01-05" and "2020-01-10"

Of course, this will append the rows to each target partition so, if you want to overwrite them, you can delete them first with:

DELETE
  dataset.t2
WHERE
  pdate BETWEEN "2020-01-05" AND "2020-01-10"

Obviously, you should be careful when deleting partitions. An extra check can be added if you only want to overwrite dates with data in the source table:

DELETE
  dataset.t2
WHERE
  pdate IN (
    SELECT sdate
    FROM dataset.t1
    WHERE sdate BETWEEN "2020-01-05" AND "2020-01-10")

You can also consider using MERGE but then you would need to take into account what happens when matching row by row.

I did some tests with this gist.

Another option is to do a piece-wise SELECT query to break the data into three date ranges and UNION ALL to bring them together.

SELECT * FROM dataset.t2
WHERE pdate < "2020-01-05" OR pdate > "2020-01-10"
UNION ALL
SELECT * FROM dataset.t1
WHERE sdate BETWEEN "2020-01-05" AND "2020-01-10"

This requires specifying a destination table with WRITE_TRUNCATE and runs in a single job but has to essentially re-write the whole table.


问:
Rewrite requests to different enpoint with nginx
I have site on joomla and subfolder folder with standalone php files.

```<code>location / {
        try_files $uri $uri/ /index.php?q=$request_uri;
}
location ~ \.php$ {
        include         fastcgi_params;
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param HTTPS on;
        fastcgi_index   index.php;
        fastcgi_pass    backend;
        fastcgi_read_timeout 90;
    }

</code>```

Now I want to do something like this:

```<code>location ~ /forder/(.*)\.php {
     try_files $uri /folder/app.php?controller=$1;
}
</code>```

When I go to https://site/folder/script.php nginx send source code of that file.
Where I go wrong?

答:
Solution for me is to put

```<code>if (!-e $request_filename){
 rewrite /folder/(.*)\.php /folder/app.php?controller=$1 last;
}
</code>```

in server section

Body:
I have site on joomla and subfolder folder with standalone php files.

location / {
        try_files $uri $uri/ /index.php?q=$request_uri;
}
location ~ \.php$ {
        include         fastcgi_params;
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param HTTPS on;
        fastcgi_index   index.php;
        fastcgi_pass    backend;
        fastcgi_read_timeout 90;
    }

Now I want to do something like this:

location ~ /forder/(.*)\.php {
     try_files $uri /folder/app.php?controller=$1;
}

When I go to https://site/folder/script.php nginx send source code of that file.
Where I go wrong?

Body:
Solution for me is to put

if (!-e $request_filename){
 rewrite /folder/(.*)\.php /folder/app.php?controller=$1 last;
}

in server section