问:
Convert a list of data frames into a single data frame with list name
I am hoping to determine an efficient way to convert a list of data frames into a single data frame. Below is my reproducible MWE:

```<code>set.seed(1)
ABAge = runif(100)
ABPoints = rnorm(100)
ACAge = runif(100)
ACPoints = rnorm(100)
BCAge = runif(100)
BCPoints = rnorm(100)

A_B <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ABAge, Points = ABPoints)
A_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ACAge, Points = ACPoints)
B_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = BCAge, Points = BCPoints)
A_B$ID <- as.character(A_B$ID)
A_C$ID <- as.character(A_C$ID)
B_C$ID <- as.character(B_C$ID)

listFormat <- list("A_B" = A_B, "A_C" = A_C, "B_C" = B_C)

dfFormat <- data.frame(ID = as.character(paste0("ID", 1:100)), A_B.Age = ABAge, A_B.Points = ABPoints, A_C.Age = ACAge, A_C.Points = ACPoints, B_C.Age = BCAge, B_C.Points = BCPoints)
dfFormat$ID = as.character(dfFormat$ID)
</code>```

This results in a data frame format (dfFormat) that looks like this:

```<code>'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.266 0.372 0.573 0.908 0.202 ...
 $ A_B.Points: num  0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C.Age   : num  0.6737 0.0949 0.4926 0.4616 0.3752 ...
 $ A_C.Points: num  0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C.Age   : num  0.814 0.929 0.147 0.75 0.976 ...
 $ B_C.Points: num  1.474 0.677 0.38 -0.193 1.578 ...
</code>```

and a list of data frames listFormat that looks like this:

```<code>List of 3
 $ A_B:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.266 0.372 0.573 0.908 0.202 ...
  ..$ Points: num [1:100] 0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.6737 0.0949 0.4926 0.4616 0.3752 ...
  ..$ Points: num [1:100] 0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.814 0.929 0.147 0.75 0.976 ...
  ..$ Points: num [1:100] 1.474 0.677 0.38 -0.193 1.578 ...
</code>```

I am hoping to come up with an automated way to convert the dfFormat to listFormat. As can be seen in the above objects there are two main conditions:

1) If there is a common column (name and contents) in each sublist of listFormat (in these examples ID), then they are not repeated in the outputted dfFormat (in this example, it has one final ID column),

2) The rest of the column names in sublists of listFormat become columns in dfFormat and have names such that they retain their sublist name (i.e "A_B") followed by a dot and then their original column name (i.e. Age), so that it becomes (i.e. "A_B.Age") in the dfFormat.

I have tried various unlist() and sapply codes but have been unsuccessful thus far. What is an efficient way to accomplish this?

Body:
I am hoping to determine an efficient way to convert a list of data frames into a single data frame. Below is my reproducible MWE:

set.seed(1)
ABAge = runif(100)
ABPoints = rnorm(100)
ACAge = runif(100)
ACPoints = rnorm(100)
BCAge = runif(100)
BCPoints = rnorm(100)

A_B <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ABAge, Points = ABPoints)
A_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ACAge, Points = ACPoints)
B_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = BCAge, Points = BCPoints)
A_B$ID <- as.character(A_B$ID)
A_C$ID <- as.character(A_C$ID)
B_C$ID <- as.character(B_C$ID)

listFormat <- list("A_B" = A_B, "A_C" = A_C, "B_C" = B_C)

dfFormat <- data.frame(ID = as.character(paste0("ID", 1:100)), A_B.Age = ABAge, A_B.Points = ABPoints, A_C.Age = ACAge, A_C.Points = ACPoints, B_C.Age = BCAge, B_C.Points = BCPoints)
dfFormat$ID = as.character(dfFormat$ID)

This results in a data frame format (dfFormat) that looks like this:

'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.266 0.372 0.573 0.908 0.202 ...
 $ A_B.Points: num  0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C.Age   : num  0.6737 0.0949 0.4926 0.4616 0.3752 ...
 $ A_C.Points: num  0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C.Age   : num  0.814 0.929 0.147 0.75 0.976 ...
 $ B_C.Points: num  1.474 0.677 0.38 -0.193 1.578 ...

and a list of data frames listFormat that looks like this:

List of 3
 $ A_B:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.266 0.372 0.573 0.908 0.202 ...
  ..$ Points: num [1:100] 0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.6737 0.0949 0.4926 0.4616 0.3752 ...
  ..$ Points: num [1:100] 0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.814 0.929 0.147 0.75 0.976 ...
  ..$ Points: num [1:100] 1.474 0.677 0.38 -0.193 1.578 ...

I am hoping to come up with an automated way to convert the dfFormat to listFormat. As can be seen in the above objects there are two main conditions:

1) If there is a common column (name and contents) in each sublist of listFormat (in these examples ID), then they are not repeated in the outputted dfFormat (in this example, it has one final ID column),

2) The rest of the column names in sublists of listFormat become columns in dfFormat and have names such that they retain their sublist name (i.e "A_B") followed by a dot and then their original column name (i.e. Age), so that it becomes (i.e. "A_B.Age") in the dfFormat.

I have tried various unlist() and sapply codes but have been unsuccessful thus far. What is an efficient way to accomplish this?

Body:
One purrr and dplyr option could be:

imap(listFormat, ~ setNames(.x, paste(rep(.y, length(.x)), names(.x), sep = ".")) %>%
      rename_at(vars(ends_with("ID")), ~ "ID")) %>%
 reduce(full_join, by = "ID")

       ID    A_B.Age   A_B.Points    A_C.Age   A_C.Points    B_C.Age   B_C.Points
1     ID1 0.26550866  0.398105880 0.67371223  0.409401840 0.81425175  1.473881181
2     ID2 0.37212390 -0.612026393 0.09485786  1.688873286 0.92877723  0.677268492
3     ID3 0.57285336  0.341119691 0.49259612  1.586588433 0.14748105  0.379962687
4     ID4 0.90820779 -1.129363096 0.46155184 -0.330907801 0.74982166 -0.192798426
5     ID5 0.20168193  1.433023702 0.37521653 -2.285235535 0.97565735  1.577891795
6     ID6 0.89838968  1.980399899 0.99109922  2.497661590 0.97479246  0.596234109
7     ID7 0.94467527 -0.367221476 0.17635071  0.667066167 0.35062557 -1.173576941
8     ID8 0.66079779 -1.044134626 0.81343521  0.541327336 0.39394906 -0.155642535
9     ID9 0.62911404  0.569719627 0.06844664 -0.013399523 0.95095101 -1.918909820
10   ID10 0.06178627 -0.135054604 0.40044975  0.510108423 0.10664832 -0.195258846


来源: stackexchange

问:
Replace only specified occurrences of string - Python Regex
I am playing around with re module in python, what i am stuck at is I want to replace only specified occurrences of the string.
for example

import re
string = "aabbaabbaabbabbaabbaa"
#I want to replace only 3rd time 'bb' appeared in the string with white space
string = re.sub("bb"," ",string,3)   #if iI do this all first 3 occurrences got replaced
print(string)
```

<p><strong>output</strong></p>

```aa aa aa aabbaabbaa
```

<p>any idea how to to replace only 3rd occurrence<br>
so the output would look like <strong>This</strong>  </p>

```aabbaabbaa aabbaabbaa
```

答:
Modify the regex so it only matches the third occurrence?

```<code>re.sub(r'(.*?bb.*?bb.*?)bb', r'\1 ', string, 1)
</code>```

This could be extended to a large number of repetitions like r'(.*?(bb.*?){9999})bb'

ContentLicense: CC BY-SA 4.0

Body:
I am playing around with re module in python, what i am stuck at is I want to replace only specified occurrences of the string.
for example

import re
string = "aabbaabbaabbabbaabbaa"
#I want to replace only 3rd time 'bb' appeared in the string with white space
string = re.sub("bb"," ",string,3)   #if iI do this all first 3 occurrences got replaced
print(string)

output

aa aa aa aabbaabbaa

any idea how to to replace only 3rd occurrence

so the output would look like This

aabbaabbaa aabbaabbaa

Body:
Modify the regex so it only matches the third occurrence?

re.sub(r'(.*?bb.*?bb.*?)bb', r'\1 ', string, 1)

This could be extended to a large number of repetitions like r'(.*?(bb.*?){9999})bb'


问:
Vector erase iterator
I have this code:

```<code>int main()
{
    vector<int> res;
    res.push_back(1);
    vector<int>::iterator it = res.begin();
    for( ; it != res.end(); it++)
    {
        it = res.erase(it);
        //if(it == res.end())
        //  return 0;
    }
}
</code>```

"A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which is the vector end if the operation erased the last element in the sequence."

This code crashes, but if I use the if(it == res.end()) portion and then return, it works. How come? Does the for loop cache the res.end() so the not equal operator fails?

答:
Something that you can do with modern C++ is using "std::remove_if" and lambda expression;

This code will remove "3" of the vector

```<code>vector<int> vec {1,2,3,4,5,6};

vec.erase(std::remove_if(begin(vec),end(vec),[](int elem){return (elem == 3);}), end(vec));
</code>```

Title: Vector erase iterator

Body:
I have this code:

int main()
{
    vector<int> res;
    res.push_back(1);
    vector<int>::iterator it = res.begin();
    for( ; it != res.end(); it++)
    {
        it = res.erase(it);
        //if(it == res.end())
        //  return 0;
    }
}

"A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which is the vector end if the operation erased the last element in the sequence."

This code crashes, but if I use the if(it == res.end()) portion and then return, it works. How come? Does the for loop cache the res.end() so the not equal operator fails?

Body:
Something that you can do with modern C++ is using "std::remove_if" and lambda expression;

This code will remove "3" of the vector

vector<int> vec {1,2,3,4,5,6};

vec.erase(std::remove_if(begin(vec),end(vec),[](int elem){return (elem == 3);}), end(vec));


问:
Roboto 'Thin' with Google Fonts
So I'm trying to get Roboto Thin working in my CSS through Google Fonts

```<code><link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:bold&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:thin&display=swap" rel="stylesheet">
</code>```

I can get the normal Roboto working just fine, but not when I try to specify the thin weight like so:

```<code>body {
    font: 16px/21px Roboto, "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
}

h1, h2, h3, h4, h5, h6 {
    font-weight: thin;
}
</code>```

It just gives me the regular weight... can anyone see what I'm doing wrong?

答: thin is not a valid keyword for font-weight. According to Google Fonts (when you select "Roboto" and then look at the "customize" list of weights) Thin corresponds to a weight of 100

Title: Roboto 'Thin' with Google Fonts

Body:
So I'm trying to get Roboto Thin working in my CSS through Google Fonts

<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:bold&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto:thin&display=swap" rel="stylesheet">

I can get the normal Roboto working just fine, but not when I try to specify the thin weight like so:

body {
    font: 16px/21px Roboto, "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
}

h1, h2, h3, h4, h5, h6 {
    font-weight: thin;
}

It just gives me the regular weight... can anyone see what I'm doing wrong?


问:
"No local user being mapped error" when using unspecified NameId format" in OpenAM SAML2
We Use OpenAM version 13.0.0

and we faced the following error during using urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified

ERROR: spAssertionConsumer.jsp: SSO failed. com.sun.identity.saml2.common.SAML2Exception: No local user being mapped. at com.sun.identity.saml2.profile.SPACSUtils.processResponse(SPACSUtils.java:1225) at org.apache.jsp.saml2.jsp.spAssertionConsumer_jsp._jspService(spAssertionConsumer_jsp.java:284) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)

答:
The hosted SP first uses the NameID map to extract the 'username' from the Subject (that holds the NameID) of the incoming SAML assertion and then use it to search the configured user data stores for an user identity subject (using the configured user search attribute). If this fails, it uses the configured account mapper to extract a 'username' attribute from the attribute statement. Here auto-federation configuration also matters.

--> It depends on the SAML response and OpenAM configuration why you run into this error. It's impossible to tell the root cause without seeing the SAML response and the OpenAM configuration. You may send it to me via (encrypted) email.


问:
com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
I am very new to the microservices and trying to run the code from link: https://dzone.com/articles/advanced-microservices-security-with-spring-and-oa . When I simply run the code I see the following error comes.

What is the issue ?

```<code>com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
    at com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient.execute(RetryableEurekaHttpClient.java:111) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.getApplications(EurekaHttpClientDecorator.java:134) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$6.execute(EurekaHttpClientDecorator.java:137) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient.execute(SessionedEurekaHttpClient.java:77) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.getApplications(EurekaHttpClientDecorator.java:134) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.DiscoveryClient.getAndStoreFullRegistry(DiscoveryClient.java:1030) [eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.DiscoveryClient.fetchRegistry(DiscoveryClient.java:944) [eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.DiscoveryClient.refreshRegistry(DiscoveryClient.java:1468) [eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.DiscoveryClient$CacheRefreshThread.run(DiscoveryClient.java:1435) [eureka-client-1.4.12.jar:1.4.12]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [na:1.8.0_144]
    at java.util.concurrent.FutureTask.run(Unknown Source) [na:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_144]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_144]

2017-09-09 18:53:11.909 ERROR 16268 --- [tbeatExecutor-0] c.n.d.s.t.d.RedirectingEurekaHttpClient  : Request execution error
</code>```

I have not installed anything special on to the system. Please let me know what do I need to install?

答:
Check your URL and port number of eureka server
 provided in "eureka.client.serviceUrl.defaultZone" property.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am very new to the microservices and trying to run the code from link: https://dzone.com/articles/advanced-microservices-security-with-spring-and-oa . When I simply run the code I see the following error comes.

What is the issue ?

com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
    at com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient.execute(RetryableEurekaHttpClient.java:111) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.getApplications(EurekaHttpClientDecorator.java:134) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$6.execute(EurekaHttpClientDecorator.java:137) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient.execute(SessionedEurekaHttpClient.java:77) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.getApplications(EurekaHttpClientDecorator.java:134) ~[eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.DiscoveryClient.getAndStoreFullRegistry(DiscoveryClient.java:1030) [eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.DiscoveryClient.fetchRegistry(DiscoveryClient.java:944) [eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.DiscoveryClient.refreshRegistry(DiscoveryClient.java:1468) [eureka-client-1.4.12.jar:1.4.12]
    at com.netflix.discovery.DiscoveryClient$CacheRefreshThread.run(DiscoveryClient.java:1435) [eureka-client-1.4.12.jar:1.4.12]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [na:1.8.0_144]
    at java.util.concurrent.FutureTask.run(Unknown Source) [na:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_144]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_144]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_144]

2017-09-09 18:53:11.909 ERROR 16268 --- [tbeatExecutor-0] c.n.d.s.t.d.RedirectingEurekaHttpClient  : Request execution error

I have not installed anything special on to the system. Please let me know what do I need to install?


问:
Vuejs: Passing SAVE function into CRUD component
I am struggeling with a proper solution which requires an advanced parent-child communication in vuejs. There can be many different parent components which has a logic how to save data. From the other side there will be only one child component which has a list of elements and a form to create new elements but it doesn't know how to save the data.

The question is: Is there any other way (better approach) to have the same functionality but to get rid of this.$refs.child links. For example I am wondering if I can just pass a function (SaveParent1(...) or SaveParent2(...)) to the child component. But the problem is the function contains some parent's variables which won't be available in child context and those variables could be changed during the runtime.

Just few clarifications:

The methods SaveParent1 and SaveParent2 in real life return
Promise (axios).

The child-component is like a CRUD which is used
everywhere else.

At the moment the communication looks like that: CHILD -event-> PARENT -ref-> CHILD.

Bellow is the example:

```<code><div id="app">
  <h2>😀Advanced Parent-Child Communication:</h2>
  <parent-component1 param1="ABC"></parent-component1>
  <parent-component2 param2="XYZ"></parent-component2>
</div>
</code>```

```<code>Vue.component('parent-component1', {
  props: { param1: { type: String, required: true } },
  methods: {
    onChildSubmit(p) {
        // Here will be some logic to save the param. Many different parents might have different logic and all of them use the same child component. So child-component contains list, form and validation message but does not know how to save the param to the database.
      var error = SaveParent1({ form: { p: p, param1: this.param1 } });
      if (error)
        this.$refs.child.paramFailed(error);
      else
        this.$refs.child.paramAdded(p);
    }
  },
  template: `<div class="parent"><p>Here is parent ONE:</p><child-component ref="child" @submit="onChildSubmit"></child-component></div>`
});

Vue.component('parent-component2', {
  props: { param2: { type: String, required: true } },
  methods: {
    onChildSubmit(p) {
        // Here is a different logic to save the param. In prictice it is gonna be different requests to the server.
      var error = SaveParent2({ form: { p: p, param2: this.param2 } });
      if (error)
        this.$refs.child.paramFailed(error);
      else
        this.$refs.child.paramAdded(p);
    }
  },
  template: `<div class="parent"><p>Here is parent TWO:</p><child-component ref="child" @submit="onChildSubmit"></child-component></div>`
});

Vue.component('child-component', {
  data() {
    return {
      currentParam: "",
      allParams: [],
      errorMessage: ""
    }
  },
  methods: {
    submit() {
        this.errorMessage = "";
        this.$emit('submit', this.currentParam);
    },
    paramAdded(p) {
        this.currentParam = "";
        this.allParams.push(p);
    },
    paramFailed(msg) {
        this.errorMessage = msg;
    }
  },
  template: `<div><ol><li v-for="p in allParams">{{p}}</li></ol><label>Add Param: <input v-model="currentParam"></label><button @click="submit" :disabled="!currentParam">Submit</button><p class="error">{{errorMessage}}</p></div>`
});

function SaveParent1(data) {
  // Axios API to save data. Bellow is a simulation.
  if (Math.random() > 0.5)
    return null;
  else
    return 'Parent1: You are not lucky today';
}

function SaveParent2(data) {
  // Axios API to save data. Bellow is a simulation.
  if (Math.random() > 0.5)
    return null;
  else
    return 'Parent2: You are not lucky today';
}

new Vue({
  el: "#app"
});
</code>```

There is also a live demo available: https://jsfiddle.net/FairKing/novdmcxp/

答:
I think I have found a solution. So no two ways communication. I can just pass a method and the child will do everything without communicating with parent. I am happy with that I am marking it as an answer. Thanks everyone for your help.

Let me please know what do you think guys.

Bellow is my solution:

```<code><div id="app">
  <h2>😀Advanced Parent-Child Communication:</h2>
  <parent-component1 param1="ABC"></parent-component1>
  <parent-component2 param2="XYZ"></parent-component2>
</div>
</code>```

```<code>Vue.component('parent-component1', {
    props: { param1: { type: String, required: true } },
  computed: {
    saveFunc() {
        return function(p) { SaveParent1({ form: { p: p, param1: this.param1 } }); }.bind(this);
    }
  },
  template: `<div class="parent"><p>Here is parent ONE:</p><child-component :saveFunc="saveFunc"></child-component></div>`
});

Vue.component('parent-component2', {
    props: { param2: { type: String, required: true } },
  computed: {
    saveFunc() {
        return function(p) { SaveParent2({ form: { p: p, param2: this.param2 } }); }.bind(this);
    }
  },
  template: `<div class="parent"><p>Here is parent TWO:</p><child-component :saveFunc="saveFunc"></child-component></div>`
});

Vue.component('child-component', {
    props: {
    saveFunc: { type: Function, required: true }, // This is gonna be a Promise in real life.
  },
  data() {
    return {
      currentParam: "",
      allParams: [],
      errorMessage: ""
    }
  },
  methods: {
    submit() {
        this.errorMessage = "";
      var error = this.saveFunc(this.currentParam);
      if (error)
        this.paramFailed(error);
      else
        this.paramAdded(this.currentParam);
    },
    paramAdded(p) {
        this.currentParam = "";
        this.allParams.push(p);
    },
    paramFailed(msg) {
        this.errorMessage = msg;
    }
  },
  template: `<div><ol><li v-for="p in allParams">{{p}}</li></ol><label>Add Param: <input v-model="currentParam"></label><button @click="submit" :disabled="!currentParam">Submit</button><p class="error">{{errorMessage}}</p></div>`
});

function SaveParent1(data) {
    console.log(data);
    // Axios API to save data
    if (Math.random() > 0.5)
    return null;
  else
    return 'Parent1: You are not lucky today';
}

function SaveParent2(data) {
    console.log(data);
    // Axios API to save data
    if (Math.random() > 0.5)
    return null;
  else
    return 'Parent2: You are not lucky today';
}

new Vue({
  el: "#app"
});
</code>```

The demo link: https://jsfiddle.net/FairKing/novdmcxp/126/

Body:
I am struggeling with a proper solution which requires an advanced parent-child communication in vuejs. There can be many different parent components which has a logic how to save data. From the other side there will be only one child component which has a list of elements and a form to create new elements but it doesn't know how to save the data.

The question is: Is there any other way (better approach) to have the same functionality but to get rid of this.$refs.child links. For example I am wondering if I can just pass a function (SaveParent1(...) or SaveParent2(...)) to the child component. But the problem is the function contains some parent's variables which won't be available in child context and those variables could be changed during the runtime.

Just few clarifications:

The methods SaveParent1 and SaveParent2 in real life return
Promise (axios).

The child-component is like a CRUD which is used
everywhere else.

At the moment the communication looks like that: CHILD -event-> PARENT -ref-> CHILD.

Bellow is the example:

😀Advanced Parent-Child Communication:

  <parent-component1 param1="ABC"></parent-component1>
  <parent-component2 param2="XYZ"></parent-component2>

Vue.component('parent-component1', {
  props: { param1: { type: String, required: true } },
  methods: {
    onChildSubmit(p) {
        // Here will be some logic to save the param. Many different parents might have different logic and all of them use the same child component. So child-component contains list, form and validation message but does not know how to save the param to the database.
      var error = SaveParent1({ form: { p: p, param1: this.param1 } });
      if (error)
        this.$refs.child.paramFailed(error);
      else
        this.$refs.child.paramAdded(p);
    }
  },
  template: `<div class="parent"><p>Here is parent ONE:</p><child-component ref="child" @submit="onChildSubmit"></child-component></div>`
});

Vue.component('parent-component2', {
  props: { param2: { type: String, required: true } },
  methods: {
    onChildSubmit(p) {
        // Here is a different logic to save the param. In prictice it is gonna be different requests to the server.
      var error = SaveParent2({ form: { p: p, param2: this.param2 } });
      if (error)
        this.$refs.child.paramFailed(error);
      else
        this.$refs.child.paramAdded(p);
    }
  },
  template: `<div class="parent"><p>Here is parent TWO:</p><child-component ref="child" @submit="onChildSubmit"></child-component></div>`
});

Vue.component('child-component', {
  data() {
    return {
      currentParam: "",
      allParams: [],
      errorMessage: ""
    }
  },
  methods: {
    submit() {
        this.errorMessage = "";
        this.$emit('submit', this.currentParam);
    },
    paramAdded(p) {
        this.currentParam = "";
        this.allParams.push(p);
    },
    paramFailed(msg) {
        this.errorMessage = msg;
    }
  },
  template: `

{{p}}

Add Param: <input v-model="currentParam"><button @click="submit" :disabled="!currentParam">Submit</button>
{{errorMessage}}

`
});

function SaveParent1(data) {
  // Axios API to save data. Bellow is a simulation.
  if (Math.random() > 0.5)
    return null;
  else
    return 'Parent1: You are not lucky today';
}

function SaveParent2(data) {
  // Axios API to save data. Bellow is a simulation.
  if (Math.random() > 0.5)
    return null;
  else
    return 'Parent2: You are not lucky today';
}

new Vue({
  el: "#app"
});

There is also a live demo available: https://jsfiddle.net/FairKing/novdmcxp/

Body:
I think I have found a solution. So no two ways communication. I can just pass a method and the child will do everything without communicating with parent. I am happy with that I am marking it as an answer. Thanks everyone for your help.

Let me please know what do you think guys.

Bellow is my solution:

<div id="app">
  <h2>&#128512;Advanced Parent-Child Communication:</h2>
  <parent-component1 param1="ABC"></parent-component1>
  <parent-component2 param2="XYZ"></parent-component2>
</div>

Vue.component('parent-component1', {
    props: { param1: { type: String, required: true } },
  computed: {
    saveFunc() {
        return function(p) { SaveParent1({ form: { p: p, param1: this.param1 } }); }.bind(this);
    }
  },
  template: `<div class="parent"><p>Here is parent ONE:</p><child-component :saveFunc="saveFunc"></child-component></div>`
});

Vue.component('parent-component2', {
    props: { param2: { type: String, required: true } },
  computed: {
    saveFunc() {
        return function(p) { SaveParent2({ form: { p: p, param2: this.param2 } }); }.bind(this);
    }
  },
  template: `<div class="parent"><p>Here is parent TWO:</p><child-component :saveFunc="saveFunc"></child-component></div>`
});

Vue.component('child-component', {
    props: {
    saveFunc: { type: Function, required: true }, // This is gonna be a Promise in real life.
  },
  data() {
    return {
      currentParam: "",
      allParams: [],
      errorMessage: ""
    }
  },
  methods: {
    submit() {
        this.errorMessage = "";
      var error = this.saveFunc(this.currentParam);
      if (error)
        this.paramFailed(error);
      else
        this.paramAdded(this.currentParam);
    },
    paramAdded(p) {
        this.currentParam = "";
        this.allParams.push(p);
    },
    paramFailed(msg) {
        this.errorMessage = msg;
    }
  },
  template: `<div><ol><li v-for="p in allParams">{{p}}</li></ol><label>Add Param: <input v-model="currentParam"></label><button @click="submit" :disabled="!currentParam">Submit</button><p class="error">{{errorMessage}}</p></div>`
});

function SaveParent1(data) {
    console.log(data);
    // Axios API to save data
    if (Math.random() > 0.5)
    return null;
  else
    return 'Parent1: You are not lucky today';
}

function SaveParent2(data) {
    console.log(data);
    // Axios API to save data
    if (Math.random() > 0.5)
    return null;
  else
    return 'Parent2: You are not lucky today';
}

new Vue({
  el: "#app"
});

The demo link: https://jsfiddle.net/FairKing/novdmcxp/126/


问:
Django data hierarchy question
I am new to Django and I am trying to build a data hierarchy that follows this pattern:

There will be several Communities - say Huntsville, Phoenix, and Madison.

Each of those communities will be able to have several distinct Categories. For example, Huntsville may have Hunting, fishing, and skiing - and Phoenix may have running, biking, and swimming.  Then each of the particular categories will have a number of distinct detail views.  I tried to make this happen with:

```<code>from django.db import models

class Community(models.Model):
    name = models.CharField(max_length=200) #arbitrary max length

class Category(models.Model):
    community = models.ForeignKey(Community)
    category = models.CharField(max_length=200) #arbitrary max length

class Detail_View(models.Model):
    category = models.ForeignKey(Category)
    detailView = models.CharField(max_length=200) #arbitrary max length
    website = models.CharField(max_length=200) #arbitrary max length
</code>```

but it doesn't really seem to be working the correctly and I can't quite figure out why.

Any thoughts?

答:
I'm not sure I fully understand the behavior you're looking for, but I have some advice anyway.

First, it looks like you're implementing a one-to-many when you really want a many-to-many.

Check out http://docs.djangoproject.com/en/1.3/ref/models/relations/

Per that link, use models.ManyToManyField instead of models.ForeignKey

Also if you meant to define this as a one-to-many, you probably don't want Category to reference Community.  Use the phrase "has a" or "has many" to determine this.  Since a Community "has a" Category, the ForeignKey (or ManyToManyField) should be defined on the Community model, not the Category one.

I'd strongly recommend taking a look at the freely available Django Book project, especially the chapter on Advanced Models

Hope this helps!

Title: Django data hierarchy question

Body:
I am new to Django and I am trying to build a data hierarchy that follows this pattern:

There will be several Communities - say Huntsville, Phoenix, and Madison.

Each of those communities will be able to have several distinct Categories. For example, Huntsville may have Hunting, fishing, and skiing - and Phoenix may have running, biking, and swimming.  Then each of the particular categories will have a number of distinct detail views.  I tried to make this happen with:

from django.db import models

class Community(models.Model):
    name = models.CharField(max_length=200) #arbitrary max length

class Category(models.Model):
    community = models.ForeignKey(Community)
    category = models.CharField(max_length=200) #arbitrary max length

class Detail_View(models.Model):
    category = models.ForeignKey(Category)
    detailView = models.CharField(max_length=200) #arbitrary max length
    website = models.CharField(max_length=200) #arbitrary max length

but it doesn't really seem to be working the correctly and I can't quite figure out why.

Any thoughts?


问:
chrome extension WebSocket connection to 'ws://localhost:9090/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I am trying to build a chrome new tab extension, everything is smooth so far and working great but i keep getting this error sometimes on extension page WebSocket connection to 'ws://localhost:9090/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
 and when it happens i will have to reload the extension or rebuild it again for it to stop.
I don't user websocket at all(i guess) i only make couple of request using axios.
here is my manifest

```<code>{
  "name": "kura-new-tab",
  "description": "An elegant new tab browser extension made with vue.",
  "version": 1.0,
  "manifest_version": 2,
  "icons": {
    "48": "icons/icon_48.png",
    "128": "icons/icon_128.png"
  },
  "author": "AmrBinBashir",
  "browser_action": {
    "default_title": "kura-new-tab"
  },
  "chrome_url_overrides": {
    "newtab": "index.html"
  },
  "background": {
    "presistent": false,
    "scripts": ["background.js"]
  },
  "permissions": ["background", "storage", "https://*.bing.com/*", "https://*.unsplash.com/*", "tabs"]
}
</code>```

here is an img of the error

答: The problem was i build the extension in development mode rather than production mode</p>

Body:
I am trying to build a chrome new tab extension, everything is smooth so far and working great but i keep getting this error sometimes on extension page WebSocket connection to 'ws://localhost:9090/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
 and when it happens i will have to reload the extension or rebuild it again for it to stop.
I don't user websocket at all(i guess) i only make couple of request using axios.
here is my manifest

{
  "name": "kura-new-tab",
  "description": "An elegant new tab browser extension made with vue.",
  "version": 1.0,
  "manifest_version": 2,
  "icons": {
    "48": "icons/icon_48.png",
    "128": "icons/icon_128.png"
  },
  "author": "AmrBinBashir",
  "browser_action": {
    "default_title": "kura-new-tab"
  },
  "chrome_url_overrides": {
    "newtab": "index.html"
  },
  "background": {
    "presistent": false,
    "scripts": ["background.js"]
  },
  "permissions": ["background", "storage", "https://*.bing.com/*", "https://*.unsplash.com/*", "tabs"]
}

here is an img of the error


问:
Changing the name of major to aliasName
everyone, I am trying to write code  that checks if there is alias name show it and if there is not then show the full name

This is my data:

This is My Code for showing FullName:

```<code>var TopStudents = await GetTopStudentsFromDb(count);
var codes = TopStudents.Select(e => e.StudentCode).Distinct().ToList();
var Students = await GetStudeentByCode(codes);

foreach (var St in TopStudents)
{
   St.StudentsName =
       Students.FirstOrDefault(e => e.Code == St.StudentCode)?.NameMajor.Refine();
}
</code>```

this code works and shows the name now I want to change it to show the alias name of the major what should I do?
I want to check if it has Alias name show it if it doesn't then show the name.

答:
The best will be to add a property on you TopStudens type that uses the null null-coalescing operator ?? - like:

```<code>public class TopStudents {

  [NotMapped] // not persisted in database.
  public string AliasOrNameMajor => Alias ?? NameMajor;
}
</code>```

and then do it this way:

```<code>foreach (var St in TopStudents)
{
   St.StudentsName =
       Students.FirstOrDefault(e => e.Code == St.StudentCode)?.AliasOrNameMajor;
}
</code>```

Title: Changing the name of major to aliasName

Body:
everyone, I am trying to write code  that checks if there is alias name show it and if there is not then show the full name

This is my data:

This is My Code for showing FullName:

var TopStudents = await GetTopStudentsFromDb(count);
var codes = TopStudents.Select(e => e.StudentCode).Distinct().ToList();
var Students = await GetStudeentByCode(codes);

foreach (var St in TopStudents)
{
   St.StudentsName =
       Students.FirstOrDefault(e => e.Code == St.StudentCode)?.NameMajor.Refine();
}

this code works and shows the name now I want to change it to show the alias name of the major what should I do?
I want to check if it has Alias name show it if it doesn't then show the name.

Body:
The best will be to add a property on you TopStudens type that uses the null null-coalescing operator ?? - like:

public class TopStudents {

  [NotMapped] // not persisted in database.
  public string AliasOrNameMajor => Alias ?? NameMajor;
}

and then do it this way:

foreach (var St in TopStudents)
{
   St.StudentsName =
       Students.FirstOrDefault(e => e.Code == St.StudentCode)?.AliasOrNameMajor;
}


问:
Displaying Google Plus user profile picture in Android app
Am trying to display the profile picture of users logged into my app through Google+ but am not sure how to do this.To get the image (and other information), google provides the code

```<code>@Override
public void onConnected() {
...
if (mPlusClient.getCurrentPerson() != null) {
    Person currentPerson = mPlusClient.getCurrentPerson();
    String personName = currentPerson.getDisplayName();
    String personPhoto = currentPerson.getImage();
    String personGooglePlusProfile = currentPerson.getUrl();
}
}
</code>```

I am aware that ordinarily i would need to get any image i want to display from res/drawable... but i don't know what to do with the value of personPhoto (which somehow get's changed from type String to Image when you paste the code in Eclipse.

答:
This is the solution that worked on my Android app. I developed it from an answer above by Naveen Kumar Yadav.

Prerequisites
- I am using a Google Sign-In API for my login.
- I have an XML Code with an ImageView that has an id "client_dp"

Add this dependency to your app-level build.gradle file

```<code>dependencies {compile 'com.github.bumptech.glide:glide:3.8.0'}
</code>```

Then add this code to your activity java file

```<code>//Firebase get user info
firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser account = firebaseAuth.getCurrentUser();
if (account != null){
        //Display User Image from Google Account
        //Objects.requireNonNull() prevents getPhotoUrl() from returning a NullPointerException
        String personImage = Objects.requireNonNull(account.getPhotoUrl()).toString();
        ImageView userImage = findViewById(R.id.client_dp);
        Glide.with(this).load(personImage).into(userImage);
    }
</code>```

Body:
Am trying to display the profile picture of users logged into my app through Google+ but am not sure how to do this.To get the image (and other information), google provides the code

@Override
public void onConnected() {
...
if (mPlusClient.getCurrentPerson() != null) {
    Person currentPerson = mPlusClient.getCurrentPerson();
    String personName = currentPerson.getDisplayName();
    String personPhoto = currentPerson.getImage();
    String personGooglePlusProfile = currentPerson.getUrl();
}
}

I am aware that ordinarily i would need to get any image i want to display from res/drawable... but i don't know what to do with the value of personPhoto (which somehow get's changed from type String to Image when you paste the code in Eclipse.

Body:
This is the solution that worked on my Android app. I developed it from an answer above by Naveen Kumar Yadav.

Prerequisites
- I am using a Google Sign-In API for my login.
- I have an XML Code with an ImageView that has an id "client_dp"

Add this dependency to your app-level build.gradle file

dependencies {compile 'com.github.bumptech.glide:glide:3.8.0'}

Then add this code to your activity java file

//Firebase get user info
firebaseAuth = FirebaseAuth.getInstance();
FirebaseUser account = firebaseAuth.getCurrentUser();
if (account != null){
        //Display User Image from Google Account
        //Objects.requireNonNull() prevents getPhotoUrl() from returning a NullPointerException
        String personImage = Objects.requireNonNull(account.getPhotoUrl()).toString();
        ImageView userImage = findViewById(R.id.client_dp);
        Glide.with(this).load(personImage).into(userImage);
    }


问:
Write csv file using csvhelper library
I am using the following code and getting an exception ,

```<code> Exception thrown: 'CsvHelper.WriterException' in CsvHelper.dll on this line executed:

csv.WriteRecord(item);
</code>```

This is the more of the code:

```<code>using (var memoryStream = new MemoryStream())
{
    using (var writer = new StreamWriter(memoryStream))
    {
        using (var csv = new CsvHelper.CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture))
        {
            foreach (var item in csvData)
            {
                csv.WriteRecord(item); // Exception thrown here
            }
        }
    }

    var arr = memoryStream.ToArray();
    //js.SaveAs("people.csv", arr);  what type object is js? copied from the stackoverflow answer linked here
}
</code>```

This is the csvData code:

```<code>IEnumerable<DateLowHigh> csvData = stocks.candles
    .Select(c => new DateLowHigh
    {
        Time = c.datetime,
        Close = c.close,
        Low = c.low,
        High = c.high
    })
    .ToList();
</code>```

I do get the csvData.

This stackoverflow answer helped me get started.

答:
I don't know why you need to use CsvHelper when you can easily do the same with the IO library.</p>

```<code>sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.csv";
        static void Main(string[] args)
        {
            Stocks stocks = new Stocks();

            IEnumerable<DateLowHigh> csvData = stocks.candles.Select(c => new DateLowHigh
            {
                Time = c.datetime,
                Close = c.close,
                Low = c.low,
                High = c.high
            }).ToList();

            MemoryStream memoryStream = new MemoryStream();
            using (var writer = new StreamWriter(memoryStream))
            {
                string[] headers = {"Time", "Close", "Low", "High"};
                writer.WriteLine(string.Join(",", headers));
                foreach (var item in csvData)
                {
                    writer.WriteLine(string.Join(",", new string[] { item.Time.ToString(), item.Close, item.Low.ToString(), item.High.ToString() }));
                }
            }
            memoryStream.Position = 0;
        }
    }
    public class Stocks
    {
        public List<Candle> candles { get; set; }
    }
    public class Candle
    {
        public DateTime datetime { get; set; }
        public string close { get; set; }
        public int low { get; set; }
        public int high { get; set; }
    }
    public class DateLowHigh
    {
        public DateTime Time { get; set; }
        public string Close { get; set; }
        public int Low { get; set; }
        public int High { get; set; }
    }
}
</code>```

Title: Write csv file using csvhelper library

Body:
I am using the following code and getting an exception ,

 Exception thrown: 'CsvHelper.WriterException' in CsvHelper.dll on this line executed:

csv.WriteRecord(item);

This is the more of the code:

using (var memoryStream = new MemoryStream())
{
    using (var writer = new StreamWriter(memoryStream))
    {
        using (var csv = new CsvHelper.CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture))
        {
            foreach (var item in csvData)
            {
                csv.WriteRecord(item); // Exception thrown here
            }
        }
    }

    var arr = memoryStream.ToArray();
    //js.SaveAs("people.csv", arr);  what type object is js? copied from the stackoverflow answer linked here
}

This is the csvData code:

IEnumerable<DateLowHigh> csvData = stocks.candles
    .Select(c => new DateLowHigh
    {
        Time = c.datetime,
        Close = c.close,
        Low = c.low,
        High = c.high
    })
    .ToList();

I do get the csvData.

This stackoverflow answer helped me get started.

Body:
I don't know why you need to use CsvHelper when you can easily do the same with the IO library.

sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.csv";
        static void Main(string[] args)
        {
            Stocks stocks = new Stocks();

            IEnumerable<DateLowHigh> csvData = stocks.candles.Select(c => new DateLowHigh
            {
                Time = c.datetime,
                Close = c.close,
                Low = c.low,
                High = c.high
            }).ToList();

            MemoryStream memoryStream = new MemoryStream();
            using (var writer = new StreamWriter(memoryStream))
            {
                string[] headers = {"Time", "Close", "Low", "High"};
                writer.WriteLine(string.Join(",", headers));
                foreach (var item in csvData)
                {
                    writer.WriteLine(string.Join(",", new string[] { item.Time.ToString(), item.Close, item.Low.ToString(), item.High.ToString() }));
                }
            }
            memoryStream.Position = 0;
        }
    }
    public class Stocks
    {
        public List<Candle> candles { get; set; }
    }
    public class Candle
    {
        public DateTime datetime { get; set; }
        public string close { get; set; }
        public int low { get; set; }
        public int high { get; set; }
    }
    public class DateLowHigh
    {
        public DateTime Time { get; set; }
        public string Close { get; set; }
        public int Low { get; set; }
        public int High { get; set; }
    }
}


问:
search string and insert value in table
i have table having below records.The below product description are given by user in textbox in
front end(asp.net).The product description will come with single quotes or double quotes.i want to insert in the table.so how can we check whether single quotes or double quotes are exists in the
the input and insert value in the table.please help.

String s=Textbook

```<code>CREATE TABLE Product_Details(Product_Description varchar(50))

    Required Output

    Product_Description
    -------------------
    STORE('COVERED)
    STEEL("ROOFED)
</code>```

Insert statement will be differ for above two string?.

答:
I'm not sure what exactly what you are looking for.  You should be able to store text with quotes or double quotes without any trouble (note, I'm testing on Postgresql 9.4, don't have 9.2).
The problem is sometimes creating the text with the single quotes.  In those cases it is common to have two single quotes like this insert into product_details values ('STORE(''COVERED)')  The double quotes (") should not be a problem.  You can use the syntax E'STORE(\'COVERED)' instead of the two quotes.  Sometimes more readable.

If you just want to check if there are ' or "" in the input, this check is convenient:

```<code>select length(replace(product_description,'''',''))!=length(product_description),
length(replace(product_description,'"',''))!=length(product_description)
</code>```

which return true/false columns telling if single-quote exists in string in first column and double-quote in the latter.

To delete the quotes in string you can do:

select replace(replace(product_description,'"',''),'''','')

Best regards,

Bjarni

Title: search string and insert value in table

Body:
i have table having below records.The below product description are given by user in textbox in
front end(asp.net).The product description will come with single quotes or double quotes.i want to insert in the table.so how can we check whether single quotes or double quotes are exists in the
the input and insert value in the table.please help.

String s=Textbook

CREATE TABLE Product_Details(Product_Description varchar(50))

    Required Output

    Product_Description
    -------------------
    STORE('COVERED)
    STEEL("ROOFED)

Insert statement will be differ for above two string?.

Body:
I'm not sure what exactly what you are looking for.  You should be able to store text with quotes or double quotes without any trouble (note, I'm testing on Postgresql 9.4, don't have 9.2).
The problem is sometimes creating the text with the single quotes.  In those cases it is common to have two single quotes like this insert into product_details values ('STORE(''COVERED)')  The double quotes (") should not be a problem.  You can use the syntax E'STORE(\'COVERED)' instead of the two quotes.  Sometimes more readable.

If you just want to check if there are ' or "" in the input, this check is convenient:

select length(replace(product_description,'''',''))!=length(product_description),
length(replace(product_description,'"',''))!=length(product_description)

which return true/false columns telling if single-quote exists in string in first column and double-quote in the latter.

To delete the quotes in string you can do:

select replace(replace(product_description,'"',''),'''','')

Best regards,

Bjarni


问:
When i try to compile i get "unfinished string near '<eof>'
Any idea how to fix this?

I'm completely noob in .lua and i'm just translating korean map to english and encountered this and cannot continue until i find a fix.

答:
In Windows, if some text file (for example, .lua-file) is opened in "text mode", the character 0x1A (SciTE displays it as SUB with dark background color) is considered "magic", its meaning is "end of file".   In other words, all content after 0x1A is ignored.

If you really need this character inside string literal in a Lua program, you can write "\026"


问:
android black color at 85% opacity
What is the color code of black with 85% opacity?

I have #65000000 - but its too light. I need it a bit darker, at 85% opacity. How do I get that?

And why can't I setAlpha(85) on a relative layout? That's what I would want to do normally. But because this is not available, I have to do it though background color.

答:
Each component goes from 0 through 255, so 85% opacity would be 85% of 255, i.e. 216.

So: #D8000000

Title: android black color at 85% opacity


问:
Ordering of months in xaxis of Vega Lite plot
I have this code which uses year information in the dates but having the time unit as 'month' seems to force it to month ordering. This goes away if i switch to 'yearmonth', but is there a way to still only show the months but have the ordering based on the year information?</p>

答:
The month timeUnit strips away all year information by design. If you want to keep the year information in the axis, you can use the yearmonth timeunit, and use an appropriate axis format string to hide the year (Vega-Lite's temporal format strings come from d3-date-format).

Your x encoding might look something like this:

```<code>"x": {
  "field": "date",
  "type": "ordinal",
  "timeUnit": "yearmonth",
  "axis": {"title": null, "format": "%b"}
},
</code>```

Body:
The month timeUnit strips away all year information by design. If you want to keep the year information in the axis, you can use the yearmonth timeunit, and use an appropriate axis format string to hide the year (Vega-Lite's temporal format strings come from d3-date-format).

Your x encoding might look something like this:

"x": {
  "field": "date",
  "type": "ordinal",
  "timeUnit": "yearmonth",
  "axis": {"title": null, "format": "%b"}
},


问:
BMC Remedy ITSM search based on Last Resolved Date
I am trying to generate a report which should retrieve tickets that are resolved a working day before the current date. If I run the report on 14-OCt-2019 (Monday), then the results should fetch tickets resolved on 11-Oct-2019 (Friday)

I tried this query but it is not generating the expected results ( 'Last Resolved Date' >= ( $TIMESTAMP$ - 2 * 24 * 24 * 60) )

答:
Last Resolved Date sounds like a date field. You are using $TIMESTAMP$. Maybe you could consider using $DATE$ instead?

Besides that, I don't quite get the maths:

One day would be hours * minutes * seconds (24 * 60 * 60) (I don't recall if $TIMESTAMP$ uses milliseconds), nevertheless, this would give you the tickets in the last 24 hours, so If you check at 12:00 noon, you would only get part of the tickets.

I would use 'Last Resolved Date' >= ($DATE$ - ((60*60)*24))


问:
Avoid nested subscription in RXJS
I have the following code:

```<code>someService.subscribeToChanges().subscribe(value => {
    const newValue = someArray.find(val => val.id === value.id)
    if (newValue) {
       if (value.status === 'someStatus') {
          someArray.findIndex((a) => a.id === value.id)
          someArray.splice(index, 1);
       } else {
          newValue.status = value.status;
       }
    } else {
        if (value.someProp === 'abc') {
          someService.doSomeAsyncStuff().subscribe(data => {
            someService.handleData(data);
          });
        }
    }
 });
</code>```

I would like to keep the same logic while avoiding the second subscribe.

This is the code that I tried

```<code>sub$ = someService.subscribeToChanges().pipe(switchMap(value => {
  const newValue = someArray.find(val => val.id === value.id)
  if (newValue) {
       if (value.status === 'someStatus') {
          someArray.findIndex((a) => a.id === value.id)
          someArray.splice(index, 1);
       } else {
          newValue.status = value.status;
       }
  } else {
    return iif(() => value.someProp === 'ABC', someService.doSomeAsyncStuff);
  }
}));

sub$.subscribe(data => someService.handleData(data))
</code>```

This works if the iif condition is true, but if it is false, it just stops the whole stream, while I want it to keep streaming.

答:
It's always much better to keep all logic in a single chain, so you can do it for example like this. Since you don't need newValue further down the chain it's pretty simple:

```<code>someService.subscribeToChanges()
  .pipe(
    switchMap(value => {
      const newValue = someArray.find(val => val.id === value.id);
      if (!newValue && value.someProp === 'abc') {
        return someService.doSomeStuff();
      }
      return of(undefined);
    }),
  )
  .subscribe(data => {
    if (data === undefined) { // When data is set means we ran the second Observable
      doSomeStuff();
    } else {
      someService.handleData(data);
    }
  });

</code>```

If for someService.doSomeStuff() is undefined a valid response then I'd wrap its response with some object like { response: data } so you'll always know where it came from.

Try to avoid making multiple subscriptions until it's really necessary because that brings  more things you have to be aware of (like order of subscriptions, sharing Observables and so on) and it's always easier to read RxJS chains in top-down order like it was synchronous code.

Title: Avoid nested subscription in RXJS

Body:
I have the following code:

someService.subscribeToChanges().subscribe(value => {
    const newValue = someArray.find(val => val.id === value.id)
    if (newValue) {
       if (value.status === 'someStatus') {
          someArray.findIndex((a) => a.id === value.id)
          someArray.splice(index, 1);
       } else {
          newValue.status = value.status;
       }
    } else {
        if (value.someProp === 'abc') {
          someService.doSomeAsyncStuff().subscribe(data => {
            someService.handleData(data);
          });
        }
    }
 });

I would like to keep the same logic while avoiding the second subscribe.

This is the code that I tried

sub$ = someService.subscribeToChanges().pipe(switchMap(value => {
  const newValue = someArray.find(val => val.id === value.id)
  if (newValue) {
       if (value.status === 'someStatus') {
          someArray.findIndex((a) => a.id === value.id)
          someArray.splice(index, 1);
       } else {
          newValue.status = value.status;
       }
  } else {
    return iif(() => value.someProp === 'ABC', someService.doSomeAsyncStuff);
  }
}));

sub$.subscribe(data => someService.handleData(data))

This works if the iif condition is true, but if it is false, it just stops the whole stream, while I want it to keep streaming.

Body:
It's always much better to keep all logic in a single chain, so you can do it for example like this. Since you don't need newValue further down the chain it's pretty simple:

someService.subscribeToChanges()
  .pipe(
    switchMap(value => {
      const newValue = someArray.find(val => val.id === value.id);
      if (!newValue && value.someProp === 'abc') {
        return someService.doSomeStuff();
      }
      return of(undefined);
    }),
  )
  .subscribe(data => {
    if (data === undefined) { // When data is set means we ran the second Observable
      doSomeStuff();
    } else {
      someService.handleData(data);
    }
  });

If for someService.doSomeStuff() is undefined a valid response then I'd wrap its response with some object like { response: data } so you'll always know where it came from.

Try to avoid making multiple subscriptions until it's really necessary because that brings  more things you have to be aware of (like order of subscriptions, sharing Observables and so on) and it's always easier to read RxJS chains in top-down order like it was synchronous code.


问:
I am not able to install Angular/Cli onto my ubuntu 18 system
I am trying to install Angular/CLI onto my Ubuntu system.

Ubuntu 18.04.4 LTS 64 bit

```<code> node -v

npm -v
</code>```

npm version is 3.5.2

```<code>npm install -g @angular/cli
</code>```

I have installed Node and its showing version as v8.10.0 but when I try to install Angular/cli It shows some error as below

```<code> npm install -g @angular/cli
- |---------------------------------------------------------------------------|
WARN engine @angular/cli@9.0.2: wanted: {"node":">= 10.13.0","npm":">= 6.11.0","yarn":">= 1.13.0"} (current: {"node":"8.10.0","npm":"3.5.2"})
WARN engine @angular/cli@9.0.2: wanted: {"node":">= 10.13.0","npm":">= 6.11.0","loadDep:uuid -> get       / |##########---------------------------------------|
WARN engine @angular-devkit/architect@0.900.2: wanted: {"node":">= 10.13.0","npmloadDep:uuid -> get       - |##########---------------------------------------|
WARN engine @angular-devkit/core@9.0.2: wanted: {"node":">= 10.13.0","npm":">= 6.11.0","yarn":">= 1.13.0"} (current: {"node":"8.10.0","npm":"3.5.2"})
WARN engine @angular-devkit/schematics@9.0.2: wanted: {"node":">= 10.13.0","npm"loadDep:uuid -> get       | |##########---------------------------------------|
WARN engine @schematics/angular@9.0.2: wanted: {"node":">= 10.13.0","npm":">= 6.loadDep:uuid -> network   | |##########---------------------------------------|
WARN engine @schematics/update@0.900.2: wanted: {"node":">= 10.13.0","npm":">= 6npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/@angular/cli
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/@angular
/usr/local/lib
`-- @angular/cli@9.0.2

npm ERR! Linux 5.3.0-28-generic
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "-g" "@angular/cli"
npm ERR! node v8.10.0
npm ERR! npm  v3.5.2
npm ERR! path /usr/local/lib/node_modules/@angular/cli
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access

npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules/@angular/cli'
npm ERR!  { Error: EACCES: permission denied, access '/usr/local/lib/node_modules/@angular/cli'
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules/@angular/cli' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/sagar/npm-debug.log
sagar@sagar-HP-Notebook:~$ ng -v
Node.js version v8.10.0 detected.
The Angular CLI requires a minimum Node.js version of either v10.13 or v12.0.

 ng -v

Node.js version v8.10.0 detected.
The Angular CLI requires a minimum Node.js version of either v10.13 or v12.0.
</code>```

Can anyone please help me to get rid of this error.

答:
You have not write permission to create directory, try it with :</p>

```<code>sudo npm install -g @angular/cli
</code>```

Body:
I am trying to install Angular/CLI onto my Ubuntu system.

Ubuntu 18.04.4 LTS 64 bit

 node -v

npm -v

npm version is 3.5.2

npm install -g @angular/cli

I have installed Node and its showing version as v8.10.0 but when I try to install Angular/cli It shows some error as below

 npm install -g @angular/cli
- |---------------------------------------------------------------------------|
WARN engine @angular/cli@9.0.2: wanted: {"node":">= 10.13.0","npm":">= 6.11.0","yarn":">= 1.13.0"} (current: {"node":"8.10.0","npm":"3.5.2"})
WARN engine @angular/cli@9.0.2: wanted: {"node":">= 10.13.0","npm":">= 6.11.0","loadDep:uuid -> get       / |##########---------------------------------------|
WARN engine @angular-devkit/architect@0.900.2: wanted: {"node":">= 10.13.0","npmloadDep:uuid -> get       - |##########---------------------------------------|
WARN engine @angular-devkit/core@9.0.2: wanted: {"node":">= 10.13.0","npm":">= 6.11.0","yarn":">= 1.13.0"} (current: {"node":"8.10.0","npm":"3.5.2"})
WARN engine @angular-devkit/schematics@9.0.2: wanted: {"node":">= 10.13.0","npm"loadDep:uuid -> get       | |##########---------------------------------------|
WARN engine @schematics/angular@9.0.2: wanted: {"node":">= 10.13.0","npm":">= 6.loadDep:uuid -> network   | |##########---------------------------------------|
WARN engine @schematics/update@0.900.2: wanted: {"node":">= 10.13.0","npm":">= 6npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/@angular/cli
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules/@angular
/usr/local/lib
`-- @angular/cli@9.0.2

npm ERR! Linux 5.3.0-28-generic
npm ERR! argv "/usr/bin/node" "/usr/bin/npm" "install" "-g" "@angular/cli"
npm ERR! node v8.10.0
npm ERR! npm  v3.5.2
npm ERR! path /usr/local/lib/node_modules/@angular/cli
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! syscall access

npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules/@angular/cli'
npm ERR!  { Error: EACCES: permission denied, access '/usr/local/lib/node_modules/@angular/cli'
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   syscall: 'access',
npm ERR!   path: '/usr/local/lib/node_modules/@angular/cli' }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! Please include the following file with any support request:
npm ERR!     /home/sagar/npm-debug.log
sagar@sagar-HP-Notebook:~$ ng -v
Node.js version v8.10.0 detected.
The Angular CLI requires a minimum Node.js version of either v10.13 or v12.0.

 ng -v

Node.js version v8.10.0 detected.
The Angular CLI requires a minimum Node.js version of either v10.13 or v12.0.

Can anyone please help me to get rid of this error.

Body:
You have not write permission to create directory, try it with :

sudo npm install -g @angular/cli


问:
What is meaning of `T&` when returing `T` from function?
I see some code like this:

```<code>const std::vector<obj>& value = function();
</code>```

And function() define as follow:

```<code>std::vector<obj> function()
{
   std::vector<obj> v {/* ... */};
   return v;
}
</code>```

What is meaning of & in const std::vector<obj>& value ? is get a reference or copy of local function() variable ?

答:
It is declaring value to be a reference to constant std::vector<obj>.

References that can bind to temporaries (references-to-const and rvalue-references) can extend the lifetime of the object they reference under some circumstances though, and this is one of those circumstances.  That means that function's return value has its lifetime extended to the lifetime of value.

Pre-C++17 this could, in theory, avoid making an extra copy from the return value of function to value (though every compiler I know of would have elided the copy anyway).  Since C++17 it's guaranteed that no copy is made, so lifetime-extension like this doesn't serve much of a purpose anymore.

Body:
I see some code like this:

const std::vector<obj>& value = function();

And function() define as follow:

std::vector<obj> function()
{
   std::vector<obj> v {/* ... */};
   return v;
}

What is meaning of & in const std::vector<obj>& value ? is get a reference or copy of local function() variable ?


问:
storing time in PHP
data stored in table1 is with time stamp. syntax used to store time stamp is NOW(). stored time format is in 2011-05-17 00:46:19. my question is how do I access latest data by time and how do I display time say "the data stored 10 minutes ago" or 5 seconds ago or 1 day etc. I am using MySQL and PHP.

答:
this is something i have done in my code before, might be of use</p>

```<code>$sql  ="select datetimecol from table1 where x=y, etc";

$result = mysql_query($sql);
// TODO check for mysql errors

list($datetimecol) = mysql_fetch_row($result);

$timestamp = strtotime($datetimecol);

$diff = time() - $timestamp;

if ($diff < 600) {
    // less then 10 minutes
    return 'Hot off the press';
} else if ($diff < 3600) {
    // less then 1 hour
    return sprintf('%d minutes ago', ($diff / 60));
} else if ($diff < 7200) {
    // less then 2 hours
    return '1 hour ago';
} else if ($diff < 43200) {
    // less then 12 hours
    return sprintf('%d hours ago', ($diff / 3600));
} else if ($diff < 86400) {
    // less then 24 hours and on same day
    if (date('j') == date('j', $timestamp)) {
        return 'Today';
    } else {
        return 'Yesterday';
    }
} else if ($diff < 172800) {
    // less then 48 hours and on next day
    if (date('i') == date('j', $timestamp + (60 * 60 * 24))) {
        return 'Yesterday';
    } else {
        return date('l', $timestamp);
    }
} else if ($diff < 604800) {
    return date('l', $timestamp);
} else {
    return date('r', $timestamp);
}
</code>```

Title: storing time in PHP

Body:
this is something i have done in my code before, might be of use

$sql  ="select datetimecol from table1 where x=y, etc";

$result = mysql_query($sql);
// TODO check for mysql errors

list($datetimecol) = mysql_fetch_row($result);

$timestamp = strtotime($datetimecol);

$diff = time() - $timestamp;

if ($diff < 600) {
    // less then 10 minutes
    return 'Hot off the press';
} else if ($diff < 3600) {
    // less then 1 hour
    return sprintf('%d minutes ago', ($diff / 60));
} else if ($diff < 7200) {
    // less then 2 hours
    return '1 hour ago';
} else if ($diff < 43200) {
    // less then 12 hours
    return sprintf('%d hours ago', ($diff / 3600));
} else if ($diff < 86400) {
    // less then 24 hours and on same day
    if (date('j') == date('j', $timestamp)) {
        return 'Today';
    } else {
        return 'Yesterday';
    }
} else if ($diff < 172800) {
    // less then 48 hours and on next day
    if (date('i') == date('j', $timestamp + (60 * 60 * 24))) {
        return 'Yesterday';
    } else {
        return date('l', $timestamp);
    }
} else if ($diff < 604800) {
    return date('l', $timestamp);
} else {
    return date('r', $timestamp);
}


问:
Python Save Image from URL to ZipFile
How do I save an image from a URL to a zipfile? For example I am trying to save this image to a zipfile but it keeps throwing the error "File not found".

What am I doing wrong?

```<code>from zipfile import ZipFile
from tempfile import TempFile
import urllib.request

with TemporaryFile() as tf:
    with ZipFile(tf, mode='w') as zf:
        image_url = 'https://upload.wikimedia.org/wikipedia/commons/a/ab/Wurmseegurke.jpg'
        url = urllib.request.open(image_url)
        filename = image_url.split('/')[-1]
        zf.write(filename, url.read())
</code>```

Here is the full error: FileNotFoundError: [Errno 2] No such file or directory: 'Wurmseegurke.jpg'

答:
The TemporaryFile get deleted after it is closed, so your image wont be available after it was written into it.
You need to use writestr() to create a 'file object' in the zip:

```<code>from zipfile import ZipFile
import urllib.request
import os

image_url = 'https://upload.wikimedia.org/wikipedia/commons/a/ab/Wurmseegurke.jpg'
url = urllib.request.urlopen(image_url)
filename = image_url.split('/')[-1]

zipPath = '/tmp/%s.zip' % filename
with ZipFile(zipPath, mode='w') as zf:
    zf.writestr(filename, url.read())
print(os.path.exists(zipPath))  # probing a zip file was written!
</code>```

Output:

```<code>True
</code>```

Title: Python Save Image from URL to ZipFile

Body:
How do I save an image from a URL to a zipfile? For example I am trying to save this image to a zipfile but it keeps throwing the error "File not found".

What am I doing wrong?

from zipfile import ZipFile
from tempfile import TempFile
import urllib.request

with TemporaryFile() as tf:
    with ZipFile(tf, mode='w') as zf:
        image_url = 'https://upload.wikimedia.org/wikipedia/commons/a/ab/Wurmseegurke.jpg'
        url = urllib.request.open(image_url)
        filename = image_url.split('/')[-1]
        zf.write(filename, url.read())

Here is the full error: FileNotFoundError: [Errno 2] No such file or directory: 'Wurmseegurke.jpg'

Body:
The TemporaryFile get deleted after it is closed, so your image wont be available after it was written into it.
You need to use writestr() to create a 'file object' in the zip:

from zipfile import ZipFile
import urllib.request
import os

image_url = 'https://upload.wikimedia.org/wikipedia/commons/a/ab/Wurmseegurke.jpg'
url = urllib.request.urlopen(image_url)
filename = image_url.split('/')[-1]

zipPath = '/tmp/%s.zip' % filename
with ZipFile(zipPath, mode='w') as zf:
    zf.writestr(filename, url.read())
print(os.path.exists(zipPath))  # probing a zip file was written!

Output:

True


问:
pass const pointer of large struct to a function or a go channel
How to pass const pointer of large struct to a function or a go channel.
Purpose of this ask is:

Avoid the accidental modification of pointer by the function

Avoid the copy of the struct object while passing to
function/channel

This functionality is very common in C++, C#, Java, but how can we achieve the same in golang?

============== Update 2 ===================

Thank you @zarkams, @mkopriva and @peterSO
It was the compiler optimization causing the same result in both byValue() and byPointer().
Modified the functions byValue() and byPointer() by adding
data.array[0] = reverse(data.array[0]), just to make compiler not to make the functions inline.

```<code>func byValue(data Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func byPointer(data *Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}
</code>```

After that running the benchmarks, passing by pointer was much efficient than passing by value.

```<code>C:\Users\anikumar\Desktop\TestGo>go test -bench=.
goos: windows
goarch: amd64
BenchmarkByValue-4         18978             58228 ns/op               3 B/op          1 allocs/op
BenchmarkByPointer-4    40034295                33.1 ns/op             3 B/op          1 allocs/op
PASS
ok      _/C_/Users/anikumar/Desktop/TestGo      3.336s

C:\Users\anikumar\Desktop\TestGo>go test -gcflags -N -run=none -bench=.
goos: windows
goarch: amd64
BenchmarkByValue-4         20961             59380 ns/op               3 B/op          1 allocs/op
BenchmarkByPointer-4    31386213                36.5 ns/op             3 B/op          1 allocs/op
PASS
ok      _/C_/Users/anikumar/Desktop/TestGo      3.909s
</code>```

============== Update ===================

Based on feedback from @zerkms, I created a test to find the performance difference between copy by value and copy by the pointer.

```<code>package main

import (
    "log"
    "time"
)

const size = 99999

// Data ...
type Data struct {
    array [size]string
}

func main() {
    // Preparing large data
    var data Data
    for i := 0; i < size; i++ {
        data.array[i] = "This is really long string"
    }

    // Starting test
    const max = 9999999999
    start := time.Now()
    for i := 0; i < max; i++ {
        byValue(data)
    }
    elapsed := time.Since(start)
    log.Printf("By Value took %s", elapsed)

    start = time.Now()
    for i := 0; i < max; i++ {
        byPointer(&data)
    }
    elapsed = time.Since(start)
    log.Printf("By Pointer took %s", elapsed)
}

func byValue(data Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func byPointer(data *Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}
</code>```

After 10 iterations of the above program, I did not find any difference in execution time.

```<code>C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:03 By Value took 5.2798936s
2020/02/16 15:52:09 By Pointer took 5.3466306s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:18 By Value took 5.3596692s
2020/02/16 15:52:23 By Pointer took 5.2724685s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:29 By Value took 5.2359938s
2020/02/16 15:52:34 By Pointer took 5.2838676s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:42 By Value took 5.8374936s
2020/02/16 15:52:49 By Pointer took 6.9524342s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:53:40 By Value took 5.4364867s
2020/02/16 15:53:46 By Pointer took 5.8712875s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:53:54 By Value took 5.5481591s
2020/02/16 15:54:00 By Pointer took 5.5600314s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:10 By Value took 5.4753771s
2020/02/16 15:54:16 By Pointer took 6.4368084s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:24 By Value took 5.4783356s
2020/02/16 15:54:30 By Pointer took 5.5312314s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:39 By Value took 5.4853542s
2020/02/16 15:54:45 By Pointer took 5.5541164s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:57 By Value took 5.4633856s
2020/02/16 15:55:03 By Pointer took 5.4863226s
</code>```

Looks like @zerkms is right. It is not because of language, it is because of modern hardware.

答:
Meaningless microbenchmarks produce meaningless results.

In Go, all arguments are passed by value.

For your updated example (TestGo),

```<code>$ go version
go version devel +6917529cc6 Sat Feb 15 16:40:12 2020 +0000 linux/amd64
$ go run microbench.go
2020/02/16 13:12:56 By Value took 2.877045229s
2020/02/16 13:12:59 By Pointer took 2.875847918s
$
</code>```

Go compilers are usually optimizing compilers. For example,

```<code>./microbench.go:39:6: can inline byValue
./microbench.go:43:6: can inline byPointer
./microbench.go:26:10: inlining call to byValue
./microbench.go:33:12: inlining call to byPointer
</code>```

There is no function call overhead. Therefore, there is no difference in execution time.

microbench.go:

```<code>package main

import (
    "log"
    "time"
)

const size = 99999

// Data ...
type Data struct {
    array [size]string
}

func main() {
    // Preparing large data
    var data Data
    for i := 0; i < size; i++ {
        data.array[i] = "This is really long string"
    }

    // Starting test
    const max = 9999999999
    start := time.Now()
    for i := 0; i < max; i++ {
        byValue(data)
    }
    elapsed := time.Since(start)
    log.Printf("By Value took %s", elapsed)

    start = time.Now()
    for i := 0; i < max; i++ {
        byPointer(&data)
    }
    elapsed = time.Since(start)
    log.Printf("By Pointer took %s", elapsed)
}

func byValue(data Data) int {
    return len(data.array)
}

func byPointer(data *Data) int {
    return len(data.array)
}
</code>```

ADDENDUM

Comment: @Anil8753 another thing to note is that Go standard library has a testing package which provides some useful functionality for benchmarking. For example next to your main.go file add a main_test.go file (the file name is important) and add these two benchmarks to it and then from inside the folder run this command go test -run=none -bench=., this will print how many operations were executed, how much time a single operation took, how much memory a single operation required, and how many allocations were required. – mkopriva

Go compilers are usually optimizing compilers. Modern hardware is usually heavily optimized.

For mkopriva's microbenchmark,

```<code>$ go test microbench.go mkopriva_test.go -bench=.
BenchmarkByValue-4     1000000000   0.289 ns/op   0 B/op   0 allocs/op
BenchmarkByPointer-4   1000000000   0.575 ns/op   0 B/op   0 allocs/op
$
</code>```

However, for mkopriva's microbenchmark with a sink,

```<code>$ go test microbench.go sink_test.go -bench=.
BenchmarkByValue-4     1000000000   0.576 ns/op   0 B/op   0 allocs/op
BenchmarkByPointer-4   1000000000   0.592 ns/op   0 B/op   0 allocs/op
$
</code>```

mkopriva_test.go:

```<code>package main

import (
    "testing"
)

func BenchmarkByValue(b *testing.B) {
    var data Data
    b.ReportAllocs()
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        byValue(data)
    }
}

func BenchmarkByPointer(b *testing.B) {
    var data Data
    b.ReportAllocs()
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        byPointer(&data)
    }
}
</code>```

sink_test.go:

```<code>package main

import (
    "testing"
)

var banchInt int

func BenchmarkByValue(b *testing.B) {
    var data Data
    b.ReportAllocs()
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        banchInt = byValue(data)
    }
}

func BenchmarkByPointer(b *testing.B) {
    var data Data
    b.ReportAllocs()
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        banchInt = byPointer(&data)
    }
}
</code>```

Body:
How to pass const pointer of large struct to a function or a go channel.
Purpose of this ask is:

Avoid the accidental modification of pointer by the function

Avoid the copy of the struct object while passing to
function/channel

This functionality is very common in C++, C#, Java, but how can we achieve the same in golang?

============== Update 2 ===================

Thank you @zarkams, @mkopriva and @peterSO
It was the compiler optimization causing the same result in both byValue() and byPointer().
Modified the functions byValue() and byPointer() by adding
data.array[0] = reverse(data.array[0]), just to make compiler not to make the functions inline.

func byValue(data Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func byPointer(data *Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

After that running the benchmarks, passing by pointer was much efficient than passing by value.

C:\Users\anikumar\Desktop\TestGo>go test -bench=.
goos: windows
goarch: amd64
BenchmarkByValue-4         18978             58228 ns/op               3 B/op          1 allocs/op
BenchmarkByPointer-4    40034295                33.1 ns/op             3 B/op          1 allocs/op
PASS
ok      _/C_/Users/anikumar/Desktop/TestGo      3.336s

C:\Users\anikumar\Desktop\TestGo>go test -gcflags -N -run=none -bench=.
goos: windows
goarch: amd64
BenchmarkByValue-4         20961             59380 ns/op               3 B/op          1 allocs/op
BenchmarkByPointer-4    31386213                36.5 ns/op             3 B/op          1 allocs/op
PASS
ok      _/C_/Users/anikumar/Desktop/TestGo      3.909s

============== Update ===================

Based on feedback from @zerkms, I created a test to find the performance difference between copy by value and copy by the pointer.

package main

import (
    "log"
    "time"
)

const size = 99999

// Data ...
type Data struct {
    array [size]string
}

func main() {
    // Preparing large data
    var data Data
    for i := 0; i < size; i++ {
        data.array[i] = "This is really long string"
    }

    // Starting test
    const max = 9999999999
    start := time.Now()
    for i := 0; i < max; i++ {
        byValue(data)
    }
    elapsed := time.Since(start)
    log.Printf("By Value took %s", elapsed)

    start = time.Now()
    for i := 0; i < max; i++ {
        byPointer(&data)
    }
    elapsed = time.Since(start)
    log.Printf("By Pointer took %s", elapsed)
}

func byValue(data Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func byPointer(data *Data) int {
    data.array[0] = reverse(data.array[0])
    return len(data.array)
}

func reverse(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

After 10 iterations of the above program, I did not find any difference in execution time.

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:03 By Value took 5.2798936s
2020/02/16 15:52:09 By Pointer took 5.3466306s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:18 By Value took 5.3596692s
2020/02/16 15:52:23 By Pointer took 5.2724685s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:29 By Value took 5.2359938s
2020/02/16 15:52:34 By Pointer took 5.2838676s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:52:42 By Value took 5.8374936s
2020/02/16 15:52:49 By Pointer took 6.9524342s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:53:40 By Value took 5.4364867s
2020/02/16 15:53:46 By Pointer took 5.8712875s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:53:54 By Value took 5.5481591s
2020/02/16 15:54:00 By Pointer took 5.5600314s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:10 By Value took 5.4753771s
2020/02/16 15:54:16 By Pointer took 6.4368084s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:24 By Value took 5.4783356s
2020/02/16 15:54:30 By Pointer took 5.5312314s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:39 By Value took 5.4853542s
2020/02/16 15:54:45 By Pointer took 5.5541164s

C:\Users\anikumar\Desktop\TestGo>TestGo.exe
2020/02/16 15:54:57 By Value took 5.4633856s
2020/02/16 15:55:03 By Pointer took 5.4863226s

Looks like @zerkms is right. It is not because of language, it is because of modern hardware.

Body:
Meaningless microbenchmarks produce meaningless results.

In Go, all arguments are passed by value.

For your updated example (TestGo),

$ go version
go version devel +6917529cc6 Sat Feb 15 16:40:12 2020 +0000 linux/amd64
$ go run microbench.go
2020/02/16 13:12:56 By Value took 2.877045229s
2020/02/16 13:12:59 By Pointer took 2.875847918s
$

Go compilers are usually optimizing compilers. For example,

./microbench.go:39:6: can inline byValue
./microbench.go:43:6: can inline byPointer
./microbench.go:26:10: inlining call to byValue
./microbench.go:33:12: inlining call to byPointer

There is no function call overhead. Therefore, there is no difference in execution time.

microbench.go:

package main

import (
    "log"
    "time"
)

const size = 99999

// Data ...
type Data struct {
    array [size]string
}

func main() {
    // Preparing large data
    var data Data
    for i := 0; i < size; i++ {
        data.array[i] = "This is really long string"
    }

    // Starting test
    const max = 9999999999
    start := time.Now()
    for i := 0; i < max; i++ {
        byValue(data)
    }
    elapsed := time.Since(start)
    log.Printf("By Value took %s", elapsed)

    start = time.Now()
    for i := 0; i < max; i++ {
        byPointer(&data)
    }
    elapsed = time.Since(start)
    log.Printf("By Pointer took %s", elapsed)
}

func byValue(data Data) int {
    return len(data.array)
}

func byPointer(data *Data) int {
    return len(data.array)
}

ADDENDUM

Comment: @Anil8753 another thing to note is that Go standard library has a testing package which provides some useful functionality for benchmarking. For example next to your main.go file add a main_test.go file (the file name is important) and add these two benchmarks to it and then from inside the folder run this command go test -run=none -bench=., this will print how many operations were executed, how much time a single operation took, how much memory a single operation required, and how many allocations were required. – mkopriva

Go compilers are usually optimizing compilers. Modern hardware is usually heavily optimized.

For mkopriva's microbenchmark,

$ go test microbench.go mkopriva_test.go -bench=.
BenchmarkByValue-4     1000000000   0.289 ns/op   0 B/op   0 allocs/op
BenchmarkByPointer-4   1000000000   0.575 ns/op   0 B/op   0 allocs/op
$

However, for mkopriva's microbenchmark with a sink,

$ go test microbench.go sink_test.go -bench=.
BenchmarkByValue-4     1000000000   0.576 ns/op   0 B/op   0 allocs/op
BenchmarkByPointer-4   1000000000   0.592 ns/op   0 B/op   0 allocs/op
$

mkopriva_test.go:

package main

import (
    "testing"
)

func BenchmarkByValue(b *testing.B) {
    var data Data
    b.ReportAllocs()
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        byValue(data)
    }
}

func BenchmarkByPointer(b *testing.B) {
    var data Data
    b.ReportAllocs()
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        byPointer(&data)
    }
}

sink_test.go:

package main

import (
    "testing"
)

var banchInt int

func BenchmarkByValue(b *testing.B) {
    var data Data
    b.ReportAllocs()
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        banchInt = byValue(data)
    }
}

func BenchmarkByPointer(b *testing.B) {
    var data Data
    b.ReportAllocs()
    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        banchInt = byPointer(&data)
    }
}


问:
How to access application resources in code, c#, wp7
I know you can access page resources by using the following code:

```<code>btn.Style = Resources["ButtonStle"] as Style;
</code>```

But how do you access an application wide resource?

答:
You can access the application through the static Application.Current property.</p>

```<code>btn.Style = Application.Current.Resources["ButtonStyle"] as Style;
</code>```

Body:
I know you can access page resources by using the following code:

btn.Style = Resources["ButtonStle"] as Style;

But how do you access an application wide resource?

Body:
You can access the application through the static Application.Current property.

btn.Style = Application.Current.Resources["ButtonStyle"] as Style;