问:
Check whether there is an Internet connection available on Flutter app
I have a network call to be executed. But before doing that I need to check whether the device have internet connectivity.

This is what i have done so far:

```<code>  var connectivityResult = new Connectivity().checkConnectivity();// User defined class
    if (connectivityResult == ConnectivityResult.mobile ||
        connectivityResult == ConnectivityResult.wifi) {*/
    this.getData();
    } else {
      neverSatisfied();
    }
</code>```

Above method is not working.

答:
I've created a package that (I think) deals reliably with this issue.

The package on pub.dev

The package on GitHub

Discussion is very welcome. You can use the issues tracker on GitHub.

I no longer think this below is a reliable method:

Wanna add something to @Oren's answer: you should really add one more catch, which will catch all other exceptions (just to be safe), OR just remove the exception type altogether and use a catch, that deals with all of the exceptions:

Case 1:

try {
  await Firestore.instance
    .runTransaction((Transaction tx) {})
    .timeout(Duration(seconds: 5));
  hasConnection = true;
} on PlatformException catch(_) { // May be thrown on Airplane mode
  hasConnection = false;
} on TimeoutException catch(_) {
  hasConnection = false;
} catch (_) {
  hasConnection = false;
}
```

<p>or even simpler...</p>

<p>Case 2:</p>

<pre class="lang-dart prettyprint-override"><code>
try {
  await Firestore.instance
    .runTransaction((Transaction tx) {})
    .timeout(Duration(seconds: 5));
  hasConnection = true;
} catch (_) {
  hasConnection = false;
}
</code>```

Body:
I have a network call to be executed. But before doing that I need to check whether the device have internet connectivity.

This is what i have done so far:

  var connectivityResult = new Connectivity().checkConnectivity();// User defined class
    if (connectivityResult == ConnectivityResult.mobile ||
        connectivityResult == ConnectivityResult.wifi) {*/
    this.getData();
    } else {
      neverSatisfied();
    }

Above method is not working.

Body:
I've created a package that (I think) deals reliably with this issue.

The package on pub.dev

The package on GitHub

Discussion is very welcome. You can use the issues tracker on GitHub.

I no longer think this below is a reliable method:

Wanna add something to @Oren's answer: you should really add one more catch, which will catch all other exceptions (just to be safe), OR just remove the exception type altogether and use a catch, that deals with all of the exceptions:

Case 1:

try {
  await Firestore.instance
    .runTransaction((Transaction tx) {})
    .timeout(Duration(seconds: 5));
  hasConnection = true;
} on PlatformException catch(_) { // May be thrown on Airplane mode
  hasConnection = false;
} on TimeoutException catch(_) {
  hasConnection = false;
} catch (_) {
  hasConnection = false;
}

or even simpler...

Case 2:

try {
  await Firestore.instance
    .runTransaction((Transaction tx) {})
    .timeout(Duration(seconds: 5));
  hasConnection = true;
} catch (_) {
  hasConnection = false;
}


来源: stackexchange

问:
Problem to pass argument from bash script to C program
I have some problems passing argument from bash file to C program.
I'm using a bash script to compile C program like this:

```<code>gcc -O0 filec1.c -lm -o fileoutput
./fileoutput $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11
</code>```

Now if I print each argument in bash file adding these lines:

```<code>for i in $@; do
    echo $i
done
</code>```

each argument passed is correctly printed but if I print each argument in the c file that has just a main with the following lines:

```<code>int main(int argc, char **argv){
    for(int i=0; i<argc; i++){
        printf("%s\n", argv[i]);
    }
}
</code>```

the output for the arguments after 9th are wrong or not printed.
Someone can help me please?

答:
If you are referring to bash arguments inside a bash script, you can use "$@"
instead of individual arguments, it expands to whatever arguments you pass to it.

Edit

https://stackoverflow.com/a/3898681/152016 refer to the bash man page, explaining the meaning of that special variable, there are other useful variables too like $# and $?.

Added quotes around the variable thanks to @DanielPryden comment. See a very good explanation why, here: https://stackoverflow.com/a/3990540/152016

ContentLicense: CC BY-SA 4.0

Body:
I have some problems passing argument from bash file to C program.
I'm using a bash script to compile C program like this:

gcc -O0 filec1.c -lm -o fileoutput
./fileoutput $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11

Now if I print each argument in bash file adding these lines:

for i in $@; do
    echo $i
done

each argument passed is correctly printed but if I print each argument in the c file that has just a main with the following lines:

int main(int argc, char **argv){
    for(int i=0; i<argc; i++){
        printf("%s\n", argv[i]);
    }
}

the output for the arguments after 9th are wrong or not printed.
Someone can help me please?


问:
Teach ASP.NET MVC to treat key-less query values as boolean flags
If a query value in URL doesn't have a key, e.g.: http://site.com?update
and an action has bool argument named update.
I want that update argument to received value true if 'update' value is present in the URL, and false otherwise.

Example:

Action: public ActionResult MyAction(string name, bool update) {...}

URL: http://site.com/path?name=Bob&update

Expected action call: controller.MyAction("Bob", true);

if URL is http://site.com/path?name=Bob (notice no update)

then expected call is controller.MyAction("Bob", false);

It is not a big deal, I do know I can just get Request.Query and find values with key=null, but I want to have it done through the framework.

Where do I begin?

I'm using ASP.NET MVC 3

答:
Doing this through the framework would probably require you to implement your own value provider with a corresponding value provider factory and add the factory to ValueProviderFactories. You would probably implement it similar to the existing QueryStringValueProviderFactory and QueryStringValueProvider but then add your own implementation of GetValue that includes the additional logic you wanted to return true/false based on if there is a value provided for the query string key. Here is a link on adding a value provider, and check out the QueryStringValueProvider in the framework.

http://mgolchin.net/posts/19/dive-deep-into-mvc-ivalueprovider

ContentLicense: CC BY-SA 3.0


问:
NodeJs facing the issue while using async waterfall
I am calling 2 API request 1 after another so I decided to use the waterfall model but I am facing the issue in it

I have tried so much but not able to solve the issue.

Below is my code:

```<code>var unirest = require("unirest");
var async = require("async")

exports.user = (req, res, next) => {
    const qry = req.params.id
    async.waterfall([
        (nextCall) => {
            var req = unirest("GET", API_URL1);
            req.query({
               // some query
            });
            req.headers({
               // some headers
            });
            req.end(function(subCount) {
                // if (resp.error) throw new Error(resp.error);
                var channelSubCount = subCount.body
                nextCall(null, data)
            });
        },
        (data, nextCall => {
            console.log(channelSubCount, 'data')
            var reqs = unirest("GET", API_URL2);

            reqs.query({
              // some query
            });

            reqs.headers({
                // some headers
            });

            reqs.end(function(res) {
                // if (res.error) throw new Error(res.error);
                console.log(res.body);
                return nextCall(null, {
                    name: 'abc',
                    photo: 'src',
                    count: data
                })
            });
        })
    ], function(finalData) {
        // if (error) { alert('Something is wrong!'); }
        console.log('final')
        res.status(200).json(
            finalData
        );
    });
};
</code>```

ERROR:
Reference Error: data is not defined

I don't understand why this is happening.

Also some please show me the right way to implement the above things with optimizations.

Any help appreciated...

答:
Looks like you forgot to close parentheses here in your second arrow function definition:

```<code>(data, nextCall => {
</code>```

It's still a valid JavaScript, but the interpreter now treats data not as a function incoming parameter (as you need), but as a variable. But it's not defined anywhere, therefore you have that error.

Make it like this and it will work:

```<code>(data, nextCall) => {
</code>```

Body:
I am calling 2 API request 1 after another so I decided to use the waterfall model but I am facing the issue in it

I have tried so much but not able to solve the issue.

Below is my code:

var unirest = require("unirest");
var async = require("async")

exports.user = (req, res, next) => {
    const qry = req.params.id
    async.waterfall([
        (nextCall) => {
            var req = unirest("GET", API_URL1);
            req.query({
               // some query
            });
            req.headers({
               // some headers
            });
            req.end(function(subCount) {
                // if (resp.error) throw new Error(resp.error);
                var channelSubCount = subCount.body
                nextCall(null, data)
            });
        },
        (data, nextCall => {
            console.log(channelSubCount, 'data')
            var reqs = unirest("GET", API_URL2);

            reqs.query({
              // some query
            });

            reqs.headers({
                // some headers
            });

            reqs.end(function(res) {
                // if (res.error) throw new Error(res.error);
                console.log(res.body);
                return nextCall(null, {
                    name: 'abc',
                    photo: 'src',
                    count: data
                })
            });
        })
    ], function(finalData) {
        // if (error) { alert('Something is wrong!'); }
        console.log('final')
        res.status(200).json(
            finalData
        );
    });
};

ERROR:
Reference Error: data is not defined

I don't understand why this is happening.

Also some please show me the right way to implement the above things with optimizations.

Any help appreciated...

Body:
Looks like you forgot to close parentheses here in your second arrow function definition:

(data, nextCall => {

It's still a valid JavaScript, but the interpreter now treats data not as a function incoming parameter (as you need), but as a variable. But it's not defined anywhere, therefore you have that error.

Make it like this and it will work:

(data, nextCall) => {


问:
Deploying Helm workloads with Terraform on GKE cluster
I am trying to use Terraform Helm provider (https://www.terraform.io/docs/providers/helm/index.html) to deploy a workload to GKE cluster.

I am more or less following Google's example - https://github.com/GoogleCloudPlatform/terraform-google-examples/blob/master/example-gke-k8s-helm/helm.tf, but I do want to use RBAC by creating the service account manually.

My helm.tf looks like this:

```<code>variable "helm_version" {
  default = "v2.13.1"
}

data "google_client_config" "current" {}

provider "helm" {
  tiller_image = "gcr.io/kubernetes-helm/tiller:${var.helm_version}"
  install_tiller = false # Temporary

  kubernetes {
    host                   = "${google_container_cluster.data-dome-cluster.endpoint}"
    token                  = "${data.google_client_config.current.access_token}"

    client_certificate     = "${base64decode(google_container_cluster.data-dome-cluster.master_auth.0.client_certificate)}"
    client_key             = "${base64decode(google_container_cluster.data-dome-cluster.master_auth.0.client_key)}"
    cluster_ca_certificate = "${base64decode(google_container_cluster.data-dome-cluster.master_auth.0.cluster_ca_certificate)}"
  }
}

resource "helm_release" "nginx-ingress" {
  name  = "ingress"
  chart = "stable/nginx-ingress"

  values = [<<EOF
rbac:
  create: false
controller:
  stats:
    enabled: true
  metrics:
    enabled: true
  service:
    annotations:
      cloud.google.com/load-balancer-type: "Internal"
    externalTrafficPolicy: "Local"
EOF
  ]

  depends_on = [
    "google_container_cluster.data-dome-cluster",
  ]
}
</code>```

I am getting the following error:

```<code>Error: Error applying plan:

1 error(s) occurred:

* module.data-dome-cluster.helm_release.nginx-ingress: 1 error(s) occurred:

* helm_release.nginx-ingress: error creating tunnel: "pods is forbidden: User \"client\" cannot list pods in the namespace \"kube-system\""

Terraform does not automatically rollback in the face of errors.
Instead, your Terraform state file has been partially updated with
any resources that successfully completed. Please address the error
above and apply again to incrementally change your infrastructure.
</code>```

This happens after I manually created Helm RBAC and installed Tiller.

I also tried to set "install_tiller=true" before with exactly the same error when Tiller was installed

"kubectl get pods" works without any problems.

What is this user "client" and why it is forbidden from accessing the cluster?

Thanks

答:
Creating resources for the service account and cluster role binding explicitly works for me:</p>

```<code>resource "kubernetes_service_account" "helm_account" {
  depends_on = [
    "google_container_cluster.data-dome-cluster",
  ]
  metadata {
    name      = "${var.helm_account_name}"
    namespace = "kube-system"
  }
}

resource "kubernetes_cluster_role_binding" "helm_role_binding" {
  metadata {
    name = "${kubernetes_service_account.helm_account.metadata.0.name}"
  }
  role_ref {
    api_group = "rbac.authorization.k8s.io"
    kind      = "ClusterRole"
    name      = "cluster-admin"
  }
  subject {
    api_group = ""
    kind      = "ServiceAccount"
    name      = "${kubernetes_service_account.helm_account.metadata.0.name}"
    namespace = "kube-system"
  }
  provisioner "local-exec" {
    command = "sleep 15"
  }
}

provider "helm" {
  service_account = "${kubernetes_service_account.helm_account.metadata.0.name}"
  tiller_image = "gcr.io/kubernetes-helm/tiller:${var.helm_version}"
  #install_tiller = false # Temporary

  kubernetes {
    host                   = "${google_container_cluster.data-dome-cluster.endpoint}"
    token                  = "${data.google_client_config.current.access_token}"

    client_certificate     = "${base64decode(google_container_cluster.data-dome-cluster.master_auth.0.client_certificate)}"
    client_key             = "${base64decode(google_container_cluster.data-dome-cluster.master_auth.0.client_key)}"
    cluster_ca_certificate = "${base64decode(google_container_cluster.data-dome-cluster.master_auth.0.cluster_ca_certificate)}"
  }
}

</code>```

Body:
I am trying to use Terraform Helm provider (https://www.terraform.io/docs/providers/helm/index.html) to deploy a workload to GKE cluster.

I am more or less following Google's example - https://github.com/GoogleCloudPlatform/terraform-google-examples/blob/master/example-gke-k8s-helm/helm.tf, but I do want to use RBAC by creating the service account manually.

My helm.tf looks like this:

variable "helm_version" {
  default = "v2.13.1"
}

data "google_client_config" "current" {}

provider "helm" {
  tiller_image = "gcr.io/kubernetes-helm/tiller:${var.helm_version}"
  install_tiller = false # Temporary

  kubernetes {
    host                   = "${google_container_cluster.data-dome-cluster.endpoint}"
    token                  = "${data.google_client_config.current.access_token}"

    client_certificate     = "${base64decode(google_container_cluster.data-dome-cluster.master_auth.0.client_certificate)}"
    client_key             = "${base64decode(google_container_cluster.data-dome-cluster.master_auth.0.client_key)}"
    cluster_ca_certificate = "${base64decode(google_container_cluster.data-dome-cluster.master_auth.0.cluster_ca_certificate)}"
  }
}

resource "helm_release" "nginx-ingress" {
  name  = "ingress"
  chart = "stable/nginx-ingress"

  values = [<<EOF
rbac:
  create: false
controller:
  stats:
    enabled: true
  metrics:
    enabled: true
  service:
    annotations:
      cloud.google.com/load-balancer-type: "Internal"
    externalTrafficPolicy: "Local"
EOF
  ]

  depends_on = [
    "google_container_cluster.data-dome-cluster",
  ]
}

I am getting the following error:

Error: Error applying plan:

1 error(s) occurred:

* module.data-dome-cluster.helm_release.nginx-ingress: 1 error(s) occurred:

* helm_release.nginx-ingress: error creating tunnel: "pods is forbidden: User \"client\" cannot list pods in the namespace \"kube-system\""

Terraform does not automatically rollback in the face of errors.
Instead, your Terraform state file has been partially updated with
any resources that successfully completed. Please address the error
above and apply again to incrementally change your infrastructure.

This happens after I manually created Helm RBAC and installed Tiller.

I also tried to set "install_tiller=true" before with exactly the same error when Tiller was installed

"kubectl get pods" works without any problems.

What is this user "client" and why it is forbidden from accessing the cluster?

Thanks

Body:
Creating resources for the service account and cluster role binding explicitly works for me:

resource "kubernetes_service_account" "helm_account" {
  depends_on = [
    "google_container_cluster.data-dome-cluster",
  ]
  metadata {
    name      = "${var.helm_account_name}"
    namespace = "kube-system"
  }
}

resource "kubernetes_cluster_role_binding" "helm_role_binding" {
  metadata {
    name = "${kubernetes_service_account.helm_account.metadata.0.name}"
  }
  role_ref {
    api_group = "rbac.authorization.k8s.io"
    kind      = "ClusterRole"
    name      = "cluster-admin"
  }
  subject {
    api_group = ""
    kind      = "ServiceAccount"
    name      = "${kubernetes_service_account.helm_account.metadata.0.name}"
    namespace = "kube-system"
  }
  provisioner "local-exec" {
    command = "sleep 15"
  }
}

provider "helm" {
  service_account = "${kubernetes_service_account.helm_account.metadata.0.name}"
  tiller_image = "gcr.io/kubernetes-helm/tiller:${var.helm_version}"
  #install_tiller = false # Temporary

  kubernetes {
    host                   = "${google_container_cluster.data-dome-cluster.endpoint}"
    token                  = "${data.google_client_config.current.access_token}"

    client_certificate     = "${base64decode(google_container_cluster.data-dome-cluster.master_auth.0.client_certificate)}"
    client_key             = "${base64decode(google_container_cluster.data-dome-cluster.master_auth.0.client_key)}"
    cluster_ca_certificate = "${base64decode(google_container_cluster.data-dome-cluster.master_auth.0.cluster_ca_certificate)}"
  }
}


问:
How to use if __name__ == '__main__':
whenever I import this script it runs without being called and to avoid that I need to use if __name__ == '__main__':, I am confused how to use it here in this code
It would be great if someone can help me with this

```<code>import pyperclip

passwords = {'Facebook': 'xxxx', 'Instagram': 'xxxxxx', 'Youtube': 'xxxxxxx'}

tries = 0
tries_remaining = 3
pass_len = len(passwords)

def ask():
    mast_pass = 'HailHydra'
    ask_mast_pass = input('Please enter the master password: ')
    if ask_mast_pass == mast_pass:
        print(f"{pass_len} found.")
        for x in passwords.keys():
            print(x)

        which_pass = input('Type the name of the password title you are
looking for: ')
        paswd = passwords[which_pass]
        pyperclip.copy(paswd)
        print('Password Copied to clipboard.')

        exit()
    else:
        print('Incorrect Password, Please Try again')

while tries < tries_remaining:
    tries += 1
    ask()
    print(f"{3 - tries} tries remaining")

print('***Do not try to breach the system***')
</code>```

答:
Put your while loop under the <code>__name__</code> check. That is the what will run if you import this script. </p>

```<code>import pyperclip

passwords = {'Facebook': 'xxxx', 'Instagram': 'xxxxxx', 'Youtube': 'xxxxxxx'}

tries = 0
tries_remaining = 3
pass_len = len(passwords)

def ask():
    mast_pass = 'HailHydra'
    ask_mast_pass = input('Please enter the master password: ')
    if ask_mast_pass == mast_pass:
        print(f"{pass_len} found.")
        for x in passwords.keys():
            print(x)

        which_pass = input('Type the name of the password title you are
looking for: ')
        paswd = passwords[which_pass]
        pyperclip.copy(paswd)
        print('Password Copied to clipboard.')

        exit()
    else:
        print('Incorrect Password, Please Try again')

if __name__ == '__main__':
    while tries < tries_remaining:
        tries += 1
        ask()
        print(f"{3 - tries} tries remaining")

    print('***Do not try to breach the system***')
</code>```

Title: How to use if __name__ == '__main__':

Body:
whenever I import this script it runs without being called and to avoid that I need to use if __name__ == '__main__':, I am confused how to use it here in this code
It would be great if someone can help me with this

import pyperclip

passwords = {'Facebook': 'xxxx', 'Instagram': 'xxxxxx', 'Youtube': 'xxxxxxx'}

tries = 0
tries_remaining = 3
pass_len = len(passwords)

def ask():
    mast_pass = 'HailHydra'
    ask_mast_pass = input('Please enter the master password: ')
    if ask_mast_pass == mast_pass:
        print(f"{pass_len} found.")
        for x in passwords.keys():
            print(x)

        which_pass = input('Type the name of the password title you are
looking for: ')
        paswd = passwords[which_pass]
        pyperclip.copy(paswd)
        print('Password Copied to clipboard.')

        exit()
    else:
        print('Incorrect Password, Please Try again')

while tries < tries_remaining:
    tries += 1
    ask()
    print(f"{3 - tries} tries remaining")

print('***Do not try to breach the system***')

Body:
Put your while loop under the __name__ check. That is the what will run if you import this script.

import pyperclip

passwords = {'Facebook': 'xxxx', 'Instagram': 'xxxxxx', 'Youtube': 'xxxxxxx'}

tries = 0
tries_remaining = 3
pass_len = len(passwords)

def ask():
    mast_pass = 'HailHydra'
    ask_mast_pass = input('Please enter the master password: ')
    if ask_mast_pass == mast_pass:
        print(f"{pass_len} found.")
        for x in passwords.keys():
            print(x)

        which_pass = input('Type the name of the password title you are
looking for: ')
        paswd = passwords[which_pass]
        pyperclip.copy(paswd)
        print('Password Copied to clipboard.')

        exit()
    else:
        print('Incorrect Password, Please Try again')

if __name__ == '__main__':
    while tries < tries_remaining:
        tries += 1
        ask()
        print(f"{3 - tries} tries remaining")

    print('***Do not try to breach the system***')


问:
using distinct command
using distinct command in SQL is good practice or not? is there any drawback of distinct command?</p>

答:
It is part of the language, so should be used.

Is some circumstances using DISTINCT may cause a table scan where otherwise one would not occur.

You will need to test for each of your own use cases to see if there is an impact and find a workaround if the impact is unacceptable.

Title: using distinct command


问:
How to get JavaFX and Java 11 working in IntelliJ IDEA
With the recent Java 11 release, JavaFX is no longer included in the JDK.  I have an existing JavaFX project.  I am interested in learning how to change it from a Java 10 project to a Java 11.  I am certain I have installed Java 11 correctly, and I am able to change the default SDK from Java 10 to Java 11.  What I don't know is how I might get JavaFX working with Java 11.

I have downloaded the latest JavaFX release here.  I have extracted it to my Java folder which contains my other JDK's, but I really don't know what to do at this point.  I have read some lengthy guides that describe how to connect a project using Maven or Gradle, but I have never used these.  Is there a way to add JavaFX support in the IntelliJ menus?

答:
You could download a version of java which includes JavaFX from Azul. See: Download Azul Zulu Builds of OpenJDK.
In that case there's no special setup involved to run JavaFx applications on Java 11 - it's built-in, just like in Java 8.

You can also download these 'full' versions from Bellsoft's JDK and JRE distribution site: Download Liberica JDK


问:
Effect size for interaction in Mixed model with R
I am testing a mixed model with 2 categorical predictors (with 2 levels both).
I would like to know the effect size of the 2 categorical predictors and the interaction.

I'm using lmer package

How can I obtain these results?

答: I think you can do this with R.squaredLR function in the MuMinin package from CRAN. You take your experimental model and the null and feed them both in. See page 55 of the  doc here: https://cran.r-project.org/web/packages/MuMIn/MuMIn.pdf. </p>


问:
How to open link in Safari from an HTML hosted in a web browser control?
We have an iphone app that hosts a web browser control which points to a website whose sole purpose is to display information for the application. I would like to know if it is possible to have an anchor/button open Safari using HTML/JavaScript. If it is possible, how so?

Thanks...

答:
You can setup a delegate for the UIWebview you are using. In this delegate, write something like this:

```<code>-(bool) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //You might need to set up an "interceptLinks"-Bool since you don't want to intercept the initial loading of the content
    if (self.interceptLinks) {
        NSURL *url = request.URL;
        //This launches Safari with your URL
        [[UIApplication sharedApplication] openURL:url];
        return NO;
    }
    //No need to intercept the initial request to fill the WebView
    else {
        self.interceptLinks = TRUE;
        return YES;
    }
}
</code>```

If you only want to intercept some links, you can parse the url and only open Safari if necessary.

Body:
You can setup a delegate for the UIWebview you are using. In this delegate, write something like this:

-(bool) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    //You might need to set up an "interceptLinks"-Bool since you don't want to intercept the initial loading of the content
    if (self.interceptLinks) {
        NSURL *url = request.URL;
        //This launches Safari with your URL
        [[UIApplication sharedApplication] openURL:url];
        return NO;
    }
    //No need to intercept the initial request to fill the WebView
    else {
        self.interceptLinks = TRUE;
        return YES;
    }
}

If you only want to intercept some links, you can parse the url and only open Safari if necessary.


问:
adding an object to an array with redux
I'm having a problem with redux.
when I use
store.dispatch( addExpense( {description: "Rent"} ) );
in my app.js file it works and the object is added. But when I try to use it in a context of an component in a separated file it doesn't. The console does't throw any error.
When I use other action like "search" in the same component it works fine. So there's no problem with the connection. It seems that for some reasons it can't change the state.

```<code>//ACTIONS

export const addExpense = ( { description="", amount=0 } = {}) => ({
    type: "ADD_EXPENSE",
    expense: {
        description,
        amount
}
})

//REDUCERS
const expenseReducer = ( state = [], action) => {
    switch(action.type) {
        case "ADD_EXPENSE":
            return [...state, action.expense]

        case "EDIT_EXPENSE": //<- this works
            return state.map( (expense) => {
                if (expense.id === action.id)
                return  {
                    ...expense, ...action.update }
                else return expense
        } )
        default: return state
    }

const filterReducer = ( state = {text:""}, action) => {
    switch(action.type){
        case "FIND_TEXT": //<- this works
            return { ...state, text:action.text }
        default: return state;
    }
}
//COMPONENT

const AddEx = ( props ) => (
    <div>
        <form onSubmit={(e) => {
            e.preventDefault;
            props.dispatch(addExpense ( {description: document.getElementById("addedEx").value} ))
            console.log(document.getElementById("addedEx").value);
//it shows the correct value in the console but the state stays unchanged
        } } >
            <input type="text" id="addedEx"/>
            <button type="submit">submit</button>
        </form>

//SEARACH -> works
        <input
        type="text" value={props.filter.text}
        onChange={(e) => {
            props.dispatch(findText({text:e.target.value}))
        }}
        />
    </div>
)
</code>```

答:
You are adding the value to state instead of expenses, do return [...state.expense, action.expense]

```<code>//REDUCERS
const expenseReducer = (state = [], action) => {
  switch (action.type) {
    case 'ADD_EXPENSE':
      return {
        ...state,
        expense: [...state.expense, action.expense]
      };

    case 'EDIT_EXPENSE': //<- this works
      return state.map(expense => {
        if (expense.id === action.id)
          return {
            ...expense,
            ...action.update
          };
        else return expense;
      });
    default:
      return state;
  }
};
</code>```

    ```

Title: adding an object to an array with redux

Body:
I'm having a problem with redux.
when I use
store.dispatch( addExpense( {description: "Rent"} ) );
in my app.js file it works and the object is added. But when I try to use it in a context of an component in a separated file it doesn't. The console does't throw any error.
When I use other action like "search" in the same component it works fine. So there's no problem with the connection. It seems that for some reasons it can't change the state.

//ACTIONS

export const addExpense = ( { description="", amount=0 } = {}) => ({
    type: "ADD_EXPENSE",
    expense: {
        description,
        amount
}
})

//REDUCERS
const expenseReducer = ( state = [], action) => {
    switch(action.type) {
        case "ADD_EXPENSE":
            return [...state, action.expense]

        case "EDIT_EXPENSE": //<- this works
            return state.map( (expense) => {
                if (expense.id === action.id)
                return  {
                    ...expense, ...action.update }
                else return expense
        } )
        default: return state
    }

const filterReducer = ( state = {text:""}, action) => {
    switch(action.type){
        case "FIND_TEXT": //<- this works
            return { ...state, text:action.text }
        default: return state;
    }
}
//COMPONENT

const AddEx = ( props ) => (

        <form onSubmit={(e) => {
            e.preventDefault;
            props.dispatch(addExpense ( {description: document.getElementById("addedEx").value} ))
            console.log(document.getElementById("addedEx").value);
//it shows the correct value in the console but the state stays unchanged
        } } >
            <input type="text" id="addedEx"/>
            <button type="submit">submit</button>
        </form>

//SEARACH -> works
        <input
        type="text" value={props.filter.text}
        onChange={(e) => {
            props.dispatch(findText({text:e.target.value}))
        }}
        />

)

Body:
You are adding the value to state instead of expenses, do return [...state.expense, action.expense]

//REDUCERS
const expenseReducer = (state = [], action) => {
  switch (action.type) {
    case 'ADD_EXPENSE':
      return {
        ...state,
        expense: [...state.expense, action.expense]
      };

    case 'EDIT_EXPENSE': //<- this works
      return state.map(expense => {
        if (expense.id === action.id)
          return {
            ...expense,
            ...action.update
          };
        else return expense;
      });
    default:
      return state;
  }
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.1/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.0.3/react-redux.min.js"></script>
<script src="http://wzrd.in/standalone/uuid%2Fv1@latest"></script>

<div id="root"></div>

    <script type="text/babel">
      const { Provider, connect } = ReactRedux;
      const { applyMiddleware, createStore, combineReducers } = Redux;
      const ADD_EXPENSE = 'ADD_EXPENSE';

      function addExpense(payload) {
        return { type: ADD_EXPENSE, payload };
      }

      const initialState = {
        expense: [],
      };

      function rootReducer(state = initialState, action) {
        if (action.type === ADD_EXPENSE) {
          return {
            ...state,
            expense: [...state.expense, action.payload]
          };
        }
        return state;
      }

      const store = createStore(rootReducer);

      const mapStateToProps = state => {
        return { expense: state.expense };
      };

      function mapDispatchToProps(dispatch) {
        return {
          addExpense: expense => dispatch(addExpense(expense))
        };
      }

      const ConnectedList = ({ expense, addExpense }) => {
        return (
          <div>
            <ul className="list-group list-group-flush">
              {expense.map(el => (
                <li className="list-group-item" key={el.id}>
                  {`${el.description} - $${el.amount}`}
                </li>
              ))}
            </ul>
          </div>
        );
      };

      const List = connect(
        mapStateToProps,
      )(ConnectedList);

      class ExpenseForm extends React.Component {
        state = {
          description: '',
          amount: 0,
        }

        handleSubmit = (e) => {
          e.preventDefault();

          if (!this.state.description || this.state.amount === 0) {
            return
          }

          const { description, amount } = this.state;

          this.props.addExpense({
            description,
            amount,
            id: uuidv1()
          });

          this.setState({
            description: '',
            amount: 0
          })
        }

        handleInput = (e) => {
          this.setState({
            [e.target.name]: e.target.value
          })
        }

        render() {
          return (
            <form onSubmit={this.handleSubmit}>
              <input name="description" placeholder="Description" onChange={this.handleInput} value={this.state.description} />
              <input type="number" name="amount" placeholder="Amount" onChange={this.handleInput} value={this.state.amount} />
              <input type="submit" />
            </form>
          )
        }

      }

      const Form = connect(null, mapDispatchToProps)(ExpenseForm);

      class App extends React.Component {
        render() {
          return (
            <div>
              <List />
              <Form />
            </div>
          );
        }
      }
      ReactDOM.render(
        <Provider store={store}>
          <App />
        </Provider>,
        document.getElementById('root')
      );
    </script>


问:
how can i get json response for weather response
i'm using weather map api to get current weather i did get the temperature but i have probleme to get description for it </p>

```<code>class WeatherResponse {

  @SerializedName("sys")
  var sys: Sys? = null

  @SerializedName("main")
  var main: Main? = null

  @SerializedName("weather")
  var weather: Weather? = null
}

class Main {
  @SerializedName("temp")
  var temp: Float = 0.0f
  @SerializedName("humidity")
  var humidity: Float = 0.0f
  @SerializedName("pressure")
  var pressure: Float = 0.0f
  @SerializedName("temp_min")
  var temp_min: Float = 0.0f
  @SerializedName("temp_max")
  var temp_max: Float = 0.0f
}

class Sys {
  @SerializedName("country")
  var country: String? = null
}
</code>```

<p>this is the response from the url </p>

```<code>  {"coord":{"lon":139,"lat":35},
  "sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
  "weather":[{"id":804,"main":"clouds","description":"overcast
   clouds","icon":"04n"}],
  "main":
  {"temp":289.5,"humidity":89,"pressure":1013,"temp_min"
  :287.04,"temp_max" :292.04},
  "wind":{"speed":7.31,"deg":187.002},
  "rain":{"3h":0},
 "clouds":{"all":92},
 "dt":1369824698,
 "id":1851632,
"name":"Shuzenji",
 "cod":200}
</code>```

答:
EDIT: Sorry, this is a python solution.

If you convert the json string to a dictionary, you can try the following:

```<code>weather_dict = json.loads(json_str)
print(weather_dict['weather'][0]['description'])
</code>```

output:

```<code>overcast clouds
</code>```

Body:
i'm using weather map api to get current weather i did get the temperature but i have probleme to get description for it

class WeatherResponse {

  @SerializedName("sys")
  var sys: Sys? = null

  @SerializedName("main")
  var main: Main? = null

  @SerializedName("weather")
  var weather: Weather? = null
}

class Main {
  @SerializedName("temp")
  var temp: Float = 0.0f
  @SerializedName("humidity")
  var humidity: Float = 0.0f
  @SerializedName("pressure")
  var pressure: Float = 0.0f
  @SerializedName("temp_min")
  var temp_min: Float = 0.0f
  @SerializedName("temp_max")
  var temp_max: Float = 0.0f
}

class Sys {
  @SerializedName("country")
  var country: String? = null
}

this is the response from the url

  {"coord":{"lon":139,"lat":35},
  "sys":{"country":"JP","sunrise":1369769524,"sunset":1369821049},
  "weather":[{"id":804,"main":"clouds","description":"overcast
   clouds","icon":"04n"}],
  "main":
  {"temp":289.5,"humidity":89,"pressure":1013,"temp_min"
  :287.04,"temp_max" :292.04},
  "wind":{"speed":7.31,"deg":187.002},
  "rain":{"3h":0},
 "clouds":{"all":92},
 "dt":1369824698,
 "id":1851632,
"name":"Shuzenji",
 "cod":200}

Body:
EDIT: Sorry, this is a python solution.

If you convert the json string to a dictionary, you can try the following:

weather_dict = json.loads(json_str)
print(weather_dict['weather'][0]['description'])

output:

overcast clouds


问:
How to view this specific data in page?
I am trying to build a blog website as follow:

Category Model

```<code>public class Category
    {
        public int CategoryID { get; set; }
        public String CategoryName { get; set; }
        public virtual List<Article> Articles { get; set; }
    }
</code>```

Article Model

```<code>public class Article
    {
        public int Id { get; set; }
        public string Header { get; set; }
        public string Content { get; set; }
        public byte[] BlogImage{ get; set; }
        public DateTime? CreationDate{ get; set; }
        public int? CategoryID{ get; set; }
        public virtual Category Category { get; set; }
    }

</code>```

So, how can I send data in ActionResult function and view blog card in page like this image?

```<code>public ActionResult Index()
        {
            using (MvcBlogContext context = new MvcBlogContext())
            {
                 // how to code here?
            }
        }
</code>```

```<code><div class="row">
     @foreach (var item in Model)
     {
           <div class="col-md-4">
            // how to view category name here?
           </div>
     }
</div>

<div class="row">
     @foreach (var item in Model)
     {
           <div class="col-md-4">
                <div class="post post-widget"
                     // how to view from 2nd to 4th blog here?
                </div>
           </div>
     }
</div>
</code>```

Can you help me about this?

答:
To answer one of your questions - selecting the first entry and then the rest you could try

```<code>@foreach (var item in Model.Take(1))
</code>```

for the first row, and then

```<code>@foreach (var item in Model.Skip(1))
</code>```

for the rest. It assumes that the data in your model is ordered appropriately.

Title: How to view this specific data in page?

Body:
I am trying to build a blog website as follow:

Category Model

public class Category
    {
        public int CategoryID { get; set; }
        public String CategoryName { get; set; }
        public virtual List
 Articles { get; set; }
    }

Article Model

public class Article
    {
        public int Id { get; set; }
        public string Header { get; set; }
        public string Content { get; set; }
        public byte[] BlogImage{ get; set; }
        public DateTime? CreationDate{ get; set; }
        public int? CategoryID{ get; set; }
        public virtual Category Category { get; set; }
    }

So, how can I send data in ActionResult function and view blog card in page like this image?

public ActionResult Index()
        {
            using (MvcBlogContext context = new MvcBlogContext())
            {
                 // how to code here?
            }
        }

     @foreach (var item in Model)
     {

            // how to view category name here?

     }

     @foreach (var item in Model)
     {

                <div class="post post-widget"
                     // how to view from 2nd to 4th blog here?

     }

Can you help me about this?

Body:
To answer one of your questions - selecting the first entry and then the rest you could try

@foreach (var item in Model.Take(1))

for the first row, and then

@foreach (var item in Model.Skip(1))

for the rest. It assumes that the data in your model is ordered appropriately.


问:
Accessing elements of arrays within an array
Example:

```<code>matrix = np.zeros((2, 2), dtype=np.ndarray)
matrix[0, 0] = np.array([1, 2])
matrix[0, 1] = np.array([3, 4])
matrix[1, 0] = np.array([5, 6])
matrix[1, 1] = np.array([7, 8])
</code>```

I would like to create a matrix from the left entries of each array, i.e.

```<code>[[1, 3], [5, 7]]
</code>```

Is there a shorthand way of doing this? I have tried matrix[:,:][0] but this doesn't yield what I want...

Any help would be much appreciated!

答:
Here are a few options, slowest to fastest.

```<code>>>> import operator as op
>>> import itertools as it
>>>
>>> np.rec.fromrecords(matrix)['f0']
array([[1, 2],
       [5, 6]])
>>> timeit(lambda:np.rec.fromrecords(matrix)['f0'], number=100_000)
5.490952266845852
>>>
>>> np.vectorize(op.itemgetter(0), otypes=(int,))(matrix)
array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.vectorize(op.itemgetter(0), otypes=(int,))(matrix), number=100_000)
1.1551978620700538
>>>
>>> np.stack(matrix.ravel())[:,0].reshape(matrix.shape)
array([[1, 3],
       [5, 7]])
>>> timeit(lambda: np.stack(matrix.ravel())[:,0].reshape(matrix.shape), number=100_000)
0.9197127181105316
>>>
>>> np.reshape(next(zip(*matrix.reshape(-1))), matrix.shape)
array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.reshape(next(zip(*matrix.reshape(-1))), matrix.shape), number=100_000)
0.7601758309174329
>>>
>>> np.fromiter(it.chain.from_iterable(matrix.reshape(-1)), int)[::2].reshape(matrix.shape)
array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.fromiter(it.chain.from_iterable(matrix.reshape(-1)), int)[::2].reshape(matrix.shape), number=100_000)
0.5561180629301816
>>>
>>> np.frompyfunc(op.itemgetter(0), 1, 1)(matrix).astype(int)array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.frompyfunc(op.itemgetter(0), 1, 1)(matrix).astype(int), number=100_000)
0.2731688329949975
>>>
>>> np.array(matrix.tolist())[...,0]
array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.array(matrix.tolist())[...,0], number=100_000)
0.249452771153301
</code>```

You may get different rank order for other problem sizes or platforms.

Body:
Example:

matrix = np.zeros((2, 2), dtype=np.ndarray)
matrix[0, 0] = np.array([1, 2])
matrix[0, 1] = np.array([3, 4])
matrix[1, 0] = np.array([5, 6])
matrix[1, 1] = np.array([7, 8])

I would like to create a matrix from the left entries of each array, i.e.

[[1, 3], [5, 7]]

Is there a shorthand way of doing this? I have tried matrix[:,:][0] but this doesn't yield what I want...

Any help would be much appreciated!

Body:
Here are a few options, slowest to fastest.

>>> import operator as op
>>> import itertools as it
>>>
>>> np.rec.fromrecords(matrix)['f0']
array([[1, 2],
       [5, 6]])
>>> timeit(lambda:np.rec.fromrecords(matrix)['f0'], number=100_000)
5.490952266845852
>>>
>>> np.vectorize(op.itemgetter(0), otypes=(int,))(matrix)
array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.vectorize(op.itemgetter(0), otypes=(int,))(matrix), number=100_000)
1.1551978620700538
>>>
>>> np.stack(matrix.ravel())[:,0].reshape(matrix.shape)
array([[1, 3],
       [5, 7]])
>>> timeit(lambda: np.stack(matrix.ravel())[:,0].reshape(matrix.shape), number=100_000)
0.9197127181105316
>>>
>>> np.reshape(next(zip(*matrix.reshape(-1))), matrix.shape)
array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.reshape(next(zip(*matrix.reshape(-1))), matrix.shape), number=100_000)
0.7601758309174329
>>>
>>> np.fromiter(it.chain.from_iterable(matrix.reshape(-1)), int)[::2].reshape(matrix.shape)
array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.fromiter(it.chain.from_iterable(matrix.reshape(-1)), int)[::2].reshape(matrix.shape), number=100_000)
0.5561180629301816
>>>
>>> np.frompyfunc(op.itemgetter(0), 1, 1)(matrix).astype(int)array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.frompyfunc(op.itemgetter(0), 1, 1)(matrix).astype(int), number=100_000)
0.2731688329949975
>>>
>>> np.array(matrix.tolist())[...,0]
array([[1, 3],
       [5, 7]])
>>> timeit(lambda:np.array(matrix.tolist())[...,0], number=100_000)
0.249452771153301

You may get different rank order for other problem sizes or platforms.


问:
Any way to to include original parameters in fscanf in C
I'm trying to see if when I do

```<code>fscanf(inputSTREAM, "$%s$", out)
</code>```

I can also return the $ signs - is there a way?

答:
Note that in "$%s$" the second dollar is useless, as %s means "sequence of non-white space characters". So, the terminating dollar is already scanned by the %s. All you need to do is scan the initial dollar with %c at the beginning, e.g. try this:

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

int main (void)
{
    char out[64];

    while (fscanf (stdin, " %c%62s", &out[0], &out[1]) == 2 && out[0] == '$') {
        printf (">>%s<<\n", out);
    }
    return 0;
}

$ ./a.out
$fooo$
>>$fooo$<<
$bar$
>>$bar$<<
   $baz   $
>>$baz<<
  $  boing   $
>>$$<<
$ ./a.out
  $zap$
>>$zap$<<
  $   oink$
>>$oink$<<
^D
$
</code>```

Note that 62 in %62s is two less than the sizeof out to leave room for the initial dollar and terminating 0.

Body:
I'm trying to see if when I do

fscanf(inputSTREAM, "$%s$", out)

I can also return the $ signs - is there a way?

Body:
Note that in "$%s$" the second dollar is useless, as %s means "sequence of non-white space characters". So, the terminating dollar is already scanned by the %s. All you need to do is scan the initial dollar with %c at the beginning, e.g. try this:

#include <stdio.h>

int main (void)
{
    char out[64];

    while (fscanf (stdin, " %c%62s", &out[0], &out[1]) == 2 && out[0] == '$') {
        printf (">>%s<<\n", out);
    }
    return 0;
}

$ ./a.out
$fooo$
>>$fooo$<<
$bar$
>>$bar$<<
   $baz   $
>>$baz<<
  $  boing   $
>>$$<<
$ ./a.out
  $zap$
>>$zap$<<
  $   oink$
>>$oink$<<
^D
$

Note that 62 in %62s is two less than the sizeof out to leave room for the initial dollar and terminating 0.


问:
how can i retrieve all the childrens by n1ql query
I am planning to retrieve the child elements all the parent, How can i retrieve it, being inside the array of array objects.

```<code>SELECT sd.*
FROM test AS t
UNNEST stateDetails AS sd;
</code>```

```<code>{
   "type":"countries",
   "docName":"CountryData",
   "countryDetails":[
      {
         "name":"US",
         "code":"+1",
         "stateInfo":[
            {
               "name":"Florida",
               "id":"1212"
            },
            {
               "name":"NewYork",
               "id":"1214"
            }
         ]
      },
       {
         "name":"France",
         "code":"+33",
         "stateInfo":[
            {
               "name":"Grand Est",
               "id":"5212"
            },
            {
               "name":"Brittany",
               "id":"5214"
            }
         ]
      }
   ]
}
</code>```

I am expecting the following output to bring out the state details of all the countries with their respective country Name

```<code>        [
            {
               "countryName":"US",
               "name":"Florida",
               "id":"1212"
            },
            {
               "countryName":"US",
               "name":"NewYork",
               "id":"1214"
            },
            {
               "countryName":"France",
               "name":"Grand Est",
               "id":"5212"
            },
            {
               "countryName":"France",
               "name":"Brittany",
               "id":"5214"
            }
         ]
</code>```

答:
Use double UNNEST and project what you need</p>

```<code>SELECT cd.name AS countryName, sd.name, sd.id
FROM test AS t
UNNEST t.countryDetails AS cd
UNNEST cd.stateInfo AS sd
WHERE t.type = "countries";
</code>```

Body:
I am planning to retrieve the child elements all the parent, How can i retrieve it, being inside the array of array objects.

SELECT sd.*
FROM test AS t
UNNEST stateDetails AS sd;

{
   "type":"countries",
   "docName":"CountryData",
   "countryDetails":[
      {
         "name":"US",
         "code":"+1",
         "stateInfo":[
            {
               "name":"Florida",
               "id":"1212"
            },
            {
               "name":"NewYork",
               "id":"1214"
            }
         ]
      },
       {
         "name":"France",
         "code":"+33",
         "stateInfo":[
            {
               "name":"Grand Est",
               "id":"5212"
            },
            {
               "name":"Brittany",
               "id":"5214"
            }
         ]
      }
   ]
}

I am expecting the following output to bring out the state details of all the countries with their respective country Name

        [
            {
               "countryName":"US",
               "name":"Florida",
               "id":"1212"
            },
            {
               "countryName":"US",
               "name":"NewYork",
               "id":"1214"
            },
            {
               "countryName":"France",
               "name":"Grand Est",
               "id":"5212"
            },
            {
               "countryName":"France",
               "name":"Brittany",
               "id":"5214"
            }
         ]

Body:
Use double UNNEST and project what you need

SELECT cd.name AS countryName, sd.name, sd.id
FROM test AS t
UNNEST t.countryDetails AS cd
UNNEST cd.stateInfo AS sd
WHERE t.type = "countries";


问:
Incorrect syntax near the keyword 'FOR', while the same code worked in a guide
I'm trying to roll up multiple rows into one with FOR XML PATH. I'm not sure why I got the error "Incorrect syntax near the keyword 'FOR'"

I was following this guide: https://www.mssqltips.com/sqlservertip/2914/rolling-up-multiple-rows-into-a-single-row-and-column-for-sql-server-data/

```<code>SELECT
    movie.name, movie.date, movie.filelocation,
    movie.imdb, movie.description,
    STUFF ((SELECT ';' + genre.name
            FROM genre
            WHERE genre.id = mov_genr.gen_id
              AND movie.id = mov_genr.mov_id
            FOR XML PATH ('')), 1, 1, '') [genres]
FROM
    movie
FULL JOIN
    mov_genr on movie.id = mov_genr.mov_id
FULL JOIN
    genre on mov_genr.gen_id = genre.id
</code>```

I have 3 tables, movie with a bunch of movies, mov_genr which is a table that connects movies with genres, and genre table, which contains the genres.

I want a query that shows me all the movies and all the genres for those movies but don't duplicate the movie rows and just shows the genres as 1 connected string.

答:
You are missing comma before STUFF:

```<code>Select movie.name,movie.date,movie.filelocation, movie.imdb, movie.description, -- here

    STUFF ((SELECT ';' + genre.name FROM genre
    WHERE genre.id = mov_genr.gen_id AND movie.id = mov_genr.mov_id
    FOR XML PATH ('')), 1,1,'') [genres]

FROM movie
FULL JOIN mov_genr on movie.id = mov_genr.mov_id
FULL JOIN genre on mov_genr.gen_id = genre.id
</code>```

Body:
I'm trying to roll up multiple rows into one with FOR XML PATH. I'm not sure why I got the error "Incorrect syntax near the keyword 'FOR'"

I was following this guide: https://www.mssqltips.com/sqlservertip/2914/rolling-up-multiple-rows-into-a-single-row-and-column-for-sql-server-data/

SELECT
    movie.name, movie.date, movie.filelocation,
    movie.imdb, movie.description,
    STUFF ((SELECT ';' + genre.name
            FROM genre
            WHERE genre.id = mov_genr.gen_id
              AND movie.id = mov_genr.mov_id
            FOR XML PATH ('')), 1, 1, '') [genres]
FROM
    movie
FULL JOIN
    mov_genr on movie.id = mov_genr.mov_id
FULL JOIN
    genre on mov_genr.gen_id = genre.id

I have 3 tables, movie with a bunch of movies, mov_genr which is a table that connects movies with genres, and genre table, which contains the genres.

I want a query that shows me all the movies and all the genres for those movies but don't duplicate the movie rows and just shows the genres as 1 connected string.

Body:
You are missing comma before STUFF:

Select movie.name,movie.date,movie.filelocation, movie.imdb, movie.description, -- here

    STUFF ((SELECT ';' + genre.name FROM genre
    WHERE genre.id = mov_genr.gen_id AND movie.id = mov_genr.mov_id
    FOR XML PATH ('')), 1,1,'') [genres]

FROM movie
FULL JOIN mov_genr on movie.id = mov_genr.mov_id
FULL JOIN genre on mov_genr.gen_id = genre.id


问:
AbsoluteLayout.LayoutBounds position using Xamarin.form Xaml
In Xamarin.form Xaml :When I am giving AbsoulteLayout layoutBounds(.5,.5,.5,.5) its coming on center but not for ios... and If I'm using (.75,.75,.5,.5) its coming on center for ios not for android in Xamarin form xaml page.....How to have same layoutBounds for both ios and android

Given Example:

```<code><AbsoluteLayout BackgroundColor="#99000000"
                    HorizontalOptions="FillAndExpand"
                    IsVisible="{Binding xyz}"
                    VerticalOptions="FillAndExpand">

      <AbsoluteLayout x:Name="xyz"
                     AbsoluteLayout.LayoutBounds="0.5, 0.5, 0.5, 0.5"
                     AbsoluteLayout.LayoutFlags="All"
                       BackgroundColor="Transparent"
                       HorizontalOptions="CenterAndExpand"
                       VerticalOptions="CenterAndExpand" />
</AbsoluteLayout>
</code>```

答:
This way we can use platforms directives for LayoutBounds in AbsoluteLayout for every controls

```<code><Label AbsoluteLayout.LayoutFlags="PositionProportional">
  <Label.AbsoluteLayout.LayoutBounds>
         <OnPlatform x:TypeArguments="Rectangle" iOS="..." Android="..." />
    </Label.AbsoluteLayout.LayoutBounds>
</Label>
</code>```

Body:
In Xamarin.form Xaml :When I am giving AbsoulteLayout layoutBounds(.5,.5,.5,.5) its coming on center but not for ios... and If I'm using (.75,.75,.5,.5) its coming on center for ios not for android in Xamarin form xaml page.....How to have same layoutBounds for both ios and android

Given Example:

<AbsoluteLayout BackgroundColor="#99000000"
                    HorizontalOptions="FillAndExpand"
                    IsVisible="{Binding xyz}"
                    VerticalOptions="FillAndExpand">

      <AbsoluteLayout x:Name="xyz"
                     AbsoluteLayout.LayoutBounds="0.5, 0.5, 0.5, 0.5"
                     AbsoluteLayout.LayoutFlags="All"
                       BackgroundColor="Transparent"
                       HorizontalOptions="CenterAndExpand"
                       VerticalOptions="CenterAndExpand" />
</AbsoluteLayout>

Body:
This way we can use platforms directives for LayoutBounds in AbsoluteLayout for every controls

<Label AbsoluteLayout.LayoutFlags="PositionProportional">
  <Label.AbsoluteLayout.LayoutBounds>
         <OnPlatform x:TypeArguments="Rectangle" iOS="..." Android="..." />
    </Label.AbsoluteLayout.LayoutBounds>
</Label>


答:
Your code doesn't make sense.  I think you want:

```<code>Select m.*,
       STUFF( (SELECT ';' + genre.name
               FROM mov_genr mg JOIN
                    genre g
                    ON g.id = mg.gen_id
               WHERE m.id = mg.mov_id
               FOR XML PATH ('')
              ), 1, 1, '') as genres
FROM movie m;
</code>```

One problem is a missing comma.

But you have logic problems as well.  You want want row per movie (presumably), so joins are not appropriate in the outer query.

Further FULL JOIN is almost never needed with a well-designed data model.

Table aliases make the query easier to write and to read.

Title: Incorrect syntax near the keyword 'FOR', while the same code worked in a guide

Body:
Your code doesn't make sense.  I think you want:

Select m.*,
       STUFF( (SELECT ';' + genre.name
               FROM mov_genr mg JOIN
                    genre g
                    ON g.id = mg.gen_id
               WHERE m.id = mg.mov_id
               FOR XML PATH ('')
              ), 1, 1, '') as genres
FROM movie m;

One problem is a missing comma.

But you have logic problems as well.  You want want row per movie (presumably), so joins are not appropriate in the outer query.

Further FULL JOIN is almost never needed with a well-designed data model.

Table aliases make the query easier to write and to read.


问:
Passing tokens from lexer to parser
I am writing a handcrafted lexer and a parser in C++. I have written the lexer in such a way that if it finds for example a ; it prints "SEMICOLON", if it finds while it prints "KEYWORD", if it finds hello it prints "IDENTIFIER" ,etc,etc. However now I need to pass these tokens to a parser. How can this be done for example using a list? And I found that I need to store the token type and token value

答:
Use an std::map in such a way:

```<code>std::map<string, string> my_map = {
    { ";", "SEMICOLON" },
    { "while", "KEYWORD" },
    ...
 };
</code>```

Title: Passing tokens from lexer to parser

Body:
Use an std::map in such a way:

std::map<string, string> my_map = {
    { ";", "SEMICOLON" },
    { "while", "KEYWORD" },
    ...
 };


问:
c# Delegate Throws System.InvalidOperationException
I have a Thread that retrieves infos from an xml file. In my main form I have a checkbox that in case a boolean in the xml is true must be checked by the thread. I have created a Delegate but despite this when the thread tries to change the value of the checkbox a System.InvalidOperationException is thrown. Why ?!? </p>

```<code>private delegate void ProjectFileReloadDelegate(string pp);

private void ProjectFileReload(string projectPath)
{
    if (this.InvokeRequired)
    {
        this.Invoke(new ProjectFileReloadDelegate(ProjectFileReload), projectPath);
    }
    else
    {
        //This throws the exception
        //I retrive the anchorMode Info
        anchorMode.Checked = ProjectOptions_v000.AnchorMode;
    }
</code>```

答:
On one of my projects, which handled quite a few API, I used Task to handle async api calls. Due to the uncertainty on weather it would be on Main GUI thread or another I used Task.Factory.StartNew with a TaskScheduler.FromCurrentSynchronizationContext() as parameter to handle any code updating the GUI. The reference for this is from Microsoft the section titled "Specifying a synchronization context"
The TaskScheduler.FromCurrentSynchronizationContext() tells it run on gui thread.

This is how I would update your code to prevent Exceptions from updating GUI content on other threads.

```<code>    private delegate void ProjectFileReloadDelegate(string pp);

    private void ProjectFileReload(string projectPath)
    {
        if (this.InvokeRequired)
        {
            this.Invoke(new ProjectFileReloadDelegate(ProjectFileReload), projectPath);
        }
        else
        {
            //This throws the exception
            //I retrive the anchorMode Info

            Task.Factory.StartNew(
                       delegate {
                           anchorMode.Checked = ProjectOptions_v000.AnchorMode;
                       }, TaskScheduler.FromCurrentSynchronizationContext()
                   );
</code>```

Body:
I have a Thread that retrieves infos from an xml file. In my main form I have a checkbox that in case a boolean in the xml is true must be checked by the thread. I have created a Delegate but despite this when the thread tries to change the value of the checkbox a System.InvalidOperationException is thrown. Why ?!?

private delegate void ProjectFileReloadDelegate(string pp);

private void ProjectFileReload(string projectPath)
{
    if (this.InvokeRequired)
    {
        this.Invoke(new ProjectFileReloadDelegate(ProjectFileReload), projectPath);
    }
    else
    {
        //This throws the exception
        //I retrive the anchorMode Info
        anchorMode.Checked = ProjectOptions_v000.AnchorMode;
    }

Body:
On one of my projects, which handled quite a few API, I used Task to handle async api calls. Due to the uncertainty on weather it would be on Main GUI thread or another I used Task.Factory.StartNew with a TaskScheduler.FromCurrentSynchronizationContext() as parameter to handle any code updating the GUI. The reference for this is from Microsoft the section titled "Specifying a synchronization context"
The TaskScheduler.FromCurrentSynchronizationContext() tells it run on gui thread.

This is how I would update your code to prevent Exceptions from updating GUI content on other threads.

    private delegate void ProjectFileReloadDelegate(string pp);

    private void ProjectFileReload(string projectPath)
    {
        if (this.InvokeRequired)
        {
            this.Invoke(new ProjectFileReloadDelegate(ProjectFileReload), projectPath);
        }
        else
        {
            //This throws the exception
            //I retrive the anchorMode Info

            Task.Factory.StartNew(
                       delegate {
                           anchorMode.Checked = ProjectOptions_v000.AnchorMode;
                       }, TaskScheduler.FromCurrentSynchronizationContext()
                   );


问:
Change PHP version used by Composer on Windows
I have already use WAMP 2.5 with PHP 5.5.12, and with Composer.
The php is on:

```<code>C:\wamp\bin\php\php5.5.12
</code>```

For new project, I need to use nginx and installed PHP 7.
The php is on:

```<code>C:\nginx\php
</code>```

Now, using GitBash MINGW32, I tried to install laravel 5.3 using Composer create-project but it said

```<code>[InvalidArgumentException]
Could not find package laravel/laravel with version 5.3 in a version
installable using your PHP version 5.5.12.
</code>```

I already put both C:\wamp\bin\php\php5.5.12 and C:\nginx\php on Windows System PATH variable.

How do I change the PHP version used by Composer?

答:
Although this question was solved, the answer didn't help me. I will explain how I managed to make composer to work in a version of PHP different from the one which is installed by default on my OS (PHP 7.1.1) as well as in my environment variables (these will not be changed !). Note that I'm using Xampp, but the principle remains the same for Wamp.

Starting from this answer :

Start up Git Bash

Type cd ~/ to go to your home folder

Type touch .bash_profile to create your new file.

Edit .bash_profile with your favorite editor

In my case I have a folder named php733 inside xampp folder which corresponds to PHP 7.3.3. This is this other answer that helped me in creating the alias :

```<code>alias composer733='/c/[xampp folder]/php733/php.exe /c/ProgramData/ComposerSetup/bin/composer.phar '
</code>```

Then, type . .bash_profile to reload .bash_profile and update any functions you add. Notice the space between the two dots !

Finally, type this command in Git Bash :

```<code>composer733 [whatever you wan]
</code>```

Example : in the project that requires at least PHP 7.1.3

Using composer :

```<code>$ composer update
This package requires php ^7.1.3 but your HHVM version does not satisfy that requirement.
</code>```

Using composer733 (the alias I created) :

```<code>$ composer733 update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 98 installs, 0 updates, 0 removals
  - Installing [...] (v1.11.0): Loading from cache
</code>```

It works, without having to change the environment variables

Body:
I have already use WAMP 2.5 with PHP 5.5.12, and with Composer.
The php is on:

C:\wamp\bin\php\php5.5.12

For new project, I need to use nginx and installed PHP 7.
The php is on:

C:\nginx\php

Now, using GitBash MINGW32, I tried to install laravel 5.3 using Composer create-project but it said

[InvalidArgumentException]
Could not find package laravel/laravel with version 5.3 in a version
installable using your PHP version 5.5.12.

I already put both C:\wamp\bin\php\php5.5.12 and C:\nginx\php on Windows System PATH variable.

How do I change the PHP version used by Composer?

Body:
Although this question was solved, the answer didn't help me. I will explain how I managed to make composer to work in a version of PHP different from the one which is installed by default on my OS (PHP 7.1.1) as well as in my environment variables (these will not be changed !). Note that I'm using Xampp, but the principle remains the same for Wamp.

Starting from this answer :

Start up Git Bash

Type cd ~/ to go to your home folder

Type touch .bash_profile to create your new file.

Edit .bash_profile with your favorite editor

In my case I have a folder named php733 inside xampp folder which corresponds to PHP 7.3.3. This is this other answer that helped me in creating the alias :

alias composer733='/c/[xampp folder]/php733/php.exe /c/ProgramData/ComposerSetup/bin/composer.phar '

Then, type . .bash_profile to reload .bash_profile and update any functions you add. Notice the space between the two dots !

Finally, type this command in Git Bash :

composer733 [whatever you wan]

Example : in the project that requires at least PHP 7.1.3

Using composer :

$ composer update
This package requires php ^7.1.3 but your HHVM version does not satisfy that requirement.

Using composer733 (the alias I created) :

$ composer733 update
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 98 installs, 0 updates, 0 removals
  - Installing [...] (v1.11.0): Loading from cache

It works, without having to change the environment variables


问:
How do spaces work in a regular expression with grep in the bash shell?
The way I would read the regular expression below:

a space char

a slash char

a 'n' char

zero or more space chars

end of line

But this test fails:

```<code>$ echo "Some Text \n " | grep " \\n *$"
</code>```

If I delete a space in the regular expression, does not fail

```<code>$ echo "Some Text \n " | grep "\\n *$"
Some Text \n
</code>```

答:
Try this:

```<code>echo "Some Text \n " | grep ' \\n *$'
</code>```

Note the single quotes. This serverfault question has more information about single vs. double quotes. With single quotes, the string is treated literally.

Here's an explanation. When you do:

echo "Test\n", you get Test\n as the output, because echo doesn't translate the escape sequences (unless you send it the -e flag).

echo "Test\n" | grep '\n', it only matches the n. This is because \n is an "escaped n" (it doesn't seem to translate into an actual newline). If you want it to match the \ and the n, you need to do echo "Test\n" | grep '\\n'.

Body:
The way I would read the regular expression below:

a space char

a slash char

a 'n' char

zero or more space chars

end of line

But this test fails:

$ echo "Some Text \n " | grep " \\n *$"

If I delete a space in the regular expression, does not fail

$ echo "Some Text \n " | grep "\\n *$"
Some Text \n

Body:
Try this:

echo "Some Text \n " | grep ' \\n *$'

Note the single quotes. This serverfault question has more information about single vs. double quotes. With single quotes, the string is treated literally.

Here's an explanation. When you do:

echo "Test\n", you get Test\n as the output, because echo doesn't translate the escape sequences (unless you send it the -e flag).

echo "Test\n" | grep '\n', it only matches the n. This is because \n is an "escaped n" (it doesn't seem to translate into an actual newline). If you want it to match the \ and the n, you need to do echo "Test\n" | grep '\\n'.


问:
looping with nested []struct in Go?
I have a structure I'm working with, and I'm not sure how to loop through it properly. I would like to access the field names, but all it is doing is just incrementally counting at each loop.

Here is my structure:

```<code>type ImgurJson struct {
      Status int16 `json:"status"`
      Success bool `json:"success"`
      Data []struct {
            Width int16 `json:"width"`
            Points int32 `json:"points"`
            CommentCount int32 `json:"comment_count"`
            TopicId int32 `json:"topic_id"`
            AccountId int32 `json:"account_id"`
            Ups int32 `json:"ups"`
            Downs int32 `json:"downs"`
            Bandwidth int64 `json:"bandwidth"`
            Datetime int64 `json:"datetime"`
            Score int64 `json:"score"`
            Account_Url string `json:"account_url"`
            Topic string `json:"topic"`
            Link string `json:"link"`
            Id string `json:"id"`
            Description string`json:"description"`
            CommentPreview string `json:"comment_preview"`
            Vote string `json:"vote"`
            Title string `json:"title"`
            Section string `json:"section"`
            Favorite bool `json:"favorite"`
            Is_Album bool `json:"is_album"`
            Nsfw bool `json:"nsfw"`
             } `json:"data"`
}
</code>```

Here is my function:

```<code>func parseJson(file string) {
      jsonFile, err := ioutil.ReadFile(file)
      if err != nil {
            ...
            }
      jsonParser := ImgurJson{}
      err = json.Unmarshal(jsonFile, &jsonParser)
      for field, value := range jsonParser.Data {
            fmt.Print("key: ", field, "\n")
            fmt.Print("value: ", value, "\n")
      }
}
</code>```

How do I loop through a nested, []struct in Go and return the fields? I've seen several posts about reflection, but I don't understand if that would assist me or not. I can return the values of each field, but I don't understand how to map the field name to the key value.

Edit:

Renamed "keys" to "field", sorry! Didn't realise they were called fields.

I would like to be able to print:

```<code>field: Width
value: 1234
</code>```

I would like to learn how to do this so I can later call a specific field by name so I can map it to a SQL column name.

答:
You can also iterate using normal golang for loop on nested struct.</p>

```<code>type ImgurJson struct {
      Status int16 `json:"status"`
      Success bool `json:"success"`
      Data []struct {
            Width int16 `json:"width"`
            Points int32 `json:"points"`
            CommentCount int32 `json:"comment_count"`
            TopicId int32 `json:"topic_id"`
            AccountId int32 `json:"account_id"`
            Ups int32 `json:"ups"`
            Downs int32 `json:"downs"`
            Bandwidth int64 `json:"bandwidth"`
            Datetime int64 `json:"datetime"`
            Score int64 `json:"score"`
            Account_Url string `json:"account_url"`
            Topic string `json:"topic"`
            Link string `json:"link"`
            Id string `json:"id"`
            Description string`json:"description"`
            CommentPreview string `json:"comment_preview"`
            Vote string `json:"vote"`
            Title string `json:"title"`
            Section string `json:"section"`
            Favorite bool `json:"favorite"`
            Is_Album bool `json:"is_album"`
            Nsfw bool `json:"nsfw"`
             } `json:"data"`
}

func parseJson(file string) {
      jsonFile, err := ioutil.ReadFile(file)
      if err != nil {
            ...
            }
      jsonParser := ImgurJson{}
      err = json.Unmarshal(jsonFile, &jsonParser)
      for i :=0; i<len(jsonParser.Data); i++ {
            fmt.Print("key: ", jsonParser.Data[i].TopicId, "\n")
      }
}
</code>```

Title: looping with nested []struct in Go?

Body:
I have a structure I'm working with, and I'm not sure how to loop through it properly. I would like to access the field names, but all it is doing is just incrementally counting at each loop.

Here is my structure:

type ImgurJson struct {
      Status int16 `json:"status"`
      Success bool `json:"success"`
      Data []struct {
            Width int16 `json:"width"`
            Points int32 `json:"points"`
            CommentCount int32 `json:"comment_count"`
            TopicId int32 `json:"topic_id"`
            AccountId int32 `json:"account_id"`
            Ups int32 `json:"ups"`
            Downs int32 `json:"downs"`
            Bandwidth int64 `json:"bandwidth"`
            Datetime int64 `json:"datetime"`
            Score int64 `json:"score"`
            Account_Url string `json:"account_url"`
            Topic string `json:"topic"`
            Link string `json:"link"`
            Id string `json:"id"`
            Description string`json:"description"`
            CommentPreview string `json:"comment_preview"`
            Vote string `json:"vote"`
            Title string `json:"title"`
            Section string `json:"section"`
            Favorite bool `json:"favorite"`
            Is_Album bool `json:"is_album"`
            Nsfw bool `json:"nsfw"`
             } `json:"data"`
}

Here is my function:

func parseJson(file string) {
      jsonFile, err := ioutil.ReadFile(file)
      if err != nil {
            ...
            }
      jsonParser := ImgurJson{}
      err = json.Unmarshal(jsonFile, &jsonParser)
      for field, value := range jsonParser.Data {
            fmt.Print("key: ", field, "\n")
            fmt.Print("value: ", value, "\n")
      }
}

How do I loop through a nested, []struct in Go and return the fields? I've seen several posts about reflection, but I don't understand if that would assist me or not. I can return the values of each field, but I don't understand how to map the field name to the key value.

Edit:

Renamed "keys" to "field", sorry! Didn't realise they were called fields.

I would like to be able to print:

field: Width
value: 1234

I would like to learn how to do this so I can later call a specific field by name so I can map it to a SQL column name.

Body:
You can also iterate using normal golang for loop on nested struct.

type ImgurJson struct {
      Status int16 `json:"status"`
      Success bool `json:"success"`
      Data []struct {
            Width int16 `json:"width"`
            Points int32 `json:"points"`
            CommentCount int32 `json:"comment_count"`
            TopicId int32 `json:"topic_id"`
            AccountId int32 `json:"account_id"`
            Ups int32 `json:"ups"`
            Downs int32 `json:"downs"`
            Bandwidth int64 `json:"bandwidth"`
            Datetime int64 `json:"datetime"`
            Score int64 `json:"score"`
            Account_Url string `json:"account_url"`
            Topic string `json:"topic"`
            Link string `json:"link"`
            Id string `json:"id"`
            Description string`json:"description"`
            CommentPreview string `json:"comment_preview"`
            Vote string `json:"vote"`
            Title string `json:"title"`
            Section string `json:"section"`
            Favorite bool `json:"favorite"`
            Is_Album bool `json:"is_album"`
            Nsfw bool `json:"nsfw"`
             } `json:"data"`
}

func parseJson(file string) {
      jsonFile, err := ioutil.ReadFile(file)
      if err != nil {
            ...
            }
      jsonParser := ImgurJson{}
      err = json.Unmarshal(jsonFile, &jsonParser)
      for i :=0; i<len(jsonParser.Data); i++ {
            fmt.Print("key: ", jsonParser.Data[i].TopicId, "\n")
      }
}


问:
Python escaping re.split treat backslash+symbol as another symbol
I have an input string which somehow remind the html code, but tags using the square brackets instead of angular.

The input string is:
str = r'Lorem ipsum [dolor] sit amet'
I process it with re.split using pattern
ptr = r'\[.*?\]'
to detect the tags. The result is a list
list = [r'Lorem ipsum ', r'[dolor]', r' sit amet']
The problem is that the two-symbol sequence \[ should mean [ symbol, not starting a tag.

re.split(r'\[.*?\]', r'Lorem \[ipsum\] \\[dolor] sit amet')
gives
[r'Lorem \', r'[ipsum\]', r' \\', r'[dolor]', r' sit amet']
while I want to get
[r'Lorem ipsum \[dolor\] \\', r'[dolor]', r' sit amet']

So what I want is to understand is how to say to re.split that two-symbol sequence \x is and escape sequence and should be treated asa single symbol?

答:
Thank you for your suggestions. Thank to them I found the solution I need.

To display the problem, let substitute the tags [atag] with <atag>. BUT, the sequence \[ should remain untouched, since it's "escaped". The backslash should be also "escaped", i.e. \\ remain untouched so that \\[ transforms into \\<. But, again, \\\[ remains \\\[. An so on.

The following code

```<code>import re

test_str = r"Lorem \[ipsum\] dolor [sit\]amet], consetetur [sadipscing\\] elitr, \\[sed] diam [nonumy]"

regex = r"(?P<prefix>[^\\](\\\\)*)\[(?P<expression>.*?[^\\](\\\\)*)\]"
subst = r"\g<prefix><\g<expression>>"

print (re.sub(regex, subst, test_str))
</code>```

results in

```<code>Lorem \[ipsum\] dolor <sit\]amet>, consetetur <sadipscing\\> elitr, \\<sed> diam <nonumy>
</code>```

As wished.

Hope this will help someone.

Body:
Thank you for your suggestions. Thank to them I found the solution I need.

To display the problem, let substitute the tags [atag] with <atag>. BUT, the sequence \[ should remain untouched, since it's "escaped". The backslash should be also "escaped", i.e. \\ remain untouched so that \\[ transforms into \\<. But, again, \\\[ remains \\\[. An so on.

The following code

import re

test_str = r"Lorem \[ipsum\] dolor [sit\]amet], consetetur [sadipscing\\] elitr, \\[sed] diam [nonumy]"

regex = r"(?P<prefix>[^\\](\\\\)*)\[(?P<expression>.*?[^\\](\\\\)*)\]"
subst = r"\g<prefix><\g<expression>>"

print (re.sub(regex, subst, test_str))

results in

Lorem \[ipsum\] dolor <sit\]amet>, consetetur <sadipscing\\> elitr, \\<sed> diam <nonumy>

As wished.

Hope this will help someone.


问:
Insert a form data to salesforce
I tried to insert form data from sitecore to salesforce using REST API.Here Below is my code sample.

```<code>  postAsync("https:///services/data/v45.0/composite/tree/Lead__c",JSon Data);

async static void postAsync(string url, JObject o)
        {
            using (HttpClient client = new HttpClient())
            {
                var param = Newtonsoft.Json.JsonConvert.SerializeObject(o);
                HttpContent contentPost = new StringContent(param, Encoding.UTF8, "application/json");

                using (HttpResponseMessage response = await client.PostAsync(string.Format(url), contentPost).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode()))
                {

                    if (response.IsSuccessStatusCode)
                    {
                        using (HttpContent content = response.Content)
                        {
                            string myContent = await content.ReadAsStringAsync();
                            HttpContentHeaders headers = content.Headers;
                            Console.WriteLine(myContent);
                            Console.WriteLine(headers);

                        }
                    }
                    else { Console.WriteLine("This is doing my head in!!!!!!!!!!"); }
                }
            }
        }
</code>```

It does not insert data to salesforce . Where I need to  use client security and security token ? How I insert data to salesforce ? Is this correct flow for inserting data to salesforce ?

答:
I see two issues here.

There is no authentication to Salesforce REST API. You are required to authenticate before calling Salesforce and must supply a Session Id received from the authentication process in the headers of your REST request.

Salesforce provides examples of authenticating in Java (but not C#) using the Web Server OAuth flow. The platform supports many OAuth flows and you'll need to determine which is the appropriate choice for your application. If you're doing server-to-server integration, Web Server or JWT is probably the right choice.

If you don't want to use OAuth - and you absolutely should - you can get a Session Id by making a login() call to the SOAP API instead. It's not recommended, though.

Once you have the Session Id, you'll include it as an Authentication: Bearer <Id> header.

The only way around authentication is exposing a custom Apex REST endpoint as part of a publicly-accessible Force.com Site. This is rarely a good design choice.

You're using the Composite Tree resources, which is likely more than you need to create a Lead record unless you are trying to add related records along with it. For simple record creation, just use the Record Create endpoint.

Title: Insert a form data to salesforce

Body:
I tried to insert form data from sitecore to salesforce using REST API.Here Below is my code sample.

  postAsync("https:///services/data/v45.0/composite/tree/Lead__c",JSon Data);

async static void postAsync(string url, JObject o)
        {
            using (HttpClient client = new HttpClient())
            {
                var param = Newtonsoft.Json.JsonConvert.SerializeObject(o);
                HttpContent contentPost = new StringContent(param, Encoding.UTF8, "application/json");

                using (HttpResponseMessage response = await client.PostAsync(string.Format(url), contentPost).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode()))
                {

                    if (response.IsSuccessStatusCode)
                    {
                        using (HttpContent content = response.Content)
                        {
                            string myContent = await content.ReadAsStringAsync();
                            HttpContentHeaders headers = content.Headers;
                            Console.WriteLine(myContent);
                            Console.WriteLine(headers);

                        }
                    }
                    else { Console.WriteLine("This is doing my head in!!!!!!!!!!"); }
                }
            }
        }

It does not insert data to salesforce . Where I need to  use client security and security token ? How I insert data to salesforce ? Is this correct flow for inserting data to salesforce ?


问:
What units to pass UI methods?
Reading the Supporting Multiple Screens of the Android developer guide it says it is always best to use density independent pixels (dp) instead of pixels and it also says Android handles most of the application rendering on different density devices.

Now my question is, if we look at the padding function of the View class

setPadding (int left, int top, int
  right, int bottom)

```<code>left     the left padding in pixels
top       the top padding in pixels
right   the right padding in pixels
bottom    the bottom padding in pixels
</code>```

When I use this function is it alright to pass direct values or do I have to pass converted values, from dp to px, to best show the UI in all devices?

答:
Convert your dip value to pixels and pad with that.</p>

```<code>final float scale = getContext().getResources().getDisplayMetrics().density;

int valuePixels = (int)(valueDip * scale);
</code>```

Title: What units to pass UI methods?

Body:
Reading the Supporting Multiple Screens of the Android developer guide it says it is always best to use density independent pixels (dp) instead of pixels and it also says Android handles most of the application rendering on different density devices.

Now my question is, if we look at the padding function of the View class

setPadding (int left, int top, int
  right, int bottom)

left     the left padding in pixels
top       the top padding in pixels
right   the right padding in pixels
bottom    the bottom padding in pixels

When I use this function is it alright to pass direct values or do I have to pass converted values, from dp to px, to best show the UI in all devices?

Body:
Convert your dip value to pixels and pad with that.

final float scale = getContext().getResources().getDisplayMetrics().density;

int valuePixels = (int)(valueDip * scale);


问:
Is it bad practice to use temporary variables to avoid typing?
I sometimes use temporary variables to shorten the identifiers:

```<code>private function doSomething() {
    $db = $this->currentDatabase;
    $db->callMethod1();
    $db->callMethod2();
    $db->callMethod3();
    $db->...
}
</code>```

Although this is a PHP example, I'm asking in general:

Is this bad practice? Are there any drawbacks?

答:
A getter will solve your problem:

```<code>private function doSomething() {
    getDB()->callMethod1();
    getDB()->callMethod2();
    getDB()->callMethod3();
}
</code>```

by clean code N.

ContentLicense: CC BY-SA 2.5

Body:
I sometimes use temporary variables to shorten the identifiers:

private function doSomething() {
    $db = $this->currentDatabase;
    $db->callMethod1();
    $db->callMethod2();
    $db->callMethod3();
    $db->...
}

Although this is a PHP example, I'm asking in general:

Is this bad practice? Are there any drawbacks?

Body:
A getter will solve your problem:

private function doSomething() {
    getDB()->callMethod1();
    getDB()->callMethod2();
    getDB()->callMethod3();
}

by clean code N.


问:
Dax Finding date based on Criteria calculated Column
I couldn't find an answer for my issue elsewhere, so trying my luck here.

I have sales table and my final result should determine if there were sales made for same person in specific period of time, for example within 7 business days. for example:

For ID 123 I have to flag it that sale for products A,B,C where within specified period.

For ID 1234 only sales of products A and B meet the criteria product C was sold in irrelevant time frame.

I've created a date table with indicators that determine for each date if the date is a working day, but i am struggling to calculate the relevant last working day

For example: I need that for 01/01/2019 i will get 10/01/2019 date, based on NUMOFDAYS and FinalWorkday = TRUE, which basically means that i have to count NUMOFDAYS times TRUE statement for each date and return corresponding date.

After that step done I think that it would be pretty easy for me to determine if the sale for a person was made in specific time frame.

If someone can give me direction for that much appreciated

Thank you in advance

答:
You could use a DateTable like this one:

I used the following DAX-expressions for the calculated columns:

```<code>nrDays = 7

isWorkDay = WEEKDAY('DateTable'[Date],2) < 6

rankWorkingDays =  RANKX ( FILTER ( DateTable, DateTable[isWorkDay] = TRUE () ),
    DateTable[Date] , , ASC )

LastWorkDay = LOOKUPVALUE ( DateTable[Date],
    DateTable[isWorkDay], TRUE (),
    DateTable[rankWorkingDays], DateTable[rankWorkingDays] + DateTable[nrDays])
</code>```

Body:
You could use a DateTable like this one:

I used the following DAX-expressions for the calculated columns:

nrDays = 7

isWorkDay = WEEKDAY('DateTable'[Date],2) < 6

rankWorkingDays =  RANKX ( FILTER ( DateTable, DateTable[isWorkDay] = TRUE () ),
    DateTable[Date] , , ASC )

LastWorkDay = LOOKUPVALUE ( DateTable[Date],
    DateTable[isWorkDay], TRUE (),
    DateTable[rankWorkingDays], DateTable[rankWorkingDays] + DateTable[nrDays])


问:
How to reverse query selection with subquery or pivoting
I have an SQL query as the following

```<code>SELECT Count(L.id) As Count, U.name As Name, L.action As Action
FROM tabel1 L LEFT JOIN tabel2 U ON L.uId = U.id
WHERE L.date >= '1/1/2018 12:00:00 AM' AND L.date <= '11/2/2019 12:00:00 AM' AND L.nId IN (18161, 18156, 4924, 18129, 18073, 18070, 18140, 2588, 18141, 18139, 18144, 18143, 18142, 6741, 16796, 3333, 6364, 6367, 6370, 6373, 17991, 7812, 11148, 7799, 11074)
group by U.name, L.action
ORDER BY U.name, L.action
</code>```

Its result as following

```<code>Count   Name        Action
--------------------------
24      User 1      Create
31      User 1      Edit
252     User 2      Create
48      User 2      Edit
257     User 3      Create
29      User 3      Edit
3       User 4      Create
216     User 5      Create
287     User 5      Edit
256     User 6      Edit
9       User 6      Create
1       User 6      Delete
101     User 7      Edit
</code>```

I need to get the result as following

```<code>Name      Create      Edit      Delete
--------------------------------------
User 1    24          31        0
User 2    252         48        0
User 3    257         29        0
User 4    3           0         0
User 5    216         287       0
User 6    256         9         1
User 7    0           101       0
</code>```

How can I achieve that?

答:
Just use conditional aggregation:

```<code>SELECT U.name As Name,
       SUM(CASE WHEN l.Action = 'Create' THEN 1 ELSE 0 END) as num_created,
       SUM(CASE WHEN l.Action = 'Edit' THEN 1 ELSE 0 END) as num_edited,
       SUM(CASE WHEN l.Action = 'Delete' THEN 1 ELSE 0 END) as num_deleted
FROM tabel1 L LEFT JOIN
     tabel2 U
     ON L.uId = U.id
WHERE L.date >= '2018-01-01' AND
      L.date <= '2019-02-11' AND
      L.nId IN (18161, 18156, 4924, 18129, 18073, 18070, 18140, 2588, 18141, 18139, 18144, 18143, 18142, 6741, 16796, 3333, 6364, 6367, 6370, 6373, 17991, 7812, 11148, 7799, 11074)
GROUP BY U.name
ORDER BY U.name;
</code>```

Note that I also simplified the date comparisons and introduces ISO standard formats.  However, I'm not sure if the later date is 2019-02-11 or 2019-11-02.

Body:
I have an SQL query as the following

SELECT Count(L.id) As Count, U.name As Name, L.action As Action
FROM tabel1 L LEFT JOIN tabel2 U ON L.uId = U.id
WHERE L.date >= '1/1/2018 12:00:00 AM' AND L.date <= '11/2/2019 12:00:00 AM' AND L.nId IN (18161, 18156, 4924, 18129, 18073, 18070, 18140, 2588, 18141, 18139, 18144, 18143, 18142, 6741, 16796, 3333, 6364, 6367, 6370, 6373, 17991, 7812, 11148, 7799, 11074)
group by U.name, L.action
ORDER BY U.name, L.action

Its result as following

Count   Name        Action
--------------------------
24      User 1      Create
31      User 1      Edit
252     User 2      Create
48      User 2      Edit
257     User 3      Create
29      User 3      Edit
3       User 4      Create
216     User 5      Create
287     User 5      Edit
256     User 6      Edit
9       User 6      Create
1       User 6      Delete
101     User 7      Edit

I need to get the result as following

Name      Create      Edit      Delete
--------------------------------------
User 1    24          31        0
User 2    252         48        0
User 3    257         29        0
User 4    3           0         0
User 5    216         287       0
User 6    256         9         1
User 7    0           101       0

How can I achieve that?

Body:
Just use conditional aggregation:

SELECT U.name As Name,
       SUM(CASE WHEN l.Action = 'Create' THEN 1 ELSE 0 END) as num_created,
       SUM(CASE WHEN l.Action = 'Edit' THEN 1 ELSE 0 END) as num_edited,
       SUM(CASE WHEN l.Action = 'Delete' THEN 1 ELSE 0 END) as num_deleted
FROM tabel1 L LEFT JOIN
     tabel2 U
     ON L.uId = U.id
WHERE L.date >= '2018-01-01' AND
      L.date <= '2019-02-11' AND
      L.nId IN (18161, 18156, 4924, 18129, 18073, 18070, 18140, 2588, 18141, 18139, 18144, 18143, 18142, 6741, 16796, 3333, 6364, 6367, 6370, 6373, 17991, 7812, 11148, 7799, 11074)
GROUP BY U.name
ORDER BY U.name;

Note that I also simplified the date comparisons and introduces ISO standard formats.  However, I'm not sure if the later date is 2019-02-11 or 2019-11-02.


问:
webpack-cli can't find webpack module
i have installed webpack globally and when i run webpack it says

```<code>One CLI for webpack must be installed. These are recommended choices, delivered as separate packages:
 - webpack-cli (https://github.com/webpack/webpack-cli)
   The original webpack full-featured CLI.
We will use "npm" to install the CLI via "npm install -D".
Do you want to install 'webpack-cli' (yes/no):
</code>```

and I say yes, the webpack-cli seems to be installed correctly but i got an error message that says

```<code>{ Error: Cannot find module 'webpack'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (C:\Users\TOSHIBA\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
    at Object.<anonymous> (C:\Users\TOSHIBA\node_modules\webpack-cli\bin\convert-argv.js:7:24)
    at Module._compile (C:\Users\TOSHIBA\node_modules\v8-compile-cache\v8-compile-cache.js:178:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at yargs.parse (C:\Users\TOSHIBA\node_modules\webpack-cli\bin\cli.js:228:14)
    at Object.parse (C:\Users\TOSHIBA\node_modules\yargs\yargs.js:567:18)
    at C:\Users\TOSHIBA\node_modules\webpack-cli\bin\cli.js:206:8
    at Object.<anonymous> (C:\Users\TOSHIBA\node_modules\webpack-cli\bin\cli.js:505:3)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at runCommand.then (C:\Users\TOSHIBA\AppData\Roaming\npm\node_modules\webpack\bin\webpack.js:143:5)
    at process._tickCallback (internal/process/next_tick.js:68:7) code: 'MODULE_NOT_FOUND' }
</code>```

what is possibility goes wrong?

答: Try to npm link webpack-cli to Link Globally installed package of your project

Title: webpack-cli can't find webpack module

Body:
i have installed webpack globally and when i run webpack it says

One CLI for webpack must be installed. These are recommended choices, delivered as separate packages:
 - webpack-cli (https://github.com/webpack/webpack-cli)
   The original webpack full-featured CLI.
We will use "npm" to install the CLI via "npm install -D".
Do you want to install 'webpack-cli' (yes/no):

and I say yes, the webpack-cli seems to be installed correctly but i got an error message that says

{ Error: Cannot find module 'webpack'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:582:15)
    at Function.Module._load (internal/modules/cjs/loader.js:508:25)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (C:\Users\TOSHIBA\node_modules\v8-compile-cache\v8-compile-cache.js:159:20)
    at Object.<anonymous> (C:\Users\TOSHIBA\node_modules\webpack-cli\bin\convert-argv.js:7:24)
    at Module._compile (C:\Users\TOSHIBA\node_modules\v8-compile-cache\v8-compile-cache.js:178:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at yargs.parse (C:\Users\TOSHIBA\node_modules\webpack-cli\bin\cli.js:228:14)
    at Object.parse (C:\Users\TOSHIBA\node_modules\yargs\yargs.js:567:18)
    at C:\Users\TOSHIBA\node_modules\webpack-cli\bin\cli.js:206:8
    at Object.<anonymous> (C:\Users\TOSHIBA\node_modules\webpack-cli\bin\cli.js:505:3)
    at Module._compile (internal/modules/cjs/loader.js:701:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
    at Module.load (internal/modules/cjs/loader.js:600:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
    at Function.Module._load (internal/modules/cjs/loader.js:531:3)
    at Module.require (internal/modules/cjs/loader.js:637:17)
    at require (internal/modules/cjs/helpers.js:22:18)
    at runCommand.then (C:\Users\TOSHIBA\AppData\Roaming\npm\node_modules\webpack\bin\webpack.js:143:5)
    at process._tickCallback (internal/process/next_tick.js:68:7) code: 'MODULE_NOT_FOUND' }

what is possibility goes wrong?