问:
How to get instance of InstancePerRequest object inside a Singleton
I am new to Autofac, I really like its lifetime scope features, but I am having an issue.

I need to use an instance of an object created on a InstancePerRequest basis from a singleton in an assembly that doesn't have a refence to .Net MVC Web

I tried what this post suggests but it doesn't work. I get this exception:

No scope with a tag matching 'AutofacWebRequest' is visible from the
  scope in which the instance was requested.

What is the correct way to get/use an InstancePerRequest object in a Singleton?

Update
I would like to clarify, considering Travis answer, we don't want to hold a captive dependency of the InstancePerRequest item in the singleton. We want to request the item each time we use it. We've analyzed and it would be more expensive to make the singleton an InstancePerRequest than request the InstancePerRequest item to the container each time we use it.
Is this considered a bad practice? It is rather common to have certain things you need to access at the Request level and have a Singleton use them.

答: Don't get per request items in a singleton. That creates a captive dependency which is bad news. Switch the singleton to be per request as well.</p>


来源: stackexchange

问:
Set <select> element depending on another <select> element
I need a select element's options to change depending on the value of another.

```<code><select id="first">
    <option value="1">one</option> // When you click this one, all the values of #second change (arbitrary number of entries)
    <option value="2">two</option> // When you click this one, all the values of #second change to something else (not necessarily the same number)
</select>
<select id="second">
    <option value="thisChanges">soDoesThis</option>
    <option value="thisToo">andThis</option>
</select>

<script>
    $("#first").on("change", function() {
        <pseudo>
            if #first == "1"
                #second = {"this", "that", "the other"}
            else if #first == "2"
                #second = {"more", "even more", "yet another", "still more"}
        </pseudo>
    }
</script>
</code>```

This is pretty much what I'm after (took me years to figure out how to completely replace the values of a select box), but the button click event doesn't even work. It was working a minute ago, although the for loop was not.

Obviously for my use case I would check if the select is clicked and retrieve its value with .val(), but I figured this button is easier for debugging.

JSFiddle

HTML:

```<code><select id="sel">
  <option value="1">One</option>
  <option value="2">Two</option>
</select>

<button>
Click me
</button>
</code>```

JS:

```<code>var list = ['11', 'Eleven', '12', 'Twelve', '13', 'Thirteen'];
$('button').on('click', function () {
        alert('click');
    var sel = $('#sel');
    alert('1');
    sel.empty();
    alert('2');
    for (i = 0, i < list.length; i+2) {
        $('#sel').append('<option value="' + list[i] + '">' + list[i+1] + '</option>');
    }
    alert('3');
});
</code>```

答:
I think you requirement similiar to the cascading dropdownlist, if i have understood correctly.

Ex jquery code:

```<code>$(document).ready(function () {
  $("#state").prop("disabled", true);
  $("#country").change(function () {
    if ($("#country").val() != "Please select") {
       var options = {};
       options.url = "/home/getstates";
       options.type = "POST";
       options.data = JSON.stringify({ country: $("#country").val() });
       options.dataType = "json";
       options.contentType = "application/json";
       options.success = function (states) {
       $("#state").empty();
       for (var i = 0; i < states.length; i++) {
         $("#state").append("<option>" + states[i] + "</option>");
       }
       $("#state").prop("disabled", false);
    };
    options.error = function () { alert("Error retrieving states!"); };
    $.ajax(options);
  }
  else {
    $("#state").empty();
    $("#state").prop("disabled", true);
  }
 });
});
</code>```

Kindly refer this good article for the complete code:

http://www.binaryintellect.net/articles/b58fde6b-415e-454d-985b-d5dc4ad2fca8.aspx

Hope it will helps

Thanks

Karthik

ContentLicense: CC BY-SA 3.0

Body:
I need a select element's options to change depending on the value of another.

<select id="first">
    <option value="1">one</option> // When you click this one, all the values of #second change (arbitrary number of entries)
    <option value="2">two</option> // When you click this one, all the values of #second change to something else (not necessarily the same number)
</select>
<select id="second">
    <option value="thisChanges">soDoesThis</option>
    <option value="thisToo">andThis</option>
</select>

This is pretty much what I'm after (took me years to figure out how to completely replace the values of a select box), but the button click event doesn't even work. It was working a minute ago, although the for loop was not.

Obviously for my use case I would check if the select is clicked and retrieve its value with .val(), but I figured this button is easier for debugging.

JSFiddle

HTML:

<select id="sel">
  <option value="1">One</option>
  <option value="2">Two</option>
</select>

<button>
Click me
</button>

JS:

var list = ['11', 'Eleven', '12', 'Twelve', '13', 'Thirteen'];
$('button').on('click', function () {
        alert('click');
    var sel = $('#sel');
    alert('1');
    sel.empty();
    alert('2');
    for (i = 0, i < list.length; i+2) {
        $('#sel').append('<option value="' + list[i] + '">' + list[i+1] + '</option>');
    }
    alert('3');
});

Body:
I think you requirement similiar to the cascading dropdownlist, if i have understood correctly.

Ex jquery code:

$(document).ready(function () {
  $("#state").prop("disabled", true);
  $("#country").change(function () {
    if ($("#country").val() != "Please select") {
       var options = {};
       options.url = "/home/getstates";
       options.type = "POST";
       options.data = JSON.stringify({ country: $("#country").val() });
       options.dataType = "json";
       options.contentType = "application/json";
       options.success = function (states) {
       $("#state").empty();
       for (var i = 0; i < states.length; i++) {
         $("#state").append("<option>" + states[i] + "</option>");
       }
       $("#state").prop("disabled", false);
    };
    options.error = function () { alert("Error retrieving states!"); };
    $.ajax(options);
  }
  else {
    $("#state").empty();
    $("#state").prop("disabled", true);
  }
 });
});

Kindly refer this good article for the complete code:

http://www.binaryintellect.net/articles/b58fde6b-415e-454d-985b-d5dc4ad2fca8.aspx

Hope it will helps

Thanks

Karthik


问:
How to revoke Google user access oauth login
I have found for facebook: DELETE /{user_id}/permissions
But not found like above for Google
 I am using following Laravel package https://github.com/oriceon/oauth-5-laravel</p>

答:
you need to revoke the oauth token

$client->revokeToken();

check the documentation when using oauth2 this might help you
https://developers.google.com/identity/protocols/OAuth2WebServer


问:
Can you use the asp.net membership provider in a windows application?
The Asp.Net membership provider has some clear uses in a web app.  I am thinking about trying to leverage some of the features in a windows application (more specifically WPF).  Does anyone know if it is possible to use the core features in a windows app?  I am mostly just looking for it to create my database tables, and maintain users, roles, and profiles.  I obviously do not need to use the built-in web controls (e.g. Login).</p>

答:
Yes.  Membership, roles and profiles are all features of Visual Studio 2008 Client Application Services (Services tab of a project properties)

http://msdn.microsoft.com/en-us/library/bb384297.aspx

http://channel9.msdn.com/posts/DanielMoth/Client-Application-Services-with-Visual-Studio-2008/

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: foson

LastEditorDisplayName: foson


问:
Yahoo Finance URL not working
I have been using the following URL to fetch historical data from yahoo finance for quite some time now but it stopped working as of yesterday.

https://ichart.finance.yahoo.com/table.csv?s=SPY

When browsing to this site it says:

Will be right back...

Thank you for your patience.

Our engineers are working quickly to resolve the issue.

However, since this issue is still existing since yesterday I am starting to think that they discontinued this service?

My SO search only pointed me to this topic, which was related to https though...

Is anyone else experiencing this issue?
How can I resolve this problem? Do they offer a different access to their historical data?

答:
I was on the same boat. I managed to get the CSV downloaded from Yahoo with some vb.net frankencode I made from bits and pieces off Google, SOF and some head-scratching.

However, I discovered Intrinio (look it up), signed up, and my free account gets me 500 historic data api calls a day, with much more data and much more accurate than Yahoo. I rewrote my code for the Intrinio API, and I'm happy as a clam.

BTW, I don't work or have anything to do with Intrinio, but they saved my butt big time...

Title: Yahoo Finance URL not working


问:
Transforming an array to object
How would I approach a task of transforming an array of arrays of arrays into an array of objects using javascript? E.g.  </p>

```<code>[
     [
          [a,b],[c,d],[e,f]
     ],
     [
          [g,h],[i,j],[k,l]
     ]
]
</code>```

<p>---></p>

```<code>[
     {a:b, c:d, e:f}, {g:h, i:j, k:l}
]
</code>```

答:
functional data transformation with map and reduce

You can use map and reduce to achieve the desired data shape

const data = [
  [ ['a', 1], ['b', 2], ['c', 3] ],
  [ ['d', 4], ['e', 5], ['f', 6] ]
]

const data2 = data.map(pairs =>
  pairs.reduce((obj, [k,v]) =>
    Object.assign(obj, { [k]: v }), {}))

console.log(data2)
// [ { a: 1, b: 2, c: 3 }, { d: 4, e: 5, f: 6 } ]```
</div>
</div>
</p>

<hr>

<p><strong>generic functions</strong></p>

<p>The above transformation is cognitively dense and can be decomposed into two helpful functions – these two functions <code>mapReducer</code> and <code>pair2obj</code> are generic enough that we can easily reuse them in other parts of our program</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const mapReducer = (f, g) =>
  (acc, x) => f (acc, g (x))

const pair2obj = ([x, y]) =>
  ({ [x]: y })

const data = [
  [ ['a', 1], ['b', 2], ['c', 3] ],
  [ ['d', 4], ['e', 5], ['f', 6] ]
]

const data2 = data.map (pairs =>
  pairs.reduce(mapReducer(Object.assign, pair2obj), {}))

console.log(data2)
// [ { a: 1, b: 2, c: 3 }, { d: 4, e: 5, f: 6 } ]</code>```

native Map

If you can use Map objects in your program, this is probably better because your data is already in the format that the Map constructor accepts

const data = [
  [
    ['a',1],['b',2],['c',3]
  ],
  [
    ['d',4],['e',5],['f',6]
  ]
]

const data2 = data.map(pairs => new Map(pairs))

console.log(data2[0].get('a')) // 1
console.log(data2[0].get('b')) // 2
console.log(data2[0].get('c')) // 3
console.log(data2[1].get('d')) // 4
console.log(data2[1].get('e')) // 5
console.log(data2[1].get('f')) // 6```

Title: Transforming an array to object

Body:
How would I approach a task of transforming an array of arrays of arrays into an array of objects using javascript? E.g.

[
     [
          [a,b],[c,d],[e,f]
     ],
     [
          [g,h],[i,j],[k,l]
     ]
]

--->

[
     {a:b, c:d, e:f}, {g:h, i:j, k:l}
]

Body:
functional data transformation with map and reduce

You can use map and reduce to achieve the desired data shape

const data = [
  [ ['a', 1], ['b', 2], ['c', 3] ],
  [ ['d', 4], ['e', 5], ['f', 6] ]
]

const data2 = data.map(pairs =>
  pairs.reduce((obj, [k,v]) =>
    Object.assign(obj, { [k]: v }), {}))

console.log(data2)
// [ { a: 1, b: 2, c: 3 }, { d: 4, e: 5, f: 6 } ]

generic functions

The above transformation is cognitively dense and can be decomposed into two helpful functions – these two functions mapReducer and pair2obj are generic enough that we can easily reuse them in other parts of our program

const mapReducer = (f, g) =>
  (acc, x) => f (acc, g (x))

const pair2obj = ([x, y]) =>
  ({ [x]: y })

const data = [
  [ ['a', 1], ['b', 2], ['c', 3] ],
  [ ['d', 4], ['e', 5], ['f', 6] ]
]

const data2 = data.map (pairs =>
  pairs.reduce(mapReducer(Object.assign, pair2obj), {}))

console.log(data2)
// [ { a: 1, b: 2, c: 3 }, { d: 4, e: 5, f: 6 } ]

native Map

If you can use Map objects in your program, this is probably better because your data is already in the format that the Map constructor accepts

const data = [
  [
    ['a',1],['b',2],['c',3]
  ],
  [
    ['d',4],['e',5],['f',6]
  ]
]

const data2 = data.map(pairs => new Map(pairs))

console.log(data2[0].get('a')) // 1
console.log(data2[0].get('b')) // 2
console.log(data2[0].get('c')) // 3
console.log(data2[1].get('d')) // 4
console.log(data2[1].get('e')) // 5
console.log(data2[1].get('f')) // 6


问:
Sequential filtering using data.table in R
I have data as follows:

```<code>PERMNO date DLSTCD
    10 1983     NA
    10 1985    250
    10 1986     NA
    10 1986     NA
    10 1987    240
    10 1987     NA
    11 1984     NA
    11 1984     NA
    11 1985     NA
    11 1987     NA
    12 1984    240
</code>```

I need to filter rows based on following criteria:

For each PERMNO, sort data by date

Parse through the sorted data and delete rows after a company gets delisted (ie. DLSTCD != NA)

If the first row corresponds to company getting delisted, do not include any rows for that company

Based on these criteria, following is my expected output:

```<code>PERMNO date DLSTCD
    10 1983     NA
    10 1985    250
    11 1984     NA
    11 1984     NA
    11 1985     NA
    11 1987     NA
</code>```

I am using data.table in R to work with this data. The example above is an oversimplified version of my actual data, which contains around 3M rows corresponding to 30k PERMNOs.

I implemented three different methods for doing this, as can be seen here:

 r-fiddle: http://www.r-fiddle.org/#/fiddle?id=4GapqSbX&version=3

Below I compare my implementations using a small dataset of 50k rows. Here are my results:

Time Comparison

```<code>system.time(dt <- filterbydelistingcode(dt))   # 39.962 seconds
system.time(dt <- filterbydelistcoderowindices(dt))   # 39.014 seconds
system.time(dt <- filterbydelistcodeinline(dt))   # 114.3 seconds
</code>```

As you can see all my implementations are extremely inefficient. Can someone please help me implement a much faster version for this? Thank you.

Edit: Here is a link to a sample dataset of 50k rows that I used for time comparison: https://ufile.io/q9d8u

Also, here is a customized read function for this data:

```<code>readdata = function(filename){
    data = read.csv(filename,header=TRUE, colClasses = c(date = "Date"))
    PRCABS = abs(data$PRC)
    mcap = PRCABS * data$SHROUT
    hpr = data$RET
    HPR = as.numeric(levels(hpr))[hpr]
    HPR[HPR==""] = NA
    data = cbind(data,PRCABS,mcap, HPR)
    return(data)
}

data <- readdata('fewdata.csv')
dt <- as.data.table(data)
</code>```

答:
Building on @thelatemail's answer, here are two more variations on the same theme.

In both cases, setkey() first makes things easier to reason with :

```<code>setkey(dat,PERMNO,date)  # sort by PERMNO, then by date within PERMNO
</code>```

Option 1 : stack the data you want (if any) from each group

```<code>system.time(
  ans1 <- dat[, {
    w = first(which(!is.na(DLSTCD)))
    if (!length(w)) .SD
    else if (w>1) .SD[seq_len(w)]
  }, keyby=PERMNO]
)
   user  system elapsed
  2.604   0.000   2.605
</code>```

That's quite slow because allocating and populating all the little bits of memory for the result for each group, only then to be stacked into one single result in the end again, takes time and memory.

Option 2 : (closer to the way you phrased the question) find the row numbers to delete, then delete them.

```<code>system.time({
  todelete <- dat[, {
    w = first(which(!is.na(DLSTCD)))
    if (length(w)) .I[seq.int(from=if (w==1) 1 else w+1, to=.N)]
  }, keyby=PERMNO]

  ans2 <- dat[ -todelete$V1 ]
})
   user  system elapsed
  0.160   0.000   0.159
</code>```

That's faster because it's only stacking row numbers to delete followed by a single operation to delete the required rows in one bulk operation. Since it's grouping by the first column of the key, it uses the key to make the grouping faster (groups are contiguous in RAM).

More info can be found about ?.SD and ?.I on this manual page.

You can inspect and debug what is happening inside each group just by adding a call to browser() and having a look as follows.

```<code>> ans1 <- dat[, {
     browser()
     w = first(which(!is.na(DLSTCD)))
     if (!length(w)) .SD
     else if (w>1) .SD[seq_len(w)]
   }, keyby=PERMNO]
Browse[1]> .SD      # type .SD to look at it
        date DLSTCD
  1:   21679     NA
  2:   46408      1
  3:   68378     NA
  4:   75362     NA
  5:   77690     NA
 ---
111: 2396559      1
112: 2451629     NA
113: 2461958     NA
114: 2484403     NA
115: 2485217     NA
Browse[1]> w   # doesn't exist yet because browser() before that line
Error: object 'w' not found
Browse[1]> w = first(which(!is.na(DLSTCD)))  # copy and paste line
Browse[1]> w
[1] 2
Browse[1]> if (!length(w)) .SD else if (w>1) .SD[seq_len(w)]
    date DLSTCD
1: 21679     NA
2: 46408      1
Browse[1]> # that is what is returned for this group
Browse[1]> n   # or type n to step to next line
debug at #3: w = first(which(!is.na(DLSTCD)))
Browse[2]> help  # for browser commands
</code>```

Let's say you find a problem or bug with one particular PERMNO.  You can make the call to browser conditional as follows.

```<code>> ans1 <- dat[, {
     if (PERMNO==42) browser()
     w = first(which(!is.na(DLSTCD)))
     if (!length(w)) .SD
     else if (w>1) .SD[seq_len(w)]
  }, keyby=PERMNO]
Browse[1]> .SD
        date DLSTCD
  1:   31018     NA
  2:   35803      1
  3:   37494     NA
  4:   50012     NA
  5:   52459     NA
 ---
128: 2405818     NA
129: 2429995     NA
130: 2455519     NA
131: 2478605      1
132: 2497925     NA
Browse[1]>
</code>```

Body:
I have data as follows:

PERMNO date DLSTCD
    10 1983     NA
    10 1985    250
    10 1986     NA
    10 1986     NA
    10 1987    240
    10 1987     NA
    11 1984     NA
    11 1984     NA
    11 1985     NA
    11 1987     NA
    12 1984    240

I need to filter rows based on following criteria:

For each PERMNO, sort data by date

Parse through the sorted data and delete rows after a company gets delisted (ie. DLSTCD != NA)

If the first row corresponds to company getting delisted, do not include any rows for that company

Based on these criteria, following is my expected output:

PERMNO date DLSTCD
    10 1983     NA
    10 1985    250
    11 1984     NA
    11 1984     NA
    11 1985     NA
    11 1987     NA

I am using data.table in R to work with this data. The example above is an oversimplified version of my actual data, which contains around 3M rows corresponding to 30k PERMNOs.

I implemented three different methods for doing this, as can be seen here:

 r-fiddle: http://www.r-fiddle.org/#/fiddle?id=4GapqSbX&version=3

Below I compare my implementations using a small dataset of 50k rows. Here are my results:

Time Comparison

system.time(dt <- filterbydelistingcode(dt))   # 39.962 seconds
system.time(dt <- filterbydelistcoderowindices(dt))   # 39.014 seconds
system.time(dt <- filterbydelistcodeinline(dt))   # 114.3 seconds

As you can see all my implementations are extremely inefficient. Can someone please help me implement a much faster version for this? Thank you.

Edit: Here is a link to a sample dataset of 50k rows that I used for time comparison: https://ufile.io/q9d8u

Also, here is a customized read function for this data:

readdata = function(filename){
    data = read.csv(filename,header=TRUE, colClasses = c(date = "Date"))
    PRCABS = abs(data$PRC)
    mcap = PRCABS * data$SHROUT
    hpr = data$RET
    HPR = as.numeric(levels(hpr))[hpr]
    HPR[HPR==""] = NA
    data = cbind(data,PRCABS,mcap, HPR)
    return(data)
}

data <- readdata('fewdata.csv')
dt <- as.data.table(data)

Body:
Building on @thelatemail's answer, here are two more variations on the same theme.

In both cases, setkey() first makes things easier to reason with :

setkey(dat,PERMNO,date)  # sort by PERMNO, then by date within PERMNO

Option 1 : stack the data you want (if any) from each group

system.time(
  ans1 <- dat[, {
    w = first(which(!is.na(DLSTCD)))
    if (!length(w)) .SD
    else if (w>1) .SD[seq_len(w)]
  }, keyby=PERMNO]
)
   user  system elapsed
  2.604   0.000   2.605

That's quite slow because allocating and populating all the little bits of memory for the result for each group, only then to be stacked into one single result in the end again, takes time and memory.

Option 2 : (closer to the way you phrased the question) find the row numbers to delete, then delete them.

system.time({
  todelete <- dat[, {
    w = first(which(!is.na(DLSTCD)))
    if (length(w)) .I[seq.int(from=if (w==1) 1 else w+1, to=.N)]
  }, keyby=PERMNO]

  ans2 <- dat[ -todelete$V1 ]
})
   user  system elapsed
  0.160   0.000   0.159

That's faster because it's only stacking row numbers to delete followed by a single operation to delete the required rows in one bulk operation. Since it's grouping by the first column of the key, it uses the key to make the grouping faster (groups are contiguous in RAM).

More info can be found about ?.SD and ?.I on this manual page.

You can inspect and debug what is happening inside each group just by adding a call to browser() and having a look as follows.

> ans1 <- dat[, {
     browser()
     w = first(which(!is.na(DLSTCD)))
     if (!length(w)) .SD
     else if (w>1) .SD[seq_len(w)]
   }, keyby=PERMNO]
Browse[1]> .SD      # type .SD to look at it
        date DLSTCD
  1:   21679     NA
  2:   46408      1
  3:   68378     NA
  4:   75362     NA
  5:   77690     NA
 ---
111: 2396559      1
112: 2451629     NA
113: 2461958     NA
114: 2484403     NA
115: 2485217     NA
Browse[1]> w   # doesn't exist yet because browser() before that line
Error: object 'w' not found
Browse[1]> w = first(which(!is.na(DLSTCD)))  # copy and paste line
Browse[1]> w
[1] 2
Browse[1]> if (!length(w)) .SD else if (w>1) .SD[seq_len(w)]
    date DLSTCD
1: 21679     NA
2: 46408      1
Browse[1]> # that is what is returned for this group
Browse[1]> n   # or type n to step to next line
debug at #3: w = first(which(!is.na(DLSTCD)))
Browse[2]> help  # for browser commands

Let's say you find a problem or bug with one particular PERMNO.  You can make the call to browser conditional as follows.

> ans1 <- dat[, {
     if (PERMNO==42) browser()
     w = first(which(!is.na(DLSTCD)))
     if (!length(w)) .SD
     else if (w>1) .SD[seq_len(w)]
  }, keyby=PERMNO]
Browse[1]> .SD
        date DLSTCD
  1:   31018     NA
  2:   35803      1
  3:   37494     NA
  4:   50012     NA
  5:   52459     NA
 ---
128: 2405818     NA
129: 2429995     NA
130: 2455519     NA
131: 2478605      1
132: 2497925     NA
Browse[1]>


问:
Angular 2. Remove @Hostlistener()
How can I removed @Hostlistener() in Angular 2, like used removeEventListener in Native JS?

Example:
I have many dropDown components in my page. When dropDown opened I want to add handler on document click event and to remove handler when dropDown closed.

Native JS:

```<code>function handler(){
  //do something
}
document.addEventListener('click', handler); // add handler
document.removeEventListener('click', handler); // remove handler
</code>```

Angular 2:

```<code>  @HostListener('document: click') onDocumentClick () {
    // do something
  }

  // How can I remove handler?
</code>```

答:
Julia Passynkova Answer is almost correct.

Just remove the quotation marks around "document", like this:

```<code>// subscribe
this.handler = this.renderer.listen(document, "click", event =>{...});

// unsubscribe
this.handler();
</code>```

Annotation:

I find @Smiranin comment quite usefull. As Angular 2 makes use of Rxjs, a better way would be to create a dedicated service for these types of events and expose subjects on it. Components can than consume the subjects event stream resulting in the same behaviour. This would make the code more decoupled, easier to test and robust to API changes.

Title: Angular 2. Remove @Hostlistener()

Body:
How can I removed @Hostlistener() in Angular 2, like used removeEventListener in Native JS?

Example:
I have many dropDown components in my page. When dropDown opened I want to add handler on document click event and to remove handler when dropDown closed.

Native JS:

function handler(){
  //do something
}
document.addEventListener('click', handler); // add handler
document.removeEventListener('click', handler); // remove handler

Angular 2:

  @HostListener('document: click') onDocumentClick () {
    // do something
  }

  // How can I remove handler?

Body:
Julia Passynkova Answer is almost correct.

Just remove the quotation marks around "document", like this:

// subscribe
this.handler = this.renderer.listen(document, "click", event =>{...});

// unsubscribe
this.handler();

Annotation:

I find @Smiranin comment quite usefull. As Angular 2 makes use of Rxjs, a better way would be to create a dedicated service for these types of events and expose subjects on it. Components can than consume the subjects event stream resulting in the same behaviour. This would make the code more decoupled, easier to test and robust to API changes.

ContentLicense: CC BY-SA 4.0


问:
How to add a div that does not damage the view?
My case is like this

My view is like this :

```<code><div class="form-group">
    <div class="col-sm-10">
        <ul class="list-inline list-photo">
            @foreach($product->photos as $i => $photo)
            <li id="thumbnail-view-{{$i}}" >
                  ...
            </li>
            @endforeach

            @for($i = count($product->photos); $i < 5; $i++)
                <li id="thumbnail-upload-li-{{$i}}">
                    <a href="javascript:" class="thumbnail thumbnail-upload" id="thumbnail-view-{{$i}}">
                        <span class="fa fa-plus fa-2x"></span>
                    </a>
                </li>
                ...
            @endfor
            </div>
        </ul>
    </div>
</div>
</code>```

I want to add div before @for like this :

```<code><div id="test">
    @for($i = count($product->photos); $i < 5; $i++)
        <li id="thumbnail-upload-li-{{$i}}">
            ...
        </li>
        ...
    @endfor
</div>
</code>```

When I add div, the view becomes not tidy

I need to add div. So I want to call it from javascript

How can I solve the problem?

答:
The reason your view "becomes not tidy", as you put it, is because you are producing invalid HTML. The only valid child of
 is an
 element. You therefore have two choices, either use multiple lists and add a class/ID to each one, like this:

```<code><ul class="list-inline list-photo thumbnail-view">
    @foreach($product->photos as $i => $photo)
    <li id="thumbnail-view-{{$i}}" >
            ...
    </li>
    @endforeach
</ul>
<ul class="list-inline list-photo thumbnail-upload">
    @for($i = count($product->photos); $i < 5; $i++)
        <li id="thumbnail-upload-li-{{$i}}">
            <a href="javascript:" class="thumbnail thumbnail-upload" id="thumbnail-view-{{$i}}">
                <span class="fa fa-plus fa-2x"></span>
            </a>
        </li>
        ...
    @endfor
</ul>
</code>```

Or you can apply a class to specific row(s) you want to select with JavaScript or CSS if you want to style them differently:

```<code><ul class="list-inline list-photo">
    @foreach($product->photos as $i => $photo)
    <li id="thumbnail-view-{{$i}}" class="thumbnail-view">
            ...
    </li>
    @endforeach

    @for($i = count($product->photos); $i < 5; $i++)
        <li id="thumbnail-upload-li-{{$i}}" class="thumbnail-upload">
            <a href="javascript:" class="thumbnail thumbnail-upload" id="thumbnail-view-{{$i}}">
                <span class="fa fa-plus fa-2x"></span>
            </a>
        </li>
        ...
    @endfor
</ul>
</code>```

Body:
My case is like this

My view is like this :

            @foreach($product->photos as $i => $photo)

                  ...

            @endforeach

            @for($i = count($product->photos); $i < 5; $i++)

                ...
            @endfor

I want to add div before @for like this :

    @for($i = count($product->photos); $i < 5; $i++)

            ...

        ...
    @endfor

When I add div, the view becomes not tidy

I need to add div. So I want to call it from javascript

How can I solve the problem?

Body:
The reason your view "becomes not tidy", as you put it, is because you are producing invalid HTML. The only valid child of <ul> is an <li> element. You therefore have two choices, either use multiple lists and add a class/ID to each one, like this:

<ul class="list-inline list-photo thumbnail-view">
    @foreach($product->photos as $i => $photo)
    <li id="thumbnail-view-{{$i}}" >
            ...
    </li>
    @endforeach
</ul>
<ul class="list-inline list-photo thumbnail-upload">
    @for($i = count($product->photos); $i < 5; $i++)
        <li id="thumbnail-upload-li-{{$i}}">
            <a href="javascript:" class="thumbnail thumbnail-upload" id="thumbnail-view-{{$i}}">
                <span class="fa fa-plus fa-2x"></span>
            </a>
        </li>
        ...
    @endfor
</ul>

Or you can apply a class to specific row(s) you want to select with JavaScript or CSS if you want to style them differently:

<ul class="list-inline list-photo">
    @foreach($product->photos as $i => $photo)
    <li id="thumbnail-view-{{$i}}" class="thumbnail-view">
            ...
    </li>
    @endforeach

    @for($i = count($product->photos); $i < 5; $i++)
        <li id="thumbnail-upload-li-{{$i}}" class="thumbnail-upload">
            <a href="javascript:" class="thumbnail thumbnail-upload" id="thumbnail-view-{{$i}}">
                <span class="fa fa-plus fa-2x"></span>
            </a>
        </li>
        ...
    @endfor
</ul>


问:
depending on directories in make
This is a followup to my earlier question: SO 4403861 because the suggested solutions broke the dependencies, making the makefile useless.  I can't figure out why.

I am using gnu make 3.82
I have a rule that works if the obj directory has been created:

```<code>objdir:=../obj
$(objdir)/%.o: %.C
    $(COMPILE) -MM -MT$(objdir)/$(notdir $@) $< -o $(DEPDIR)/$(notdir $(basename $<).d )
    $(COMPILE) -o $(objdir)/$(notdir $@ ) -c $<
</code>```

However, if the obj directory isn't there, make fails.  I wanted make to automatically create ../obj on demand, so I added what I thought was very simple:

```<code>$(objdir)/%.o: %.C $(objdir)
    $(COMPILE) -MM -MT$(objdir)/$(notdir $@) $< -o $(DEPDIR)/$(notdir $(basename $<).d )
    $(COMPILE) -o $(objdir)/$(notdir $@ ) -c $<

$(objdir):
   if [ ! -d $(objdir) ] ; then mkdir $(objdir) ; fi
</code>```

When I do so, make always forces the compile, every time.  Why?  The mkdir should not happen unless there is no directory?  Why are dependencies destroyed by this simple change?

答:
As answered already, you cannot put a  directory with output files as a dependency, because it is updated every time.

One solution (stated above) is to put a mkdir -p before each build, like this:

```<code>objdir:=../obj
$(objdir)/%.o: %.C
    @mkdir -p $(objdir) $(DEPDIR) ...
    $(COMPILE) -MM -MT$(objdir)/$(notdir $@) $< -o $(DEPDIR)/$(notdir $(basename $<).d )
    $(COMPILE) -o $(objdir)/$(notdir $@ ) -c $<
</code>```

But I don't love this solution, because it forces running an extra process lots and lots of times.  However, knowing the reason for the error, there is another way:

```<code>exe: dirs $(OBJ)
</code>```

In the primary target, the one building the executable, just insert a target dirs before the objects.  Since it's hit in order:

```<code>dirs:
    @mkdir -p $(objdir) $(DESTDIR) ...
</code>```

and this is only done once for the entire build, rather than once per file.

Title: depending on directories in make

Body:
This is a followup to my earlier question: SO 4403861 because the suggested solutions broke the dependencies, making the makefile useless.  I can't figure out why.

I am using gnu make 3.82
I have a rule that works if the obj directory has been created:

objdir:=../obj
$(objdir)/%.o: %.C
    $(COMPILE) -MM -MT$(objdir)/$(notdir $@) $< -o $(DEPDIR)/$(notdir $(basename $<).d )
    $(COMPILE) -o $(objdir)/$(notdir $@ ) -c $<

However, if the obj directory isn't there, make fails.  I wanted make to automatically create ../obj on demand, so I added what I thought was very simple:

$(objdir)/%.o: %.C $(objdir)
    $(COMPILE) -MM -MT$(objdir)/$(notdir $@) $< -o $(DEPDIR)/$(notdir $(basename $<).d )
    $(COMPILE) -o $(objdir)/$(notdir $@ ) -c $<

$(objdir):
   if [ ! -d $(objdir) ] ; then mkdir $(objdir) ; fi

When I do so, make always forces the compile, every time.  Why?  The mkdir should not happen unless there is no directory?  Why are dependencies destroyed by this simple change?

Body:
As answered already, you cannot put a  directory with output files as a dependency, because it is updated every time.

One solution (stated above) is to put a mkdir -p before each build, like this:

objdir:=../obj
$(objdir)/%.o: %.C
    @mkdir -p $(objdir) $(DEPDIR) ...
    $(COMPILE) -MM -MT$(objdir)/$(notdir $@) $< -o $(DEPDIR)/$(notdir $(basename $<).d )
    $(COMPILE) -o $(objdir)/$(notdir $@ ) -c $<

But I don't love this solution, because it forces running an extra process lots and lots of times.  However, knowing the reason for the error, there is another way:

exe: dirs $(OBJ)

In the primary target, the one building the executable, just insert a target dirs before the objects.  Since it's hit in order:

dirs:
    @mkdir -p $(objdir) $(DESTDIR) ...

and this is only done once for the entire build, rather than once per file.


问:
Using C# to get content from URL followed by this error "WebRequest does not contain a definition for GetRespone and ..."
This code comes from Microsoft's documentation. I put this code in a Console app and a Windows Form app separately.

In the Console app, there is an error : “WebRequest does not contain a definition for GetRespone and …”

But in the Windows Form app, there is no error.

I really don't know why this happen. I am a beginner of C#, so this question may be stupid. But I feel very confused. Please explain to me.
Thank you!

Below are two screenshots for these two situation:

enter image description here

enter image description here

Here is the code.

```<code>using System;
using System.IO;
using System.Net;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request for the URL.
            WebRequest request = WebRequest.Create(
              "http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams and the response.
            reader.Close();
            response.Close();
        }
    }
}
</code>```

答:
Steps below made mine successful

New a solution - a Visual C# Console Application in Visual Studio. Name your project something as "ConsoleApp1".

Copy and paste code within main function from the web, to newly generated Main function.

Add below using statements

```<code>using System.Net;
using System.IO;
</code>```

Run it by press "F5". It's successful. But the window closed as soon as it completes.

For you to see the output result, put a break point at "}" statement to avoid the window to close. Alternatively, you can add below as last C# statement. Then you need to click any key to close the console window.

Console.ReadKey();

The output, I got:

```<code>OK
<html><head><title>Microsoft Corporation</title><meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"></meta><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><meta name="SearchTitle" content="Microsoft.com" scheme=""></meta><meta name="Description" content="Get product information, support, and news from Microsoft." scheme=""></meta><meta name="Title" content="Microsoft.com Home Page" scheme=""></meta><meta name="Keywords" content="Microsoft, product, support, help, training, Office, Windows, software, download, trial, preview, demo,  business, security, update, free, computer, PC, server, search, download, install, news" scheme=""></meta><meta name="SearchDescription" content="Microsoft.com Homepage" scheme=""></meta></head><body><p>Your current User-Agent string appears to be from an automated process, if this is incorrect, please click this link:<a href="http://www.microsoft.com/en/us/default.aspx?redir=true">United States English Microsoft Homepage</a></p></body></html>
</code>```

Body:
This code comes from Microsoft's documentation. I put this code in a Console app and a Windows Form app separately.

In the Console app, there is an error : “WebRequest does not contain a definition for GetRespone and …”

But in the Windows Form app, there is no error.

I really don't know why this happen. I am a beginner of C#, so this question may be stupid. But I feel very confused. Please explain to me.
Thank you!

Below are two screenshots for these two situation:

enter image description here

enter image description here

Here is the code.

using System;
using System.IO;
using System.Net;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request for the URL.
            WebRequest request = WebRequest.Create(
              "http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            Stream dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams and the response.
            reader.Close();
            response.Close();
        }
    }
}

Body:
Steps below made mine successful

New a solution - a Visual C# Console Application in Visual Studio. Name your project something as "ConsoleApp1".

Copy and paste code within main function from the web, to newly generated Main function.

Add below using statements

using System.Net;
using System.IO;

Run it by press "F5". It's successful. But the window closed as soon as it completes.

For you to see the output result, put a break point at "}" statement to avoid the window to close. Alternatively, you can add below as last C# statement. Then you need to click any key to close the console window.

Console.ReadKey();

The output, I got:

OK
<html><head><title>Microsoft Corporation</title><meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"></meta><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><meta name="SearchTitle" content="Microsoft.com" scheme=""></meta><meta name="Description" content="Get product information, support, and news from Microsoft." scheme=""></meta><meta name="Title" content="Microsoft.com Home Page" scheme=""></meta><meta name="Keywords" content="Microsoft, product, support, help, training, Office, Windows, software, download, trial, preview, demo,  business, security, update, free, computer, PC, server, search, download, install, news" scheme=""></meta><meta name="SearchDescription" content="Microsoft.com Homepage" scheme=""></meta></head><body><p>Your current User-Agent string appears to be from an automated process, if this is incorrect, please click this link:<a href="http://www.microsoft.com/en/us/default.aspx?redir=true">United States English Microsoft Homepage</a></p></body></html>


问:
How to change the Bot/Skype channel incoming message text format
Bot emulator works fine with the clear text responses but when I try to do the same via Skype the bot response with;

I don't understand, please try again

I found out that Skype auto-formats the email by wrapping it in  tags - XMM format and I am a bit stuck what's supposed to do. I think changing the incoming text format to plain-text would fix this.

I found this like for a similar issue on Github but this is on C# and I am using Node.JS.

How do I change the default text format of the bot/skype channel to plain text instead of markdown so Skype auto-formatting would not happen?

Updated according to href="https://stackoverflow.com/a/44454525/257727">@ezequiel-jadib but still no luck. Maybe I am doing it wrong?

```<code>// bot.js
bot.use(...[logger]);

// logger.js
module.exports = exports = {
    receive: (e, next) => {
        e.textFormat('plain');
        logConversation(e);
        next();
    },
    send: (e, next) => {
        logConversation(e);
        next();
    }
};
</code>```

答:
To get around this situation, you need to validate if you have an HTML wrapped email address, then extract the email portion from the string before saving it to session.dialogData.

For example replace line 40:

```<code>const usernameOrEmail = session.dialogData.usernameOrEmail = results.response;
</code>```

with:

```<code>// where results.response is in the format '<a href="hello@world.com">hello@world.com</a>'
var exampleEmailWrappedInHtml = results.response;

// validate if we have email wrapped in HTML from Skype
if(exampleEmailWrappedInHtml.match(/<a href="mailto:/i)) {
    console.log('HTML wrapped email detected!');
    const usernameOrEmail = session.dialogData.usernameOrEmail = exampleEmailWrappedInHtml.split('>')[1].split('<')[0];
} else {
    console.log('no match.');
}
</code>```

Body:
Bot emulator works fine with the clear text responses but when I try to do the same via Skype the bot response with;

I don't understand, please try again

I found out that Skype auto-formats the email by wrapping it in  tags - XMM format and I am a bit stuck what's supposed to do. I think changing the incoming text format to plain-text would fix this.

I found this like for a similar issue on Github but this is on C# and I am using Node.JS.

How do I change the default text format of the bot/skype channel to plain text instead of markdown so Skype auto-formatting would not happen?

Updated according to @ezequiel-jadib but still no luck. Maybe I am doing it wrong?

// bot.js
bot.use(...[logger]);

// logger.js
module.exports = exports = {
    receive: (e, next) => {
        e.textFormat('plain');
        logConversation(e);
        next();
    },
    send: (e, next) => {
        logConversation(e);
        next();
    }
};

Body:
To get around this situation, you need to validate if you have an HTML wrapped email address, then extract the email portion from the string before saving it to session.dialogData.

For example replace line 40:

const usernameOrEmail = session.dialogData.usernameOrEmail = results.response;

with:

// where results.response is in the format '<a href="hello@world.com">hello@world.com</a>'
var exampleEmailWrappedInHtml = results.response;

// validate if we have email wrapped in HTML from Skype
if(exampleEmailWrappedInHtml.match(/<a href="mailto:/i)) {
    console.log('HTML wrapped email detected!');
    const usernameOrEmail = session.dialogData.usernameOrEmail = exampleEmailWrappedInHtml.split('>')[1].split('<')[0];
} else {
    console.log('no match.');
}


问:
Programmatically authenticate to Google Compute Engine via service access key
After researching the Google Compute Documentation I found out that there is no example of authentication via a generated Service Access Key.

I tried it with the following code (this is line 69)

```<code>GoogleCredential credential = new GoogleCredential.Builder()
                .setClientSecrets(authorize())
                .build();
</code>```

and

```<code>private static  GoogleClientSecrets authorize() {
    // initialize client secrets object
    GoogleClientSecrets clientSecrets;
    // load client secrets
    try {
        clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(
                GCEImporter.class.getResourceAsStream("/client_secrets.json")));

    } catch(IOException e){
        e.printStackTrace();
        return null;
    }

    return clientSecrets;
}
</code>```

the client_secrets.json is the generated file from google which looks like this

```<code>{
 "type": "service_account",
 "project_id": "...",
 "private_key_id": "...",
 "private_key": "-----BEGIN PRIVATE KEY-----...-----END PRIVATE KEY-----\n",
 "client_email": "....iam.gserviceaccount.com",
 "client_id": "...",
 "auth_uri": "https://accounts.google.com/o/oauth2/auth",
 "token_uri": "https://accounts.google.com/o/oauth2/token",
 "auth_provider_x509_cert_url":
 "https://www.googleapis.com/oauth2/v1/certs",
 "client_x509_cert_url":
 "https://www.googleapis.com/robot/v1/metadata/x509/..."
}
</code>```

all I receive when executing this code is

```<code>java.lang.IllegalArgumentException
at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkArgument(Preconditions.java:111)
at com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:37)
at com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.getDetails(GoogleClientSecrets.java:82)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential$Builder.setClientSecrets(GoogleCredential.java:559)
at net.bytesource.jira.asset.synchronization.importer.google.gce.GCEImporter.getAssets(GCEImporter.java:69)
at net.bytesource.jira.asset.synchronization.importer.google.gce.GoogleImporterTest.getAssets(GoogleImporterTest.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

Does anybody have a solution to this problem?

答:
There are few issues here:

The private key info json file that you downloaded when you created a new service account from the IAM page is not in the format that is expected by Client Secrets.

You're trying to follow the [OAuth steps that are meant for Desktop and mobile apps][2]. This will not work with Google Cloud APIs.

The recommended and simpler way for authorizing with Google Cloud APIs is to use Application Default Credentials which is described here and here.

In short what you need to do is (based on the outline here):

Set the path to the JSON file you have in the environment variable GOOGLE_APPLICATION_CREDENTIALS.

Create the GoogleCredential object as shown below.

GoogleCredential credential = GoogleCredential.getApplicationDefault();

After the above step, you should be able to talk to any of the Google Cloud APIs. In case of GCE, you will create an instance of Compute

Compute compute = new Compute.Builder
    (transport, jsonFactory, credential).build();

I am just copying and pasting the example from compute.instances.insert API here.

```<code>/*
 * BEFORE RUNNING:
 * ---------------
 * 1. If not already done, enable the Compute Engine API
 *    and check the quota for your project at
 *    https://console.developers.google.com/apis/api/compute
 * 2. This sample uses Application Default Credentials for authentication.
 *    If not already done, install the gcloud CLI from
 *    https://cloud.google.com/sdk and run
 *    `gcloud beta auth application-default login`.
 *    For more information, see
 *    https://developers.google.com/identity/protocols/application-default-credentials
 * 3. Install the Java client library on Maven or Gradle. Check installation
 *    instructions at https://github.com/google/google-api-java-client.
 *    On other build systems, you can add the jar files to your project from
 *    https://developers.google.com/resources/api-libraries/download/compute/v1/java
 */
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.model.Instance;
import com.google.api.services.compute.model.Operation;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;

public class ComputeExample {
  public static void main(String args[]) throws IOException, GeneralSecurityException {
    // Project ID for this request.
    String project = ""; // TODO: Update placeholder value.

    // The name of the zone for this request.
    String zone = ""; // TODO: Update placeholder value.

    // TODO: Assign values to desired fields of `requestBody`:
    Instance requestBody = new Instance();

    Compute computeService = createComputeService();
    Compute.Instances.Insert request =
        computeService.instances().insert(project, zone, requestBody);

    Operation response = request.execute();

    // TODO: Change code below to process the `response` object:
    System.out.println(response);
  }

  public static Compute createComputeService() throws IOException, GeneralSecurityException {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    if (credential.createScopedRequired()) {
      credential =
          credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
    }

    return new Compute.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName("Google-ComputeSample/0.1")
        .build();
  }
}
</code>```

Body:
After researching the Google Compute Documentation I found out that there is no example of authentication via a generated Service Access Key.

I tried it with the following code (this is line 69)

GoogleCredential credential = new GoogleCredential.Builder()
                .setClientSecrets(authorize())
                .build();

and

private static  GoogleClientSecrets authorize() {
    // initialize client secrets object
    GoogleClientSecrets clientSecrets;
    // load client secrets
    try {
        clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(
                GCEImporter.class.getResourceAsStream("/client_secrets.json")));

    } catch(IOException e){
        e.printStackTrace();
        return null;
    }

    return clientSecrets;
}

the client_secrets.json is the generated file from google which looks like this

{
 "type": "service_account",
 "project_id": "...",
 "private_key_id": "...",
 "private_key": "-----BEGIN PRIVATE KEY-----...-----END PRIVATE KEY-----\n",
 "client_email": "....iam.gserviceaccount.com",
 "client_id": "...",
 "auth_uri": "https://accounts.google.com/o/oauth2/auth",
 "token_uri": "https://accounts.google.com/o/oauth2/token",
 "auth_provider_x509_cert_url":
 "https://www.googleapis.com/oauth2/v1/certs",
 "client_x509_cert_url":
 "https://www.googleapis.com/robot/v1/metadata/x509/..."
}

all I receive when executing this code is

java.lang.IllegalArgumentException
at com.google.api.client.repackaged.com.google.common.base.Preconditions.checkArgument(Preconditions.java:111)
at com.google.api.client.util.Preconditions.checkArgument(Preconditions.java:37)
at com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets.getDetails(GoogleClientSecrets.java:82)
at com.google.api.client.googleapis.auth.oauth2.GoogleCredential$Builder.setClientSecrets(GoogleCredential.java:559)
at net.bytesource.jira.asset.synchronization.importer.google.gce.GCEImporter.getAssets(GCEImporter.java:69)
at net.bytesource.jira.asset.synchronization.importer.google.gce.GoogleImporterTest.getAssets(GoogleImporterTest.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Does anybody have a solution to this problem?

Body:
There are few issues here:

The private key info json file that you downloaded when you created a new service account from the IAM page is not in the format that is expected by Client Secrets.

You're trying to follow the [OAuth steps that are meant for Desktop and mobile apps][2]. This will not work with Google Cloud APIs.

The recommended and simpler way for authorizing with Google Cloud APIs is to use Application Default Credentials which is described here and here.

In short what you need to do is (based on the outline here):

Set the path to the JSON file you have in the environment variable GOOGLE_APPLICATION_CREDENTIALS.

Create the GoogleCredential object as shown below.

GoogleCredential credential = GoogleCredential.getApplicationDefault();

After the above step, you should be able to talk to any of the Google Cloud APIs. In case of GCE, you will create an instance of Compute

Compute compute = new Compute.Builder
    (transport, jsonFactory, credential).build();

I am just copying and pasting the example from compute.instances.insert API here.

/*
 * BEFORE RUNNING:
 * ---------------
 * 1. If not already done, enable the Compute Engine API
 *    and check the quota for your project at
 *    https://console.developers.google.com/apis/api/compute
 * 2. This sample uses Application Default Credentials for authentication.
 *    If not already done, install the gcloud CLI from
 *    https://cloud.google.com/sdk and run
 *    `gcloud beta auth application-default login`.
 *    For more information, see
 *    https://developers.google.com/identity/protocols/application-default-credentials
 * 3. Install the Java client library on Maven or Gradle. Check installation
 *    instructions at https://github.com/google/google-api-java-client.
 *    On other build systems, you can add the jar files to your project from
 *    https://developers.google.com/resources/api-libraries/download/compute/v1/java
 */
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.compute.Compute;
import com.google.api.services.compute.model.Instance;
import com.google.api.services.compute.model.Operation;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;

public class ComputeExample {
  public static void main(String args[]) throws IOException, GeneralSecurityException {
    // Project ID for this request.
    String project = ""; // TODO: Update placeholder value.

    // The name of the zone for this request.
    String zone = ""; // TODO: Update placeholder value.

    // TODO: Assign values to desired fields of `requestBody`:
    Instance requestBody = new Instance();

    Compute computeService = createComputeService();
    Compute.Instances.Insert request =
        computeService.instances().insert(project, zone, requestBody);

    Operation response = request.execute();

    // TODO: Change code below to process the `response` object:
    System.out.println(response);
  }

  public static Compute createComputeService() throws IOException, GeneralSecurityException {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();

    GoogleCredential credential = GoogleCredential.getApplicationDefault();
    if (credential.createScopedRequired()) {
      credential =
          credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform"));
    }

    return new Compute.Builder(httpTransport, jsonFactory, credential)
        .setApplicationName("Google-ComputeSample/0.1")
        .build();
  }
}


问:
Intent does not clear on backpress, items in "on create" keep stacking. android
Im creating an app to access items form a database to view people in certain gorups/a team roster. When I search a group, I connect, create an intent and pass in the info from the search, and create buttons corresponding to the group members. On the "back press" I try to have the intent be cleared, remove the buttons and views, basically to destroy the activity. But, it does not work. When I click the back button, then call the method again, the buttons created form the first time I created the activity are still present, and the new buttons stack below the old ones.

Creating the intent:

```<code>public void run() {
            //connect to db
            try {
                System.out.println("Connecting to a selected database...");
                Class.forName("com.mysql.jdbc.Driver");
                Connection c = DriverManager.getConnection(url, "Schauls276_stacy", "123456");
                System.out.println("Made connection");
                Statement st = c.createStatement();
                //create query
                System.out.println("Executing Query...");
                switch (info){
                    case "Electrical":
                        sql = "SELECT * FROM `roster` WHERE roster.team LIKE \"E%\"" ;

                        break;
                    case "Programming":
                        sql = "SELECT * FROM `roster` WHERE roster.team LIKE \"P%\"" ;
                        break;
                    case "Drive":
                        sql = "SELECT * FROM `roster` WHERE roster.team LIKE \"D%\"" ;
                        break;
                    case "Marketing":
                        sql = "SELECT * FROM `roster` WHERE roster.team LIKE \"M%\"" ;
                        break;
                }
                //execute query
                PreparedStatement statement = c.prepareStatement(sql);
                ResultSet rs = statement.executeQuery();
                if(rs == null){
                    //create a pop up window to say there was no one found
                    System.out.println("rs is NULL");
                }else{
                    while(rs.next()){
                        groupString = groupString + (rs.getString("name") + "\n");
                        System.out.println("Found person: " + rs.getString("name"));
                    }
                }
                c.close();
                System.out.println("Connection Terminated.");

                Bundle bun = new Bundle();
                bun.putString("KEY", groupString);
                groupIntent.putExtras(bun);
                startActivity(groupIntent);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }).start();
</code>```

And then inside the intent:

```<code>private String text;
private String[] splitted;
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_group_members);

    //create the scroll view
    ScrollView sv = (ScrollView) this.findViewById(R.id.sv);
    //create the linear layout
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);

    //get the bundled items
    Bundle items = getIntent().getExtras();

    // get the text and split it
    if(items != null){
        text = items.getString("KEY");
    }
    splitted = text.split("\n");
    //create the new buttons, add them to the ll,  then add the ll to the sv
    for(int i = 0; i < splitted.length; i++){
        mButton = new Button(this);
        mButton.setId(i);
        mButton.setText(splitted[i]);
        mButton.setOnClickListener(this);
        ll.addView(mButton);

    }
    sv.addView(ll);
}
@Override
public void onClick(View v) {
    System.out.println("Button pressed! Button: " + splitted[v.getId()]);
}

@Override
public void onBackPressed(){
    System.out.println("Back Pressed");
    getIntent().removeExtra("Key");
    finish();
}
</code>```

After the first creation:

After the second creation:

答: It appears that your groupString variable is global and you keep appending your names to the same variable. Clear the groupString variable before using it in your while(rs.next()) loop.

Body:
Im creating an app to access items form a database to view people in certain gorups/a team roster. When I search a group, I connect, create an intent and pass in the info from the search, and create buttons corresponding to the group members. On the "back press" I try to have the intent be cleared, remove the buttons and views, basically to destroy the activity. But, it does not work. When I click the back button, then call the method again, the buttons created form the first time I created the activity are still present, and the new buttons stack below the old ones.

Creating the intent:

public void run() {
            //connect to db
            try {
                System.out.println("Connecting to a selected database...");
                Class.forName("com.mysql.jdbc.Driver");
                Connection c = DriverManager.getConnection(url, "Schauls276_stacy", "123456");
                System.out.println("Made connection");
                Statement st = c.createStatement();
                //create query
                System.out.println("Executing Query...");
                switch (info){
                    case "Electrical":
                        sql = "SELECT * FROM `roster` WHERE roster.team LIKE \"E%\"" ;

                        break;
                    case "Programming":
                        sql = "SELECT * FROM `roster` WHERE roster.team LIKE \"P%\"" ;
                        break;
                    case "Drive":
                        sql = "SELECT * FROM `roster` WHERE roster.team LIKE \"D%\"" ;
                        break;
                    case "Marketing":
                        sql = "SELECT * FROM `roster` WHERE roster.team LIKE \"M%\"" ;
                        break;
                }
                //execute query
                PreparedStatement statement = c.prepareStatement(sql);
                ResultSet rs = statement.executeQuery();
                if(rs == null){
                    //create a pop up window to say there was no one found
                    System.out.println("rs is NULL");
                }else{
                    while(rs.next()){
                        groupString = groupString + (rs.getString("name") + "\n");
                        System.out.println("Found person: " + rs.getString("name"));
                    }
                }
                c.close();
                System.out.println("Connection Terminated.");

                Bundle bun = new Bundle();
                bun.putString("KEY", groupString);
                groupIntent.putExtras(bun);
                startActivity(groupIntent);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }).start();

And then inside the intent:

private String text;
private String[] splitted;
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_group_members);

    //create the scroll view
    ScrollView sv = (ScrollView) this.findViewById(R.id.sv);
    //create the linear layout
    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);

    //get the bundled items
    Bundle items = getIntent().getExtras();

    // get the text and split it
    if(items != null){
        text = items.getString("KEY");
    }
    splitted = text.split("\n");
    //create the new buttons, add them to the ll,  then add the ll to the sv
    for(int i = 0; i < splitted.length; i++){
        mButton = new Button(this);
        mButton.setId(i);
        mButton.setText(splitted[i]);
        mButton.setOnClickListener(this);
        ll.addView(mButton);

    }
    sv.addView(ll);
}
@Override
public void onClick(View v) {
    System.out.println("Button pressed! Button: " + splitted[v.getId()]);
}

@Override
public void onBackPressed(){
    System.out.println("Back Pressed");
    getIntent().removeExtra("Key");
    finish();
}

After the first creation:

After the second creation:


问:
React native view container with different top and bottom background color
Trying to create a view with soft border. The header should have a different color and the footer to have a different color. I tried all the possibilities but couldn't figure out. At the moment i have the below code which creates a view with soft border and i want to achieve this.

```<code><View style={{borderWidth: 1, borderRadius: 10, padding: 10}}>
      <View>
            <Text style={styles.name}>
                SECTOR REPORTS
            </Text>
            <Button title="ADD SECTOR REPORT"/>
    </View>
</code>```

答:
You can set overflow: hidden on container view, but it's only works on iOS.

overflow:hidden is not supported on Android

check this issue

if you want to achieve this on Android, you can use these style props on header and footer components

borderTopLeftRadius

borderTopRightRadius

borderBottomRightRadius

borderBottomLeftRadius

here is an example: demo

Body:
Trying to create a view with soft border. The header should have a different color and the footer to have a different color. I tried all the possibilities but couldn't figure out. At the moment i have the below code which creates a view with soft border and i want to achieve this.

<View style={{borderWidth: 1, borderRadius: 10, padding: 10}}>
      <View>
            <Text style={styles.name}>
                SECTOR REPORTS
            </Text>
            <Button title="ADD SECTOR REPORT"/>
    </View>


问:
filtering multiple dates across database in sql?
I have a database that I am trying to filter out by time stamped dates. Since the dates occur over a 15 year time span, I want to filter everything by month (ex all of the january data together). I also have other conditions to filter data, but the logic is getting screwed up when I filter things doing
ex)

```<code>where x=y
and id.number=165
and {id.date between UNIX_DATE('01-01-2015') and UNIX_DATE('31-01-2015')
     or id.date between UNIX_DATE('01-01-2016') and UNIX_DATE(-31-01-2016')}
</code>```

I know I can't break it into that braced condition, since it returns an error for me. Is there a way to group the conditions together so the logic is conditionA AND conditionB AND (dateyearA OR dateyearB OR dateyearC or....)?

答:
The ANSI SQL standard provides a way of extracting the month from a date.  You should use that:

```<code>where x = y and
     id.number = 165 and
     extract(month from id.date) = 1
</code>```

That should greatly simplify your code.  Not all databases support extract().  Most support either extract() or the month() function.  All have this functionality using some function.

Body:
I have a database that I am trying to filter out by time stamped dates. Since the dates occur over a 15 year time span, I want to filter everything by month (ex all of the january data together). I also have other conditions to filter data, but the logic is getting screwed up when I filter things doing
ex)

where x=y
and id.number=165
and {id.date between UNIX_DATE('01-01-2015') and UNIX_DATE('31-01-2015')
     or id.date between UNIX_DATE('01-01-2016') and UNIX_DATE(-31-01-2016')}

I know I can't break it into that braced condition, since it returns an error for me. Is there a way to group the conditions together so the logic is conditionA AND conditionB AND (dateyearA OR dateyearB OR dateyearC or....)?

Body:
The ANSI SQL standard provides a way of extracting the month from a date.  You should use that:

where x = y and
     id.number = 165 and
     extract(month from id.date) = 1

That should greatly simplify your code.  Not all databases support extract().  Most support either extract() or the month() function.  All have this functionality using some function.


问:
.NET assembly in current domain cannot be found
I have a project I am working that will search all loaded assemblies for any class that implements a certain interface. Then it will create an instance of that class and invoke a method of the interface. The code ran great on simple projects in testing environments. At the heart of it is the following function:

```<code>    public static List<Type> GetLoadedTypes(Type targetType)
    {
        var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
            .SelectMany(a => a.GetTypes())
            .Where(t => targetType.IsAssignableFrom(t)).ToList();
        return types;
    }
</code>```

I have another project that inserted this code into and the LINQ query fails because one of the assemblies in the domain cannot be found.

System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Practices.ObjectBuilder, Version=1.0.51206.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

I don't directly reference this assembly in any of my projects. How can I find out which assembly references it? How did the assembly even get into the domain if it cannot be found?

EDIT:
I am using Enterprise Library in the project but I am already referencing the Microsoft.Practices.ObjectBuilder2.dll. Apparently there is a difference between the two assemblies. Is that correct?

Thanks!
Jeff

答:
You can use the "Assembly Binding Log Viewer" (Fuslogvw.exe) that belongs to the dotnet2.0sdk (maybe also in later edition) . If logging is enabled it can show you wich assemblies are loaded and which assembly caused it to load.

For details see http://msdn.microsoft.com/en-us/library/e74a18c4(v=vs.80).aspx

Body:
I have a project I am working that will search all loaded assemblies for any class that implements a certain interface. Then it will create an instance of that class and invoke a method of the interface. The code ran great on simple projects in testing environments. At the heart of it is the following function:

    public static List<Type> GetLoadedTypes(Type targetType)
    {
        var types = AppDomain.CurrentDomain.GetAssemblies().ToList()
            .SelectMany(a => a.GetTypes())
            .Where(t => targetType.IsAssignableFrom(t)).ToList();
        return types;
    }

I have another project that inserted this code into and the LINQ query fails because one of the assemblies in the domain cannot be found.

System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Practices.ObjectBuilder, Version=1.0.51206.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

I don't directly reference this assembly in any of my projects. How can I find out which assembly references it? How did the assembly even get into the domain if it cannot be found?

EDIT:
I am using Enterprise Library in the project but I am already referencing the Microsoft.Practices.ObjectBuilder2.dll. Apparently there is a difference between the two assemblies. Is that correct?

Thanks!
Jeff


问:
Where are JSTL <fmt:message> data stored and how can I access it
Where are JSTL  messages stored and how can I access it without using a JSP tag? The reason is I am trying to get this information from client-side javascript.

The end goal is to be able to access this data from the Java backend and create an API endpoint to expose it to the front-end without relying on JSP compilation.

Thanks for your help :)

答:
JavaScript is executed on client side while JSTL is done on server side. So it is not possible to pass JavaScript variables in <fmt:message> tag.

You may have to use Ajax or get all variables needed by client side on server side.


问:
What is the alternation operator in Lua patterns?
In regex, | is used for alternation. What is the corresponding character in Lua patterns?

答:
Another workaround is: Instead of:

apple|orange

Write:

[ao][pr][pa][ln][eg]

Explanation: match alternate letters from each word. voila!


问:
I get a corrupted file when opening an email attachment sent with the PHP version of SendGrid mail
I am trying to send attachments with SendGrid through PHP, but keep getting a corrupted file error when I open the attachment.  The error message "We're sorry. We can't open 'file.docx' because we found a problem with its contents" and when I click on the details of the error I see "The file is corrupt and cannot be opened"

My code looks like the below:

```<code>$sendGridLoginInfo = $contactViaEmail->getSendGridLoginInfo();
        $sendgrid = new SendGrid($sendGridLoginInfo['Username'], $sendGridLoginInfo['Password']);
        $mail = new SendGrid\Mail();
        //Add the tracker args
        $mail->addUniqueArgument("EmailID", $emailID);
        $mail->addUniqueArgument("EmailGroupID", $emailGroupID);
        /*
        *    INSERT THE SUBSITUTIONS FOR SEND GRID
        */
        foreach ($availableSubstitutions as $availableSubstitution)
        {
            $mail->addSubstitution("[[" . $availableSubstitution . "]]", $substitutions[$availableSubstitution]);
        }

        /*
        *    ADD EACH EMAIL AS A NEW ADD TO
        *    This makes it BCC (because each person gets their own copy) and each person gets their own individualized email.
        */
        foreach ($emailInfo['SendToEmailAddress'] as $toEmail)
        {

            if ($sendToLoggedInUser)
            {
                $mail->addTo($adminEmailAddress);
            }
            else
            {
                $mail->addTo($toEmail);
            }
            $trashCount++;
        }

        //Set the subject
        $mail->setSubject($emailInfo['EmailSubject']);

        //Instantiate the HTML Purifier (for removing the html)
        $config = HTMLPurifier_Config::createDefault();
        $config->set('HTML', 'Allowed', '');
        $purifier = new HTMLPurifier($config);
        $mail->setText($purifier->purify($emailBody));
        $mail->setHtml($emailBody);

        if ($emailInfo['AttachmentID'])
        {
            $sql = "SELECT
                        AttachmentPath
                    FROM
                        EmailAttachments
                    WHERE
                        EmailAttachments.AttachmentID = :attachmentID";
            if ($query = $pdoLink->prepare($sql))
            {
                $bindValues = array();
                $bindValues[":attachmentID"] = $emailInfo['AttachmentID'];

                if ($query->execute($bindValues))
                {
                    if ($row = $query->fetch(\PDO::FETCH_ASSOC))
                    {
                        $attachment = "";
                        $mail->addAttachment($sitedb . $row['AttachmentPath']);
                    }
                }
            }
        }

        if ($sendToLoggedInUser)
        {
            $mail->setFrom($adminEmailAddress);
            $mail->setReplyTo($adminEmailAddress);
        }
        else
        {
            $mail->setFrom($emailInfo['FromAddress']);
            $mail->setReplyTo($emailInfo['ReplyTo']);
        }
        $mail->setFromName($emailInfo['FromName']);

        $sendgrid->web->send($mail);
</code>```

I've played with the content type and everything else that I can think of and just cannot find out what is causing the attachments to be corrupted.

答:
You need to create an attachment object to add an attachment, you can't use the path directly like you are. SendGrid requires files to be sent as base64 encoded strings.

You'll need to create the attachment object, you could do this as a method:

```<code>public function getAttachment($path)
{
    if (!file_exists($path)) {
        return false;
    }

    $attachment = new SendGrid\Attachment;
    $attachment->setContent(base64_encode(file_get_contents($path)));
    $attachment->setType(mime_content_type($path));
    $attachment->setFilename(basename($path));
    $attachment->setDisposition('attachment');
    return $attachment;
}
</code>```

Then add it to your email:

```<code>$attachment = $this->getAttachment($sitedb . $row['AttachmentPath']);
if ($attachment instanceof SendGrid\Attachment) {
    $mail->addAttachment($attachment);
}
</code>```

Body:
I am trying to send attachments with SendGrid through PHP, but keep getting a corrupted file error when I open the attachment.  The error message "We're sorry. We can't open 'file.docx' because we found a problem with its contents" and when I click on the details of the error I see "The file is corrupt and cannot be opened"

My code looks like the below:

$sendGridLoginInfo = $contactViaEmail->getSendGridLoginInfo();
        $sendgrid = new SendGrid($sendGridLoginInfo['Username'], $sendGridLoginInfo['Password']);
        $mail = new SendGrid\Mail();
        //Add the tracker args
        $mail->addUniqueArgument("EmailID", $emailID);
        $mail->addUniqueArgument("EmailGroupID", $emailGroupID);
        /*
        *    INSERT THE SUBSITUTIONS FOR SEND GRID
        */
        foreach ($availableSubstitutions as $availableSubstitution)
        {
            $mail->addSubstitution("[[" . $availableSubstitution . "]]", $substitutions[$availableSubstitution]);
        }

        /*
        *    ADD EACH EMAIL AS A NEW ADD TO
        *    This makes it BCC (because each person gets their own copy) and each person gets their own individualized email.
        */
        foreach ($emailInfo['SendToEmailAddress'] as $toEmail)
        {

            if ($sendToLoggedInUser)
            {
                $mail->addTo($adminEmailAddress);
            }
            else
            {
                $mail->addTo($toEmail);
            }
            $trashCount++;
        }

        //Set the subject
        $mail->setSubject($emailInfo['EmailSubject']);

        //Instantiate the HTML Purifier (for removing the html)
        $config = HTMLPurifier_Config::createDefault();
        $config->set('HTML', 'Allowed', '');
        $purifier = new HTMLPurifier($config);
        $mail->setText($purifier->purify($emailBody));
        $mail->setHtml($emailBody);

        if ($emailInfo['AttachmentID'])
        {
            $sql = "SELECT
                        AttachmentPath
                    FROM
                        EmailAttachments
                    WHERE
                        EmailAttachments.AttachmentID = :attachmentID";
            if ($query = $pdoLink->prepare($sql))
            {
                $bindValues = array();
                $bindValues[":attachmentID"] = $emailInfo['AttachmentID'];

                if ($query->execute($bindValues))
                {
                    if ($row = $query->fetch(\PDO::FETCH_ASSOC))
                    {
                        $attachment = "";
                        $mail->addAttachment($sitedb . $row['AttachmentPath']);
                    }
                }
            }
        }

        if ($sendToLoggedInUser)
        {
            $mail->setFrom($adminEmailAddress);
            $mail->setReplyTo($adminEmailAddress);
        }
        else
        {
            $mail->setFrom($emailInfo['FromAddress']);
            $mail->setReplyTo($emailInfo['ReplyTo']);
        }
        $mail->setFromName($emailInfo['FromName']);

        $sendgrid->web->send($mail);

I've played with the content type and everything else that I can think of and just cannot find out what is causing the attachments to be corrupted.

Body:
You need to create an attachment object to add an attachment, you can't use the path directly like you are. SendGrid requires files to be sent as base64 encoded strings.

You'll need to create the attachment object, you could do this as a method:

public function getAttachment($path)
{
    if (!file_exists($path)) {
        return false;
    }

    $attachment = new SendGrid\Attachment;
    $attachment->setContent(base64_encode(file_get_contents($path)));
    $attachment->setType(mime_content_type($path));
    $attachment->setFilename(basename($path));
    $attachment->setDisposition('attachment');
    return $attachment;
}

Then add it to your email:

$attachment = $this->getAttachment($sitedb . $row['AttachmentPath']);
if ($attachment instanceof SendGrid\Attachment) {
    $mail->addAttachment($attachment);
}


问:
How to catch runtime error from a function invoked from a waitgroup?
How to handle crashes in a waitgroup gracefully?

In other words, in the following snippet of code, how to catch the panics/crashes of goroutines invoking method do()?

```<code>func do(){
    str := "abc"
    fmt.Print(str[3])
    defer func() {
        if err := recover(); err != nil {
            fmt.Print(err)
        }
    }()
}

func main() {
    var wg sync.WaitGroup

    for i := 0; i < 1; i++ {
        wg.Add(1)
        go do()
        defer func() {
            wg.Done()
            if err := recover(); err != nil {
                fmt.Print(err)
            }
        }()
    }
    wg.Wait()
    fmt.Println("This line should be printed after all those invocations fail.")
}
</code>```

答:
@icza did a fantastic job explaining how to appropriately use WaitGroup and its functions Wait and Done

I like WaitGroup simplicity. However, I do not like that we need to pass the reference to the goroutine because that would mean that the concurrency logic would be mixed with your business logic.

So I came up with this generic function to solve this problem for me:

```<code>// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}
</code>```

So your example could be solved this way:

```<code>func do() {
    defer func() {
        if err := recover(); err != nil {
            fmt.Println(err)
        }
    }()

    str := "abc"
    fmt.Print(str[3])
}

func main() {
    Parallelize(do, do, do)

    fmt.Println("This line should be printed after all those invocations fail.")
}
</code>```

If you would like to use it, you can find it here https://github.com/shomali11/util

Body:
How to handle crashes in a waitgroup gracefully?

In other words, in the following snippet of code, how to catch the panics/crashes of goroutines invoking method do()?

func do(){
    str := "abc"
    fmt.Print(str[3])
    defer func() {
        if err := recover(); err != nil {
            fmt.Print(err)
        }
    }()
}

func main() {
    var wg sync.WaitGroup

    for i := 0; i < 1; i++ {
        wg.Add(1)
        go do()
        defer func() {
            wg.Done()
            if err := recover(); err != nil {
                fmt.Print(err)
            }
        }()
    }
    wg.Wait()
    fmt.Println("This line should be printed after all those invocations fail.")
}

Body:
@icza did a fantastic job explaining how to appropriately use WaitGroup and its functions Wait and Done

I like WaitGroup simplicity. However, I do not like that we need to pass the reference to the goroutine because that would mean that the concurrency logic would be mixed with your business logic.

So I came up with this generic function to solve this problem for me:

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}

So your example could be solved this way:

func do() {
    defer func() {
        if err := recover(); err != nil {
            fmt.Println(err)
        }
    }()

    str := "abc"
    fmt.Print(str[3])
}

func main() {
    Parallelize(do, do, do)

    fmt.Println("This line should be printed after all those invocations fail.")
}

If you would like to use it, you can find it here https://github.com/shomali11/util


问:
Use a bash script/grep/sed in order to replace class names with the file name itself
I currently have a directory that contains numerous .java files, all with different names. ie. name.java, name2.java, name3.java

I am trying to write a script that loops through all of the files in the directory and changes their class names (inside the file) to match the file name itself.

Currently, all of the .java files contain the class name MyCritter. I want to change all instances of MyCritter in each of the files to the name of the particular java file itself. I wrote a script to try and replace all of the MyCritter terms, however I am getting no change in output. The code is getting frozen after printing the echo line for the first name of the file:

```<code>#!/bin/bash

dir1="/Users/path to folder"
subs=`ls $dir1`
for a in $subs;
do
  echo a
  [ -f "$a" ]
  grep -lr "MyCritter" * | xargs sed “s/MyCritter/$a/g”
done
</code>```

output to terminal: name.java --> then infinite loop/gets stuck

The above code prints the name of the first file in the directory once, but then gets stuck. When I change my second line to this: [ -f "$a" ] || continue  it runs through the whole code, but fails to update the files.

I've tried other variations of grep including:

```<code>grep -lr -e "MyCritter" * | xargs sed -i “s/MyCritter/$a/g”
grep -lr -e "MyCritter" . | xargs sed -i “s/MyCritter/$a/g”
grep -lr -e "MyCritter" . | xargs sed “s/MyCritter/$a/g”
</code>```

I was primarily using this site to guide me: http://isaacsukin.com/news/2013/06/command-line-tip-replace-word-all-files-directory

Any push in the right direction would be much appreciated!

答:
As others mentioned, there are syntax errors in your code and shellcheck can easily detect those.

One of the alternate ways this can be done is:

#!/bin/bash

dir1="Absolute_path_for_dir"
for f in $dir1/*.java;do
    # Extract name from /path/name.java
    filename=$(basename "$f" .java)

    # Replace ALL occurrences of MyCritter with filename in file $f
    sed -i "s/MyCritter/$filename/g" "$f"
done
```

Body:
I currently have a directory that contains numerous .java files, all with different names. ie. name.java, name2.java, name3.java

I am trying to write a script that loops through all of the files in the directory and changes their class names (inside the file) to match the file name itself.

Currently, all of the .java files contain the class name MyCritter. I want to change all instances of MyCritter in each of the files to the name of the particular java file itself. I wrote a script to try and replace all of the MyCritter terms, however I am getting no change in output. The code is getting frozen after printing the echo line for the first name of the file:

#!/bin/bash

dir1="/Users/path to folder"
subs=`ls $dir1`
for a in $subs;
do
  echo a
  [ -f "$a" ]
  grep -lr "MyCritter" * | xargs sed “s/MyCritter/$a/g”
done

output to terminal: name.java --> then infinite loop/gets stuck

The above code prints the name of the first file in the directory once, but then gets stuck. When I change my second line to this: [ -f "$a" ] || continue  it runs through the whole code, but fails to update the files.

I've tried other variations of grep including:

grep -lr -e "MyCritter" * | xargs sed -i “s/MyCritter/$a/g”
grep -lr -e "MyCritter" . | xargs sed -i “s/MyCritter/$a/g”
grep -lr -e "MyCritter" . | xargs sed “s/MyCritter/$a/g”

I was primarily using this site to guide me: http://isaacsukin.com/news/2013/06/command-line-tip-replace-word-all-files-directory

Any push in the right direction would be much appreciated!


问:
Removing min from LinkedList
I want to remove 3 from this list but I am not sure where to start. I am storing a sequence of numbers in a Priority Queue that implements a linked list and trying to locate the min and remove it from the priority queue using the removeMin method

```<code>import java.util.Iterator;
import java.util.LinkedList;
public class Test {

    static LinkedList<Integer> list = new LinkedList<Integer>();

    public static void main(String[] args) {

        list.add(10);
        list.add(4);
        list.add(12);
        list.add(3);
        list.add(7);
        System.out.println(removeMin());
    }

    public static Integer removeMin() {
        LinkedList<Integer> pq = new LinkedList<Integer>();
        Iterator it = pq.iterator();

        for (int i = 0; i < list.size(); i++) {
            pq.add(list.remove());
        }

        int min = pq.get(0);

        while (it.hasNext()) {
            // help here
        }

        return pq.remove();
    }
</code>```

答:
Try this:

Solution 1

```<code>LinkedList<Integer> list = new LinkedList<Integer>();
        list.add(10);
        list.add(4);
        list.add(12);
        list.add(3);
        list.add(7);
        Collections.sort(list);
        list.removeFirst();
        list.forEach(System.out::println);
</code>```

Solution 2:

```<code> LinkedList<Integer> list = new LinkedList<Integer>();
    list.add(10);
    list.add(4);
    list.add(12);
    list.add(3);
    list.add(7);

    int min=Integer.MAX_VALUE;
    int pos=0;
    int remPos=0;
    Iterator<Integer> iterator = list.iterator();

    while(iterator.hasNext()){
        Integer element = iterator.next();
        if(element<min){
            min=element;
            remPos=pos;
        }
        pos++;
    }

    list.remove(remPos);
    list.forEach(System.out::println);
</code>```

Title: Removing min from LinkedList

Body:
I want to remove 3 from this list but I am not sure where to start. I am storing a sequence of numbers in a Priority Queue that implements a linked list and trying to locate the min and remove it from the priority queue using the removeMin method

import java.util.Iterator;
import java.util.LinkedList;
public class Test {

    static LinkedList<Integer> list = new LinkedList<Integer>();

    public static void main(String[] args) {

        list.add(10);
        list.add(4);
        list.add(12);
        list.add(3);
        list.add(7);
        System.out.println(removeMin());
    }

    public static Integer removeMin() {
        LinkedList<Integer> pq = new LinkedList<Integer>();
        Iterator it = pq.iterator();

        for (int i = 0; i < list.size(); i++) {
            pq.add(list.remove());
        }

        int min = pq.get(0);

        while (it.hasNext()) {
            // help here
        }

        return pq.remove();
    }

Body:
Try this:

Solution 1

LinkedList<Integer> list = new LinkedList<Integer>();
        list.add(10);
        list.add(4);
        list.add(12);
        list.add(3);
        list.add(7);
        Collections.sort(list);
        list.removeFirst();
        list.forEach(System.out::println);

Solution 2:

 LinkedList<Integer> list = new LinkedList<Integer>();
    list.add(10);
    list.add(4);
    list.add(12);
    list.add(3);
    list.add(7);

    int min=Integer.MAX_VALUE;
    int pos=0;
    int remPos=0;
    Iterator<Integer> iterator = list.iterator();

    while(iterator.hasNext()){
        Integer element = iterator.next();
        if(element<min){
            min=element;
            remPos=pos;
        }
        pos++;
    }

    list.remove(remPos);
    list.forEach(System.out::println);