问:
regex to add spaces in specific places
I have a 14 digits long number that I need to split into this format:

```<code>xxx xxx xxx xxxxx
</code>```

I have a regex that splits every 3 characters starting from the end (because of the lookahead?)

```<code>(?=(\d{3})+(?!\d))
</code>```

Which gives me:

```<code>xx xxx xxx xxx xxx
</code>```

I tried using lookbehind in regex101.com but I get a pattern error...

```<code>(?<=(\d{3})+(?!\d))
</code>```

How can I use lookbehind so that it starts from the begining of the string (if that's my issue) and how can I repeat the pattern only 3 times and then switch to a \d{5} ?

答:
You can use something like so: https://regex101.com/r/yqmyvs/3

The regex for this being:

```<code>(?:\d{3})(?:\d{2}$)?
</code>```

This basically says: I want groups of three numbers, unless it's the end of the string in which case I want 5.

Though, as commented on your question, this isn't really something you would normally use regex for.

Title: regex to add spaces in specific places

Body:
I have a 14 digits long number that I need to split into this format:

xxx xxx xxx xxxxx

I have a regex that splits every 3 characters starting from the end (because of the lookahead?)

(?=(\d{3})+(?!\d))

Which gives me:

xx xxx xxx xxx xxx

I tried using lookbehind in regex101.com but I get a pattern error...

(?<=(\d{3})+(?!\d))

How can I use lookbehind so that it starts from the begining of the string (if that's my issue) and how can I repeat the pattern only 3 times and then switch to a \d{5} ?

Body:
You can use something like so: https://regex101.com/r/yqmyvs/3

The regex for this being:

(?:\d{3})(?:\d{2}$)?

This basically says: I want groups of three numbers, unless it's the end of the string in which case I want 5.

Though, as commented on your question, this isn't really something you would normally use regex for.


来源: stackexchange

问:
"too many values to unpack error" when trying to create a batch in pyglet
I have been trying to get batches to work in pyglet, but I am completely confused by the error message "too many values to unpack" coming from the pyglet/graphics/__init__.py file. My guess is that that I am doing something wrong syntaxwise when adding the geometry to the batch.

I cut down my code to the essential parts that create the error:

```<code>from pyglet.gl import *
from pyglet.graphics import *
import pyglet

batch = pyglet.graphics.Batch()
img = pyglet.image.load('pic.png')
texture = img.get_texture()

class TextureEnableGroup(pyglet.graphics.Group):
    def set_state(self):
        glEnable(GL_TEXTURE_2D)
    def unset_state(self):
        glDisable(GL_TEXTURE_2D)

texture_enable_group = TextureEnableGroup()

class TextureBindGroup(pyglet.graphics.Group):
    def __init__(self, texture):
        super(TextureBindGroup, self).__init__(parent=texture_enable_group)
        self.texture = texture
    def set_state(self):
        glBindTexture(GL_TEXTURE_2D, self.texture.id)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    def __eq__(self, other):
        return (self.__class__ is other.__class__ and self.texture == other.__class__)

batch.add(12, GL_TRIANGLES, TextureBindGroup(texture), (('t2f', (0, 0)), ('v3f', (64, 64, 0)), ('t2f', (1, 1)), ('v3f', (-64, -64, 205)), ('t2f', (0, 1)), ('v3f', (-64, 64, 205)), ('t2f', (1, 1)), ('v3f', (64, -64, 205)), ('t2f', (1, 0)), ('v3f', (64, 64, 0)), ('t2f', (0, 1)), ('v3f', (-64, -64, 205))))
</code>```

答:
I would guess that your 4th argument to batch.add() does not follow a format that pyglet expects.  It might be useful to check this.

Also, looking at the lines in pyglet where the error occurs could give you more information.  The problem is likely to be a problem with the arguments you pass to a pyglet function.

PS: the documentation for add might be of interest.

ContentLicense: CC BY-SA 2.5

Body:
I have been trying to get batches to work in pyglet, but I am completely confused by the error message "too many values to unpack" coming from the pyglet/graphics/__init__.py file. My guess is that that I am doing something wrong syntaxwise when adding the geometry to the batch.

I cut down my code to the essential parts that create the error:

from pyglet.gl import *
from pyglet.graphics import *
import pyglet

batch = pyglet.graphics.Batch()
img = pyglet.image.load('pic.png')
texture = img.get_texture()

class TextureEnableGroup(pyglet.graphics.Group):
    def set_state(self):
        glEnable(GL_TEXTURE_2D)
    def unset_state(self):
        glDisable(GL_TEXTURE_2D)

texture_enable_group = TextureEnableGroup()

class TextureBindGroup(pyglet.graphics.Group):
    def __init__(self, texture):
        super(TextureBindGroup, self).__init__(parent=texture_enable_group)
        self.texture = texture
    def set_state(self):
        glBindTexture(GL_TEXTURE_2D, self.texture.id)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    def __eq__(self, other):
        return (self.__class__ is other.__class__ and self.texture == other.__class__)

batch.add(12, GL_TRIANGLES, TextureBindGroup(texture), (('t2f', (0, 0)), ('v3f', (64, 64, 0)), ('t2f', (1, 1)), ('v3f', (-64, -64, 205)), ('t2f', (0, 1)), ('v3f', (-64, 64, 205)), ('t2f', (1, 1)), ('v3f', (64, -64, 205)), ('t2f', (1, 0)), ('v3f', (64, 64, 0)), ('t2f', (0, 1)), ('v3f', (-64, -64, 205))))


问:
How to apply google oauth on kibana?
I need to apply google oauth on kibana for security purpose. </p>

答:
You'll probably need to write a plugin for Kibana, this article goes in some details on how to accomplish that, the catch with this approach is that you'll need x-pack(which is a paid product) to accomplish that as described there, but it's also possible to write a plugin without x-pack anyway, just some extra work.

Other option, where you won't need x-pack would be to have a reverse proxy in front of your kibana where you can implement the oauth and you could configure that kibana only accepts requests from that rev-proxy.

ContentLicense: CC BY-SA 3.0

Title: How to apply google oauth on kibana?


问:
Setting focus by id AngularJS
Upon clicking + button, the focus is shifted to another input field in HTML. I want to keep the focus on the current input field unless the user clicks on another input field. That's when I want to move the focus to the clicked input field.

```<code><div layout="row" layout-align="center center">
    <md-input-container  class="md-block" flex="50">
        <input required id="circleTimeWordListEditText" type="text" placeholder="Words List" ng-model="circleTime.word"/>

        <div ng-messages="$error">
            <div ng-message="required">This is required.</div>
        </div>
    </md-input-container>
</div>

<div layout="row" layout-align="center center">
    <md-button class="md-raised md-primary" type="submit"
               ng-click="circleTime.onAddButtonClicked()">+
    </md-button>
</div>
</code>```

Currently I am doing this:

```<code>document.getElementById('circleTimeWordListEditText').focus();
</code>```

and I have tried this as well but it gives me NOSEL error.

```<code>angular.element('circleTimeWordListEditText').focus();
</code>```

I tried this solution too:

```<code>mainApp.factory('focus', function($timeout, $window) {
    return function(id) {
        // timeout makes sure that it is invoked after any other event has been triggered.
        // e.g. click events that need to run before the focus or
        // inputs elements that are in a disabled state but are enabled when those events
        // are triggered.
        $timeout(function() {
            var element = $window.document.getElementById(id);
            if(element)
                element.focus();
        });
    };
});

mainApp.directive('eventFocus', function(focus) {
    return function(scope, elem, attr) {
        elem.on(attr.eventFocus, function() {
            focus(attr.eventFocusId);
        });

        // Removes bound events in the element itself
        // when the scope is destroyed
        scope.$on('$destroy', function() {
            elem.off(attr.eventFocus);
        });
    };
});

onAddButtonClicked : function(elem) {
            //do stuff

            focus('circleTimeWordListEditText');
            /*var temp = document.getElementById('circleTimeWordListEditText');
            alert(temp);
            temp.focus();
            angular.element('circleTimeWordListEditText');
            angular.element('circleTimeWordListEditText').focus();*/
        }
    },
</code>```

but it doesn't work either.

What is the recommended solution to this problem?

答:
I was having the same issue. This worked for me. I hope this works for you too!

```<code>function someFunction()
{
var element = angular.element("#id here");
element.focus()
}
</code>```

For you, the following may work:

```<code>function onAddButtonClicked()
{
   var element = angular.element("#circleTimeWordListEditText");
   element.focus()
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Setting focus by id AngularJS

Body:
Upon clicking + button, the focus is shifted to another input field in HTML. I want to keep the focus on the current input field unless the user clicks on another input field. That's when I want to move the focus to the clicked input field.

    <md-input-container  class="md-block" flex="50">
        <input required id="circleTimeWordListEditText" type="text" placeholder="Words List" ng-model="circleTime.word"/>

This is required.

    </md-input-container>

    <md-button class="md-raised md-primary" type="submit"
               ng-click="circleTime.onAddButtonClicked()">+
    </md-button>

Currently I am doing this:

document.getElementById('circleTimeWordListEditText').focus();

and I have tried this as well but it gives me NOSEL error.

angular.element('circleTimeWordListEditText').focus();

I tried this solution too:

mainApp.factory('focus', function($timeout, $window) {
    return function(id) {
        // timeout makes sure that it is invoked after any other event has been triggered.
        // e.g. click events that need to run before the focus or
        // inputs elements that are in a disabled state but are enabled when those events
        // are triggered.
        $timeout(function() {
            var element = $window.document.getElementById(id);
            if(element)
                element.focus();
        });
    };
});

mainApp.directive('eventFocus', function(focus) {
    return function(scope, elem, attr) {
        elem.on(attr.eventFocus, function() {
            focus(attr.eventFocusId);
        });

        // Removes bound events in the element itself
        // when the scope is destroyed
        scope.$on('$destroy', function() {
            elem.off(attr.eventFocus);
        });
    };
});

onAddButtonClicked : function(elem) {
            //do stuff

            focus('circleTimeWordListEditText');
            /*var temp = document.getElementById('circleTimeWordListEditText');
            alert(temp);
            temp.focus();
            angular.element('circleTimeWordListEditText');
            angular.element('circleTimeWordListEditText').focus();*/
        }
    },

but it doesn't work either.

What is the recommended solution to this problem?

Body:
I was having the same issue. This worked for me. I hope this works for you too!

function someFunction()
{
var element = angular.element("#id here");
element.focus()
}

For you, the following may work:

function onAddButtonClicked()
{
   var element = angular.element("#circleTimeWordListEditText");
   element.focus()
}


问:
Using jq to compare two fields from same json and printing some other field as a result
I have json data in following format

```<code>{
  "body": [
    {
      "username": "name1",
      "id": "4444"
    },
    {
      "username": "name2",
      "id": "5555"
    }
  ],
  "meta": {
    "input": "name1"
  }}
</code>```

Given this data I want to match the "username"s in the body with "meta.input" and if there is a match return/print related id.

答:
jq solution:

```<code>jq '.meta.input as $meta | .body[] | select(.username == $meta).id' input.json
</code>```

The output:

```<code>"4444"
</code>```

.meta.input as $meta - assigning .meta.input key value to $meta variable for further comparison

Body:
I have json data in following format

{
  "body": [
    {
      "username": "name1",
      "id": "4444"
    },
    {
      "username": "name2",
      "id": "5555"
    }
  ],
  "meta": {
    "input": "name1"
  }}

Given this data I want to match the "username"s in the body with "meta.input" and if there is a match return/print related id.

Body:
jq solution:

jq '.meta.input as $meta | .body[] | select(.username == $meta).id' input.json

The output:

"4444"

.meta.input as $meta - assigning .meta.input key value to $meta variable for further comparison


问:
My business address isn't showing in Google Place ID
I know this question has been asked beforehand, and I was wondering whether someone could tell me my Google Place ID because I have followed other answers but had no luck, I want it so that I can post a review link.

This is my business on maps - https://www.google.co.uk/maps/place/Demeanour+Customs/@52.378986,0.932232,15z/data=!4m2!3m1!1s0x0:0xd69e990a1537e44d?sa=X&ved=0ahUKEwjssorKvvTUAhWsCsAKHXdKB9MQ_BIIYDAK

答:
From the call to:

https://maps.googleapis.com/maps/api/place/textsearch/json?query=Demeanour%20Customs&key=YourKey

We get the following results, your place id is highlighted:

```<code>{
   "html_attributions" : [],
   "results" : [
      {
         "formatted_address" : "Common Road, Hopton IP22 2QU, United Kingdom",
         "geometry" : {
            "location" : {
               "lat" : 52.378986,
               "lng" : 0.9322319999999998
            },
            "viewport" : {
               "northeast" : {
                  "lat" : 52.38033498029149,
                  "lng" : 0.9335809802915019
               },
               "southwest" : {
                  "lat" : 52.37763701970849,
                  "lng" : 0.9308830197084978
               }
            }
         },
         "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
         "id" : "690b7ddc30ccef065dcc64e46ce0e2ad7936d977",
         "name" : "Demeanour Customs",
         "opening_hours" : {
            "open_now" : true,
            "weekday_text" : []
         },
         "photos" : [
            {
               "height" : 630,
               "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/108914736063426931463/photos\"\u003eDemeanour Customs\u003c/a\u003e"
               ],
               "photo_reference" : "CmRaAAAAoYmW_yjX5k5Q8Ra8gJsBputCHubMK0lo6SF73fNr1-isx7pVBqy4To8dXpXr3ECirXel_pKjD44CrDWVb6vqw6xKLc7AV4tErTEwgL5UnjizAyTrcRTfObgTpOyuOHGaEhDPpsShhN6jGTvzZT08zVtNGhRFUxbPiXSNnpTCs1JrVZdSq7HCtg",
               "width" : 1702
            }
         ],
         "place_id" : "ChIJDVPTd0rI2UcRTeQ3FQqZntY",
         "reference" : "CmRSAAAAVXhOWK1IHyF8CKo_zjZtUVQXdFeNCCukCjiWE-X3JnEx0DdeJIDjXLpA4foqLDRZAVbPki72oM7tmhadvhAwlnBAGRljRdC8EVTbxjBxj8eDd-xZikpx7fNDaoCQFMIeEhAHIvtNywS7nsI3MZ5Vvi94GhTBFsCNb_a8g7TxDlbNvPBapJC4vQ",
         "types" : [ "point_of_interest", "establishment" ]
      }
   ],
   "status" : "OK"
}
</code>```

"place_id" : "ChIJDVPTd0rI2UcRTeQ3FQqZntY",

Body:
From the call to:

https://maps.googleapis.com/maps/api/place/textsearch/json?query=Demeanour%20Customs&key=YourKey

We get the following results, your place id is highlighted:

{
   "html_attributions" : [],
   "results" : [
      {
         "formatted_address" : "Common Road, Hopton IP22 2QU, United Kingdom",
         "geometry" : {
            "location" : {
               "lat" : 52.378986,
               "lng" : 0.9322319999999998
            },
            "viewport" : {
               "northeast" : {
                  "lat" : 52.38033498029149,
                  "lng" : 0.9335809802915019
               },
               "southwest" : {
                  "lat" : 52.37763701970849,
                  "lng" : 0.9308830197084978
               }
            }
         },
         "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
         "id" : "690b7ddc30ccef065dcc64e46ce0e2ad7936d977",
         "name" : "Demeanour Customs",
         "opening_hours" : {
            "open_now" : true,
            "weekday_text" : []
         },
         "photos" : [
            {
               "height" : 630,
               "html_attributions" : [
                  "\u003ca href=\"https://maps.google.com/maps/contrib/108914736063426931463/photos\"\u003eDemeanour Customs\u003c/a\u003e"
               ],
               "photo_reference" : "CmRaAAAAoYmW_yjX5k5Q8Ra8gJsBputCHubMK0lo6SF73fNr1-isx7pVBqy4To8dXpXr3ECirXel_pKjD44CrDWVb6vqw6xKLc7AV4tErTEwgL5UnjizAyTrcRTfObgTpOyuOHGaEhDPpsShhN6jGTvzZT08zVtNGhRFUxbPiXSNnpTCs1JrVZdSq7HCtg",
               "width" : 1702
            }
         ],
         "place_id" : "ChIJDVPTd0rI2UcRTeQ3FQqZntY",
         "reference" : "CmRSAAAAVXhOWK1IHyF8CKo_zjZtUVQXdFeNCCukCjiWE-X3JnEx0DdeJIDjXLpA4foqLDRZAVbPki72oM7tmhadvhAwlnBAGRljRdC8EVTbxjBxj8eDd-xZikpx7fNDaoCQFMIeEhAHIvtNywS7nsI3MZ5Vvi94GhTBFsCNb_a8g7TxDlbNvPBapJC4vQ",
         "types" : [ "point_of_interest", "establishment" ]
      }
   ],
   "status" : "OK"
}

"place_id" : "ChIJDVPTd0rI2UcRTeQ3FQqZntY",


问:
CSS Hover on a div to show another div not working
I'm trying to change the opacity of a div when I hover on another div, but it isn't working at all. Here's the HTML:

.chatdate {
  padding-top: 10px;
  opacity: 0.5;
  transition: opacity 1s ease-in-out;
}

.workstream-comment:hover .chatdate {
  background: red;
  opacity: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-lg-12">
  <div class="row">
    <div class="col-lg-10">
      <div class="workstream-comment">
        ...
      </div>
    </div>
    <div class="col-lg-2">
      <div class="chatdate text-center">
        <h6>15/07/2017</h6>
        <br>
        <h1>11:07</h1>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-lg-10">
      <div class="workstream-comment">
        ...
      </div>
    </div>
    <div class="col-lg-2">
      <div class="chatdate text-center">
        <h6>15/07/2017</h6>
        <br>
        <h1>11:07</h1>
      </div>
    </div>
  </div>
</div></code>```

Can anyone tell me what I'm doing wrong?
Thanks

答: Nirav Joshi's answer is great ! I would add an explanation to why your code wouldn't work. What you're saying in your css is that the .chatdate class is a child inside the .workstream-comment, so it is normal this won't work this way, because when you hover the .workstream-comment class content it's looking for .chatdate div inside the .workstream-comment div. That's why you should use some javascript to handle it :) </p>

Body:
I'm trying to change the opacity of a div when I hover on another div, but it isn't working at all. Here's the HTML:

.chatdate {
  padding-top: 10px;
  opacity: 0.5;
  transition: opacity 1s ease-in-out;
}

.workstream-comment:hover .chatdate {
  background: red;
  opacity: 1;
}

        ...

15/07/2017

11:07

        ...

15/07/2017

11:07

Can anyone tell me what I'm doing wrong?
Thanks


问:
How to incorporate features from a latent semantic analysis as independent variables in a predictive model
I am trying to run logistic regression using text data in R. I have built a term document matrix and a corresponding latent semantic space. In my understanding, LSA is used in deriving 'concepts' out of 'terms' which could help in dimension reduction. Here's my code:

```<code>tdm = TermDocumentMatrix(corpus, control = list(tokenize=myngramtoken,weighting=myweight))
tdm = removeSparseTerms(tdm,0.98)
tdm = as.matrix(tdm)
tdm.lsa = lsa(tdm,dimcalc_share())
tdm.lsa_tk=as.data.frame(tdm.lsa$tk)
tdm.lsa_dk=as.data.frame(tdm.lsa$dk)
tdm.lsa_sk=as.data.frame(tdm.lsa$sk)
</code>```

This gives features as V1, V2, V3.... V21. Is it possible to use these as the independent variables in my logistic regression? If so, how can I do it?

答:
In the above example the table tdm.lsa_dk is a matrix of 'concepts' as columns and the documents where they appear as rows. This can be used as the new training and testing data set for further analysis, in this case, logistic regression. The independent variable (from the original dataset) is to be added to the new dataset.
The table tdm.lsa_sk can be used for variable selection. It shows the 'concept' variables in decreasing order of importance.</p>

```<code>     # the $dk part of the lsa will behave as your new dataset

    new.dataset <- tdm.lsa_dk
    new.dataset$y.var <- original.dataset$y.var

     # creating training and testing dataset out of the new dataset

    test_index <- createDataPartition(new.dataset$y, p = .2, list = F)
    Test<-new.dataset[test_index,]
    Train<-new.dataset[-test_index,]

     # create model

    model<-glm(y.var~., data=Train, family="binomial")
    prediction<-predict(model, Test, type="response")
</code>```

Body:
I am trying to run logistic regression using text data in R. I have built a term document matrix and a corresponding latent semantic space. In my understanding, LSA is used in deriving 'concepts' out of 'terms' which could help in dimension reduction. Here's my code:

tdm = TermDocumentMatrix(corpus, control = list(tokenize=myngramtoken,weighting=myweight))
tdm = removeSparseTerms(tdm,0.98)
tdm = as.matrix(tdm)
tdm.lsa = lsa(tdm,dimcalc_share())
tdm.lsa_tk=as.data.frame(tdm.lsa$tk)
tdm.lsa_dk=as.data.frame(tdm.lsa$dk)
tdm.lsa_sk=as.data.frame(tdm.lsa$sk)

This gives features as V1, V2, V3.... V21. Is it possible to use these as the independent variables in my logistic regression? If so, how can I do it?

Body:
In the above example the table tdm.lsa_dk is a matrix of 'concepts' as columns and the documents where they appear as rows. This can be used as the new training and testing data set for further analysis, in this case, logistic regression. The independent variable (from the original dataset) is to be added to the new dataset.
The table tdm.lsa_sk can be used for variable selection. It shows the 'concept' variables in decreasing order of importance.

     # the $dk part of the lsa will behave as your new dataset

    new.dataset <- tdm.lsa_dk
    new.dataset$y.var <- original.dataset$y.var

     # creating training and testing dataset out of the new dataset

    test_index <- createDataPartition(new.dataset$y, p = .2, list = F)
    Test<-new.dataset[test_index,]
    Train<-new.dataset[-test_index,]

     # create model

    model<-glm(y.var~., data=Train, family="binomial")
    prediction<-predict(model, Test, type="response")


问:
Why we need to pass "$event" in ng-click?
I know we can perform click events like ng-click="clickMe()" in angular.But I just gone through some examples.In that $event is passed into that like this ng-click="clickMe()" .
Why we need to pass $event?
What is the difference between ng-click="clickMe()" and ng-click="clickMe($event)" ?
Please anyone explain.

答:
You don't need to, and most of the time you shouldn't. From all clicks in javascript, there is an Event-object available. $event just happens to be the way to access those in javascript.

If you are interested in more about the events, try this (not really related but good to know), if you are using chrome dev-tools, check the Sources-tab and on the right side you have watches and breakpoints. There is also a drop down for "Event Listener Breakpoints".  There you'll find a whole lot of possible events.

Try checking the checkbox for "Mouse" -> "click" for example, and then click somewhere on the page.  The script will pause (very likely somewhere in jquery) and you can inspect the mouseevent directly under the Scope dropdown.


问:
PHP: Convert unicode codepoint to UTF-8
I have my data in this format: U+597D or like this U+6211. I want to convert them to UTF-8 (original characters are 好 and 我). How can I do it?

答:
PHP 7+

As of PHP 7, you can use the Unicode codepoint escape syntax to do this.

echo "\u{597D}"; outputs 好.

Title: PHP: Convert unicode codepoint to UTF-8


问:
Is it possible to create cluster in EMR by giving all the configurations from json file
I want to automate the cluster creation task in EMR. I have a json file
which contains configurations which need to be applied on new cluster and I want to write a shell script which automates this task for me.

Is it possible to create cluster in EMR by giving all the configurations from json file?

For example I have this file

```<code>{
"Cluster": {
    "Ec2InstanceAttributes": {
        "EmrManagedMasterSecurityGroup": "sg-00b10b71",
        "RequestedEc2AvailabilityZones": [],
        "AdditionalSlaveSecurityGroups": [],
        "AdditionalMasterSecurityGroups": [],
        "RequestedEc2SubnetIds": [
            "subnet-02291b3e"
        ],
        "Ec2SubnetId": "subnet-02291b3e",
        "IamInstanceProfile": "EMR_EC2_DefaultRole",
        "Ec2KeyName": "perf_key_pair",
        "Ec2AvailabilityZone": "us-east-1e",
        "EmrManagedSlaveSecurityGroup": "sg-f2b30983"
    },
    "Name": "NitinJ-Perf",
    "ServiceRole": "EMR_DefaultRole",
    "Tags": [
        {
            "Value": "Perf-Nitink",
            "Key": "Qubole"
        }
    ],
    "Applications": [
        {
            "Version": "3.7.2",
            "Name": "Ganglia"
        },
        {
            "Version": "2.7.3",
            "Name": "Hadoop"
        },
        {
            "Version": "2.1.1",
            "Name": "Hive"
        },
        {
            "Version": "0.16.0",
            "Name": "Pig"
        },
        {
            "Version": "0.8.4",
            "Name": "Tez"
        }
    ],
    "MasterPublicDnsName": "ec2-34-229-254-217.compute-1.amazonaws.com",
    "ScaleDownBehavior": "TERMINATE_AT_INSTANCE_HOUR",
    "InstanceGroups": [
        {
            "RequestedInstanceCount": 4,
            "Status": {
                "Timeline": {
                    "ReadyDateTime": 1499150835.979,
                    "CreationDateTime": 1499150533.99
                },
                "State": "RUNNING",
                "StateChangeReason": {
                    "Message": ""
                }
            },
            "Name": "Core Instance Group",
            "InstanceGroupType": "CORE",
            "EbsBlockDevices": [],
            "ShrinkPolicy": {},
            "Id": "ig-34P3CVF8ZL5CW",
            "Configurations": [],
            "InstanceType": "r3.4xlarge",
            "Market": "ON_DEMAND",
            "RunningInstanceCount": 4
        },
        {
            "RequestedInstanceCount": 1,
            "Status": {
                "Timeline": {
                    "ReadyDateTime": 1499150804.591,
                    "CreationDateTime": 1499150533.99
                },
                "State": "RUNNING",
                "StateChangeReason": {
                    "Message": ""
                }
            },
            "Name": "Master Instance Group",
            "InstanceGroupType": "MASTER",
            "EbsBlockDevices": [],
            "ShrinkPolicy": {},
            "Id": "ig-3V7EHQ36187PY",
            "Configurations": [],
            "InstanceType": "r3.4xlarge",
            "Market": "ON_DEMAND",
            "RunningInstanceCount": 1
        }
    ],
    "Configurations": [
        {
            "Properties": {
                "hive.vectorized.execution.enabled": "true"
            },
            "Classification": "hive-site"
        }
    ]
}
}
</code>```

Can I create a cluster on EMR by using some command like

```<code>aws emr create-cluster --cli-input-json file://'pwd'/emr_cluster_up.json
</code>```

答:
There is no such option through the AWS CLI as per the AWS CLI documentation. But if you want to automate the EMR cluster creation using a JSON file. You can use Cloud formation and automate the cluster creation.

Getting Started with AWS CloudFormation

Body:
I want to automate the cluster creation task in EMR. I have a json file
which contains configurations which need to be applied on new cluster and I want to write a shell script which automates this task for me.

Is it possible to create cluster in EMR by giving all the configurations from json file?

For example I have this file

{
"Cluster": {
    "Ec2InstanceAttributes": {
        "EmrManagedMasterSecurityGroup": "sg-00b10b71",
        "RequestedEc2AvailabilityZones": [],
        "AdditionalSlaveSecurityGroups": [],
        "AdditionalMasterSecurityGroups": [],
        "RequestedEc2SubnetIds": [
            "subnet-02291b3e"
        ],
        "Ec2SubnetId": "subnet-02291b3e",
        "IamInstanceProfile": "EMR_EC2_DefaultRole",
        "Ec2KeyName": "perf_key_pair",
        "Ec2AvailabilityZone": "us-east-1e",
        "EmrManagedSlaveSecurityGroup": "sg-f2b30983"
    },
    "Name": "NitinJ-Perf",
    "ServiceRole": "EMR_DefaultRole",
    "Tags": [
        {
            "Value": "Perf-Nitink",
            "Key": "Qubole"
        }
    ],
    "Applications": [
        {
            "Version": "3.7.2",
            "Name": "Ganglia"
        },
        {
            "Version": "2.7.3",
            "Name": "Hadoop"
        },
        {
            "Version": "2.1.1",
            "Name": "Hive"
        },
        {
            "Version": "0.16.0",
            "Name": "Pig"
        },
        {
            "Version": "0.8.4",
            "Name": "Tez"
        }
    ],
    "MasterPublicDnsName": "ec2-34-229-254-217.compute-1.amazonaws.com",
    "ScaleDownBehavior": "TERMINATE_AT_INSTANCE_HOUR",
    "InstanceGroups": [
        {
            "RequestedInstanceCount": 4,
            "Status": {
                "Timeline": {
                    "ReadyDateTime": 1499150835.979,
                    "CreationDateTime": 1499150533.99
                },
                "State": "RUNNING",
                "StateChangeReason": {
                    "Message": ""
                }
            },
            "Name": "Core Instance Group",
            "InstanceGroupType": "CORE",
            "EbsBlockDevices": [],
            "ShrinkPolicy": {},
            "Id": "ig-34P3CVF8ZL5CW",
            "Configurations": [],
            "InstanceType": "r3.4xlarge",
            "Market": "ON_DEMAND",
            "RunningInstanceCount": 4
        },
        {
            "RequestedInstanceCount": 1,
            "Status": {
                "Timeline": {
                    "ReadyDateTime": 1499150804.591,
                    "CreationDateTime": 1499150533.99
                },
                "State": "RUNNING",
                "StateChangeReason": {
                    "Message": ""
                }
            },
            "Name": "Master Instance Group",
            "InstanceGroupType": "MASTER",
            "EbsBlockDevices": [],
            "ShrinkPolicy": {},
            "Id": "ig-3V7EHQ36187PY",
            "Configurations": [],
            "InstanceType": "r3.4xlarge",
            "Market": "ON_DEMAND",
            "RunningInstanceCount": 1
        }
    ],
    "Configurations": [
        {
            "Properties": {
                "hive.vectorized.execution.enabled": "true"
            },
            "Classification": "hive-site"
        }
    ]
}
}

Can I create a cluster on EMR by using some command like

aws emr create-cluster --cli-input-json file://'pwd'/emr_cluster_up.json


问:
Cannot list user's directories android
My problem is that when I call

```<code>dir.listFiles()
</code>```

on a directory, user's folders (like DCIM, Ringtones, Downloads, ecc..) are not shown, so  folders like

```<code> /sdcard
</code>```

or similars seems to be empty, but when i check them with ES File Explorer the directories are perfectly shown.

Please help me!

I am working in API 24

答:
Thanks to @VladMatvienko i solved the issue
I just requested the WRITE_EXTERNAL_STORAGE permissions at runtime, so that the user will be asked to grant the permission, now it works like a charm!

Link: https://developer.android.com/training/permissions/requesting.html

Title: Cannot list user's directories android

Body:
My problem is that when I call

dir.listFiles()

on a directory, user's folders (like DCIM, Ringtones, Downloads, ecc..) are not shown, so  folders like

 /sdcard

or similars seems to be empty, but when i check them with ES File Explorer the directories are perfectly shown.

Please help me!

I am working in API 24


问:
categories of a section appear of the same order
I have the following structure of categories under the Info-s section. The latter four categories appear to all have been allocated of the 3rd position. Either changing this number on the admin screen or in the order drop-down inside of the category pages doesn't seem to have any effect.

I suspect this is due to the way those categories have been created (using the Copy functionality).

Any ideas?

答: By deleting and reorganising the section with its respective categories seemed to have fixed this.</p>


问:
My login script doesn't properly query the database
Whenever I login with a registered user my script fails with the following message:

Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\login\login.php on line 9

  Notice: Undefined variable: sql in C:\xampp\htdocs\login\login.php on line 10

  Warning: mysqli_query() expects at least 2 parameters, 1 given

The script should query the database to see if the user is valid, but it never comes that far. The actual code is listed below.

connect.php

```<code><?php
    mysqli_connect ("localhost","root", "");
    $db = mysqli_select_db("login");
?>
</code>```

login.php

```<code><?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    require_once('connect.php');
    extract($_POST);

    $result = mysqli_query("select * from users where username = '$username' and password = '$password'");
    $result = mysqli_query( $sql);

    if ( $password == $row['password']) {
        header("location : home.php");
    }
    else {
        echo "failed to login! try again";
    }
?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Login page</title>
        <link href="style.css" type="text/css" rel="stylesheet">
    </head>
    <body>
        <div id="frm">
            <form action="login.php" method="POST" style="width: 232px; padding-left: 490px;">
                <h1>Login</h1>

                <p>
                    <label>Username</label>
                    <input type="text" id="username" name="username"/>
                </p>

                <p>
                    <label>password</label>
                    <input type="password" id="password" name="password"/>
                </p>

                <p>
                    <input type="submit" id="btn" value="login" style="border-radius: 30%; background-color: gold; box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);"/>
                </p>

                <p>
                    Not yet a member <a href="register.php">Register here</a>
                </p>
            </form>
        </div>
    </body>
</html>
</code>```

答:
The problem is so simple.

You did not execute the query at all.

add mysqli_query($connectionVar,$sql); just below $sql

mysqli_select_db() expects exactly 2 parameters, 1 given

this is what you need.

mysqli_select_db($connectionVar,"DATABASENAME");

update:

remove  the select_db function on your con and run this :

```<code> $link = mysqli_connect ("localhost","root", "","login");
</code>```

then

mysqli_query($link,$sql);

Body:
Whenever I login with a registered user my script fails with the following message:

Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\login\login.php on line 9

  Notice: Undefined variable: sql in C:\xampp\htdocs\login\login.php on line 10

  Warning: mysqli_query() expects at least 2 parameters, 1 given

The script should query the database to see if the user is valid, but it never comes that far. The actual code is listed below.

connect.php

<?php
    mysqli_connect ("localhost","root", "");
    $db = mysqli_select_db("login");
?>

login.php

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);

    require_once('connect.php');
    extract($_POST);

    $result = mysqli_query("select * from users where username = '$username' and password = '$password'");
    $result = mysqli_query( $sql);

    if ( $password == $row['password']) {
        header("location : home.php");
    }
    else {
        echo "failed to login! try again";
    }
?>

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Login page</title>
        <link href="style.css" type="text/css" rel="stylesheet">

            <form action="login.php" method="POST" style="width: 232px; padding-left: 490px;">

Login

                    Username
                    <input type="text" id="username" name="username"/>

                    password
                    <input type="password" id="password" name="password"/>

                    <input type="submit" id="btn" value="login" style="border-radius: 30%; background-color: gold; box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);"/>

                    Not yet a member Register here

            </form>

Body:
The problem is so simple.

You did not execute the query at all.

add mysqli_query($connectionVar,$sql); just below $sql

mysqli_select_db() expects exactly 2 parameters, 1 given

this is what you need.

mysqli_select_db($connectionVar,"DATABASENAME");

update:

remove  the select_db function on your con and run this :

 $link = mysqli_connect ("localhost","root", "","login");

then

mysqli_query($link,$sql);


问:
Date extraction from datepickers
I have 2 datepickers in my sheet "From" and "To". I want to record the date selected from these datepickers in variables and then refer to the input data sheet between the given range and extract data. I have written some code.

```<code>Sub PITimeseries()
Dim a As Object
Dim b As Object
Dim c As Date
Set a = DTPicker1.Value
Set b = DTPicker2.Value

Sheet9.Select
Dim rng As Range, cell As Range, rng1 As Range
Set rng = Range("B5:B71")
Set rng1 = Range("H5:H71")
For Each cell In rng
If cell.Value = a Or cell.Value = b Then
</code>```

example
Now I am stuck as to how I will make the corresponding date match cell true or false.

答:
Try this out:

```<code>Private Sub CommandButton1_Click()
Dim a As Date, b As Date, c As Date
Dim sht As Worksheet
Dim rng As Range, cell As Range, rng1 As Range

Set sht = Worksheets("Sheet9")
Set rng = sht.Range("B5:B71")
Set rng1 = sht.Range("H5:H71")

a = DTPicker1.Value
b = DTPicker2.Value

For Each cell In rng
c = CDate(cell.Value)
If c >= a And c <= b Then
    sht.Cells(cell.Row, "H").Value = "True"
Else
    sht.Cells(cell.Row, "H").Value = "False"
End If
Next cell
End Sub
</code>```

So your variable types were kind of wrong and for OR only one of the two conditions have to fit. And please dont use .Select, always objectify .Range, .Cells etc..

Title: Date extraction from datepickers

Body:
I have 2 datepickers in my sheet "From" and "To". I want to record the date selected from these datepickers in variables and then refer to the input data sheet between the given range and extract data. I have written some code.

Sub PITimeseries()
Dim a As Object
Dim b As Object
Dim c As Date
Set a = DTPicker1.Value
Set b = DTPicker2.Value

Sheet9.Select
Dim rng As Range, cell As Range, rng1 As Range
Set rng = Range("B5:B71")
Set rng1 = Range("H5:H71")
For Each cell In rng
If cell.Value = a Or cell.Value = b Then

example
Now I am stuck as to how I will make the corresponding date match cell true or false.

Body:
Try this out:

Private Sub CommandButton1_Click()
Dim a As Date, b As Date, c As Date
Dim sht As Worksheet
Dim rng As Range, cell As Range, rng1 As Range

Set sht = Worksheets("Sheet9")
Set rng = sht.Range("B5:B71")
Set rng1 = sht.Range("H5:H71")

a = DTPicker1.Value
b = DTPicker2.Value

For Each cell In rng
c = CDate(cell.Value)
If c >= a And c <= b Then
    sht.Cells(cell.Row, "H").Value = "True"
Else
    sht.Cells(cell.Row, "H").Value = "False"
End If
Next cell
End Sub

So your variable types were kind of wrong and for OR only one of the two conditions have to fit. And please dont use .Select, always objectify .Range, .Cells etc..


问:
Why isn't the pattern in this code exhaustive?
```<code>splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith f [] = []
splitWith f list = pre : (splitWith f suf)
    where (pre, suf) = break f list
</code>```

<p>This function should split a list according to a predicate. But I get an infinite recursion. </p>

答:
It'd be because this will continually add an empty list to the end.

You can see this is if you take some arbitrary quantity of values from the infinite collection:

```<code>*Main> take 10 $ splitWith (==5) [1,2,3,4,5]
[[1,2,3,4],[],[],[],[],[],[],[],[],[]]
</code>```

If you break (==5) [5], the result is ([],[5]) which gets pattern matched into pre as [] and suf as [5]. The next iteration gets the same break (==5) [5] to evaluate... and so it goes.

update:

I'm not sure of the exact semantics you're after, but this might be helpful in formulating the function you want:

```<code>splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith f [] = []
splitWith f xs = doSplitWith [] xs
  where
    doSplitWith first second @ (y:ys) =
      if f y
      then (reverse first) : [second]
      else doSplitWith (y:first) ys

splitWith' f xs = takeWhile (not . f) xs : [dropWhile (not . f) xs]
</code>```

Tho I guess that'd be more like splitAt or something, wouldn't it?

Body:
splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith f [] = []
splitWith f list = pre : (splitWith f suf)
    where (pre, suf) = break f list

This function should split a list according to a predicate. But I get an infinite recursion.

Body:
It'd be because this will continually add an empty list to the end.

You can see this is if you take some arbitrary quantity of values from the infinite collection:

*Main> take 10 $ splitWith (==5) [1,2,3,4,5]
[[1,2,3,4],[],[],[],[],[],[],[],[],[]]

If you break (==5) [5], the result is ([],[5]) which gets pattern matched into pre as [] and suf as [5]. The next iteration gets the same break (==5) [5] to evaluate... and so it goes.

update:

I'm not sure of the exact semantics you're after, but this might be helpful in formulating the function you want:

splitWith :: (a -> Bool) -> [a] -> [[a]]
splitWith f [] = []
splitWith f xs = doSplitWith [] xs
  where
    doSplitWith first second @ (y:ys) =
      if f y
      then (reverse first) : [second]
      else doSplitWith (y:first) ys

splitWith' f xs = takeWhile (not . f) xs : [dropWhile (not . f) xs]

Tho I guess that'd be more like splitAt or something, wouldn't it?


问:
Android Studio: Error parsing XML & URI is not registered
After adding a new Activity to my project I get following error while compiling the layout

Gradle: Error parsing XML: not well-formed (invalid token)

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:orientation="vertical" >

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_password"
        android:text="<password>"/>
</LinearLayout>
</code>```

"http://schemas.android.com/apk/res/android" is marked red and hovering pops following message up

URI is not registered ( Setting | Project Settings | Schemas and DTDs )

My Settings>Project Settings>Schemas and DTDs look like that:
Project Settings>Schemas and DTDs">

I already found some similar questions around here but nothing helped me to solve this issue. I hope someone has an idea... :)

答:
Some special characters not allowed here.
Directly to assign text then with warning

```<code>android:text="value"
</code>```

@string file from get then avoid warning

```<code>android:text="@string/hello"
</code>```

res/values/strings.xml

```<code> <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello!</string>
</resources>
</code>```

Body:
After adding a new Activity to my project I get following error while compiling the layout

Gradle: Error parsing XML: not well-formed (invalid token)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:orientation="vertical" >

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_password"
        android:text="<password>"/>
</LinearLayout>

"http://schemas.android.com/apk/res/android" is marked red and hovering pops following message up

URI is not registered ( Setting | Project Settings | Schemas and DTDs )

My Settings>Project Settings>Schemas and DTDs look like that:
Project Settings>Schemas and DTDs">

I already found some similar questions around here but nothing helped me to solve this issue. I hope someone has an idea... :)

Body:
Some special characters not allowed here.
Directly to assign text then with warning

android:text="value"

@string file from get then avoid warning

android:text="@string/hello"

res/values/strings.xml

 <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello!</string>
</resources>


问:
Unable to close window application with user defined button and what is perfect process to call application from window service
I am new for c# developer and I tried to close my window application with following code. I hide close button of form and add user defined button to close application.

```<code> private void closeBtn_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
            //Environment.Exit(1);
            //Application.Exit();
            //this.Close();
        }
</code>```

But process still running on Task Manager. Actually I am calling this application from Window service. But application is not closing properly.

```<code>private void callback(Object state)
        {
    string strAppPath;
                        strAppPath = @"D:\VSPythonProject\Reminder_WApp\Reminder_WApp\bin\Debug\Reminder_WApp.exe"; //System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) +
                        System.Diagnostics.Process.Start(strAppPath);

                        ApplicationLoader.PROCESS_INFORMATION procInfo;
                        ApplicationLoader.StartProcessAndBypassUAC(strAppPath, out procInfo);
    }
</code>```

答:
check ApplicationLoader event. That call twice.

For closing application use below code :

```<code>System.Windows.Forms.Application.Exit();
</code>```

instead of

```<code>System.Environment.Exit(0);
</code>```

To close running threads use:

```<code>System.Windows.Forms.Application.ExitThread( );
</code>```

To close running form use :

```<code>this.close();
</code>```

For console application use:

```<code>System.Environment.Exit(0);
</code>```

Body:
I am new for c# developer and I tried to close my window application with following code. I hide close button of form and add user defined button to close application.

 private void closeBtn_Click(object sender, EventArgs e)
        {
            System.Environment.Exit(0);
            //Environment.Exit(1);
            //Application.Exit();
            //this.Close();
        }

But process still running on Task Manager. Actually I am calling this application from Window service. But application is not closing properly.

private void callback(Object state)
        {
    string strAppPath;
                        strAppPath = @"D:\VSPythonProject\Reminder_WApp\Reminder_WApp\bin\Debug\Reminder_WApp.exe"; //System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) +
                        System.Diagnostics.Process.Start(strAppPath);

                        ApplicationLoader.PROCESS_INFORMATION procInfo;
                        ApplicationLoader.StartProcessAndBypassUAC(strAppPath, out procInfo);
    }

Body:
check ApplicationLoader event. That call twice.

For closing application use below code :

System.Windows.Forms.Application.Exit();

instead of

System.Environment.Exit(0);

To close running threads use:

System.Windows.Forms.Application.ExitThread( );

To close running form use :

this.close();

For console application use:

System.Environment.Exit(0);


问:
How to use batch requests for Gmail Send API
I am currently sending more than one Emails at a time using Gmail API. I am doing this sequentially:

Send an Email via GmailAPI

Wait for response from GmailAPI.

When response is received, update the Record with ThreadID returned by GmailAPI.

Repeat steps 1-3 for other emails.

I was reading about batching your sendEmail API requests,so that we make one call to API and handle the responses.
Although i am able to batch my all request and send it,

I am not sure about how to handle Responses. If i have 30 Send Email Requests in the batch request, when the response is received for the batch, how do i figure out which response is for which Email?

Here is my Implementation

```<code>BatchRequest batch  = gmailService.batch();
gmailService.users().messages().send("me", message).queue(batch, callback);
batch.execute();

    final List<Message> messages = new ArrayList<Message>();
        JsonBatchCallback<Message> callback = new JsonBatchCallback<Message>() {
            public void onSuccess(Message message, HttpHeaders  responseHeaders) {
                System.out.println("MessageThreadID:"+ message.getThreadId());
                System.out.println("MessageID:"+ message.getId());
                synchronized (messages) {
                    messages.add(message);
                }
            }

            @Override
            public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders)
                    throws IOException {
            }
        };
</code>```

答:
I am not sure about how to handle Responses. If i have 30 Send Email Requests in the batch request, when the response is received for the batch, how do i figure out which response is for which Email?

According to this Batch Request Response document:

Response to a batch request

The server's response is a single standard HTTP response with a
  multipart/mixed content type; each part is the response to one of the
  requests in the batched request, in the same order as the requests.

Like the parts in the request, each response part contains a complete
  HTTP response, including a status code, headers, and body. And like
  the parts in the request, each response part is preceded by a
  Content-Type header that marks the beginning of the part.

You could get the the complete HTTP response, its status code, its headers, and its body in the order to which you made the request. So response one is for 1st request, response 2 is for 2nd request and so forth. In this way, you might figure the response for which Email.

Body:
I am currently sending more than one Emails at a time using Gmail API. I am doing this sequentially:

Send an Email via GmailAPI

Wait for response from GmailAPI.

When response is received, update the Record with ThreadID returned by GmailAPI.

Repeat steps 1-3 for other emails.

I was reading about batching your sendEmail API requests,so that we make one call to API and handle the responses.
Although i am able to batch my all request and send it,

I am not sure about how to handle Responses. If i have 30 Send Email Requests in the batch request, when the response is received for the batch, how do i figure out which response is for which Email?

Here is my Implementation

BatchRequest batch  = gmailService.batch();
gmailService.users().messages().send("me", message).queue(batch, callback);
batch.execute();

    final List<Message> messages = new ArrayList<Message>();
        JsonBatchCallback<Message> callback = new JsonBatchCallback<Message>() {
            public void onSuccess(Message message, HttpHeaders  responseHeaders) {
                System.out.println("MessageThreadID:"+ message.getThreadId());
                System.out.println("MessageID:"+ message.getId());
                synchronized (messages) {
                    messages.add(message);
                }
            }

            @Override
            public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders)
                    throws IOException {
            }
        };


问:
c# easiest way to extract substring
i have a string:

```<code>string somestring = "\\\\Tecan1\\tecan #1 output\\15939-E.ESY"
</code>```

i need to extract 15939

it will always be a 5 digit number, always preceeded by '\' and it will always "-" after it

答:
This regex does the trick for the input string you provided:

```<code>        var input = "\\\\Tecan1\\tecan #1 output\\15939-E.ESY";

        var pattern = @".*\\(\d{5})-";

        var result = Regex.Match(input, pattern).Groups[1].Value;
</code>```

But I actually like Brad's solution using Path.GetFileName more :-)

Title: c# easiest way to extract substring

Body:
i have a string:

string somestring = "\\\\Tecan1\\tecan #1 output\\15939-E.ESY"

i need to extract 15939

it will always be a 5 digit number, always preceeded by '\' and it will always "-" after it

Body:
This regex does the trick for the input string you provided:

        var input = "\\\\Tecan1\\tecan #1 output\\15939-E.ESY";

        var pattern = @".*\\(\d{5})-";

        var result = Regex.Match(input, pattern).Groups[1].Value;

But I actually like Brad's solution using Path.GetFileName more :-)


问:
Cannot add element to array
I'm new in Swift and I have issue with adding an element to an Array

I'm trying to store 6 objects from JSON to Array. But the Array is nil.

I see it add to Array when I debug it, I have no idea why it's nil after finished request JSON?

JSON:

```<code>[
    {
        "amount": "20.0",
        "date": "10/07/2016"
    },
    {
        "amount": "21.0",
        "date": "11/07/2016"
    },
    {
        "amount": "16.0",
        "date": "12/07/2016"
    },
    {
        "amount": "30.0",
        "date": "13/07/2016"
    },
    {
        "amount": "50.0",
        "date": "14/07/2016"
    },
    {
        "amount": "33.0",
        "date": "15/07/2016"
    }
]
</code>```

Service:

```<code>    class DownloadService {
    static let instance = DownloadService()
    //static var goldArray = [Gold]()
    var goldArray = [Gold]()
    func getData() {
        Alamofire.request("https://rth-recruitment.herokuapp.com/api/prices/chart_data", headers: headers).responseJSON { response in
            if let objJson = response.result.value as! NSArray?{
                for element in objJson {
                    let data = element as! NSDictionary
                    let amount = data["amount"] as! String
                    let date = data["date"] as! String
                    let gold = Gold(amount: amount, date: date)
                    self.goldArray.append(gold)
                    print(self.goldArray.count)//print 1 to 6
                }
            }
        }
        printGoldArray()
    }

    func printGoldArray(){
        for element in self.goldArray {
            print(element)//print nothing
        }
    }
}
</code>```

Gold class:

```<code>    class Gold{
    let amount:String
    let date: String

    init(amount: String, date: String) {
        self.amount = amount
        self.date = date
    }

}
</code>```

ViewController:

```<code>    class ViewController: UIViewController {
    //var dataArray = [Gold]()
    override func viewDidLoad() {
        super.viewDidLoad()
        DownloadService.instance.getData()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
</code>```

答:
First, your array is not print array element because you print it directly after closure. closure uses async paradigm. so put the print function inside closure.

and Second thing is why use to much force full unwrap. instead you can use if let or guard statement

you can see below code.

```<code>func getData() {
        Alamofire.request("https://rth-recruitment.herokuapp.com/api/prices/chart_data", headers: headers).responseJSON { response in
            if let objJson = response.result.value as? NSArray {
                for element in objJson {
                    if let data = element as? NSDictionary {
                        let amount = data["amount"] as! String
                        let date = data["date"] as! String
                        let gold = Gold(amount: amount, date: date)
                        self.goldArray.append(gold)
                        print(self.goldArray.count)
                    }
                }
            }
            printGoldArray()
        }
    }
</code>```

Title: Cannot add element to array

Body:
I'm new in Swift and I have issue with adding an element to an Array

I'm trying to store 6 objects from JSON to Array. But the Array is nil.

I see it add to Array when I debug it, I have no idea why it's nil after finished request JSON?

JSON:

[
    {
        "amount": "20.0",
        "date": "10/07/2016"
    },
    {
        "amount": "21.0",
        "date": "11/07/2016"
    },
    {
        "amount": "16.0",
        "date": "12/07/2016"
    },
    {
        "amount": "30.0",
        "date": "13/07/2016"
    },
    {
        "amount": "50.0",
        "date": "14/07/2016"
    },
    {
        "amount": "33.0",
        "date": "15/07/2016"
    }
]

Service:

    class DownloadService {
    static let instance = DownloadService()
    //static var goldArray = [Gold]()
    var goldArray = [Gold]()
    func getData() {
        Alamofire.request("https://rth-recruitment.herokuapp.com/api/prices/chart_data", headers: headers).responseJSON { response in
            if let objJson = response.result.value as! NSArray?{
                for element in objJson {
                    let data = element as! NSDictionary
                    let amount = data["amount"] as! String
                    let date = data["date"] as! String
                    let gold = Gold(amount: amount, date: date)
                    self.goldArray.append(gold)
                    print(self.goldArray.count)//print 1 to 6
                }
            }
        }
        printGoldArray()
    }

    func printGoldArray(){
        for element in self.goldArray {
            print(element)//print nothing
        }
    }
}

Gold class:

    class Gold{
    let amount:String
    let date: String

    init(amount: String, date: String) {
        self.amount = amount
        self.date = date
    }

}

ViewController:

    class ViewController: UIViewController {
    //var dataArray = [Gold]()
    override func viewDidLoad() {
        super.viewDidLoad()
        DownloadService.instance.getData()

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Body:
First, your array is not print array element because you print it directly after closure. closure uses async paradigm. so put the print function inside closure.

and Second thing is why use to much force full unwrap. instead you can use if let or guard statement

you can see below code.

func getData() {
        Alamofire.request("https://rth-recruitment.herokuapp.com/api/prices/chart_data", headers: headers).responseJSON { response in
            if let objJson = response.result.value as? NSArray {
                for element in objJson {
                    if let data = element as? NSDictionary {
                        let amount = data["amount"] as! String
                        let date = data["date"] as! String
                        let gold = Gold(amount: amount, date: date)
                        self.goldArray.append(gold)
                        print(self.goldArray.count)
                    }
                }
            }
            printGoldArray()
        }
    }


问:
Php redirect causing 302 for ajax redirect
This is my core script of login controller this means all the sanitization and verification of user is done.

code inside LoginController.php

```<code>if ( password_verify($valid['pass'], $pass) ) {
    // My session stuffs

    header('Content-Type: application/json');
    echo json_encode (array(
        'result' => 'success',
        'msg' => 'Login successful..! You will be redirected in a moment'
    ));
    redirect('user/profile'); //Ajax redirect only works when I remove this.
    exit;
}
</code>```

Code inside login.php

```<code>try {
    LoginController::UserLogin(); // Calling my method inside my controller
} catch (Exception $e) {

    echo json_encode(array(
        'error' => array(
            'msg' => $e->getMessage()
        ),
    ), JSON_PRETTY_PRINT);
    header('Content-Type: application/json');
    exit;

}

<form id="login_form" action="<?php echo htmlspecialchars(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME)); ?>" class="form" method="POST">
    <div class="form-group">
        <input type="text" name="login_username" placeholder="Enter username" class="form-control" />
    </div>
    <div class="form-group">
        <input type="password" name="login_pass" placeholder="Enter password" class="form-control" />
    </div>
    <div class="form-group">
        <input type="text" name="login_security" placeholder="Enter Security 25 * 2" class="form-control" />
    </div>
    <button class="btn btn-green" id="login-btn">Login</button>

</form>
</code>```

My ajax part

```<code>$('#login_form #login-btn').on('click', function (e) {
    e.preventDefault();

    $.ajax({
        url : $('#login_form').attr('action'),
        type: 'POST',
        dataType: 'json',
        data: $('#login_form').serialize(),
        success: function(data) {
            console.log(data);
            if (data.error) {
                $('.error').html('<div class="alert alert-danger">' + data.error.msg + '</div>');
            }
            if ( data.result === 'success' ) {
                $('.error').html('<div class="alert alert-unknown">' + data.msg + '</div>');
                setTimeout('window.location.href = "user/profile.php";',3000);
            }
        }
    });
});
</code>```

My problem: Everything works fine until I use ajax. This means the page without Ajax shows error and everything is fine. But when I use ajax the errors are returned but when the login details are correct (Valid details) the page gets stuck(The page is not redirected).

When I check the developer console what I see is this 302 for login page and the redirect is not taking place(But it works when I remove the header from the Login controller form this causes no redirect when the user does not have JavaScript disabled).

答:
Try this and see if it works:

In the LoginController.php: REMOVE the redirect after the echo part.

In the Login.php, put the header BEFORE the echo part.

In the Ajax part, chage the success part like this:

```<code>success: function(data) {
        console.log(data);
        if (data.error) {
            $('.error').html('<div class="alert alert-danger">' + data.error.msg + '</div>');
        }
        if ( data.result === 'success' ) {
            $('.error').html('<div class="alert alert-unknown">' + data.msg + '</div>');
            // -> here
            // correct setTimeout function
            setTimeout(function(){
                window.location = "user/profile.php";
            },3000);
        }
    }
</code>```

Body:
This is my core script of login controller this means all the sanitization and verification of user is done.

code inside LoginController.php

if ( password_verify($valid['pass'], $pass) ) {
    // My session stuffs

    header('Content-Type: application/json');
    echo json_encode (array(
        'result' => 'success',
        'msg' => 'Login successful..! You will be redirected in a moment'
    ));
    redirect('user/profile'); //Ajax redirect only works when I remove this.
    exit;
}

Code inside login.php

try {
    LoginController::UserLogin(); // Calling my method inside my controller
} catch (Exception $e) {

    echo json_encode(array(
        'error' => array(
            'msg' => $e->getMessage()
        ),
    ), JSON_PRETTY_PRINT);
    header('Content-Type: application/json');
    exit;

}

<form id="login_form" action="<?php echo htmlspecialchars(pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME)); ?>" class="form" method="POST">

        <input type="text" name="login_username" placeholder="Enter username" class="form-control" />

        <input type="password" name="login_pass" placeholder="Enter password" class="form-control" />

        <input type="text" name="login_security" placeholder="Enter Security 25 * 2" class="form-control" />

    <button class="btn btn-green" id="login-btn">Login</button>

</form>

My ajax part

$('#login_form #login-btn').on('click', function (e) {
    e.preventDefault();

    $.ajax({
        url : $('#login_form').attr('action'),
        type: 'POST',
        dataType: 'json',
        data: $('#login_form').serialize(),
        success: function(data) {
            console.log(data);
            if (data.error) {
                $('.error').html('
' + data.error.msg + '
');
            }
            if ( data.result === 'success' ) {
                $('.error').html('
' + data.msg + '
');
                setTimeout('window.location.href = "user/profile.php";',3000);
            }
        }
    });
});

My problem: Everything works fine until I use ajax. This means the page without Ajax shows error and everything is fine. But when I use ajax the errors are returned but when the login details are correct (Valid details) the page gets stuck(The page is not redirected).

When I check the developer console what I see is this 302 for login page and the redirect is not taking place(But it works when I remove the header from the Login controller form this causes no redirect when the user does not have JavaScript disabled).

Body:
Try this and see if it works:

In the LoginController.php: REMOVE the redirect after the echo part.

In the Login.php, put the header BEFORE the echo part.

In the Ajax part, chage the success part like this:

success: function(data) {
        console.log(data);
        if (data.error) {
            $('.error').html('<div class="alert alert-danger">' + data.error.msg + '</div>');
        }
        if ( data.result === 'success' ) {
            $('.error').html('<div class="alert alert-unknown">' + data.msg + '</div>');
            // -> here
            // correct setTimeout function
            setTimeout(function(){
                window.location = "user/profile.php";
            },3000);
        }
    }


问:
Any Method to use master jsp page with multiple actions and invoking partial jsp page into master page in Spring Web MVC Annotations. Any EXAMPLE?
Spring MVC Annotation:
Please can anyone  tell me that is there any method in spring to display URL in such manner
 ShowTab.do?module=Leads , ShowTab.do?module=Account, ShowTab.do?module=Status.     Means [partial jsp page?common controller=Actions]

for example: zoho crm
https://crm.zoho.com/crm/ShowTab.do?module=Leads
https://crm.zoho.com/crm/ShowTab.do?module=Accounts

CODE: Which gives only  crm/CreateEntity/

Expected output':crm/CreateEntity/module?=Lead   or
crm/CreateEntity/module?=Account

@RequestMapping(value = "/CreateEntity", method = RequestMethod.GET)

Code:
@Controller
public class CreateEntitiesController {

```<code>@RequestMapping(value = { "/CreateEntity" }, method = RequestMethod.GET)
public ModelAndView CreateEntity(Model model) {
    model.addAttribute("module", "CreateLeadStatus");
    return new ModelAndView("CreateEntity");

}
</code>```

                            ">Create Entity

答:
@Controller
public class CreateEntitiesController {</p>

```<code>@Autowired
private CreateEntitiesDao createentitiesdao;

  @RequestMapping(value = { "/CreateEntity" }, method = RequestMethod.GET)
  public ModelAndView CreateEntity(@RequestParam(defaultValue="",required=false)String module,Model model) {
      model.addAttribute("module", module);
     // module = module== null ? "": module;
      if(module.equals("leadstatus"))
      {
          model.addAttribute("pgtitle", "Lead Status");
          model.addAttribute("viewpg", "CreateLeadStatus.jsp");
          model.addAttribute("controllername", "Connroller name");
      }
      else if(module.equals("account"))
      {
          model.addAttribute("pgtitle", "Account");
          model.addAttribute("viewpg", "account.jsp");
          model.addAttribute("controllername", "Connroller name");
      }

      return new ModelAndView("CreateEntity");
  }
</code>```

Body:
Spring MVC Annotation:
Please can anyone  tell me that is there any method in spring to display URL in such manner
 ShowTab.do?module=Leads , ShowTab.do?module=Account, ShowTab.do?module=Status.     Means [partial jsp page?common controller=Actions]

for example: zoho crm
https://crm.zoho.com/crm/ShowTab.do?module=Leads
https://crm.zoho.com/crm/ShowTab.do?module=Accounts

CODE: Which gives only  crm/CreateEntity/

Expected output':crm/CreateEntity/module?=Lead   or
crm/CreateEntity/module?=Account

@RequestMapping(value = "/CreateEntity", method = RequestMethod.GET)

Code:
@Controller
public class CreateEntitiesController {

@RequestMapping(value = { "/CreateEntity" }, method = RequestMethod.GET)
public ModelAndView CreateEntity(Model model) {
    model.addAttribute("module", "CreateLeadStatus");
    return new ModelAndView("CreateEntity");

}

                            ">Create Entity

Body:
@Controller
public class CreateEntitiesController {

@Autowired
private CreateEntitiesDao createentitiesdao;

  @RequestMapping(value = { "/CreateEntity" }, method = RequestMethod.GET)
  public ModelAndView CreateEntity(@RequestParam(defaultValue="",required=false)String module,Model model) {
      model.addAttribute("module", module);
     // module = module== null ? "": module;
      if(module.equals("leadstatus"))
      {
          model.addAttribute("pgtitle", "Lead Status");
          model.addAttribute("viewpg", "CreateLeadStatus.jsp");
          model.addAttribute("controllername", "Connroller name");
      }
      else if(module.equals("account"))
      {
          model.addAttribute("pgtitle", "Account");
          model.addAttribute("viewpg", "account.jsp");
          model.addAttribute("controllername", "Connroller name");
      }

      return new ModelAndView("CreateEntity");
  }


问:
Binary coded decimal (BCD) to Hexadecimal conversion
can someone explain to me how to convert BCD to Hexadecimal? For example how can i convert 98(BCD) to Hexadecimal.
Thanks.</p>

答:
I don't quite understand your question, but I'm guessing that e.g. someone gives you a number 98 encoded in BCD, which would be:

1001 1000

and you are supposed to get:

62H

What I would propose:

1) convert BCD-encoded value to decimal value (D)

2) convert D to hexadecimal value.

Depending on which programming language you choose, this task will be easier or harder.

EDIT: In Java it could be:

```<code>    byte bcd = (byte)0x98; // BCD value: 1001 1000

    int decimal = (bcd & 0xF) + (((int)bcd & 0xF0) >> 4)*10;

    System.out.println(
            Integer.toHexString(decimal)
    );
</code>```

Body:
I don't quite understand your question, but I'm guessing that e.g. someone gives you a number 98 encoded in BCD, which would be:

1001 1000

and you are supposed to get:

62H

What I would propose:

1) convert BCD-encoded value to decimal value (D)

2) convert D to hexadecimal value.

Depending on which programming language you choose, this task will be easier or harder.

EDIT: In Java it could be:

    byte bcd = (byte)0x98; // BCD value: 1001 1000

    int decimal = (bcd & 0xF) + (((int)bcd & 0xF0) >> 4)*10;

    System.out.println(
            Integer.toHexString(decimal)
    );


问:
Can I use IntelliJ Idea to assume a Git tracked file as unchanged?
I'd like to use the IDE IntelliJ Idea and not the terminal to execute the command

```<code>git update-index --assume-unchanged <file>
</code>```

I hope there is a tool so that I can do a multiple selection of files to assume unchanged. Anyway I cannot find such a feature.
Is there any way to do this from the IDE without using the terminal?

答:
No, it is not possible from IDEA.
https://youtrack.jetbrains.com/issue/IDEA-76682</p>

Body:
I'd like to use the IDE IntelliJ Idea and not the terminal to execute the command

git update-index --assume-unchanged <file>

I hope there is a tool so that I can do a multiple selection of files to assume unchanged. Anyway I cannot find such a feature.
Is there any way to do this from the IDE without using the terminal?


问:
How to remove disable element using JQUERY?
I use jQuery 1.8.3.

Here is my html input text box:

```<code><input type="text" name="textinput-hide" id="textinput1" placeholder="Text input" value="" disabled>
</code>```

Here how I try to remove disable element:

```<code>  $('#textinput1').removeProp('disabled');
</code>```

But the row above dosn't remove disabled  attribute. How to remove disable element

答:
If you want to remove disable attribute:-

$('input').each(function(){
  if($(this).prop("disabled")){
    $(this).prop("disabled", false);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="textinput-hide" id="textinput1" placeholder="Text input1" value="" disabled><br><br>

<input type="text" name="textinput-hide" id="textinput2" placeholder="Text input2" value=""></code>```

If you want to remove complete element itself:-

$('input').each(function(){
  if($(this).prop("disabled")){
    $(this).remove();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" name="textinput-hide" id="textinput1" placeholder="Text input1" value="" disabled><br>

<input type="text" name="textinput-hide" id="textinput2" placeholder="Text input2" value=""></code>```

Body:
I use jQuery 1.8.3.

Here is my html input text box:

<input type="text" name="textinput-hide" id="textinput1" placeholder="Text input" value="" disabled>

Here how I try to remove disable element:

  $('#textinput1').removeProp('disabled');

But the row above dosn't remove disabled  attribute. How to remove disable element

Body:
If you want to remove disable attribute:-

$('input').each(function(){
  if($(this).prop("disabled")){
    $(this).prop("disabled", false);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="textinput-hide" id="textinput1" placeholder="Text input1" value="" disabled><br><br>

<input type="text" name="textinput-hide" id="textinput2" placeholder="Text input2" value="">

If you want to remove complete element itself:-

$('input').each(function(){
  if($(this).prop("disabled")){
    $(this).remove();
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" name="textinput-hide" id="textinput1" placeholder="Text input1" value="" disabled><br>

<input type="text" name="textinput-hide" id="textinput2" placeholder="Text input2" value="">


问:
Spotify token post- call return error website instead of error or token
I'm trying to use Authorization Code flow instead of Implicit Grant which I use currently. Here is documentation of both flows. I'm using spotify API from my Angular 2 application. First three steps go well and I get code from callback call. But when I make post call to https://accounts.spotify.com/api/token I get CORS exception because call returns website which is prohibited by browsers. Return page is same as clicking this link https://accounts.spotify.com/api/token. I try call this api by using curl and here is what I notice.
When calling this:

```<code>curl -H "Authorization: Basic ZjM...zE=" -d grant_type=authorization_code -d code=MQCbtKe...44KN -d redirect_uri=https%3A%2F%2Fwww.foo.com%2Fauth https://accounts.spotify.com/api/token
</code>```

It return error json message and complaining invalid client.

When I remove data it return that error html page.

```<code>curl -H "Authorization: Basic ZjM...zE=" https://accounts.spotify.com/api/token
</code>```

So I assume that in my code the problem is same or something similar. So is it ok to set those parameters to POST call body? It seems that spotify endpoint doesn't get my parameters at all and that is why it doesn't return error message. Here is example provided by spotify and here here is documentation of Angular http component.

Here is my TypeScript call:

```<code>var data  = {
    redirect_uri: this.config.redirectUri,
    grant_type: 'authorization_code',
    code : code
};

let headers = this.getTokenHeaders();
let address = "https://accounts.spotify.com/api/token";
return this.http.post(address,data, new RequestOptions({headers: headers}))
    .toPromise()
    .then(res =>
    {
        let body = res.json();
        localStorage.setItem('spotify-access-token', body.access_token);
        localStorage.setItem('spotify-refresh-token', body.refresh_token);
        var expiresIn = body.expires_in;

        return true;
    })
    .catch(err=>
    {
        return false;
    });

getTokenHeaders()
    {
        return new Headers(this.accountAuth());
    }

private accountAuth(): Object {
    var auth = {
        'Authorization': 'Basic ' + (new Buffer(this.config.clientId + ':' + this.config.clientSecret).toString('base64')),
        'Content-Type': 'application/x-www-form-urlencoded'
        //'Content-Type':'application/json'
    };
    return auth;
}
</code>```

I have tried to set Content-Type to application/json and application/x-www-form-urlencoded.

答:
I found this answer https://stackoverflow.com/a/28406268/8081009 and tried it from server side and got same error page there as well when I used message body for delivering parameters. Then I changed parameters to url like this:

```<code>var url = "/api/token?redirect_uri=http://localhost:8080/callback.html&grant_type=authorization_code&code="+code;
</code>```

Now I'm getting correct message. Hopefully this help someone.

So don't use api/token from client side and set parameters to url.

Body:
I'm trying to use Authorization Code flow instead of Implicit Grant which I use currently. Here is documentation of both flows. I'm using spotify API from my Angular 2 application. First three steps go well and I get code from callback call. But when I make post call to https://accounts.spotify.com/api/token I get CORS exception because call returns website which is prohibited by browsers. Return page is same as clicking this link https://accounts.spotify.com/api/token. I try call this api by using curl and here is what I notice.
When calling this:

curl -H "Authorization: Basic ZjM...zE=" -d grant_type=authorization_code -d code=MQCbtKe...44KN -d redirect_uri=https%3A%2F%2Fwww.foo.com%2Fauth https://accounts.spotify.com/api/token

It return error json message and complaining invalid client.

When I remove data it return that error html page.

curl -H "Authorization: Basic ZjM...zE=" https://accounts.spotify.com/api/token

So I assume that in my code the problem is same or something similar. So is it ok to set those parameters to POST call body? It seems that spotify endpoint doesn't get my parameters at all and that is why it doesn't return error message. Here is example provided by spotify and here here is documentation of Angular http component.

Here is my TypeScript call:

var data  = {
    redirect_uri: this.config.redirectUri,
    grant_type: 'authorization_code',
    code : code
};

let headers = this.getTokenHeaders();
let address = "https://accounts.spotify.com/api/token";
return this.http.post(address,data, new RequestOptions({headers: headers}))
    .toPromise()
    .then(res =>
    {
        let body = res.json();
        localStorage.setItem('spotify-access-token', body.access_token);
        localStorage.setItem('spotify-refresh-token', body.refresh_token);
        var expiresIn = body.expires_in;

        return true;
    })
    .catch(err=>
    {
        return false;
    });

getTokenHeaders()
    {
        return new Headers(this.accountAuth());
    }

private accountAuth(): Object {
    var auth = {
        'Authorization': 'Basic ' + (new Buffer(this.config.clientId + ':' + this.config.clientSecret).toString('base64')),
        'Content-Type': 'application/x-www-form-urlencoded'
        //'Content-Type':'application/json'
    };
    return auth;
}

I have tried to set Content-Type to application/json and application/x-www-form-urlencoded.

Body:
I found this answer https://stackoverflow.com/a/28406268/8081009 and tried it from server side and got same error page there as well when I used message body for delivering parameters. Then I changed parameters to url like this:

var url = "/api/token?redirect_uri=http://localhost:8080/callback.html&grant_type=authorization_code&code="+code;

Now I'm getting correct message. Hopefully this help someone.

So don't use api/token from client side and set parameters to url.


问:
Convert ImmutableListMultimap to Map using Collectors.toMap
I would like to convert a  ImmutableListMultimap<String, Character> to Map<String, List<Character>>.
I used to do it in the non-stream way as follows

```<code>    void convertMultiMaptoList(ImmutableListMultimap<String, Character> reverseImmutableMultiMap) {
            Map<String, List<Character>> result = new TreeMap<>();
          for( Map.Entry<String, Character> entry: reverseImmutableMultiMap.entries()) {
              String key = entry.getKey();
              Character t = entry.getValue();
          result.computeIfAbsent(key, x-> new ArrayList<>()).add(t);
       }
       //reverseImmutableMultiMap.entries().stream().collect(Collectors.toMap)
}
</code>```

I was wondering how to write the above same logic using java8 stream way (Collectors.toMap).

Please share your thoughts

答:
Well there is already a asMap that you can use to make this easier:

```<code>    Builder<String, Character> builder = ImmutableListMultimap.builder();
    builder.put("12", 'c');
    builder.put("12", 'c');

    ImmutableListMultimap<String, Character> map = builder.build();

    Map<String, List<Character>> map2 = map.asMap()
            .entrySet()
            .stream()
            .collect(Collectors.toMap(Entry::getKey, e -> new ArrayList<>(e.getValue())));
</code>```

If on the other hand you are OK with the return type of the asMap than it's a simple method call:

```<code> ImmutableMap<String, Collection<Character>> asMap =  map.asMap();
</code>```

Body:
I would like to convert a  ImmutableListMultimap<String, Character> to Map<String, List<Character>>.
I used to do it in the non-stream way as follows

    void convertMultiMaptoList(ImmutableListMultimap<String, Character> reverseImmutableMultiMap) {
            Map<String, List<Character>> result = new TreeMap<>();
          for( Map.Entry<String, Character> entry: reverseImmutableMultiMap.entries()) {
              String key = entry.getKey();
              Character t = entry.getValue();
          result.computeIfAbsent(key, x-> new ArrayList<>()).add(t);
       }
       //reverseImmutableMultiMap.entries().stream().collect(Collectors.toMap)
}

I was wondering how to write the above same logic using java8 stream way (Collectors.toMap).

Please share your thoughts

Body:
Well there is already a asMap that you can use to make this easier:

    Builder<String, Character> builder = ImmutableListMultimap.builder();
    builder.put("12", 'c');
    builder.put("12", 'c');

    ImmutableListMultimap<String, Character> map = builder.build();

    Map<String, List<Character>> map2 = map.asMap()
            .entrySet()
            .stream()
            .collect(Collectors.toMap(Entry::getKey, e -> new ArrayList<>(e.getValue())));

If on the other hand you are OK with the return type of the asMap than it's a simple method call:

 ImmutableMap<String, Collection<Character>> asMap =  map.asMap();


问:
locating jar file in $PATH environment variable for java -jar command
I want to run a simple executable jar like this:

```<code>java -jar /path/to/my/jar/myjar.jar
</code>```

However, i have to put that absolute path every time I want to run it. Is there a way to tell the OS to look for the jar in $PATH environment variable?

答: The -jar directive overrides the classpath, using whatever is defined in the jar file itself. The best way to do what you need is to use a tool such as ant, a script, or copy it to somewhere where the OS can find it (as Nejc Saje suggested).</p>

Body:
I want to run a simple executable jar like this:

java -jar /path/to/my/jar/myjar.jar

However, i have to put that absolute path every time I want to run it. Is there a way to tell the OS to look for the jar in $PATH environment variable?


问:
play a local Audio in android with Cordova/PhoneGap using Media plugin
I try to play a mp3 file. This works if I change the path to the file on my local webServer, but if I run this on an Android device the sound is not played and error is :{"code":1}

this is my code

HTML:

```<code><button onclick="playAudio('sounds/blop.mp3');">hi</button>
</code>```

javascript:

```<code>function playAudio(src) {
    var url = src;
    var my_media = new Media(url,
            // success callback
             function () { console.log("playAudio():Audio Success"); },
            // error callback
             function (err) { console.log("playAudio():Audio Error: " + err);
                            alert(JSON.stringify(err))
                            }
    );
           // Play audio
    my_media.play();
}
</code>```

config.xml:

```<code><plugin name="cordova-plugin-media" spec="https://github.com/apache/cordova-plugin-media.git"/>
</code>```

I tried

```<code><button onclick="playAudio('/android_asset/www/sounds/blop.mp3');">hi</button>
</code>```

and :

```<code> <button onclick="playAudio('file:///android_asset/www/sounds/blop.mp3');">hi</button>
</code>```

But its still does not work in Android:

error :{"code":1}

is there any solution?!

Edit 1 :

The is my App structure

```<code>App
`-- www
    `-- index.html
        |+-- sounds
        |   `-- blop.mp3
        |-- js
        `-- css
</code>```

答:
UPDATE:

I checked your project and the url passed works ok, I also tested the app and for some audio files you have wrong url set like:
"sounds/PopCork.mp3"

So the actual url that you need to pass is:
 "file:///android_asset/www/sounds/PopCork.mp3"

So to make this work cross platform use:

cordova.file.applicationDirectory + ''www/sounds/PopCork.mp3"

All the best with the project!

This line should work fine:

<button onclick="playAudio('file:///android_asset/www/sounds/blop.mp3');">hi</button>

could you plz paste www folder structure?

Body:
I try to play a mp3 file. This works if I change the path to the file on my local webServer, but if I run this on an Android device the sound is not played and error is :{"code":1}

this is my code

HTML:

<button onclick="playAudio('sounds/blop.mp3');">hi</button>

javascript:

function playAudio(src) {
    var url = src;
    var my_media = new Media(url,
            // success callback
             function () { console.log("playAudio():Audio Success"); },
            // error callback
             function (err) { console.log("playAudio():Audio Error: " + err);
                            alert(JSON.stringify(err))
                            }
    );
           // Play audio
    my_media.play();
}

config.xml:

<plugin name="cordova-plugin-media" spec="https://github.com/apache/cordova-plugin-media.git"/>

I tried

<button onclick="playAudio('/android_asset/www/sounds/blop.mp3');">hi</button>

and :

 <button onclick="playAudio('file:///android_asset/www/sounds/blop.mp3');">hi</button>

But its still does not work in Android:

error :{"code":1}

is there any solution?!

Edit 1 :

The is my App structure

App
`-- www
    `-- index.html
        |+-- sounds
        |   `-- blop.mp3
        |-- js
        `-- css


问:
cannot update postgres db from 9.3 to 9.4 in AWS
I have created a RDS instance with postgres9.3.14 with Db paramgroup of 9.3 family. (through CFN template).Now , I am trying to upgrade the Db version to 9.4.11 through CFN , the upgrade is failing with below error.

DBParameterGroupFamily postgres9.3 cannot be used for this instance. Please use a Parameter Group with DBParameterGroupFamily postgres9.4

From the AWS documentation, I understood that I cannot update family of a parameter group once it is created.
I want to understand,If I try to update the Db version from 9.3 to 9.4, Does the CFN has that intelligence to delete existing DB parameter group(9.3 family) creates a new parameter group (9.4 family)with correct family?

Any help would be appreciated.

答:
try this method.
create new parameter group which belongs to postgresql 9.4, then attach newly created parameter group to RDS now start the upgrade process. </p>


问:
Kafka consumer reading messages parallel
Can we have multiple consumers to consume from a topic to achieve parallel processing in kafka.
My use case is to read messages from a single partition in parallel.  </p>

答:
The number of partitions define the level of parallelism to read from a kafka topic. But reading is (more or less) only restricted by your network capacities.

A good pattern is to separate reading and processing of messages (one thread per topic-partition for reading and multiple threads for processing this messages).


问:
How to break string by separator into multidimensional array in PHP
I have a string 'value1/value2'. The required output is $_SESSION['value1']['value2']. i tried using explode and then array_reduce over explode values but with no success.

My code looks like

```<code>function set($key, $value){
/* code */
}

set('key1/key2', 'some_text');
</code>```

required output like $_SESSION['key1']['key2'] = 'some_text';

key1/key2 is not fixed it may be 'key1' or 'key1/key2/key3' and so on.
Anyone be make fiddle of it is Highly appreciable.
Thanks

答:
For a general case (i.e. for more than two pieces), you'll need to iterate over the segments, and incrementally index further into your target array:</p>

```<code><?php
$string = 'value1/value2/value3';

$_SESSION = ['value1' => ['value2' => ['value3' => 'My String']]];

$target = $_SESSION;

foreach (explode('/', $string) as $piece) {
    $target =& $target[$piece];
}

echo $target; // My String
</code>```

Body:
I have a string 'value1/value2'. The required output is $_SESSION['value1']['value2']. i tried using explode and then array_reduce over explode values but with no success.

My code looks like

function set($key, $value){
/* code */
}

set('key1/key2', 'some_text');

required output like $_SESSION['key1']['key2'] = 'some_text';

key1/key2 is not fixed it may be 'key1' or 'key1/key2/key3' and so on.
Anyone be make fiddle of it is Highly appreciable.
Thanks

Body:
For a general case (i.e. for more than two pieces), you'll need to iterate over the segments, and incrementally index further into your target array:

<?php
$string = 'value1/value2/value3';

$_SESSION = ['value1' => ['value2' => ['value3' => 'My String']]];

$target = $_SESSION;

foreach (explode('/', $string) as $piece) {
    $target =& $target[$piece];
}

echo $target; // My String


问:
regex to add spaces in specific places
I have a 14 digits long number that I need to split into this format:

```<code>xxx xxx xxx xxxxx
</code>```

I have a regex that splits every 3 characters starting from the end (because of the lookahead?)

```<code>(?=(\d{3})+(?!\d))
</code>```

Which gives me:

```<code>xx xxx xxx xxx xxx
</code>```

I tried using lookbehind in regex101.com but I get a pattern error...

```<code>(?<=(\d{3})+(?!\d))
</code>```

How can I use lookbehind so that it starts from the begining of the string (if that's my issue) and how can I repeat the pattern only 3 times and then switch to a \d{5} ?

答:
Try this:

```<code>(\d{3})(\d{3})(\d{3})
</code>```

and replace by this:

```<code>"$1 $2 $3 "
</code>```

Regex 101 demo

const regex = /(\d{3})(\d{3})(\d{3})/g;
const str = `12345678901234`;
const subst = `$1 $2 $3 `;
const result = str.replace(regex, subst);
console.log( result);```

Title: regex to add spaces in specific places

Body:
I have a 14 digits long number that I need to split into this format:

xxx xxx xxx xxxxx

I have a regex that splits every 3 characters starting from the end (because of the lookahead?)

(?=(\d{3})+(?!\d))

Which gives me:

xx xxx xxx xxx xxx

I tried using lookbehind in regex101.com but I get a pattern error...

(?<=(\d{3})+(?!\d))

How can I use lookbehind so that it starts from the begining of the string (if that's my issue) and how can I repeat the pattern only 3 times and then switch to a \d{5} ?

Body:
Try this:

(\d{3})(\d{3})(\d{3})

and replace by this:

"$1 $2 $3 "

Regex 101 demo

const regex = /(\d{3})(\d{3})(\d{3})/g;
const str = `12345678901234`;
const subst = `$1 $2 $3 `;
const result = str.replace(regex, subst);
console.log( result);


问:
Doctype breaks jquery fadeOut method in IE!
I recently added a doctype to my page to help fix a little IE rendering problem. It looks like so:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
</code>```

My fadeOut code (I'm using stop(true,true) to restart the animation if its in progress):

```<code>$('#myElement').stop(true, true).show().fadeOut(5000);
</code>```

Now, my jquery fadeOut(5000) method doesn't fade in IE anymore. Does anyone know of a fix for this?

EDIT:
I've tried pretty much every flavor of DOCTYPE out there, and no matter which one I use, the fadeOut animation does NOT work in IE.

答: Have you tried another Doctype, like transitional or xhtml?</p>

Body:
I recently added a doctype to my page to help fix a little IE rendering problem. It looks like so:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

My fadeOut code (I'm using stop(true,true) to restart the animation if its in progress):

$('#myElement').stop(true, true).show().fadeOut(5000);

Now, my jquery fadeOut(5000) method doesn't fade in IE anymore. Does anyone know of a fix for this?

EDIT:
I've tried pretty much every flavor of DOCTYPE out there, and no matter which one I use, the fadeOut animation does NOT work in IE.