问:
Repeat a block dependent on an integer using Meteor/Blaze
I have an integer in my mongo collection to define a count, called 'tweet_count'. I need to repeat an icon based on this value, like so:

Helper:

```<code>Template.companyList.helpers({
    companies: function () {
        return Tweets.find();
    }
});
</code>```

Blaze:

```<code>{{#each companies}}
    {{ LOOP BASED ON tweet_count}}
       <i class="fa fa-circle"></i>
    {{ /LOOP }}
{{/each}}
</code>```

A sample of the Mongo collection looks like:

```<code>{
"_id" : "xxx",
"name" : "xxx",
"handle" : "xxx",
"tweet_count" : 2,
"tweets" : [
    {
        "tweet_id" : "x",
        "text" : "x",
        "created_at" : "Tue Jul 04 15:56:33 +0000 2017",
        "retweet_count" : 0,
        "from" : "x",
        "from_full_name" : "x",
        "from_profile_image" : "x"
    },
    {
        "tweet_id" : "x",
        "text" : "x9",
        "created_at" : "Tue Jul 04 15:56:47 +0000 2017",
        "retweet_count" : 0,
        "from" : "x",
        "from_full_name" : "x",
        "from_profile_image" : "x"
    }
]
}
</code>```

How can I achieve this using Meteor/Blaze? I have tried each but it only accepts an array which I do not have for this value, as it's simply a number.

答:
Just create a helper that returns an array with the size of tweet_count:

Template.companyList.helpers({
    companies: function () {
        return Tweets.find();
    },
    getTweetCount(tweet_count) {
        const ret = [];
        for (let i = 0; i < tweet_count; i++) {
            ret.push(i);
        }
        return ret;
    }
});
```

<p>It receives the tweet count and returns the empty array with size of tweet count. You call it from Blaze Syntax in the following way:</p>

<pre class="lang-html prettyprint-override"><code><template name="companyList">
    {{#each companies}}
        <span>{{this.name}}</span>
        {{#each getTweetCount this.tweet_count}}
            <i class="fa fa-circle"></i>
        {{/each}}
    {{/each}}
</template>
</code>```

The this refers to the current document, so this.tweet_count is the number that gets passed to your helper function getTweetCount.

Body:
I have an integer in my mongo collection to define a count, called 'tweet_count'. I need to repeat an icon based on this value, like so:

Helper:

Template.companyList.helpers({
    companies: function () {
        return Tweets.find();
    }
});

Blaze:

{{#each companies}}
    {{ LOOP BASED ON tweet_count}}

    {{ /LOOP }}
{{/each}}

A sample of the Mongo collection looks like:

{
"_id" : "xxx",
"name" : "xxx",
"handle" : "xxx",
"tweet_count" : 2,
"tweets" : [
    {
        "tweet_id" : "x",
        "text" : "x",
        "created_at" : "Tue Jul 04 15:56:33 +0000 2017",
        "retweet_count" : 0,
        "from" : "x",
        "from_full_name" : "x",
        "from_profile_image" : "x"
    },
    {
        "tweet_id" : "x",
        "text" : "x9",
        "created_at" : "Tue Jul 04 15:56:47 +0000 2017",
        "retweet_count" : 0,
        "from" : "x",
        "from_full_name" : "x",
        "from_profile_image" : "x"
    }
]
}

How can I achieve this using Meteor/Blaze? I have tried each but it only accepts an array which I do not have for this value, as it's simply a number.

Body:
Just create a helper that returns an array with the size of tweet_count:

Template.companyList.helpers({
    companies: function () {
        return Tweets.find();
    },
    getTweetCount(tweet_count) {
        const ret = [];
        for (let i = 0; i < tweet_count; i++) {
            ret.push(i);
        }
        return ret;
    }
});

It receives the tweet count and returns the empty array with size of tweet count. You call it from Blaze Syntax in the following way:

<template name="companyList">
    {{#each companies}}
        <span>{{this.name}}</span>
        {{#each getTweetCount this.tweet_count}}
            <i class="fa fa-circle"></i>
        {{/each}}
    {{/each}}
</template>

The this refers to the current document, so this.tweet_count is the number that gets passed to your helper function getTweetCount.


来源: stackexchange

问:
Stream file from S3 in lambda does not work
I want to load a file from S3 with line seperated values and push it into an array.

The following code does work on my local machine, but does not work executed as a lambda function. The lambda function times out (even if I bump the timeout up to 15 seconds).
Are the SDK's different? What do I miss here since I get no error message at all beside the timeout?

Lambda Env: Node 6.10
Permission to access S3 is set like this

```<code>"Statement": [{
  "Effect": "Allow",
  "Action": [
    "s3:*"
  ],
  "Resource": [
    "arn:aws:s3:::mybucket",
    "arn:aws:s3:::mybucket/*"
  ]
}]
</code>```

Code looks like this

```<code>var AWS = require('aws-sdk');
var s3 = new AWS.S3({region:'eu-central-1'});

exports.index = function(event, context, callback){
  var params = {
  Bucket: 'mybucket',
  Key: 'file.txt'
}

urls=[];

var stream = s3.getObject(params);

stream.on('httpError',function(err){
  console.log(err);
  throw err;
});

stream.on('httpData', function(chunk) {
  urls.push(chunk.toString());
});

stream.on('httpDone', function() {
  urls2 = urls.join('\n\r');
  callback(urls2);
});

stream.send();

}
</code>```

I got following error executing the lambda via AWS console

```<code>{
  "errorMessage": "2017-07-04T18:25:20.271Z 19ab7138-60e6-11e7-9e1e-c318d929bc39 Task timed out after 15.00 seconds"
}
</code>```

Thanks for any help!

答:
Handler is required to invoke the lambda function. Also, you need to mention handler name in the lambda function configuration.

```<code>exports.handler = (event, context, callback) => {
  const bucket = event.Records[0].s3.bucket.name;
  const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
  const params = {
    Bucket: bucket,
    Key: key,
  };
  var stream = s3.getObject(params);
  ....
  stream.send();
}
</code>```

eports.handler is invoked when lambda function triggers. Make sure you must define the handler name(filename.handler) in lambda function configuration.

If you trigger this code on s3 file upload it will read the uploaded s3 file. you change the bucket & key name to read any file(which exist).
Follow the documentation http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html

ContentLicense: CC BY-SA 3.0

Body:
I want to load a file from S3 with line seperated values and push it into an array.

The following code does work on my local machine, but does not work executed as a lambda function. The lambda function times out (even if I bump the timeout up to 15 seconds).
Are the SDK's different? What do I miss here since I get no error message at all beside the timeout?

Lambda Env: Node 6.10
Permission to access S3 is set like this

"Statement": [{
  "Effect": "Allow",
  "Action": [
    "s3:*"
  ],
  "Resource": [
    "arn:aws:s3:::mybucket",
    "arn:aws:s3:::mybucket/*"
  ]
}]

Code looks like this

var AWS = require('aws-sdk');
var s3 = new AWS.S3({region:'eu-central-1'});

exports.index = function(event, context, callback){
  var params = {
  Bucket: 'mybucket',
  Key: 'file.txt'
}

urls=[];

var stream = s3.getObject(params);

stream.on('httpError',function(err){
  console.log(err);
  throw err;
});

stream.on('httpData', function(chunk) {
  urls.push(chunk.toString());
});

stream.on('httpDone', function() {
  urls2 = urls.join('\n\r');
  callback(urls2);
});

stream.send();

}

I got following error executing the lambda via AWS console

{
  "errorMessage": "2017-07-04T18:25:20.271Z 19ab7138-60e6-11e7-9e1e-c318d929bc39 Task timed out after 15.00 seconds"
}

Thanks for any help!

Body:
Handler is required to invoke the lambda function. Also, you need to mention handler name in the lambda function configuration.

exports.handler = (event, context, callback) => {
  const bucket = event.Records[0].s3.bucket.name;
  const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
  const params = {
    Bucket: bucket,
    Key: key,
  };
  var stream = s3.getObject(params);
  ....
  stream.send();
}

eports.handler is invoked when lambda function triggers. Make sure you must define the handler name(filename.handler) in lambda function configuration.

If you trigger this code on s3 file upload it will read the uploaded s3 file. you change the bucket & key name to read any file(which exist).
Follow the documentation http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html


问:
Why std::move is not working with std::list
I am unable to compile the below program.

```<code>void toSin(std::list<double>&& list)
{
    std::for_each(list.begin(), list.end(), [](double& x)
    {
        x = sin(x);
    });
}

int main()
{
    std::list<double> list;
    const double pi = 3.141592;
    const double epsilon = 0.0000001;
    for (double x = 0.0; x < 2 * pi + epsilon; x = x + pi / 16)
    {
        list.push_back(x);
    }
    // Start thread
    std::thread th(toSin, std::move(list));
    th.join();
    return 0;
}
</code>```

I get > error C2664: 'void (std::list<double,std::allocator<_Ty>> &&)' : cannot convert argument 1 from 'std::list<double,std::allocator<_Ty>>' to 'std::list<double,std::allocator<_Ty>> &&'

答:
I think that you maybe miss some #include, that code works on Visual Studio 2015

```<code>#include <algorithm>
#include <list>
#include <thread>
void toSin(std::list<double>&& list)
{
    std::for_each(list.begin(), list.end(), [](double& x)
    {
        x = sin(x);
    });
}

int main()
{
    std::list<double> list;
    const double pi = 3.141592;
    const double epsilon = 0.0000001;
    for (double x = 0.0; x < 2 * pi + epsilon; x = x + pi / 16)
    {
        list.push_back(x);
    }
    // Start thread
    std::thread th(toSin, std::move(list));
    th.join();
    return 0;
}
</code>```

Body:
I am unable to compile the below program.

void toSin(std::list<double>&& list)
{
    std::for_each(list.begin(), list.end(), [](double& x)
    {
        x = sin(x);
    });
}

int main()
{
    std::list<double> list;
    const double pi = 3.141592;
    const double epsilon = 0.0000001;
    for (double x = 0.0; x < 2 * pi + epsilon; x = x + pi / 16)
    {
        list.push_back(x);
    }
    // Start thread
    std::thread th(toSin, std::move(list));
    th.join();
    return 0;
}

I get > error C2664: 'void (std::list<double,std::allocator<_Ty>> &&)' : cannot convert argument 1 from 'std::list<double,std::allocator<_Ty>>' to 'std::list<double,std::allocator<_Ty>> &&'

Body:
I think that you maybe miss some #include, that code works on Visual Studio 2015

#include <algorithm>
#include <list>
#include <thread>
void toSin(std::list<double>&& list)
{
    std::for_each(list.begin(), list.end(), [](double& x)
    {
        x = sin(x);
    });
}

int main()
{
    std::list<double> list;
    const double pi = 3.141592;
    const double epsilon = 0.0000001;
    for (double x = 0.0; x < 2 * pi + epsilon; x = x + pi / 16)
    {
        list.push_back(x);
    }
    // Start thread
    std::thread th(toSin, std::move(list));
    th.join();
    return 0;
}


问:
NSPopupButton in view based NSTableView: getting bindings to work

Problem Description

I'm trying to achieve something that should be simple and fairly common: having a bindings populated NSPopupButton inside bindings populated NSTableView. Apple describes this for a cell based table in the their documentation Implementing To-One Relationships Using Pop-Up Menus and it looks like this:

I can't get this to work for a view based table. The "Author" popup won't populate itself no matter what I do.

I have two array controllers, one for the items in the table (Items) and one for the authors (Authors), both associated with the respective entities in my core data model. I bind the NSManagedPopup in my cell as follows in interface builder:

Content -> Authors (Controller Key: arrangedObjects)

Content Values -> Authors (Controller Key: arrangedObjects, Model Key Path: name)

Selected Object -> Table Cell View (Model Key Path: objectValue.author

If I place the popup somewhere outside the table it works fine (except for the selection obviously), so I guess the binding setup should be ok.

Things I Have Already Tried

Someone suggested a workaround using an IBOutlet property to the Authors array controller but this doesn't seem to work for me either.

In another SO question it was suggested to subclass NSTableCellView and establish the required connections programmatically. I tried this but had only limited success.

If I setup the bindings as follows:

```<code>- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    NSView *view = [tableView makeViewWithIdentifier:tableColumn.identifier owner:self];

    if ([tableColumn.identifier isEqualToString:@"Author") {
        AuthorSelectorCell *authorSelectorCell = (AuthorSelectorCell *)view;
        [authorSelectorCell.popupButton bind:NSContentBinding toObject:self.authors withKeyPath:@"arrangedObjects" options:nil];
        [authorSelectorCell.popupButton bind:NSContentValuesBinding toObject:self.authors withKeyPath:@"arrangedObjects.name" options:nil];
        [authorSelectorCell.popupButton bind:NSSelectedObjectBinding toObject:view withKeyPath:@"objectValue.author" options:nil];
    }

    return view;
}
</code>```

the popup does show the list of possible authors but the current selection always shows as "No Value". If I add

```<code>[authorSelectorCell.popupButton bind:NSSelectedValueBinding toObject:view withKeyPath:@"objectValue.author.name" options:nil];
</code>```

the current selection is completely empty. The only way to make the current selection show up is by setting

```<code>[authorSelectorCell.popupButton bind:NSSelectedObjectBinding toObject:view withKeyPath:@"objectValue.author.name" options:nil];
</code>```

which will break as soon as I select a different author since it will try to assign an NSString* to an Author* property.

Any Ideas?

答:
You can try this FOUR + 1 settings for NSPopUpbutton:

In my example, "allPersons" is equivalent to your "Authors".
I have allPersons available as a property (NSArray*) in File's owner.

Additionally, I bound the tableView delegate to File's owner. If this is not bound, I just get a default list :Item1, Item2, Item3

Body:
Problem Description

I'm trying to achieve something that should be simple and fairly common: having a bindings populated NSPopupButton inside bindings populated NSTableView. Apple describes this for a cell based table in the their documentation Implementing To-One Relationships Using Pop-Up Menus and it looks like this:

I can't get this to work for a view based table. The "Author" popup won't populate itself no matter what I do.

I have two array controllers, one for the items in the table (Items) and one for the authors (Authors), both associated with the respective entities in my core data model. I bind the NSManagedPopup in my cell as follows in interface builder:

Content -> Authors (Controller Key: arrangedObjects)

Content Values -> Authors (Controller Key: arrangedObjects, Model Key Path: name)

Selected Object -> Table Cell View (Model Key Path: objectValue.author

If I place the popup somewhere outside the table it works fine (except for the selection obviously), so I guess the binding setup should be ok.

Things I Have Already Tried

Someone suggested a workaround using an IBOutlet property to the Authors array controller but this doesn't seem to work for me either.

In another SO question it was suggested to subclass NSTableCellView and establish the required connections programmatically. I tried this but had only limited success.

If I setup the bindings as follows:

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    NSView *view = [tableView makeViewWithIdentifier:tableColumn.identifier owner:self];

    if ([tableColumn.identifier isEqualToString:@"Author") {
        AuthorSelectorCell *authorSelectorCell = (AuthorSelectorCell *)view;
        [authorSelectorCell.popupButton bind:NSContentBinding toObject:self.authors withKeyPath:@"arrangedObjects" options:nil];
        [authorSelectorCell.popupButton bind:NSContentValuesBinding toObject:self.authors withKeyPath:@"arrangedObjects.name" options:nil];
        [authorSelectorCell.popupButton bind:NSSelectedObjectBinding toObject:view withKeyPath:@"objectValue.author" options:nil];
    }

    return view;
}

the popup does show the list of possible authors but the current selection always shows as "No Value". If I add

[authorSelectorCell.popupButton bind:NSSelectedValueBinding toObject:view withKeyPath:@"objectValue.author.name" options:nil];

the current selection is completely empty. The only way to make the current selection show up is by setting

[authorSelectorCell.popupButton bind:NSSelectedObjectBinding toObject:view withKeyPath:@"objectValue.author.name" options:nil];

which will break as soon as I select a different author since it will try to assign an NSString* to an Author* property.

Any Ideas?


问:
continue with if statement java
why I can't use continue with The ? : Operator    :</p>

```<code>public class TestArray {

public static void main(String[] args) {
  double[] myList = {1.9, 2.9, 3.4, 3.5};

  // Print all the array elements
  for (int i = 0; i < myList.length; i++) {
     System.out.println(myList[i] + " ");
  }

  // Finding the largest element
  double max = myList[0];
  for (int i = 1; i < myList.length; i++) {
     myList[i] > max ? max = myList[i] : continue ;
  }
  System.out.println("Max is " + max);
}
}
</code>```

答:
The ternary operator does not function like that. It is used to return one of two values depending on a boolean expression.

```<code>x = statement ? value1 : value2
</code>```

If that is not what you want then use a simple if else statement. Just replace with:

```<code>for (int i = 1; i < myList.length; i++) {
    if(myList[i] > max)
        max = myList[i]
}
</code>```

If you want you can also have a look at .max():

```<code>Arrays.stream(myList).max()
</code>```

and a bit more on how it works in: Java 8 stream's .min() and .max(): why does this compile?

Title: continue with if statement java

Body:
why I can't use continue with The ? : Operator    :

public class TestArray {

public static void main(String[] args) {
  double[] myList = {1.9, 2.9, 3.4, 3.5};

  // Print all the array elements
  for (int i = 0; i < myList.length; i++) {
     System.out.println(myList[i] + " ");
  }

  // Finding the largest element
  double max = myList[0];
  for (int i = 1; i < myList.length; i++) {
     myList[i] > max ? max = myList[i] : continue ;
  }
  System.out.println("Max is " + max);
}
}

Body:
The ternary operator does not function like that. It is used to return one of two values depending on a boolean expression.

x = statement ? value1 : value2

If that is not what you want then use a simple if else statement. Just replace with:

for (int i = 1; i < myList.length; i++) {
    if(myList[i] > max)
        max = myList[i]
}

If you want you can also have a look at .max():

Arrays.stream(myList).max()

and a bit more on how it works in: Java 8 stream's .min() and .max(): why does this compile?


问:
Is there a way to write an equality test for a VBA class with private members without exposing knowledge of the existence of those private members?
I do a fair amount of Excel VBA programming, but not a lot of it is object-oriented. Here is something that comes up every now and then that bugs me, and I'm wondering if there's something I'm missing.

In VBA, say I have a class C defined with some private members like so:

```<code>'...

Private hidden1_ As Double
Private hidden2_ As Double

'...
</code>```

If VBA worked like C++ or (most?) other languages that support OOP, I could write a member function to do an equality test between instances of class C like this:

```<code>'Error: won't compile!
Public Function equal(cinst As C) As Boolean
    equal = (hidden1_ = cinst.hidden1_ And hidden2_ = cinst.hidden2_)
End Function
</code>```

Of course, that won't compile in VBA because class member functions can only access private class members of the same instance they are invoked on. The best I've ever come up with to do this sort of thing is to instead define two member functions like this:

```<code>Public Function equalDef(hidden1 As Double, hidden2 As Double) As Boolean
    equalDef = (hidden1_ = hidden1 And hidden2_ = hidden2)
End Function

Public Function equal(cinst As C) As Boolean
    equal = cinst.equalDef(hidden1_, hidden2_)
End Function
</code>```

It's cumbersome, and it exposes knowledge of the existence of private class members, but at least it avoids actually exposing the values of private class members.

Is this the best I can do?

EDIT:

As usual, after an answer, I've realized a better way to phrase the question. It was titled "Is there a cleaner way to write an equality test for a VBA class with private members?" when Dick answered it.

答:
I would write the class like this

```<code>Private mdhidden1_ As Double
Private mdhidden2_ As Double

Public Property Get hidden1_() As Double

    hidden1_ = mdhidden1_

End Property

Public Property Get hidden2_() As Double

    hidden2_ = mdhidden2_

End Property

Private Sub Class_Initialize()

    'some method of setting variables private to the class
    mdhidden1_ = 1
    mdhidden2_ = 2

End Sub

Public Property Get IsEquivalent(clsCompare As C) As Boolean

    IsEquivalent = Me.hidden1_ = clsCompare.hidden1_ And Me.hidden2_ = clsCompare.hidden2_

End Property
</code>```

If you're forced to expose knowledge of the member anyway, you may as well make it a read-only property (Get, but no Let).  Then you can make the IsEquivalent boolean property inside the class.

ContentLicense: CC BY-SA 2.5

Body:
I do a fair amount of Excel VBA programming, but not a lot of it is object-oriented. Here is something that comes up every now and then that bugs me, and I'm wondering if there's something I'm missing.

In VBA, say I have a class C defined with some private members like so:

'...

Private hidden1_ As Double
Private hidden2_ As Double

'...

If VBA worked like C++ or (most?) other languages that support OOP, I could write a member function to do an equality test between instances of class C like this:

'Error: won't compile!
Public Function equal(cinst As C) As Boolean
    equal = (hidden1_ = cinst.hidden1_ And hidden2_ = cinst.hidden2_)
End Function

Of course, that won't compile in VBA because class member functions can only access private class members of the same instance they are invoked on. The best I've ever come up with to do this sort of thing is to instead define two member functions like this:

Public Function equalDef(hidden1 As Double, hidden2 As Double) As Boolean
    equalDef = (hidden1_ = hidden1 And hidden2_ = hidden2)
End Function

Public Function equal(cinst As C) As Boolean
    equal = cinst.equalDef(hidden1_, hidden2_)
End Function

It's cumbersome, and it exposes knowledge of the existence of private class members, but at least it avoids actually exposing the values of private class members.

Is this the best I can do?

EDIT:

As usual, after an answer, I've realized a better way to phrase the question. It was titled "Is there a cleaner way to write an equality test for a VBA class with private members?" when Dick answered it.

Body:
I would write the class like this

Private mdhidden1_ As Double
Private mdhidden2_ As Double

Public Property Get hidden1_() As Double

    hidden1_ = mdhidden1_

End Property

Public Property Get hidden2_() As Double

    hidden2_ = mdhidden2_

End Property

Private Sub Class_Initialize()

    'some method of setting variables private to the class
    mdhidden1_ = 1
    mdhidden2_ = 2

End Sub

Public Property Get IsEquivalent(clsCompare As C) As Boolean

    IsEquivalent = Me.hidden1_ = clsCompare.hidden1_ And Me.hidden2_ = clsCompare.hidden2_

End Property

If you're forced to expose knowledge of the member anyway, you may as well make it a read-only property (Get, but no Let).  Then you can make the IsEquivalent boolean property inside the class.


问:
What do green-shaded boxes in Spark DAG Visualization mean?
In Spark Web UI, there are two DAG visualizations, one for the Job:

the other for the Stage:

as explained here. The blog post does explain about the green dots in the Job's DAG, however, it says nothing about those green-shaded boxes in Stage's DAG. Could someone please give a hint?

Update: If that also means the code indicated is where data is cached, what can we do to improve the performance?

答:
It is mentioned in the link you provided that

Second, one of the RDDs is cached in the first stage (denoted by the green highlight)

So the green boxes indicate that they are being cached and future reference to those rdds won't have to be generated from scratch.


答: Use a normal if statement because a ternary operator returns a value.

Title: continue with if statement java


问:
Ionic http get not working on Android device
I am developing a simple android app using Ionic Framework where at some point I'm using this.http.get('https://somedomain.com').

Testing locally with ionic serve everything works, but on device it fails to load.

On the debug log the message is net::ERR_UNKNOWN_URL_SCHEME and I believe its because the protocol is being changed from https:// to intent:// and I don't know why.

My code is:

```<code>this.http.get('https://somedomain.com')
</code>```

and the error is:

```<code>intent://www.somedomain.com/path/2345435#Intent;scheme=https;package=com.net…ps%3A%2F%2Fwww.somedomain.com%2Ftitle%2345435%3FpreventIntent%3Dtrue;end:1
GET intent://www.somedomain.com/title/2345435
net::ERR_UNKNOWN_URL_SCHEME
</code>```

答:
Use http  in controller just like for connection webservice  in ionic</p>

```<code>$http({
     method: 'POST',
      url:  'http://come.emx/et',
      params: {'name':'parameterValue' },
        //type:'JSON',
         headers : { 'Content-Type': 'application/json' }
             }).success(function(data, status, headers, config) {
                 //success
                 }).error(function(data, status, headers, config) {
                 $ionicPopup.alert({
                 title:'error',
                //template:'From date'
                })
        });
</code>```

Body:
I am developing a simple android app using Ionic Framework where at some point I'm using this.http.get('https://somedomain.com').

Testing locally with ionic serve everything works, but on device it fails to load.

On the debug log the message is net::ERR_UNKNOWN_URL_SCHEME and I believe its because the protocol is being changed from https:// to intent:// and I don't know why.

My code is:

this.http.get('https://somedomain.com')

and the error is:

intent://www.somedomain.com/path/2345435#Intent;scheme=https;package=com.net…ps%3A%2F%2Fwww.somedomain.com%2Ftitle%2345435%3FpreventIntent%3Dtrue;end:1
GET intent://www.somedomain.com/title/2345435
net::ERR_UNKNOWN_URL_SCHEME

Body:
Use http  in controller just like for connection webservice  in ionic

$http({
     method: 'POST',
      url:  'http://come.emx/et',
      params: {'name':'parameterValue' },
        //type:'JSON',
         headers : { 'Content-Type': 'application/json' }
             }).success(function(data, status, headers, config) {
                 //success
                 }).error(function(data, status, headers, config) {
                 $ionicPopup.alert({
                 title:'error',
                //template:'From date'
                })
        });


问:
Images embedded in Articles not being displayed in migrated Joomla website
Images embedded in Articles not being displayed in migrated Joomla website

I have migrated a Joomla 3.7.2 website from an old server to a new server using a particularly messy  technique. Basically, I exported the database and then copied the important folders and it all worked remarkably well barring one very specific feature. Articles with images in them no longer display the images in the new site.

I have System - SEF enabled in both sites (and switching it off makes no difference)

I use JCE and in code view the typical line displaying the image looks like this:

In both sites.

JCE is configured to use Relative URLs in both sites. If I turn that OFF then I get the image displayed in the new site. Of course that's just a hack around the problem not a solution to it.

Path to Files Folder, and Path to Images Folder is set to images in both sites.

HTML inspector on the old site shows the

And on the new site

And if you hover over the url it says "could not load the image". The missing first '/' is clearly the problem but what is it that puts it there after the article is saved by the editor and before the html is displayed in the browser?

答: Slightly embarrassed to pretend this is an answer but today I got the prompt to update Joomla to 3.7.3 and of course immediately afterwards the problem has gone away.</p>


问:
Bootstrap columns alignment
I am using Bootstrap (v3.3.7) to design a form that contains some lines with 1 column and other lines with 2 columns:

On the line with 2 columns (Town and Country), the first field is a bit shifted to the left compared to the upper and lower lines. This is because the Town label has a width of col-md-4 in a column of col-md-6 which is different from the other labels in other lines that have a width of col-md-2 in a column of col-md-12.

I chose this design so later, on a mobile view, I will add some settings to move the town underneath town.

```<code><div class="row">
    <div class="col-md-6">
        <div class="form-group">
            <label for="town" class="col-md-4 control-label">Town</label>
            <div class="col-md-8">
                <input id="town" name="town" class="form-control" type="text" v-model="address.town">
            </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="form-group">
            <label for="address_type" class="col-md-4 control-label">Country</label>
            <div class="col-md-8">
                <select id="country_id" name="address_type" class="form-control" v-model="address.country_id">
                    <option v-for="country in countries" :value="country.id">
                        {{country.name}}
                    </option>
                </select>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-12">
        <div class="form-group">
            <label for="note" class="col-md-2 control-label">Comment</label>
            <div class="col-md-10">
                <textarea id="note" name="note" class="form-control" v-model="address.note"></textarea>
            </div>
        </div>
    </div>
</div>
</code>```

Is there a way to have the same design but with aligned inputs controls?

答: First of all you need to add a row before you add columns since rows have -15px margins from left and right and columns has 15px padding from both sides so it fits to the div perfectly. also when you add a cols & rows make sure you add it inside a container. you can  override the minus margins from the rows and padding from the columns. before you check that add a row that wrap the form-group div</p>

Title: Bootstrap columns alignment

Body:
I am using Bootstrap (v3.3.7) to design a form that contains some lines with 1 column and other lines with 2 columns:

On the line with 2 columns (Town and Country), the first field is a bit shifted to the left compared to the upper and lower lines. This is because the Town label has a width of col-md-4 in a column of col-md-6 which is different from the other labels in other lines that have a width of col-md-2 in a column of col-md-12.

I chose this design so later, on a mobile view, I will add some settings to move the town underneath town.

            Town

                <input id="town" name="town" class="form-control" type="text" v-model="address.town">

            Country

                <select id="country_id" name="address_type" class="form-control" v-model="address.country_id">
                    <option v-for="country in countries" :value="country.id">
                        {{country.name}}
                    </option>
                </select>

            Comment

                <textarea id="note" name="note" class="form-control" v-model="address.note"></textarea>

Is there a way to have the same design but with aligned inputs controls?


问:
Could not convert string to float in generator
I am trying to do some basic operations with a nest listed of data in Python 2.7.  A simplified version of my data is presented below:

```<code>resultlistdata = [
['sell','EURUSD',-1092.0,'Sometext'],
['buy','GBPUSD',2342.0,'Moretext'],
['buy','EURUSD',2122.0,'Yetmoretext'],
['not opened','','',''],
['sell','EURJPY',-483,'Difftext'],
['sell','EURJPY',269,'Anothertext'],
etc...
]
</code>```

The list is a few thousand lines long.  I'm trying to count the number of times the third item in the list is greater than or equal to zero (so the correct result in the case above would be 3).  I am using the generator expression (or is it list comprehension?):

```<code>profittrades = sum(1 for x in resultdatalist if x[2] >= 0)
</code>```

which gives an answer equal to the number of items in the list (so 6 in the case above, which is wrong).  I have also tried:

```<code>profittrades = sum(1 for x in resultdatalist if float(x[2]) >= 0)
</code>```

which gives the error "ValueError:  Could not convert string to float".

I am almost certain the problem is caused by the line where the 'not opened' occurs, and it cannot convert the empty string to a float, I just don't know what to do about it!

Is there a way to do the counting using a 'one-liner' list comprehension approach, or do I need to make a loop?

The "resultslistdata" is compiled by me, so if there is something clever I can do when creating it that would help I can give it a try.  Im reluctant to enter a value of "0" as the profit for trades that are "never opened" because later when I do averages it will skew my results (?!).

Thank you to anyone who can help me!

答:
You may use sum with the generator expression as:

```<code>>>> sum((val or 0) and val>=0 for _, _, val, _ in resultlistdata)
3
</code>```

OR, alternatively you may also use the if filter within your generator expression as:

```<code>>>> sum(1 for _, _, val, _ in resultlistdata if val and val>=0)
3
</code>```

Body:
I am trying to do some basic operations with a nest listed of data in Python 2.7.  A simplified version of my data is presented below:

resultlistdata = [
['sell','EURUSD',-1092.0,'Sometext'],
['buy','GBPUSD',2342.0,'Moretext'],
['buy','EURUSD',2122.0,'Yetmoretext'],
['not opened','','',''],
['sell','EURJPY',-483,'Difftext'],
['sell','EURJPY',269,'Anothertext'],
etc...
]

The list is a few thousand lines long.  I'm trying to count the number of times the third item in the list is greater than or equal to zero (so the correct result in the case above would be 3).  I am using the generator expression (or is it list comprehension?):

profittrades = sum(1 for x in resultdatalist if x[2] >= 0)

which gives an answer equal to the number of items in the list (so 6 in the case above, which is wrong).  I have also tried:

profittrades = sum(1 for x in resultdatalist if float(x[2]) >= 0)

which gives the error "ValueError:  Could not convert string to float".

I am almost certain the problem is caused by the line where the 'not opened' occurs, and it cannot convert the empty string to a float, I just don't know what to do about it!

Is there a way to do the counting using a 'one-liner' list comprehension approach, or do I need to make a loop?

The "resultslistdata" is compiled by me, so if there is something clever I can do when creating it that would help I can give it a try.  Im reluctant to enter a value of "0" as the profit for trades that are "never opened" because later when I do averages it will skew my results (?!).

Thank you to anyone who can help me!

Body:
You may use sum with the generator expression as:

>>> sum((val or 0) and val>=0 for _, _, val, _ in resultlistdata)
3

OR, alternatively you may also use the if filter within your generator expression as:

>>> sum(1 for _, _, val, _ in resultlistdata if val and val>=0)
3


问:
Image starts rotating from starting position after one click
I have an image which is rotated by 36°.
I used setFillAfter() and setFillEnabled(). It's saving the position but if I rotate it again it is starting from the original position. I want it to start from the position it was after rotation.</p>

```<code>Animation animation = new Animation (0,36, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
animation.setDuration(3000);
animation.setInterpolator(new LinearInterpolator());
animation.setFillAfter(true);

myImage.startAnimation(animation);
</code>```

答:
You just need to pass current angle of imageview  in Animation Constructor instead of 0 everytime. Try below code:

```<code>        int rotationAngle=36;/*angle by which you want to rotate image*/
        int mCurrRotation = 0;  /*current angle of image*/

        buttonRotate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            float fromRotation = mCurrRotation;
            float toRotation = mCurrRotation += rotationAngle;

            Animation animation = new RotateAnimation(
                    fromRotation,
                    toRotation,
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

            animation.setDuration(3000);
            animation.setFillAfter(true);
            myImage.startAnimation(animation);
        }
    });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an image which is rotated by 36°.
I used setFillAfter() and setFillEnabled(). It's saving the position but if I rotate it again it is starting from the original position. I want it to start from the position it was after rotation.

Animation animation = new Animation (0,36, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
animation.setDuration(3000);
animation.setInterpolator(new LinearInterpolator());
animation.setFillAfter(true);

myImage.startAnimation(animation);

Body:
You just need to pass current angle of imageview  in Animation Constructor instead of 0 everytime. Try below code:

        int rotationAngle=36;/*angle by which you want to rotate image*/
        int mCurrRotation = 0;  /*current angle of image*/

        buttonRotate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            float fromRotation = mCurrRotation;
            float toRotation = mCurrRotation += rotationAngle;

            Animation animation = new RotateAnimation(
                    fromRotation,
                    toRotation,
                    Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

            animation.setDuration(3000);
            animation.setFillAfter(true);
            myImage.startAnimation(animation);
        }
    });


问:
Using BeforeInsert in DHTMLX and passing variable to a form
I have a following problem: I have a scheduler that is used by different users. When a user adds an event to scheduler, a session variable containing his id must be passed to a processor where it is inserted into a database.

My first question is how do I bind a session variable to a form that is created with a scheduler.config.lightbox.sections:

```<code>  scheduler.config.lightbox.sections=[
        {name:"Customer Code", height:21, map_to:"text", type:"textarea" , focus:false},
    {name:"Photographer", height:21,  map_to:"pid", type:"select",
      options:scheduler.serverList("type")},
        {name:"time", height:72, type:"time", map_to:"auto"}
    ]
</code>```

Is it possible to bind a session variable to it?

My second question is how do I get session variable in processor.php?
Please, correct me if I'm wrong, but according to the documentation it's going to be something like this:

```<code>//... connect here
function myInsert($action){
        $new_value = rand(0,100);
        $action->set_value("name",$new_value);
}

$conn->event->attach("beforeInsert","myInsert");
// ...some code here
$conn->render_table("photographers_at_work", "id", "time, end_time, customer_code, pid");
</code>```

答:
You can use onEventCreated to assign default values (such as user id) to a newly created event:

```<code>scheduler.attachEvent("onEventCreated", function(id,e){
    var event = scheduler.getEvent(id);
    event.pid = userId;
});
</code>```

https://docs.dhtmlx.com/scheduler/api__scheduler_oneventcreated_event.html

This API event fires before lightbox is opened, so the lightbox will receive assigned values.

As for backend - yes, something like this should work. Couple of notes

$action->set_value - the first parameter is a column name

this column must be listed in properties columns you provide to connector (i.e. if you set value of column you don't have in your render_table parameters - connector will ignore it)

So something following should do:

```<code>//... connect here
function myInsert($action){
        global $userId;
        $action->set_value("pid",$userId);// ! set value of "pid" column
}

$conn->event->attach("beforeInsert","myInsert");
// ...some code here
$conn->render_table("photographers_at_work", "id", "time, end_time, customer_code, pid");
</code>```

you can enable connector logging to see actual sql requests connector generates: https://docs.dhtmlx.com/connector__php__errors.html#serversidelogging

Body:
I have a following problem: I have a scheduler that is used by different users. When a user adds an event to scheduler, a session variable containing his id must be passed to a processor where it is inserted into a database.

My first question is how do I bind a session variable to a form that is created with a scheduler.config.lightbox.sections:

  scheduler.config.lightbox.sections=[
        {name:"Customer Code", height:21, map_to:"text", type:"textarea" , focus:false},
    {name:"Photographer", height:21,  map_to:"pid", type:"select",
      options:scheduler.serverList("type")},
        {name:"time", height:72, type:"time", map_to:"auto"}
    ]

Is it possible to bind a session variable to it?

My second question is how do I get session variable in processor.php?
Please, correct me if I'm wrong, but according to the documentation it's going to be something like this:

//... connect here
function myInsert($action){
        $new_value = rand(0,100);
        $action->set_value("name",$new_value);
}

$conn->event->attach("beforeInsert","myInsert");
// ...some code here
$conn->render_table("photographers_at_work", "id", "time, end_time, customer_code, pid");

Body:
You can use onEventCreated to assign default values (such as user id) to a newly created event:

scheduler.attachEvent("onEventCreated", function(id,e){
    var event = scheduler.getEvent(id);
    event.pid = userId;
});

https://docs.dhtmlx.com/scheduler/api__scheduler_oneventcreated_event.html

This API event fires before lightbox is opened, so the lightbox will receive assigned values.

As for backend - yes, something like this should work. Couple of notes

$action->set_value - the first parameter is a column name

this column must be listed in properties columns you provide to connector (i.e. if you set value of column you don't have in your render_table parameters - connector will ignore it)

So something following should do:

//... connect here
function myInsert($action){
        global $userId;
        $action->set_value("pid",$userId);// ! set value of "pid" column
}

$conn->event->attach("beforeInsert","myInsert");
// ...some code here
$conn->render_table("photographers_at_work", "id", "time, end_time, customer_code, pid");

you can enable connector logging to see actual sql requests connector generates: https://docs.dhtmlx.com/connector__php__errors.html#serversidelogging


问:
How can I detect if a login is suspicious?
I want to detect whether or not an account sign in is suspicious, like Google is doing it. How can I achieve that, or what resources should I look at?

Scenario: My login credentials are stolen at yet another Yahoo breach, and a hacker is using those to sign into a service. I want to detect that this user is not the real user, for example, by using the location of the sign in ip address.

答:
Suspicious behaviour if the login is from

A browser you've never used before. For example, you could set a long-term signed cookie after successful login. If someone tries to login without said cookie...

A different OS or browser brand. You always use Windows and Chrome. Now someone is logging in with Kali Linux and Firefox...

A different IP or ISP. IPs can change pretty frequently but you'll often use the same ISP at work or home

A different geographical location. Say you've historically always signed in from California and Oregon. A login from India is then suspicious

A different time of day than normal for you. Say you always sign in between 9 AM and 5 PM, but someone tries to sign in at 3 AM, that's suspicious

None of these is super suspicious on their own but may be in combination


问:
Laravel 5 has one relationship
I have two tables: drugs table and formulations table. The drugs table has fields id, name, quantity and formulation_id. The formulations table has fields  id and name.

What relationship should I use to get the drugs records including the name of the formulation.

Note that 1 drug record has only one 1 formulation record.

I have tried using hasOne relashionship but doesn't work:

My view looks as follows:

```<code>@foreach($drugs as $drug)
        <li>
            <a class="padded-list" href="">{{$drug->name}} ({{$drug->formulation->name}})</a>
        </li>
        @endforeach
</code>```

My model relationship in the the Drug model looks as follows:

```<code>public function formulation()
{
    return $this->hasOne('App\Formulation');
}
</code>```

答:
Your formulation() method in your Drug model should be:</p>

```<code>public function formulation()
{
    return $this->belongsTo('App\Formulation');
}
</code>```

Title: Laravel 5 has one relationship

Body:
I have two tables: drugs table and formulations table. The drugs table has fields id, name, quantity and formulation_id. The formulations table has fields  id and name.

What relationship should I use to get the drugs records including the name of the formulation.

Note that 1 drug record has only one 1 formulation record.

I have tried using hasOne relashionship but doesn't work:

My view looks as follows:

@foreach($drugs as $drug)

            {{$drug->name}} ({{$drug->formulation->name}})

        @endforeach

My model relationship in the the Drug model looks as follows:

public function formulation()
{
    return $this->hasOne('App\Formulation');
}

Body:
Your formulation() method in your Drug model should be:

public function formulation()
{
    return $this->belongsTo('App\Formulation');
}


问:
display timespan nicely
Excuse the rough code, I'm trying to display the duration of videos given the time in seconds.
 I've had a go below but it's not working properly.

I want it to just display nicely - i.e should display 9m:59s not 09m:59s.

If hours are zero dont display hours, if minutes are zero dont display minutes.

```<code>public static string GetTimeSpan(int secs)
{
    TimeSpan t = TimeSpan.FromSeconds(secs);

    string answer;
    if (secs < 60)
    {
        answer = string.Format("{0:D2}s", t.Seconds);
    }
    else if (secs < 600)//tenmins
    {
        answer = string.Format("{0:m}m:{1:D2}s", t.Minutes, t.Seconds);

    }
    else if (secs < 3600)//hour
    {
        answer = string.Format("{0:mm}m:{1:D2}s", t.Minutes, t.Seconds);
    }
    else
    {
        answer = string.Format("{0:h}h:{1:D2}m:{2:D2}s",
                                    t.Hours,
                                    t.Minutes,
                                    t.Seconds);
    }

    return answer;
}
</code>```

答:
```<code>readonly static Char[] _colon_zero = { ':', '0' };
// ...

var ts = new TimeSpan(DateTime.Now.Ticks);
String s = ts.ToString("h\\:mm\\:ss\\.ffff").TrimStart(_colon_zero);
</code>```

<blockquote>
```.0321
6.0159
19.4833
8:22.0010
1:04:2394
19:54:03.4883```
</blockquote>

Title: display timespan nicely

Body:
Excuse the rough code, I'm trying to display the duration of videos given the time in seconds.
 I've had a go below but it's not working properly.

I want it to just display nicely - i.e should display 9m:59s not 09m:59s.

If hours are zero dont display hours, if minutes are zero dont display minutes.

public static string GetTimeSpan(int secs)
{
    TimeSpan t = TimeSpan.FromSeconds(secs);

    string answer;
    if (secs < 60)
    {
        answer = string.Format("{0:D2}s", t.Seconds);
    }
    else if (secs < 600)//tenmins
    {
        answer = string.Format("{0:m}m:{1:D2}s", t.Minutes, t.Seconds);

    }
    else if (secs < 3600)//hour
    {
        answer = string.Format("{0:mm}m:{1:D2}s", t.Minutes, t.Seconds);
    }
    else
    {
        answer = string.Format("{0:h}h:{1:D2}m:{2:D2}s",
                                    t.Hours,
                                    t.Minutes,
                                    t.Seconds);
    }

    return answer;
}

Body:
readonly static Char[] _colon_zero = { ':', '0' };
// ...

var ts = new TimeSpan(DateTime.Now.Ticks);
String s = ts.ToString("h\\:mm\\:ss\\.ffff").TrimStart(_colon_zero);

.0321
6.0159
19.4833
8:22.0010
1:04:2394
19:54:03.4883


问:
Message 'src refspec master does not match any' when pushing commits in Git
I clone my repository with:

```<code>git clone ssh://xxxxx/xx.git
</code>```

But after I change some files and add and commit them, I want to push them to the server:

```<code>git add xxx.php
git commit -m "TEST"
git push origin master
</code>```

But the error I get back is:

error: src refspec master does not match any.
error: failed to push some refs to 'ssh://xxxxx.com/project.git'
```

答:
I faced this exact problem while dealing with VCS in Android Studio. It turns out all I had to do was:

Select all files from the "app" folder;

Go to VCS (Option at top);

"Add" the files;

Committing again via terminal, or by clicking via the drop down menu, and;

Push!

Eureka! :D

Body:
I clone my repository with:

git clone ssh://xxxxx/xx.git

But after I change some files and add and commit them, I want to push them to the server:

git add xxx.php
git commit -m "TEST"
git push origin master

But the error I get back is:

error: src refspec master does not match any.
error: failed to push some refs to 'ssh://xxxxx.com/project.git'


问:
Setting value of class variable from String Request Volley in Android
I have a function named isUserExist.This func checks whether user exist on database with this email address.

In stringrequest i set the isUserExist variable "true".End of the func,func returns isUserExist.

Problem is it always returns false even if i set it true in the string request.it sets it true in the if statement.

In the class declaration of it like:

```<code>boolean isUserExist;
</code>```

And the function is:

```<code>private boolean isUserExist()
{

    StringRequest strReq = new StringRequest(Request.Method.POST,
            AppConfig.URL_USER_EXIST, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                if (error) {
                    // setting isUserExist = true
                    isUserExist = true;
                    //Log.w("debug1",String.valueOf(isUserExist);)
                    //returns true;

                } else {

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("email", mail);

            return params;
        }

    };
    AppController.getInstance().addToRequestQueue(strReq);
    //Log.w("debug2",String.valueOf(isuserExist));
    //returns false
    return isUserExist;
}
</code>```

What did i try so far :

I have searched and find these ideas.
1)to make it static
2)Declaring boolean result[] = new boolean[1]; and end of the function return result[0] which i have assaign it true in String Request.
3)Declaring isUserExist as Local variable.boolean isUserExist = false; in the beggining of the func.
4)In the firs decleration assaign it like :boolean isUserExist = false instead of boolean isUserExist;

But none of them works.

答: The better apporach is to debug your code to check if your call back method is setting your boolean variable. Set two break points; First in your outer method, Second in your call back method to see the values of  all involved variables.</p>

Body:
I have a function named isUserExist.This func checks whether user exist on database with this email address.

In stringrequest i set the isUserExist variable "true".End of the func,func returns isUserExist.

Problem is it always returns false even if i set it true in the string request.it sets it true in the if statement.

In the class declaration of it like:

boolean isUserExist;

And the function is:

private boolean isUserExist()
{

    StringRequest strReq = new StringRequest(Request.Method.POST,
            AppConfig.URL_USER_EXIST, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                if (error) {
                    // setting isUserExist = true
                    isUserExist = true;
                    //Log.w("debug1",String.valueOf(isUserExist);)
                    //returns true;

                } else {

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("email", mail);

            return params;
        }

    };
    AppController.getInstance().addToRequestQueue(strReq);
    //Log.w("debug2",String.valueOf(isuserExist));
    //returns false
    return isUserExist;
}

What did i try so far :

I have searched and find these ideas.
1)to make it static
2)Declaring boolean result[] = new boolean[1]; and end of the function return result[0] which i have assaign it true in String Request.
3)Declaring isUserExist as Local variable.boolean isUserExist = false; in the beggining of the func.
4)In the firs decleration assaign it like :boolean isUserExist = false instead of boolean isUserExist;

But none of them works.


问:
Passing array value to a query string url
I have an array of id let's say

```<code>favorites = [102,110,112,125]
</code>```

I want to retrieve the corresponding object for each id by passing it to query string like this :

```<code>public getFavorites(favs){
  let favorites = favs.join();
  let encodedUrl = encodeURIComponent(JSON.stringify({"id": favorites }));

  return this.http.get(this.api_url + '/1/query/data/getFavs?parameters='+encodedUrl, {
    headers: this.authHeader
  })
  .retry(3)
  .map(res => res.json());
}
</code>```

The problem is only one object appear in my html template and also in the console. What is the best way for me to pass an array of value to a URL as parameters in order to retrieve the associated objects?

答:
You can pass multiple parameter values with the same name over the querystring. Does that help you? For example, here's a snippet:

```<code>this.api_url + '/1/query/data/getFavs?id=101&id=110
</code>```

Here is another answer that has some more info on this.

If you have to send the ID's over in a serialized manner, consider posting the JSON instead of using the GET method. If you're trying to maintain adherence to REST verb standards by making it a get call, can you post the server code?

Body:
I have an array of id let's say

favorites = [102,110,112,125]

I want to retrieve the corresponding object for each id by passing it to query string like this :

public getFavorites(favs){
  let favorites = favs.join();
  let encodedUrl = encodeURIComponent(JSON.stringify({"id": favorites }));

  return this.http.get(this.api_url + '/1/query/data/getFavs?parameters='+encodedUrl, {
    headers: this.authHeader
  })
  .retry(3)
  .map(res => res.json());
}

The problem is only one object appear in my html template and also in the console. What is the best way for me to pass an array of value to a URL as parameters in order to retrieve the associated objects?

Body:
You can pass multiple parameter values with the same name over the querystring. Does that help you? For example, here's a snippet:

this.api_url + '/1/query/data/getFavs?id=101&id=110

Here is another answer that has some more info on this.

If you have to send the ID's over in a serialized manner, consider posting the JSON instead of using the GET method. If you're trying to maintain adherence to REST verb standards by making it a get call, can you post the server code?


问:
Connecting FTP via AWS Lambda
I have a python code that runs normally on my local computer but when I try to run in AWS Lambda, a timeout happens when trying to list the files in the directory even though it connects to the directory properly.

```<code> ftp = FTP(host,user,password)
 ftp.set_pasv(False)
 print( ftp.cwd(path) )
 print( ftp.retrlines("LIST") )
</code>```

I already tried active and passive mode but both of them don't work. The timeout is already at the max allowed which is 5 minutes.

答:
Check if your lambda has enough execution time configured to be able to do this operation.
Go to : https://us-west-2.console.aws.amazon.com/lambda/home?region=us-west-2#/functions?display=list

Change the region to your relevant region.
Select the function, say FTPLambda, go to Configuration tab and scroll down to the Advanced Settings, in here set the  Timeout to 5 minutes.
The lambda can be executed at max for five minutes.
Try to run your code and if it runs, adjust the timeout per your needs.

Title: Connecting FTP via AWS Lambda

Body:
I have a python code that runs normally on my local computer but when I try to run in AWS Lambda, a timeout happens when trying to list the files in the directory even though it connects to the directory properly.

 ftp = FTP(host,user,password)
 ftp.set_pasv(False)
 print( ftp.cwd(path) )
 print( ftp.retrlines("LIST") )

I already tried active and passive mode but both of them don't work. The timeout is already at the max allowed which is 5 minutes.


问:
Changing value of XML data using Node JS
I have a XML document that looks like this:

```<code> <Data id="1401" href="http://222222222">
  <definition id="12218" href="http://11"></definition>
  <Data-List count="1">
    <DataStep type="3">
      <completed_time>07/04/2017 17:18:11</completed_time>
      <status>3</status>
    </DataStep>
  </Data-List>
  <information>abcdefg</information>
</Data>
</code>```

I would like to change the information data abcdefg to a different piece of string that comes from a different variable.

So it looks like this:

```<code> <Data id="1401" href="http://222222222">
  <definition id="12218" href="http://11"></definition>
  <Data-List count="1">
    <DataStep type="3">
      <completed_time>07/04/2017 17:18:11</completed_time>
      <status>3</status>
    </DataStep>
  </Data-List>
  <information>example</information>
</Data>
</code>```

Is this possible to do directly in Node JS without changing this XML to a json, modifying it and then converting back to XML? I have tried this however it did not seem to work, creating weird arrays and '$' on the XML conversion.

Any suggestions on how I could do this?

答:
1)You can parse your xml document like a normal string, find information tag with regular expression and change it.

```<code>xml = xml.replace(/<information>[a-z0-9_-]*<\/information\>/, '<information>example</information>');
</code>```

2)You can use some module, like xmldoc, to parse the document. https://github.com/nfarina/xmldoc

```<code>let xmldoc = require('xmldoc');
let document = new xmldoc.XmlDocument(data.toString());
document.descendantWithPath('information').val = "example";
</code>```

Body:
I have a XML document that looks like this:

 <Data id="1401" href="http://222222222">
  <definition id="12218" href="http://11"></definition>
  <Data-List count="1">
    <DataStep type="3">
      <completed_time>07/04/2017 17:18:11</completed_time>
      <status>3</status>
    </DataStep>
  </Data-List>
  <information>abcdefg</information>
</Data>

I would like to change the information data abcdefg to a different piece of string that comes from a different variable.

So it looks like this:

 <Data id="1401" href="http://222222222">
  <definition id="12218" href="http://11"></definition>
  <Data-List count="1">
    <DataStep type="3">
      <completed_time>07/04/2017 17:18:11</completed_time>
      <status>3</status>
    </DataStep>
  </Data-List>
  <information>example</information>
</Data>

Is this possible to do directly in Node JS without changing this XML to a json, modifying it and then converting back to XML? I have tried this however it did not seem to work, creating weird arrays and '$' on the XML conversion.

Any suggestions on how I could do this?

Body:
1)You can parse your xml document like a normal string, find information tag with regular expression and change it.

xml = xml.replace(/<information>[a-z0-9_-]*<\/information\>/, '<information>example</information>');

2)You can use some module, like xmldoc, to parse the document. https://github.com/nfarina/xmldoc

let xmldoc = require('xmldoc');
let document = new xmldoc.XmlDocument(data.toString());
document.descendantWithPath('information').val = "example";


问:
How to set up DispatchGroup in asynchronous iteration?
I´m trying to set up an iteration for downloading images. The whole process works, but taking a look in the console´s output, something seems to be wrong.

```<code>func download() {

    let logos = [Logos]()
    let group = DispatchGroup()

    logos.forEach { logo in

        print("enter")
        group.enter()

        if logo?.data == nil {

            let id = logo?.id as! String

            if let checkedUrl = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/\(id).png") {

                print(checkedUrl)

                LogoRequest.init().downloadImage(url: checkedUrl) { (data)  in

                    logo?.data = data
                    print("stored")

                    group.leave()
                    print("leave")
                }
            }
        }
    }

    print("loop finished")
}
</code>```

Output:

```<code>enter
http://www.apple.com/euro/ios/ios8/a/generic/images/og.png
enter
http://www.apple.com/euro/ios/ios8/a/generic/images/eg.png
enter
http://www.apple.com/euro/ios/ios8/a/generic/images/sd.png
enter
http://www.apple.com/euro/ios/ios8/a/generic/images/hd.png
loop finished
stored
leave
stored
leave
stored
leave
stored
leave
</code>```

It looks like the iteration does not care about entering and leaving the DispatchGroup() at all. The webrequests are fired almost at the same time. In my opinion the output should look like this:

```<code>enter
http://www.apple.com/euro/ios/ios8/a/generic/images/og.png
stored
leave
enter
http://www.apple.com/euro/ios/ios8/a/generic/images/eg.png
stored
leave
...
loop finished
</code>```

Did I oversee something? Would be awesome to get some ideas.

答:
What about this:

```<code>group.notify(queue: .main) {
print("loop finished")
}
</code>```

Instead of your normal print.

edit:

```<code>func download() {

let logos = [Logos]()  // NSManagedObject
let group = DispatchGroup()

logos.forEach { logo in

    if logo?.data == nil {
        let id = logo?.id as! String
        if let checkedUrl = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/\(id).png") {

            print(checkedUrl)
             print("enter")
            group.enter()
            LogoRequest.init().downloadImage(url: checkedUrl) { (data)  in
                //this is async I think

                coin?.logo = data
                print("stored")

                group.leave()
                print("leave")
            }
        }
    }
}

group.notify(queue: .main) {
print("loop finished")
}
}
</code>```

Body:
I´m trying to set up an iteration for downloading images. The whole process works, but taking a look in the console´s output, something seems to be wrong.

func download() {

    let logos = [Logos]()
    let group = DispatchGroup()

    logos.forEach { logo in

        print("enter")
        group.enter()

        if logo?.data == nil {

            let id = logo?.id as! String

            if let checkedUrl = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/\(id).png") {

                print(checkedUrl)

                LogoRequest.init().downloadImage(url: checkedUrl) { (data)  in

                    logo?.data = data
                    print("stored")

                    group.leave()
                    print("leave")
                }
            }
        }
    }

    print("loop finished")
}

Output:

enter
http://www.apple.com/euro/ios/ios8/a/generic/images/og.png
enter
http://www.apple.com/euro/ios/ios8/a/generic/images/eg.png
enter
http://www.apple.com/euro/ios/ios8/a/generic/images/sd.png
enter
http://www.apple.com/euro/ios/ios8/a/generic/images/hd.png
loop finished
stored
leave
stored
leave
stored
leave
stored
leave

It looks like the iteration does not care about entering and leaving the DispatchGroup() at all. The webrequests are fired almost at the same time. In my opinion the output should look like this:

enter
http://www.apple.com/euro/ios/ios8/a/generic/images/og.png
stored
leave
enter
http://www.apple.com/euro/ios/ios8/a/generic/images/eg.png
stored
leave
...
loop finished

Did I oversee something? Would be awesome to get some ideas.

Body:
What about this:

group.notify(queue: .main) {
print("loop finished")
}

Instead of your normal print.

edit:

func download() {

let logos = [Logos]()  // NSManagedObject
let group = DispatchGroup()

logos.forEach { logo in

    if logo?.data == nil {
        let id = logo?.id as! String
        if let checkedUrl = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/\(id).png") {

            print(checkedUrl)
             print("enter")
            group.enter()
            LogoRequest.init().downloadImage(url: checkedUrl) { (data)  in
                //this is async I think

                coin?.logo = data
                print("stored")

                group.leave()
                print("leave")
            }
        }
    }
}

group.notify(queue: .main) {
print("loop finished")
}
}


问:
Custom FragmentDialog with round corners and not 100% screen width
I am creating a custom fragment dialog with round corners and with layout that would not fill the screen width (I would prefer if it just wrapped its content).

this is my rounded_dialog.xml in drawable folder, which is called by my Custom ThemeWithCorners as a background for the dialog. I also tried to set it as background to the linear layout which creates its content but nothing works.

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid android:color="@android:color/white"/>
<corners android:radius="20dp"
/>
</shape>
</code>```

and this is how i call the dialog:

```<code>final String FTAG = "TAG_FRAGMENT_DIALOG_CALENDAR";
    dialog = (CalendarDialog) fm.findFragmentByTag(FTAG);
    ft = fm.beginTransaction();
    if (dialog != null)
    {
        ft.remove(dialog);
    }
    dialog = CalendarDialog.newInstance(this);
    dialog.setCancelable(true);

    ft.add(dialog, FTAG);
    ft.show(dialog);
    ft.commit();
</code>```

In onCreate method of the dialog I set the style and theme:

```<code>@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(DialogFragment.STYLE_NO_TITLE, R.style.ThemeWithCorners);
}
</code>```

This is the onCreateView method:

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
getDialog().setCanceledOnTouchOutside(true);
v = (MyCalendar)inflater.inflate(R.layout.calendar_dialog, container, true)
    return v;
}
</code>```

I also tried to add this to onCreateDialog method as other answers on SO suggested but did not work either:

```<code>@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    Dialog d =  super.onCreateDialog(savedInstanceState);
    LayoutParams lp=d.getWindow().getAttributes();
    d.getWindow().setBackgroundDrawable(new ColorDrawable(0));
    lp.width=-2;lp.height=-2;lp.gravity=Gravity.CENTER;
    lp.dimAmount=0;
    lp.flags=LayoutParams.FLAG_LAYOUT_NO_LIMITS | LayoutParams.FLAG_NOT_TOUCH_MODAL;

    return d;
}
</code>```

So to sum it up, I want round corners, not 100% width of the screen, it preferably should wrap its content. Please, please, I need some help, I am really desperate about this, I´v ebeen trying it for days!

答:
Dialog background: dialog_rounded_bg.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/white" />
    <corners android:radius="12dp" />
</shape>
</code>```

Dialog layout: dialog_rounded.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/dialog_rounded_bg"
    android:minWidth="260dp"
    android:orientation="vertical"
    android:padding="24dp">
    ...
</LinearLayout>
</code>```

Dialog fragment: RoundedDialog.java

```<code>public class RoundedDialog extends DialogFragment {
    ...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_rounded, container, false);
        // Set transparent background and no title
        if (getDialog() != null && getDialog().getWindow() != null) {
            getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        }
        return view;
    }
    ...
}
</code>```

Update: If you don't set the flag Window.FEATURE_NO_TITLE, a blue line appears on top of the dialog in devices with Android ≤ 4.4.

Body:
I am creating a custom fragment dialog with round corners and with layout that would not fill the screen width (I would prefer if it just wrapped its content).

this is my rounded_dialog.xml in drawable folder, which is called by my Custom ThemeWithCorners as a background for the dialog. I also tried to set it as background to the linear layout which creates its content but nothing works.

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid android:color="@android:color/white"/>
<corners android:radius="20dp"
/>
</shape>

and this is how i call the dialog:

final String FTAG = "TAG_FRAGMENT_DIALOG_CALENDAR";
    dialog = (CalendarDialog) fm.findFragmentByTag(FTAG);
    ft = fm.beginTransaction();
    if (dialog != null)
    {
        ft.remove(dialog);
    }
    dialog = CalendarDialog.newInstance(this);
    dialog.setCancelable(true);

    ft.add(dialog, FTAG);
    ft.show(dialog);
    ft.commit();

In onCreate method of the dialog I set the style and theme:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setStyle(DialogFragment.STYLE_NO_TITLE, R.style.ThemeWithCorners);
}

This is the onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
getDialog().setCanceledOnTouchOutside(true);
v = (MyCalendar)inflater.inflate(R.layout.calendar_dialog, container, true)
    return v;
}

I also tried to add this to onCreateDialog method as other answers on SO suggested but did not work either:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
    Dialog d =  super.onCreateDialog(savedInstanceState);
    LayoutParams lp=d.getWindow().getAttributes();
    d.getWindow().setBackgroundDrawable(new ColorDrawable(0));
    lp.width=-2;lp.height=-2;lp.gravity=Gravity.CENTER;
    lp.dimAmount=0;
    lp.flags=LayoutParams.FLAG_LAYOUT_NO_LIMITS | LayoutParams.FLAG_NOT_TOUCH_MODAL;

    return d;
}

So to sum it up, I want round corners, not 100% width of the screen, it preferably should wrap its content. Please, please, I need some help, I am really desperate about this, I´v ebeen trying it for days!

Body:
Dialog background: dialog_rounded_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/white" />
    <corners android:radius="12dp" />
</shape>

Dialog layout: dialog_rounded.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/dialog_rounded_bg"
    android:minWidth="260dp"
    android:orientation="vertical"
    android:padding="24dp">
    ...
</LinearLayout>

Dialog fragment: RoundedDialog.java

public class RoundedDialog extends DialogFragment {
    ...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_rounded, container, false);
        // Set transparent background and no title
        if (getDialog() != null && getDialog().getWindow() != null) {
            getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        }
        return view;
    }
    ...
}

Update: If you don't set the flag Window.FEATURE_NO_TITLE, a blue line appears on top of the dialog in devices with Android ≤ 4.4.


问:
Pipelining setTimeout in node.js
I am writing a node.js console application. I have two setTimeout functions as follows.

```<code>setTimeout(function(){
    process.stdout.write('\n\nJokes Apart !!!\n\n');
}, 2000);

setTimeout(function(){
    process.stdout.write('\n\nLet\'s play a game !!!\n\n');
}, 1000);
</code>```

What I actually intend is, the first message should come after 2 seconds. After that, the second message should appear after 1 second. But what's happening is, the second message appears after 1 second and then the first message appears. Both the functions are being called at once as they are asynchronous. Is there any way to pipeline them?

答:
To understand what's happening, you should first understand the JS event loop and its non-blocking nature. You can read about it here: https://blog.risingstack.com/node-js-at-scale-understanding-node-js-event-loop/, or if you prefer video form, this is a great talk: https://youtu.be/8aGhZQkoFbQ

In a nutshell, the engine goes through the code - when it encounters the first setTimeout, it schedules it (for 2 seconds later), and keeps going. It then sees the second setTimeout and schedules it as well. When a second passes, the callback from the second setTimeout is triggered and executed, and only a second later, the callback from the first one is triggered. This is why you see them in that order.

Now to fixing it - all you need to do is just nest them:

```<code>setTimeout(function(){
   process.stdout.write('\n\nJokes Apart !!!\n\n');

   setTimeout(function(){
       process.stdout.write('\n\nLet\'s play a game !!!\n\n');
   }, 1000);
}, 2000);
</code>```

This causes the second setTimeout to get scheduled only when the callback from the first one is run.

Title: Pipelining setTimeout in node.js

Body:
I am writing a node.js console application. I have two setTimeout functions as follows.

setTimeout(function(){
    process.stdout.write('\n\nJokes Apart !!!\n\n');
}, 2000);

setTimeout(function(){
    process.stdout.write('\n\nLet\'s play a game !!!\n\n');
}, 1000);

What I actually intend is, the first message should come after 2 seconds. After that, the second message should appear after 1 second. But what's happening is, the second message appears after 1 second and then the first message appears. Both the functions are being called at once as they are asynchronous. Is there any way to pipeline them?

Body:
To understand what's happening, you should first understand the JS event loop and its non-blocking nature. You can read about it here: https://blog.risingstack.com/node-js-at-scale-understanding-node-js-event-loop/, or if you prefer video form, this is a great talk: https://youtu.be/8aGhZQkoFbQ

In a nutshell, the engine goes through the code - when it encounters the first setTimeout, it schedules it (for 2 seconds later), and keeps going. It then sees the second setTimeout and schedules it as well. When a second passes, the callback from the second setTimeout is triggered and executed, and only a second later, the callback from the first one is triggered. This is why you see them in that order.

Now to fixing it - all you need to do is just nest them:

setTimeout(function(){
   process.stdout.write('\n\nJokes Apart !!!\n\n');

   setTimeout(function(){
       process.stdout.write('\n\nLet\'s play a game !!!\n\n');
   }, 1000);
}, 2000);

This causes the second setTimeout to get scheduled only when the callback from the first one is run.


问:
Column-wise filtering required for WebGrid
Here I have a WebGrid, I need column wise filtering like the one in Grid.Mvc which uses Filterable(). Kindly help. Thanks.</p>

```<code> <div id="DivGrid">
@{
    var grid = new WebGrid(source: Model, canPage: true, canSort: true, rowsPerPage: 10, defaultSort: "Employee ID");
    grid.SortDirection = SortDirection.Descending;
    if (Model.Count() > 0)
    {
        <div class="moveRight"><strong> @ViewBag.SearchParameter</strong> | @grid.TotalRowCount @Html.Label("Record(s) found")</div>
        @grid.GetHtml(tableStyle: "PGrid", headerStyle: "Header", alternatingRowStyle: "altRow", htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(
            grid.Column("Employee_ID", "Employee ID", format: @<text>  <span class="display-mode grid-filter-btn">@item.Employee_ID </span> <label id="EmployeeID" class="edit-mode grid-filter-btn">@item.Employee_ID</label> </text>, style: "col1Width", canSort:true),
            grid.Column("First_Name", "First Name", format: @<text>  <span class="display-mode"> <label id="lblFirstName">@item.First_Name</label> </span> <input type="text" id="FirstName" value="@item.First_Name" class="edit-mode" /></text>, style: "col2Width", canSort:true),
            grid.Column("Last_Name", "Last Name", format: @<text> <span class="display-mode"> <label id="lblLastName">@item.Last_Name</label> </span>  <input type="text" id="LastName" value="@item.Last_Name" class="edit-mode" /> </text>, style: "col2Width", canSort:true),
            grid.Column("Date_Of_Birth", "Date Of Birth", format: item => ((item.Date_Of_Birth == null) ? "" : item.Date_Of_Birth.ToString("MM/dd/yyyy")), style: "DateOfBirth"),
            //grid.Column("Date_Of_Birth", "Date Of Birth", format: item => ((item.Date_Of_Birth == null) ? "" : item.Date_Of_Birth.ToString("MM/dd/yyyy")) ),
            grid.Column(header: "Action", canSort: false, style: "action", format: @<text>
            <button class="edit-user display-mode glyphicon glyphicon-edit"> Edit</button>
            <button class="display-mode delete-item glyphicon glyphicon-trash"> Delete</button>
            <button class="save-user edit-mode glyphicon glyphicon-save"> Save</button>
            <button class="cancel-user edit-mode glyphicon glyphicon-remove-sign"> Cancel</button></text>)));
    }
    else
    {
        <hr />@Html.Label("No, Record(s) not found")<<hr />
    }
}
</code>```

答:
As of my knowledge there is no built in option to filter data in Asp.net MVC. You need to write custom code. Please check this link
WebGrid Paging,Sorting and Filtering in ASP.NET MVC</p>

Body:
Here I have a WebGrid, I need column wise filtering like the one in Grid.Mvc which uses Filterable(). Kindly help. Thanks.

@{
    var grid = new WebGrid(source: Model, canPage: true, canSort: true, rowsPerPage: 10, defaultSort: "Employee ID");
    grid.SortDirection = SortDirection.Descending;
    if (Model.Count() > 0)
    {

 @ViewBag.SearchParameter | @grid.TotalRowCount @Html.Label("Record(s) found")

        @grid.GetHtml(tableStyle: "PGrid", headerStyle: "Header", alternatingRowStyle: "altRow", htmlAttributes: new { id = "DataTable" }, columns: grid.Columns(
            grid.Column("Employee_ID", "Employee ID", format: @<text>  @item.Employee_ID  @item.Employee_ID </text>, style: "col1Width", canSort:true),
            grid.Column("First_Name", "First Name", format: @<text>   @item.First_Name  <input type="text" id="FirstName" value="@item.First_Name" class="edit-mode" /></text>, style: "col2Width", canSort:true),
            grid.Column("Last_Name", "Last Name", format: @<text>  @item.Last_Name   <input type="text" id="LastName" value="@item.Last_Name" class="edit-mode" /> </text>, style: "col2Width", canSort:true),
            grid.Column("Date_Of_Birth", "Date Of Birth", format: item => ((item.Date_Of_Birth == null) ? "" : item.Date_Of_Birth.ToString("MM/dd/yyyy")), style: "DateOfBirth"),
            //grid.Column("Date_Of_Birth", "Date Of Birth", format: item => ((item.Date_Of_Birth == null) ? "" : item.Date_Of_Birth.ToString("MM/dd/yyyy")) ),
            grid.Column(header: "Action", canSort: false, style: "action", format: @<text>
            <button class="edit-user display-mode glyphicon glyphicon-edit"> Edit</button>
            <button class="display-mode delete-item glyphicon glyphicon-trash"> Delete</button>
            <button class="save-user edit-mode glyphicon glyphicon-save"> Save</button>
            <button class="cancel-user edit-mode glyphicon glyphicon-remove-sign"> Cancel</button></text>)));
    }
    else
    {

@Html.Label("No, Record(s) not found")<

    }
}


问:
How to have border color change on image hover/mousover?
I know how to add a border to images, but how do I change the color of the border on image hover/mouseover, I would like to to this to multiple images on the same page, so far I have failed to find a plugin that does this.

I spent like 5 hours looking for a plugin to do this, feel my pain!!!

Basically, I want an image to do what a button does. When user hovers the mouse over the button the color of the border changes.

答:
You can get by using following css

img {
  border:2px solid #000;
}
img:hover {
  border:2px solid tomato;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://via.placeholder.com/350x150" alt=""></code>```

With shadow hover effect

img {
  box-shadow:0px 0px 0px #000;
}
img:hover {
  box-shadow:0px 0px 5px #000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://via.placeholder.com/350x150" alt=""></code>```

Body:
You can get by using following css

img {
  border:2px solid #000;
}
img:hover {
  border:2px solid tomato;
}

<img src="http://via.placeholder.com/350x150" alt="">

With shadow hover effect

img {
  box-shadow:0px 0px 0px #000;
}
img:hover {
  box-shadow:0px 0px 5px #000;
}

<img src="http://via.placeholder.com/350x150" alt="">


问:
PHP: object is NULL right after creation
We have very strange errors occasionally popping up in our php logs: Trying to get property of non-object.

This exact error seems to be caused by the access to the member $shortName in the following if statement:

```<code>class MyLocaleWrapper extends SomeOtherClass {
    …
    protected static $system = NULL;
    public static function getSystemLocale() {
        if (self::$system === NULL) {
            self::$system = new self();
            debug(self::$system);
            self::$system->rfcName = SYSTEM_LOCALE_RFCNAME;
            self::$system->shortName = strtolower(Locale::getRegion(self::$system->rfcName));
            if (self::$system->shortName == '') {
                self::$system->shortName = strtolower(self::$system->rfcName);
            }
            …

# in another file:
class SomeOtherClass {
    …
    public function __construct() {
        # Some documentation about features that have been
        # removed from the constructor, but no real code in here.
        return NULL;
    }
    …

# in yet another file:
MyLocaleWrapper::getSystemLocale();
</code>```

if I dump self::$system into a log file, I see that it is NULL - right after being constructed with the keyword new.

The most interesting part is that this file is included in each and every request to our page, so it gets executed ~ 10 times per second. But occasionally it just fails without anyone touching the code (or even the server).

Has anyone else ever experienced such behavior in PHP?

答: We finally found out we were running into php bug #50027. After setting the php.ini-variable zend.enable_gc to false, the error vanished.

Body:
We have very strange errors occasionally popping up in our php logs: Trying to get property of non-object.

This exact error seems to be caused by the access to the member $shortName in the following if statement:

class MyLocaleWrapper extends SomeOtherClass {
    …
    protected static $system = NULL;
    public static function getSystemLocale() {
        if (self::$system === NULL) {
            self::$system = new self();
            debug(self::$system);
            self::$system->rfcName = SYSTEM_LOCALE_RFCNAME;
            self::$system->shortName = strtolower(Locale::getRegion(self::$system->rfcName));
            if (self::$system->shortName == '') {
                self::$system->shortName = strtolower(self::$system->rfcName);
            }
            …

# in another file:
class SomeOtherClass {
    …
    public function __construct() {
        # Some documentation about features that have been
        # removed from the constructor, but no real code in here.
        return NULL;
    }
    …

# in yet another file:
MyLocaleWrapper::getSystemLocale();

if I dump self::$system into a log file, I see that it is NULL - right after being constructed with the keyword new.

The most interesting part is that this file is included in each and every request to our page, so it gets executed ~ 10 times per second. But occasionally it just fails without anyone touching the code (or even the server).

Has anyone else ever experienced such behavior in PHP?


问:
Sending HTTP POST from Android with HttpURLConnection
I am trying to send a HTTP POST request from Android application to my PHP coded server which puts the data received from the request to a MySQL database. If I do it using HttpClient and HttpPost methods, everything works fine, but I decided to try HttpURLConnection class, because it is said to be more optimized and much newer than the old HttpClient and HttpPost classes, and, unfortunately, I can't get it to work this way. I don't receive any errors or exceptions and device is connecting to a network, but nothing happens, the given values are not written to the database. Please tell me what am I doing wrong and advice me. Maybe it is better to use HttpClient/HttpPost method?

This is my code:

```<code>private void writeToDatabase(URL url, String number, String comment) throws IOException  {
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(15 * 1000);
        httpConnection.setReadTimeout(10 * 1000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);

        List<NameValuePair> params = new ArrayList<NameValuePair>(3);
        params.add(new BasicNameValuePair("code", "****"));
        params.add(new BasicNameValuePair("number", number));
        params.add(new BasicNameValuePair("comment", comment));

        OutputStream os = httpConnection.getOutputStream();
        BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        br.write(getQuery(params));
        br.flush();
        br.close();
        os.close();

        httpConnection.connect();
}
</code>```

getQuery() function:

```<code>private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params) {
            if (first) {
                first = false;
            } else result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }

        return result.toString();
}
</code>```

And this is how and where I call the writeToDatabase() function:

```<code>Thread thread = new Thread() {

    @Override
    public void run () {
        try {
            URL url = new URL("http://www.***.com");
            writeToDatabase(url, "****", "as pats");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
};
thread.start();
</code>```

EDIT: That's SOO weird... Read the comments in the following code snippet:

```<code>private void writeToDatabase(URL url, String number, String comment) throws IOException  {
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(15 * 1000);
        httpConnection.setReadTimeout(10 * 1000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);

        httpConnection.connect();

        List<NameValuePair> params = new ArrayList<NameValuePair>(3);
        params.add(new BasicNameValuePair("code", "****"));
        params.add(new BasicNameValuePair("number", number));
        params.add(new BasicNameValuePair("comment", comment));

        OutputStream os = httpConnection.getOutputStream();
        BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        br.write(getQuery(params));
        br.flush();
        br.close();
        os.close();
        //Everything works just fine with these lines below, but without them, it doesn't work... Why is that?
        BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            Log.i("ilog", inputLine);
        }

        httpConnection.disconnect();
}
</code>```

It looks like the problem why this code didn't work is that I didn't read the response. If I read the response like this:

```<code>BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            Log.i("ilog", inputLine);
        }
</code>```

Then everything works just perfectly. But Why is that? Could anybody explain this to me? I'm very very interested!

EDIT 2: Even if I set httpConnection.setDoOutput(false); it still works perfectly as long as I read the response. Values is written to the database even if setDoOutput() is set to false. I'm totally confused...

答:
I agree with Salivan. Without checking the response code, the tcp connection will be reset before the POST is sent to the server. But no one discusses this. Is there any reason?</p>

```<code>if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = conn.getInputStream();
            }
</code>```

Body:
I am trying to send a HTTP POST request from Android application to my PHP coded server which puts the data received from the request to a MySQL database. If I do it using HttpClient and HttpPost methods, everything works fine, but I decided to try HttpURLConnection class, because it is said to be more optimized and much newer than the old HttpClient and HttpPost classes, and, unfortunately, I can't get it to work this way. I don't receive any errors or exceptions and device is connecting to a network, but nothing happens, the given values are not written to the database. Please tell me what am I doing wrong and advice me. Maybe it is better to use HttpClient/HttpPost method?

This is my code:

private void writeToDatabase(URL url, String number, String comment) throws IOException  {
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(15 * 1000);
        httpConnection.setReadTimeout(10 * 1000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);

        List<NameValuePair> params = new ArrayList<NameValuePair>(3);
        params.add(new BasicNameValuePair("code", "****"));
        params.add(new BasicNameValuePair("number", number));
        params.add(new BasicNameValuePair("comment", comment));

        OutputStream os = httpConnection.getOutputStream();
        BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        br.write(getQuery(params));
        br.flush();
        br.close();
        os.close();

        httpConnection.connect();
}

getQuery() function:

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (NameValuePair pair : params) {
            if (first) {
                first = false;
            } else result.append("&");

            result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        }

        return result.toString();
}

And this is how and where I call the writeToDatabase() function:

Thread thread = new Thread() {

    @Override
    public void run () {
        try {
            URL url = new URL("http://www.***.com");
            writeToDatabase(url, "****", "as pats");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
};
thread.start();

EDIT: That's SOO weird... Read the comments in the following code snippet:

private void writeToDatabase(URL url, String number, String comment) throws IOException  {
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(15 * 1000);
        httpConnection.setReadTimeout(10 * 1000);
        httpConnection.setRequestMethod("POST");
        httpConnection.setDoInput(true);
        httpConnection.setDoOutput(true);

        httpConnection.connect();

        List<NameValuePair> params = new ArrayList<NameValuePair>(3);
        params.add(new BasicNameValuePair("code", "****"));
        params.add(new BasicNameValuePair("number", number));
        params.add(new BasicNameValuePair("comment", comment));

        OutputStream os = httpConnection.getOutputStream();
        BufferedWriter br = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        br.write(getQuery(params));
        br.flush();
        br.close();
        os.close();
        //Everything works just fine with these lines below, but without them, it doesn't work... Why is that?
        BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            Log.i("ilog", inputLine);
        }

        httpConnection.disconnect();
}

It looks like the problem why this code didn't work is that I didn't read the response. If I read the response like this:

BufferedReader in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            Log.i("ilog", inputLine);
        }

Then everything works just perfectly. But Why is that? Could anybody explain this to me? I'm very very interested!

EDIT 2: Even if I set httpConnection.setDoOutput(false); it still works perfectly as long as I read the response. Values is written to the database even if setDoOutput() is set to false. I'm totally confused...

Body:
I agree with Salivan. Without checking the response code, the tcp connection will be reset before the POST is sent to the server. But no one discusses this. Is there any reason?

if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = conn.getInputStream();
            }


问:
Assign values to a slice struct in go ( golang )
How can I assign values to a var of type []struct ?

```<code>type Mappings []struct {
    PropA       string
    PropB       string
}

func main() {
    var test Mappings
    test = ???
}
</code>```

Thanks in advance!

答:
```<code>package main

import (
    "fmt"
)
type Mappings []struct {
    PropA       string
    PropB       string
}

func main() {
    var test Mappings
    test = Mappings{
        {PropA: "foo", PropB: "bar"},
        {PropA: "bar", PropB: "baz"},
    }
    fmt.Println(test)
}
</code>```

Body:
How can I assign values to a var of type []struct ?

type Mappings []struct {
    PropA       string
    PropB       string
}

func main() {
    var test Mappings
    test = ???
}

Thanks in advance!