问:
Adjust div position fluidly as window width changes
I have a div with multiple absolute-positioned divs within it. I would like the left position of these inner divs to move fluidly as the window is resized. An example of what I have so far can be seen here: https://jsfiddle.net/ewqmfa4d/.

How can I do this? I presume I'd use jQuery? Note that I'm not looking for media queries, but rather something that provides fluid movement as the width of the window changes.

答:
You could use a percentage for the value of the left attribute. In your Fiddle example, you would have to change your two text selectors to have to following css declarations:

```<code>#text{
  color: #c9d35f;
  top: 100px;
  left: 15%;
}

#text2{
  color: #fa48bc;
  top: 175px;
  left: 30%;
}
</code>```

Body:
You could use a percentage for the value of the left attribute. In your Fiddle example, you would have to change your two text selectors to have to following css declarations:

#text{
  color: #c9d35f;
  top: 100px;
  left: 15%;
}

#text2{
  color: #fa48bc;
  top: 175px;
  left: 30%;
}


来源: stackexchange

问:
How to setup and use an AngularJS service
I'm new to AngularJS and I am trying to use a service so I can pass data around between controllers.

I have followed the w3schools instructions (here) to setup a service, and it resulted in this:

```<code>app.service('hexafy', function() {
    this.myFunc = function(x) {
        return x.toString(16);
    }
});

app.controller('almLoginCtrl', ['$scope', '$state', function ($scope, $state, hexafy) {

    /* This function handles the user tapping the "login" button. It will process their
     * login details and allow proceed or show incorrect login details error as necessary.
     */
    $scope.almLogin = function () {
        $state.go('home');
        // Functionality needs to be added to test login data, collect and store the login data and the LWSSO
    }

    $scope.hex = hexafy.myFunc(255);
}]);
</code>```

And this is how I attempt to see its output:

```<code><h3 class="login-title">{{hex}} ALM DETAILS</h3>
</code>```

(this is surrounded by other irrelevant HTML)

This is the first service I've ever tried to create so I am just creating one that will allow me to test how it works. This code is put into the second view of a AngularJS/Cordova/Ionic hybrid app I'm building.
However, for some reason, when I run this code, this error appears in the console:

```<code>> TypeError: Cannot read property 'myFunc' of undefined...
</code>```

(stack trace omitted for brevity)

According to W3schools, and the try-it-now playground on their site, I should see "ff" displayed next to "ALM DETAILS" on the rendered HTML page. Instead, this displays:

{{HEX}} ALM DETAILS

It displays "{{HEX}}" instead of the variable's value.

Not sure if its relevant, but I build the app with a Gulp and am testing it in the chrome browser, developer mobile view.

So, what am I doing wrong when setting up the service? Why is the function output being returned as "undefined"? (or is it the function itself that is undefined?)

答:
Change

```<code>app.controller('almLoginCtrl', ['$scope', '$state', function ($scope, $state, hexafy) {
</code>```

To

```<code>app.controller('almLoginCtrl', ['$scope', '$state','hexafy', function ($scope, $state, hexafy) {
</code>```

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',['$scope','hexafy',function($scope, hexafy) {
$scope.hex=hexafy.myFunc(255);
}]);
myApp.service('hexafy', function() {
    this.myFunc = function(x) {
        return x.toString(16);
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
 <h3 class="login-title">{{hex}} ALM DETAILS</h3>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new to AngularJS and I am trying to use a service so I can pass data around between controllers.

I have followed the w3schools instructions (here) to setup a service, and it resulted in this:

app.service('hexafy', function() {
    this.myFunc = function(x) {
        return x.toString(16);
    }
});

app.controller('almLoginCtrl', ['$scope', '$state', function ($scope, $state, hexafy) {

    /* This function handles the user tapping the "login" button. It will process their
     * login details and allow proceed or show incorrect login details error as necessary.
     */
    $scope.almLogin = function () {
        $state.go('home');
        // Functionality needs to be added to test login data, collect and store the login data and the LWSSO
    }

    $scope.hex = hexafy.myFunc(255);
}]);

And this is how I attempt to see its output:

{{hex}} ALM DETAILS

(this is surrounded by other irrelevant HTML)

This is the first service I've ever tried to create so I am just creating one that will allow me to test how it works. This code is put into the second view of a AngularJS/Cordova/Ionic hybrid app I'm building.
However, for some reason, when I run this code, this error appears in the console:

> TypeError: Cannot read property 'myFunc' of undefined...

(stack trace omitted for brevity)

According to W3schools, and the try-it-now playground on their site, I should see "ff" displayed next to "ALM DETAILS" on the rendered HTML page. Instead, this displays:

{{HEX}} ALM DETAILS

It displays "{{HEX}}" instead of the variable's value.

Not sure if its relevant, but I build the app with a Gulp and am testing it in the chrome browser, developer mobile view.

So, what am I doing wrong when setting up the service? Why is the function output being returned as "undefined"? (or is it the function itself that is undefined?)

Body:
Change

app.controller('almLoginCtrl', ['$scope', '$state', function ($scope, $state, hexafy) {

To

app.controller('almLoginCtrl', ['$scope', '$state','hexafy', function ($scope, $state, hexafy) {

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',['$scope','hexafy',function($scope, hexafy) {
$scope.hex=hexafy.myFunc(255);
}]);
myApp.service('hexafy', function() {
    this.myFunc = function(x) {
        return x.toString(16);
    }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
 <h3 class="login-title">{{hex}} ALM DETAILS</h3>
</div>


问:
Pass a List of integers to a C# controller action
I am trying to pass in a list of integers to a C# controller action. I have the following code:

```<code>    HttpRequestMessage request;
    String myUrl = 'http://path/to/getData';
    List<int> data = new List<int>() { 4, 6, 1 };

    request = new HttpRequestMessage(HttpMethod.post, myUrl);
    request.Content = new StringContent(JsonConvert.SerializeObject(data, Formatting.Indented));

    HttpResponseMessage response = httpClient.SendAsync(request).Result;
    String responseString = response.Content.ReadAsStringAsync().Result;
    var data = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(responseString);
</code>```

The controller action:

```<code>    [HttpPost]
    [ActionName("getData")]
    public Response getData(List<int> myInts) {

        // ...

    }
</code>```

However the resulting responseString is:

```<code> {"Message":"An error has occurred.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type 'text/plain'.","ExceptionType":"System.InvalidOperationException}
</code>```

答:
Similar to this question - you are not sending a List<int>, you are sending a serialized list of integers (in this case, a JSON serialized string).  So you need to accept a string and deserialize at the other end, as well as handling any non-integer values that might be encountered.  Something like this:

```<code>[HttpPost]
[ActionName("getData")]
public Response getData(string myInts) {

    var myIntsList = JsonConvert.DeserializeObject<List<int>>(myInts);
    // Don't forget error handling!

}
</code>```

EDIT 2:

The other alternative is to add multiple query parameters like so:

http://path/to/getData?myInts=4&myInts=6&myInts=1

<s>This should work with the code that you have already.</s> ASP.NET can interpret multiple query parameters as a List<T>).

Sorry, you may need to add the [FromUri] attribute for the solution:

```<code>[HttpPost]
[ActionName("getData")]
public Response getData([FromUri]List<int> myInts) {

    // ...

}
</code>```

Body:
I am trying to pass in a list of integers to a C# controller action. I have the following code:

    HttpRequestMessage request;
    String myUrl = 'http://path/to/getData';
    List<int> data = new List<int>() { 4, 6, 1 };

    request = new HttpRequestMessage(HttpMethod.post, myUrl);
    request.Content = new StringContent(JsonConvert.SerializeObject(data, Formatting.Indented));

    HttpResponseMessage response = httpClient.SendAsync(request).Result;
    String responseString = response.Content.ReadAsStringAsync().Result;
    var data = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(responseString);

The controller action:

    [HttpPost]
    [ActionName("getData")]
    public Response getData(List<int> myInts) {

        // ...

    }

However the resulting responseString is:

 {"Message":"An error has occurred.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type 'text/plain'.","ExceptionType":"System.InvalidOperationException}

Body:
Similar to this question - you are not sending a List<int>, you are sending a serialized list of integers (in this case, a JSON serialized string).  So you need to accept a string and deserialize at the other end, as well as handling any non-integer values that might be encountered.  Something like this:

[HttpPost]
[ActionName("getData")]
public Response getData(string myInts) {

    var myIntsList = JsonConvert.DeserializeObject<List<int>>(myInts);
    // Don't forget error handling!

}

EDIT 2:

The other alternative is to add multiple query parameters like so:

http://path/to/getData?myInts=4&myInts=6&myInts=1

<s>This should work with the code that you have already.</s> ASP.NET can interpret multiple query parameters as a List<T>).

Sorry, you may need to add the [FromUri] attribute for the solution:

[HttpPost]
[ActionName("getData")]
public Response getData([FromUri]List<int> myInts) {

    // ...

}


问:
AttributeError: object has no attribute 'reader' online when CSV used inside of a METHOD
When I access csv.reader from a script, every thing works well but when I access it from a method inside my class, I get the following error:

```<code>AttributeError: 'GetInstgramUsernames' object has no attribute 'reader'
</code>```

I have looked at these two similar issues my problem is different

AttributeError: 'module' object has no attribute 'reader'

CSV Module AttributeError

Based on those two links, I have ensured that

A. I am pointing to the correct CSV libray

B. I don't have a csv.py file in my project

I am new to Python so it could just be a simple oversight, but I have included the code and comments on what works and what doesn't

```<code>import csv

print(csv.__file__)
# displays:
# D:\ProgramData\Anaconda2\lib\csv.pyc

reader = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))

print(list(reader))
# displays
# [['user_name'], ['mensfashionpost'], ['creativefasion']]

class GetInstgramUsernames(object):

    def read(self):
        # same line as above but produces an error
        # AttributeError: 'GetInstgramUsernames' object has no attribute 'reader'
        self.xyz = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
        print(list(self.xyz))

csv = GetInstgramUsernames()

csv.read()
</code>```

And the actual console output

```<code>python xmen.py
D:\ProgramData\Anaconda2\lib\csv.pyc
[['user_name'], ['mensfashionpost'], ['creativefasion']]
Traceback (most recent call last):
File "xmen.py", line 25, in <module>
    csv.read()
File "xmen.py", line 18, in read
    self.xyz = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
AttributeError: 'GetInstgramUsernames' object has no attribute 'reader'    D:\dev\scrapy\instagram_influencers>
</code>```

答:
If you want to add anything to the object, you need to use self.  So, the line

```<code>    reader = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
</code>```

should say

```<code>    self.reader = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
</code>```

You'll notice that you did something similar in the object initialization (the __init__ section).

Body:
When I access csv.reader from a script, every thing works well but when I access it from a method inside my class, I get the following error:

AttributeError: 'GetInstgramUsernames' object has no attribute 'reader'

I have looked at these two similar issues my problem is different

AttributeError: 'module' object has no attribute 'reader'

CSV Module AttributeError

Based on those two links, I have ensured that

A. I am pointing to the correct CSV libray

B. I don't have a csv.py file in my project

I am new to Python so it could just be a simple oversight, but I have included the code and comments on what works and what doesn't

import csv

print(csv.__file__)
# displays:
# D:\ProgramData\Anaconda2\lib\csv.pyc

reader = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))

print(list(reader))
# displays
# [['user_name'], ['mensfashionpost'], ['creativefasion']]

class GetInstgramUsernames(object):

    def read(self):
        # same line as above but produces an error
        # AttributeError: 'GetInstgramUsernames' object has no attribute 'reader'
        self.xyz = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
        print(list(self.xyz))

csv = GetInstgramUsernames()

csv.read()

And the actual console output

python xmen.py
D:\ProgramData\Anaconda2\lib\csv.pyc
[['user_name'], ['mensfashionpost'], ['creativefasion']]
Traceback (most recent call last):
File "xmen.py", line 25, in <module>
    csv.read()
File "xmen.py", line 18, in read
    self.xyz = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))
AttributeError: 'GetInstgramUsernames' object has no attribute 'reader'    D:\dev\scrapy\instagram_influencers>

Body:
If you want to add anything to the object, you need to use self.  So, the line

    reader = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))

should say

    self.reader = csv.reader(open('D:\\dev\\scrapy\\instagram_influencers\\instagram_influencers\\input\\user_names.csv','r'))

You'll notice that you did something similar in the object initialization (the __init__ section).


问:
Comparing two integers without any comparison
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

```<code>if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";
</code>```

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

答: The Perverse Idea: use an array of function pointers. Then with some arithmetic and bitwise operations get an index into that array.</p>

OwnerDisplayName: kvphxga

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

LastEditorDisplayName: kvphxga

OwnerDisplayName: Vilx-


问:
In Rails 3 how can you access the user_id of the last user in the database in your model?
Edit See Below:

```<code>class Post < ActiveRecord::Base
  last_user_id = User.last.id
  validates_inclusion_of :user_id, :in => 0..last_user_id
end
</code>```

The above solution works but as vojlo explains, once in production the code will only be executed once and the model will then validate against an incorrect range of users.

I'm working on a tutorial (rails 3.0.3) and have tried for the last half hour to figure out how to tell rails that one of the classes in my model should make sure the :user_id is within the range zero to the user_id of the last user in the database.

I know I need to be using:

```<code>validates_inclusion_of :user_id, :in 0..(can't figure out this piece)
</code>```

I was able to easily ensure the number entered for User_ID in numeric with:

```<code>validates_numericality_of :user_id
</code>```

I'm looking for information on where to research this, I took a good look at the ActiveRecord Validators documentation and didn't find much there.

答:
Why not use validates_uniquness_of :user_id?

Assuming that the range of 0..the_latest_user_id contains all existing user ids, then you are simply looking to see if it is unique. Determining its uniqueness would be the same thing as determining if it is in that range.

Body:
Edit See Below:

class Post < ActiveRecord::Base
  last_user_id = User.last.id
  validates_inclusion_of :user_id, :in => 0..last_user_id
end

The above solution works but as vojlo explains, once in production the code will only be executed once and the model will then validate against an incorrect range of users.

I'm working on a tutorial (rails 3.0.3) and have tried for the last half hour to figure out how to tell rails that one of the classes in my model should make sure the :user_id is within the range zero to the user_id of the last user in the database.

I know I need to be using:

validates_inclusion_of :user_id, :in 0..(can't figure out this piece)

I was able to easily ensure the number entered for User_ID in numeric with:

validates_numericality_of :user_id

I'm looking for information on where to research this, I took a good look at the ActiveRecord Validators documentation and didn't find much there.


问:
Terraform S3 bucket creation causes not authorized

Question

What AWS permission is required to create a S3 bucket, which causes HTTP/1.1 403 Forbidden on ec2/DescribeAccountAttributes and s3/CreateBucket. Or how to get further information on AWS side to further trouble-shoot.

Added all permissions on EC2 and S3 to the user account, but did not solve the problem.

Note

If I have all the permission as the account owner (using different account), this will not happen.

Problem

Trying to create a S3 bucket.

```<code>resource "aws_s3_bucket" "s3_bucket_tfstate" {
  bucket = "${var.s3_bucket_tfstate}"
  acl    = "private"
}
</code>```

However it causes 403 with the TF_LOG=DEBUG below.

```<code>2017/12/06 18:55:35 [DEBUG] [aws-sdk-go] DEBUG: Request ec2/DescribeAccountAttributes Details:
---[ REQUEST POST-SIGN ]-----------------------------
POST / HTTP/1.1
Host: ec2.ap-southeast-2.amazonaws.com
User-Agent: aws-sdk-go/1.12.35 (go1.9; darwin; amd64) APN/1.0 HashiCorp/1.0 Terraform/0.11.0-beta1
Content-Length: 87
Authorization: AWS4-HMAC-SHA256 Credential=<credential>/20171206/ap-southeast-2/ec2/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=****
Content-Type: application/x-www-form-urlencoded; charset=utf-8
X-Amz-Date: 20171206T075535Z
Accept-Encoding: gzip

Action=DescribeAccountAttributes&AttributeName.1=supported-platforms&Version=2016-11-15
-----------------------------------------------------
2017/12/06 18:55:35 [DEBUG] [aws-sdk-go] DEBUG: Response ec2/DescribeAccountAttributes Details:
---[ RESPONSE ]--------------------------------------
HTTP/1.1 403 Forbidden
Connection: close
Transfer-Encoding: chunked
Date: Wed, 06 Dec 2017 07:55:37 GMT
Server: AmazonEC2

-----------------------------------------------------
2017/12/06 18:55:35 [DEBUG] [aws-sdk-go] <?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>UnauthorizedOperation</Code><Message>You are not authorized to perform this operation.</Message></Error></Errors><RequestID>0b9480d5-a687-46f8-a0ca-a212c37ce3fb</RequestID></Response>
2017/12/06 18:55:35 [DEBUG] [aws-sdk-go] DEBUG: Validate Response ec2/DescribeAccountAttributes failed, not retrying, error UnauthorizedOperation: You are not authorized to perform this operation.

2017/12/06 19:55:52 [DEBUG] [aws-sdk-go] DEBUG: Request s3/CreateBucket Details:
---[ REQUEST POST-SIGN ]-----------------------------
PUT / HTTP/1.1
Host: mule-cdr-billing-adapter-config-tfstate.s3.ap-southeast-2.amazonaws.com
User-Agent: aws-sdk-go/1.12.35 (go1.9; darwin; amd64) APN/1.0 HashiCorp/1.0 Terraform/0.11.0-beta1
Content-Length: 158
Authorization: AWS4-HMAC-SHA256 Credential=****/20171206/ap-southeast-2/s3/aws4_request, SignedHeaders=content-length;host;x-amz-acl;x-amz-content-sha256;x-amz-date, Signature=****
X-Amz-Acl: private
X-Amz-Content-Sha256: 8bfaf12a44a138dc6f38eb5c291558f2c551b0f18ab6e2a5e7f9a00176b25240
X-Amz-Date: 20171206T085552Z
Accept-Encoding: gzip

<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><LocationConstraint>ap-southeast-2</LocationConstraint></CreateBucketConfiguration>
-----------------------------------------------------
2017/12/06 19:55:53 [DEBUG] [aws-sdk-go] DEBUG: Response s3/CreateBucket Details:
---[ RESPONSE ]--------------------------------------
HTTP/1.1 403 Forbidden
Connection: close
Transfer-Encoding: chunked
Content-Type: application/xml
Date: Wed, 06 Dec 2017 08:55:55 GMT
Server: AmazonS3
X-Amz-Id-2: oAttLYQ1qxta2qs03RD79G8xZxTSfDtauQZyeQ8lsq2+4LWBghg+bGjpNvL6Xl1qPnIwE8YOyRs=
X-Amz-Request-Id: 9B562398EEFDF96E

-----------------------------------------------------
2017/12/06 19:55:53 [DEBUG] [aws-sdk-go] <?xml version="1.0" encoding="UTF-8"?>
<Error><Code>AccessDenied</Code><Message>Access Denied</Message><RequestId>9B562398EEFDF96E</RequestId><HostId>oAttLYQ1qxta2qs03RD79G8xZxTSfDtauQZyeQ8lsq2+4LWBghg+bGjpNvL6Xl1qPnIwE8YOyRs=</HostId></Error>
2017/12/06 19:55:53 [DEBUG] [aws-sdk-go] DEBUG: Validate Response s3/CreateBucket failed, not retrying, error AccessDenied: Access Denied
    status code: 403, request id: 9B562398EEFDF96E, host id: oAttLYQ1qxta2qs03RD79G8xZxTSfDtauQZyeQ8lsq2+4LWBghg+bGjpNvL6Xl1qPnIwE8YOyRs=
</code>```

答:
Cause

Simulated the AWS S3 create bucket via the IAM Policy simulator and found the policy preventing the creation was MFA.

Solution

```<code>session=$(aws sts get-session-token --profile $AWS_PROFILE --serial-number $SECURITY_DEVICE_ARN --token-code $MFA_TOKEN)
export AWS_ACCESS_KEY_ID=$(echo $session | jq  -r .Credentials.AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo $session | jq  -r .Credentials.SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo $session | jq -r .Credentials.SessionToken)
export AWS_MFA_SERIAL_NUMBER=${MFA_TOKEN}
</code>```

Then run the terraform.

Body:
Question

What AWS permission is required to create a S3 bucket, which causes HTTP/1.1 403 Forbidden on ec2/DescribeAccountAttributes and s3/CreateBucket. Or how to get further information on AWS side to further trouble-shoot.

Added all permissions on EC2 and S3 to the user account, but did not solve the problem.

Note

If I have all the permission as the account owner (using different account), this will not happen.

Problem

Trying to create a S3 bucket.

resource "aws_s3_bucket" "s3_bucket_tfstate" {
  bucket = "${var.s3_bucket_tfstate}"
  acl    = "private"
}

However it causes 403 with the TF_LOG=DEBUG below.

2017/12/06 18:55:35 [DEBUG] [aws-sdk-go] DEBUG: Request ec2/DescribeAccountAttributes Details:
---[ REQUEST POST-SIGN ]-----------------------------
POST / HTTP/1.1
Host: ec2.ap-southeast-2.amazonaws.com
User-Agent: aws-sdk-go/1.12.35 (go1.9; darwin; amd64) APN/1.0 HashiCorp/1.0 Terraform/0.11.0-beta1
Content-Length: 87
Authorization: AWS4-HMAC-SHA256 Credential=<credential>/20171206/ap-southeast-2/ec2/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date, Signature=****
Content-Type: application/x-www-form-urlencoded; charset=utf-8
X-Amz-Date: 20171206T075535Z
Accept-Encoding: gzip

Action=DescribeAccountAttributes&AttributeName.1=supported-platforms&Version=2016-11-15
-----------------------------------------------------
2017/12/06 18:55:35 [DEBUG] [aws-sdk-go] DEBUG: Response ec2/DescribeAccountAttributes Details:
---[ RESPONSE ]--------------------------------------
HTTP/1.1 403 Forbidden
Connection: close
Transfer-Encoding: chunked
Date: Wed, 06 Dec 2017 07:55:37 GMT
Server: AmazonEC2

-----------------------------------------------------
2017/12/06 18:55:35 [DEBUG] [aws-sdk-go] <?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error>UnauthorizedOperation<Message>You are not authorized to perform this operation.</Message></Error></Errors><RequestID>0b9480d5-a687-46f8-a0ca-a212c37ce3fb</RequestID></Response>
2017/12/06 18:55:35 [DEBUG] [aws-sdk-go] DEBUG: Validate Response ec2/DescribeAccountAttributes failed, not retrying, error UnauthorizedOperation: You are not authorized to perform this operation.

2017/12/06 19:55:52 [DEBUG] [aws-sdk-go] DEBUG: Request s3/CreateBucket Details:
---[ REQUEST POST-SIGN ]-----------------------------
PUT / HTTP/1.1
Host: mule-cdr-billing-adapter-config-tfstate.s3.ap-southeast-2.amazonaws.com
User-Agent: aws-sdk-go/1.12.35 (go1.9; darwin; amd64) APN/1.0 HashiCorp/1.0 Terraform/0.11.0-beta1
Content-Length: 158
Authorization: AWS4-HMAC-SHA256 Credential=****/20171206/ap-southeast-2/s3/aws4_request, SignedHeaders=content-length;host;x-amz-acl;x-amz-content-sha256;x-amz-date, Signature=****
X-Amz-Acl: private
X-Amz-Content-Sha256: 8bfaf12a44a138dc6f38eb5c291558f2c551b0f18ab6e2a5e7f9a00176b25240
X-Amz-Date: 20171206T085552Z
Accept-Encoding: gzip

<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><LocationConstraint>ap-southeast-2</LocationConstraint></CreateBucketConfiguration>
-----------------------------------------------------
2017/12/06 19:55:53 [DEBUG] [aws-sdk-go] DEBUG: Response s3/CreateBucket Details:
---[ RESPONSE ]--------------------------------------
HTTP/1.1 403 Forbidden
Connection: close
Transfer-Encoding: chunked
Content-Type: application/xml
Date: Wed, 06 Dec 2017 08:55:55 GMT
Server: AmazonS3
X-Amz-Id-2: oAttLYQ1qxta2qs03RD79G8xZxTSfDtauQZyeQ8lsq2+4LWBghg+bGjpNvL6Xl1qPnIwE8YOyRs=
X-Amz-Request-Id: 9B562398EEFDF96E

-----------------------------------------------------
2017/12/06 19:55:53 [DEBUG] [aws-sdk-go] <?xml version="1.0" encoding="UTF-8"?>
<Error>AccessDenied<Message>Access Denied</Message><RequestId>9B562398EEFDF96E</RequestId><HostId>oAttLYQ1qxta2qs03RD79G8xZxTSfDtauQZyeQ8lsq2+4LWBghg+bGjpNvL6Xl1qPnIwE8YOyRs=</HostId></Error>
2017/12/06 19:55:53 [DEBUG] [aws-sdk-go] DEBUG: Validate Response s3/CreateBucket failed, not retrying, error AccessDenied: Access Denied
    status code: 403, request id: 9B562398EEFDF96E, host id: oAttLYQ1qxta2qs03RD79G8xZxTSfDtauQZyeQ8lsq2+4LWBghg+bGjpNvL6Xl1qPnIwE8YOyRs=

Body:
Cause

Simulated the AWS S3 create bucket via the IAM Policy simulator and found the policy preventing the creation was MFA.

Solution

session=$(aws sts get-session-token --profile $AWS_PROFILE --serial-number $SECURITY_DEVICE_ARN --token-code $MFA_TOKEN)
export AWS_ACCESS_KEY_ID=$(echo $session | jq  -r .Credentials.AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo $session | jq  -r .Credentials.SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo $session | jq -r .Credentials.SessionToken)
export AWS_MFA_SERIAL_NUMBER=${MFA_TOKEN}

Then run the terraform.


问:
Is it possible to use a variable as part of an image URL?
I am making a quiz on a basic website using PHP and HTML/CSS and have answers stored in a PHP array.

I would like to display the quiz answers and the corresponding images (which I have named to match) using the simplest method.
For example if $ANSWER="cat", I want to display "cat.jpg"

If it were possible to use a variable in the image URL it would be wonderful, but I haven't been able to find an example of this.

Should this syntax work?

```<code>echo '<img src=/pictures/"$ANSWER".jpg >';
</code>```

So far I'm getting no output but not sure if it's due to a bug somewhere else.

答:
Yes, try to use double quotes like:
echo "";

or still use single quote like:

```<code>echo '<img src=\'/pictures/'.$ANSWER.'.jpg \'>';
</code>```

Body:
I am making a quiz on a basic website using PHP and HTML/CSS and have answers stored in a PHP array.

I would like to display the quiz answers and the corresponding images (which I have named to match) using the simplest method.
For example if $ANSWER="cat", I want to display "cat.jpg"

If it were possible to use a variable in the image URL it would be wonderful, but I haven't been able to find an example of this.

Should this syntax work?

echo '';

So far I'm getting no output but not sure if it's due to a bug somewhere else.

Body:
Yes, try to use double quotes like:
echo "<img src='/pictures/".$ANSWER.".jpg' >";

or still use single quote like:

echo '<img src=\'/pictures/'.$ANSWER.'.jpg \'>';


问:
MVC5 Ajax.BeginForm upload form with files
I read some articles that is not possible to save files using Ajax.BeginForm.

I have a form in MVC5 that uses Ajax.BeginForm so the user has a nice responsive app without page refresh.

Now, the requirement is to add 4 fields that will hold files (file upload).

Also read that maybe with jquery.form.js this is possible.

So my questions are about other approach is this make any sense:

The form keep the Ajax.BeginForm

The user enters data into the form.

When user needs to load a file into the form, then I was thinking on uploading that file to server on the fly and store there temporarily.

When the form is saved, on server side I can get temp files and then save them.

答:
Add this</p>

```<code>  $("body").on("submit", "#frmAddProduct", function (e) {
            var form = e.target;
            if (form.dataset.ajax) {
                e.preventDefault();
                e.stopImmediatePropagation();
                var xhr = new XMLHttpRequest();
                xhr.open(form.method, form.action);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        if (form.dataset.ajaxUpdate) {
                            var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
                        }
                    }
                };
                if ($("#frmAddProduct").valid()) { xhr.send(new FormData(form)); }
            } return true;
        });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Add this

  $("body").on("submit", "#frmAddProduct", function (e) {
            var form = e.target;
            if (form.dataset.ajax) {
                e.preventDefault();
                e.stopImmediatePropagation();
                var xhr = new XMLHttpRequest();
                xhr.open(form.method, form.action);
                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        if (form.dataset.ajaxUpdate) {
                            var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
                        }
                    }
                };
                if ($("#frmAddProduct").valid()) { xhr.send(new FormData(form)); }
            } return true;
        });


问:
VS2013 or VS2015 shows "unspecified error"
When I open my worked solution (after merge from other branch) VS2013 shows error message "unspecified error" and I cannot close the window (the error's dialog jumps each time when I close it).
VS2012 opens the solution without error messages.
I suspect issue related to TFS configuration.
How can I found actual reason of the error?

答: I have removed and recreated new workspace for the project and its works for me</p>


问:
Select a range of column base on value of another column in pandas
My dataset looks like this(first row is header)

```<code>0    1    2    3    4    5
1    3    4    6    2    3
3    8    9    3    2    4
2    2    3    2    1    2
</code>```

I want to select a range of columns of the dataset based on the column [5], e.g:

```<code>1    3    4
3    8    9    3
2    2
</code>```

I have tried the following, but it did not work:

```<code>df.iloc[:,0:df['5'].values]
</code>```

答:
Recreate your dataframe </p>

```<code>df=pd.DataFrame([x[:x[5]] for x in df.values]).fillna(0)
df
Out[184]:
   0  1    2    3
0  1  3  4.0  0.0
1  3  8  9.0  3.0
2  2  2  0.0  0.0
</code>```

Body:
My dataset looks like this(first row is header)

0    1    2    3    4    5
1    3    4    6    2    3
3    8    9    3    2    4
2    2    3    2    1    2

I want to select a range of columns of the dataset based on the column [5], e.g:

1    3    4
3    8    9    3
2    2

I have tried the following, but it did not work:

df.iloc[:,0:df['5'].values]

Body:
Recreate your dataframe

df=pd.DataFrame([x[:x[5]] for x in df.values]).fillna(0)
df
Out[184]:
   0  1    2    3
0  1  3  4.0  0.0
1  3  8  9.0  3.0
2  2  2  0.0  0.0


问:
how to open file sound wav in javascript
Following is js the code to open an .mp3 file which works

```<code><script>
var audio = new Audio('Sound/Ring10.mp3');
audio.play();
</script>
</code>```

What is the js code to open .wav file format?

答:
Did you try</p>

```<code><script>
var audio = new Audio('Sound/Wavefile.wav');
audio.play();
</script>
</code>```

Body:
Following is js the code to open an .mp3 file which works

What is the js code to open .wav file format?

Body:
Did you try

<script>
var audio = new Audio('Sound/Wavefile.wav');
audio.play();
</script>


问:
Create a 12 Character Secret
I need to create some secret 12 character string in C#. It can only have regular latin characters plus digits.

Any ideas of best practices?

Thanks

答:
Here's a good article you could use. It's based on the RNGCryptoServiceProvider which is what needs to be used for ensuring real randomness. If you don't want special characters just remove the PASSWORD_CHARS_SPECIAL array used in the code. Example:

```<code>using System;
using System.Security.Cryptography;

public class RandomPassword
{
    // Define default min and max password lengths.
    private static int DEFAULT_MIN_PASSWORD_LENGTH = 8;
    private static int DEFAULT_MAX_PASSWORD_LENGTH = 10;

    // Define supported password characters divided into groups.
    // You can add (or remove) characters to (from) these groups.
    private static string PASSWORD_CHARS_LCASE = "abcdefgijkmnopqrstwxyz";
    private static string PASSWORD_CHARS_UCASE = "ABCDEFGHJKLMNPQRSTWXYZ";
    private static string PASSWORD_CHARS_NUMERIC = "23456789";

    /// <summary>
    /// Generates a random password.
    /// </summary>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    /// <remarks>
    /// The length of the generated password will be determined at
    /// random. It will be no shorter than the minimum default and
    /// no longer than maximum default.
    /// </remarks>
    public static string Generate()
    {
        return Generate(DEFAULT_MIN_PASSWORD_LENGTH,
                        DEFAULT_MAX_PASSWORD_LENGTH);
    }

    /// <summary>
    /// Generates a random password of the exact length.
    /// </summary>
    /// <param name="length">
    /// Exact password length.
    /// </param>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    public static string Generate(int length)
    {
        return Generate(length, length);
    }

    /// <summary>
    /// Generates a random password.
    /// </summary>
    /// <param name="minLength">
    /// Minimum password length.
    /// </param>
    /// <param name="maxLength">
    /// Maximum password length.
    /// </param>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    /// <remarks>
    /// The length of the generated password will be determined at
    /// random and it will fall with the range determined by the
    /// function parameters.
    /// </remarks>
    public static string Generate(int minLength,
                                  int maxLength)
    {
        // Make sure that input parameters are valid.
        if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
            return null;

        // Create a local array containing supported password characters
        // grouped by types. You can remove character groups from this
        // array, but doing so will weaken the password strength.
        char[][] charGroups = new char[][]
        {
            PASSWORD_CHARS_LCASE.ToCharArray(),
            PASSWORD_CHARS_UCASE.ToCharArray(),
            PASSWORD_CHARS_NUMERIC.ToCharArray(),
        };

        // Use this array to track the number of unused characters in each
        // character group.
        int[] charsLeftInGroup = new int[charGroups.Length];

        // Initially, all characters in each group are not used.
        for (int i = 0; i < charsLeftInGroup.Length; i++)
            charsLeftInGroup[i] = charGroups[i].Length;

        // Use this array to track (iterate through) unused character groups.
        int[] leftGroupsOrder = new int[charGroups.Length];

        // Initially, all character groups are not used.
        for (int i = 0; i < leftGroupsOrder.Length; i++)
            leftGroupsOrder[i] = i;

        // Because we cannot use the default randomizer, which is based on the
        // current time (it will produce the same "random" number within a
        // second), we will use a random number generator to seed the
        // randomizer.

        // Use a 4-byte array to fill it with random bytes and convert it then
        // to an integer value.
        byte[] randomBytes = new byte[4];

        // Generate 4 random bytes.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(randomBytes);

        // Convert 4 bytes into a 32-bit integer value.
        int seed = (randomBytes[0] & 0x7f) << 24 |
                    randomBytes[1] << 16 |
                    randomBytes[2] << 8 |
                    randomBytes[3];

        // Now, this is real randomization.
        Random random = new Random(seed);

        // This array will hold password characters.
        char[] password = null;

        // Allocate appropriate memory for the password.
        if (minLength < maxLength)
            password = new char[random.Next(minLength, maxLength + 1)];
        else
            password = new char[minLength];

        // Index of the next character to be added to password.
        int nextCharIdx;

        // Index of the next character group to be processed.
        int nextGroupIdx;

        // Index which will be used to track not processed character groups.
        int nextLeftGroupsOrderIdx;

        // Index of the last non-processed character in a group.
        int lastCharIdx;

        // Index of the last non-processed group.
        int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;

        // Generate password characters one at a time.
        for (int i = 0; i < password.Length; i++)
        {
            // If only one character group remained unprocessed, process it;
            // otherwise, pick a random character group from the unprocessed
            // group list. To allow a special character to appear in the
            // first position, increment the second parameter of the Next
            // function call by one, i.e. lastLeftGroupsOrderIdx + 1.
            if (lastLeftGroupsOrderIdx == 0)
                nextLeftGroupsOrderIdx = 0;
            else
                nextLeftGroupsOrderIdx = random.Next(0,
                                                     lastLeftGroupsOrderIdx);

            // Get the actual index of the character group, from which we will
            // pick the next character.
            nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];

            // Get the index of the last unprocessed characters in this group.
            lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;

            // If only one unprocessed character is left, pick it; otherwise,
            // get a random character from the unused character list.
            if (lastCharIdx == 0)
                nextCharIdx = 0;
            else
                nextCharIdx = random.Next(0, lastCharIdx + 1);

            // Add this character to the password.
            password[i] = charGroups[nextGroupIdx][nextCharIdx];

            // If we processed the last character in this group, start over.
            if (lastCharIdx == 0)
                charsLeftInGroup[nextGroupIdx] =
                                          charGroups[nextGroupIdx].Length;
            // There are more unprocessed characters left.
            else
            {
                // Swap processed character with the last unprocessed character
                // so that we don't pick it until we process all characters in
                // this group.
                if (lastCharIdx != nextCharIdx)
                {
                    char temp = charGroups[nextGroupIdx][lastCharIdx];
                    charGroups[nextGroupIdx][lastCharIdx] =
                                charGroups[nextGroupIdx][nextCharIdx];
                    charGroups[nextGroupIdx][nextCharIdx] = temp;
                }
                // Decrement the number of unprocessed characters in
                // this group.
                charsLeftInGroup[nextGroupIdx]--;
            }

            // If we processed the last group, start all over.
            if (lastLeftGroupsOrderIdx == 0)
                lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
            // There are more unprocessed groups left.
            else
            {
                // Swap processed group with the last unprocessed group
                // so that we don't pick it until we process all groups.
                if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
                {
                    int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
                    leftGroupsOrder[lastLeftGroupsOrderIdx] =
                                leftGroupsOrder[nextLeftGroupsOrderIdx];
                    leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
                }
                // Decrement the number of unprocessed groups.
                lastLeftGroupsOrderIdx--;
            }
        }
        return new string(password);
    }
}

class Program
{
    public static void Main()
    {
        Console.WriteLine(RandomPassword.Generate(12));
    }
}
</code>```

Title: Create a 12 Character Secret

Body:
Here's a good article you could use. It's based on the RNGCryptoServiceProvider which is what needs to be used for ensuring real randomness. If you don't want special characters just remove the PASSWORD_CHARS_SPECIAL array used in the code. Example:

using System;
using System.Security.Cryptography;

public class RandomPassword
{
    // Define default min and max password lengths.
    private static int DEFAULT_MIN_PASSWORD_LENGTH = 8;
    private static int DEFAULT_MAX_PASSWORD_LENGTH = 10;

    // Define supported password characters divided into groups.
    // You can add (or remove) characters to (from) these groups.
    private static string PASSWORD_CHARS_LCASE = "abcdefgijkmnopqrstwxyz";
    private static string PASSWORD_CHARS_UCASE = "ABCDEFGHJKLMNPQRSTWXYZ";
    private static string PASSWORD_CHARS_NUMERIC = "23456789";

    /// <summary>
    /// Generates a random password.
    /// </summary>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    /// <remarks>
    /// The length of the generated password will be determined at
    /// random. It will be no shorter than the minimum default and
    /// no longer than maximum default.
    /// </remarks>
    public static string Generate()
    {
        return Generate(DEFAULT_MIN_PASSWORD_LENGTH,
                        DEFAULT_MAX_PASSWORD_LENGTH);
    }

    /// <summary>
    /// Generates a random password of the exact length.
    /// </summary>
    /// <param name="length">
    /// Exact password length.
    /// </param>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    public static string Generate(int length)
    {
        return Generate(length, length);
    }

    /// <summary>
    /// Generates a random password.
    /// </summary>
    /// <param name="minLength">
    /// Minimum password length.
    /// </param>
    /// <param name="maxLength">
    /// Maximum password length.
    /// </param>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    /// <remarks>
    /// The length of the generated password will be determined at
    /// random and it will fall with the range determined by the
    /// function parameters.
    /// </remarks>
    public static string Generate(int minLength,
                                  int maxLength)
    {
        // Make sure that input parameters are valid.
        if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
            return null;

        // Create a local array containing supported password characters
        // grouped by types. You can remove character groups from this
        // array, but doing so will weaken the password strength.
        char[][] charGroups = new char[][]
        {
            PASSWORD_CHARS_LCASE.ToCharArray(),
            PASSWORD_CHARS_UCASE.ToCharArray(),
            PASSWORD_CHARS_NUMERIC.ToCharArray(),
        };

        // Use this array to track the number of unused characters in each
        // character group.
        int[] charsLeftInGroup = new int[charGroups.Length];

        // Initially, all characters in each group are not used.
        for (int i = 0; i < charsLeftInGroup.Length; i++)
            charsLeftInGroup[i] = charGroups[i].Length;

        // Use this array to track (iterate through) unused character groups.
        int[] leftGroupsOrder = new int[charGroups.Length];

        // Initially, all character groups are not used.
        for (int i = 0; i < leftGroupsOrder.Length; i++)
            leftGroupsOrder[i] = i;

        // Because we cannot use the default randomizer, which is based on the
        // current time (it will produce the same "random" number within a
        // second), we will use a random number generator to seed the
        // randomizer.

        // Use a 4-byte array to fill it with random bytes and convert it then
        // to an integer value.
        byte[] randomBytes = new byte[4];

        // Generate 4 random bytes.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(randomBytes);

        // Convert 4 bytes into a 32-bit integer value.
        int seed = (randomBytes[0] & 0x7f) << 24 |
                    randomBytes[1] << 16 |
                    randomBytes[2] << 8 |
                    randomBytes[3];

        // Now, this is real randomization.
        Random random = new Random(seed);

        // This array will hold password characters.
        char[] password = null;

        // Allocate appropriate memory for the password.
        if (minLength < maxLength)
            password = new char[random.Next(minLength, maxLength + 1)];
        else
            password = new char[minLength];

        // Index of the next character to be added to password.
        int nextCharIdx;

        // Index of the next character group to be processed.
        int nextGroupIdx;

        // Index which will be used to track not processed character groups.
        int nextLeftGroupsOrderIdx;

        // Index of the last non-processed character in a group.
        int lastCharIdx;

        // Index of the last non-processed group.
        int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;

        // Generate password characters one at a time.
        for (int i = 0; i < password.Length; i++)
        {
            // If only one character group remained unprocessed, process it;
            // otherwise, pick a random character group from the unprocessed
            // group list. To allow a special character to appear in the
            // first position, increment the second parameter of the Next
            // function call by one, i.e. lastLeftGroupsOrderIdx + 1.
            if (lastLeftGroupsOrderIdx == 0)
                nextLeftGroupsOrderIdx = 0;
            else
                nextLeftGroupsOrderIdx = random.Next(0,
                                                     lastLeftGroupsOrderIdx);

            // Get the actual index of the character group, from which we will
            // pick the next character.
            nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];

            // Get the index of the last unprocessed characters in this group.
            lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;

            // If only one unprocessed character is left, pick it; otherwise,
            // get a random character from the unused character list.
            if (lastCharIdx == 0)
                nextCharIdx = 0;
            else
                nextCharIdx = random.Next(0, lastCharIdx + 1);

            // Add this character to the password.
            password[i] = charGroups[nextGroupIdx][nextCharIdx];

            // If we processed the last character in this group, start over.
            if (lastCharIdx == 0)
                charsLeftInGroup[nextGroupIdx] =
                                          charGroups[nextGroupIdx].Length;
            // There are more unprocessed characters left.
            else
            {
                // Swap processed character with the last unprocessed character
                // so that we don't pick it until we process all characters in
                // this group.
                if (lastCharIdx != nextCharIdx)
                {
                    char temp = charGroups[nextGroupIdx][lastCharIdx];
                    charGroups[nextGroupIdx][lastCharIdx] =
                                charGroups[nextGroupIdx][nextCharIdx];
                    charGroups[nextGroupIdx][nextCharIdx] = temp;
                }
                // Decrement the number of unprocessed characters in
                // this group.
                charsLeftInGroup[nextGroupIdx]--;
            }

            // If we processed the last group, start all over.
            if (lastLeftGroupsOrderIdx == 0)
                lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
            // There are more unprocessed groups left.
            else
            {
                // Swap processed group with the last unprocessed group
                // so that we don't pick it until we process all groups.
                if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
                {
                    int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
                    leftGroupsOrder[lastLeftGroupsOrderIdx] =
                                leftGroupsOrder[nextLeftGroupsOrderIdx];
                    leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
                }
                // Decrement the number of unprocessed groups.
                lastLeftGroupsOrderIdx--;
            }
        }
        return new string(password);
    }
}

class Program
{
    public static void Main()
    {
        Console.WriteLine(RandomPassword.Generate(12));
    }
}


问:
How is this dispatch function coming from props?
I'm trying to learn from reading this app's code, and I am confused how you get dispatch from the props in this line of code:

```<code> _handleSubmit(e) {
    e.preventDefault();

    const { email, password } = this.refs;
    const { dispatch } = this.props;

    dispatch(Actions.signIn(email.value, password.value));
  }
</code>```

https://github.com/bigardone/phoenix-trello/blob/master/web/static/js/views/sessions/new.js#L17

Hoping someone can explain how calling this.props will return a dispatch?

答:
react-redux is a library that helps components get values from the Redux store in a predictable and performant way. The main tool it provides is a function called connect, which wraps Redux components providing them with store values as props. The key part of the code you link to is at the bottom: https://github.com/bigardone/phoenix-trello/blob/master/web/static/js/views/sessions/new.js#L70-L74.

Say you have a value in the Redux store named counter. You want your component CounterDisplay to know about this value, and update when it changes:

class CounterDisplay extends Component {
  render () {
    const { counter, dispatch } = this.props
    return (

{counter}

    )
  }
}
```

<p>Those variables are going to be undefined unless you've explicitly put the values into props the 'old fashioned way':</p>

<pre class="lang-js prettyprint-override"><code><CounterDisplay counter={1} dispatch={() => {}} />
</code>```

That's where connect comes in. It knows about the Redux store (often using another component called Provider) and can place values from it into the props of the component it's wrapping. It returns what's called a Higher Order Component (HOC): one that wraps another to perform a specific function, in this case connection to the store.

Here's how we'd get the counter value into props:

function mapStateToProps (state) {
  // Slightly confusingly, here `state` means the entire application
  // state being tracked by Redux... *not* CounterDisplay's state
  return {
    counter: state.counter
  }
}

export default connect(mapStateToProps)(CounterDisplay)
```

So instead of exporting CounterDisplay itself, we export the HOC. In addition to counter, connect will also automatically insert the dispatch function into props so we can make use of it in the component. That's the behaviour you're seeing in the source you're reviewing.

Body:
I'm trying to learn from reading this app's code, and I am confused how you get dispatch from the props in this line of code:

 _handleSubmit(e) {
    e.preventDefault();

    const { email, password } = this.refs;
    const { dispatch } = this.props;

    dispatch(Actions.signIn(email.value, password.value));
  }

https://github.com/bigardone/phoenix-trello/blob/master/web/static/js/views/sessions/new.js#L17

Hoping someone can explain how calling this.props will return a dispatch?

Body:
react-redux is a library that helps components get values from the Redux store in a predictable and performant way. The main tool it provides is a function called connect, which wraps Redux components providing them with store values as props. The key part of the code you link to is at the bottom: https://github.com/bigardone/phoenix-trello/blob/master/web/static/js/views/sessions/new.js#L70-L74.

Say you have a value in the Redux store named counter. You want your component CounterDisplay to know about this value, and update when it changes:

class CounterDisplay extends Component {
  render () {
    const { counter, dispatch } = this.props
    return (
      <div>{counter}</div>
    )
  }
}

Those variables are going to be undefined unless you've explicitly put the values into props the 'old fashioned way':

<CounterDisplay counter={1} dispatch={() => {}} />

That's where connect comes in. It knows about the Redux store (often using another component called Provider) and can place values from it into the props of the component it's wrapping. It returns what's called a Higher Order Component (HOC): one that wraps another to perform a specific function, in this case connection to the store.

Here's how we'd get the counter value into props:

function mapStateToProps (state) {
  // Slightly confusingly, here `state` means the entire application
  // state being tracked by Redux... *not* CounterDisplay's state
  return {
    counter: state.counter
  }
}

export default connect(mapStateToProps)(CounterDisplay)

So instead of exporting CounterDisplay itself, we export the HOC. In addition to counter, connect will also automatically insert the dispatch function into props so we can make use of it in the component. That's the behaviour you're seeing in the source you're reviewing.


问:
Scala: List[Future] to Future[List] disregarding failed futures
I'm looking for a way to convert an arbitrary length list of Futures to a Future of List. I'm using Playframework, so ultimately, what I really want is a Future[Result], but to make things simpler, let's just say Future[List[Int]] The normal way to do this would be to use Future.sequence(...) but there's a twist... The list I'm given usually has around 10-20 futures in it, and it's not uncommon for one of those futures to fail (they are making external web service requests).

Instead of having to retry all of them in the event that one of them fails, I'd like to be able to get at the ones that succeeded and return those.

For example, doing the following doesn't work:

```<code>import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Success
import scala.util.Failure

val listOfFutures = Future.successful(1) :: Future.failed(new Exception("Failure")) ::
                    Future.successful(3) :: Nil

val futureOfList = Future.sequence(listOfFutures)

futureOfList onComplete {
  case Success(x) => println("Success!!! " + x)
  case Failure(ex) => println("Failed !!! " + ex)
}

scala> Failed !!! java.lang.Exception: Failure
</code>```

Instead of getting the only the exception, I'd like to be able to pull the 1 and 3 out of there. I tried using Future.fold, but that apparently just calls Future.sequence behind the scenes.

答:
Scala 2.12 has an improvement on Future.transform that lends itself in an anwser with less codes.

```<code>val futures = Seq(Future{1},Future{throw new Exception})

// instead of `map` and `recover`, use `transform`
val seq = Future.sequence(futures.map(_.transform(Success(_))))

val successes = seq.map(_.collect{case Success(x)=>x})
successes
//res1: Future[Seq[Int]] = Future(Success(List(1)))

val failures = seq.map(_.collect{case Failure(x)=>x})
failures
//res2: Future[Seq[Throwable]] = Future(Success(List(java.lang.Exception)))
</code>```

Body:
I'm looking for a way to convert an arbitrary length list of Futures to a Future of List. I'm using Playframework, so ultimately, what I really want is a Future[Result], but to make things simpler, let's just say Future[List[Int]] The normal way to do this would be to use Future.sequence(...) but there's a twist... The list I'm given usually has around 10-20 futures in it, and it's not uncommon for one of those futures to fail (they are making external web service requests).

Instead of having to retry all of them in the event that one of them fails, I'd like to be able to get at the ones that succeeded and return those.

For example, doing the following doesn't work:

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.Success
import scala.util.Failure

val listOfFutures = Future.successful(1) :: Future.failed(new Exception("Failure")) ::
                    Future.successful(3) :: Nil

val futureOfList = Future.sequence(listOfFutures)

futureOfList onComplete {
  case Success(x) => println("Success!!! " + x)
  case Failure(ex) => println("Failed !!! " + ex)
}

scala> Failed !!! java.lang.Exception: Failure

Instead of getting the only the exception, I'd like to be able to pull the 1 and 3 out of there. I tried using Future.fold, but that apparently just calls Future.sequence behind the scenes.

Body:
Scala 2.12 has an improvement on Future.transform that lends itself in an anwser with less codes.

val futures = Seq(Future{1},Future{throw new Exception})

// instead of `map` and `recover`, use `transform`
val seq = Future.sequence(futures.map(_.transform(Success(_))))

val successes = seq.map(_.collect{case Success(x)=>x})
successes
//res1: Future[Seq[Int]] = Future(Success(List(1)))

val failures = seq.map(_.collect{case Failure(x)=>x})
failures
//res2: Future[Seq[Throwable]] = Future(Success(List(java.lang.Exception)))


问:
Automating- Appending two text files to create 1 Excel file daily
I have two files that come in daily to a shared drive. When they are posted, they come in with the current date as part of the file name. example ( dataset1_12517.txt and dataset2_12517.txt) the next day it posts it will be (dataset1_12617.txt and so on). They are pipe delimited files if that matters.

I am trying to automate a daily merge of these two files to a single excel file that will be overwritten with each merge (file name remains the same) so my tableau dashboard can read the output without having to make a new connection daily. The tricky part is the file names will change daily, but they follow a specific naming convention.

I have access to R Studio. I have not started writing code yet so looking for a place to start or a better solution.

答:
On a Window machine, use the copy or xcopy command lines. There are several variations on how to do it. The jist of it though is that if you supply the right switches, the source file will append to the destination file.

I like using xcopy for this. Supply the destination file name and then a list of source files.

This becomes a batch file and you can run it as a scheduled task or on demand.

This is roughly what it would look it. You may need to check the online docs to choose the right parameter switches.

```<code>xcopy C:\SRC\souce_2010235.txt newfile.txt /s
</code>```

As you play with it, you may even try using a wildcard approach.

```<code>xcopy C:\SRC\*.txt newfile.txt /s
</code>```

See Getting XCOPY to concatenate (append) for more details.

Body:
On a Window machine, use the copy or xcopy command lines. There are several variations on how to do it. The jist of it though is that if you supply the right switches, the source file will append to the destination file.

I like using xcopy for this. Supply the destination file name and then a list of source files.

This becomes a batch file and you can run it as a scheduled task or on demand.

This is roughly what it would look it. You may need to check the online docs to choose the right parameter switches.

xcopy C:\SRC\souce_2010235.txt newfile.txt /s

As you play with it, you may even try using a wildcard approach.

xcopy C:\SRC\*.txt newfile.txt /s

See Getting XCOPY to concatenate (append) for more details.


答:
To expand on Rahul's answer:

PHP is server side meaning the page is not rendered until all of the PHP has resolved on the server.

That's why his answer works. The server gets

```<code>echo "<img src='/pictures/".$ANSWER.".jpg' />";
</code>```

resolves $ANSWER to whatever the variable is set to and provides to the client side:

```<code><img src='/pictures/my_answer.jpg' />
</code>```

Title: Is it possible to use a variable as part of an image URL?

Body:
To expand on Rahul's answer:

PHP is server side meaning the page is not rendered until all of the PHP has resolved on the server.

That's why his answer works. The server gets

echo "<img src='/pictures/".$ANSWER.".jpg' />";

resolves $ANSWER to whatever the variable is set to and provides to the client side:

<img src='/pictures/my_answer.jpg' />


问:
laravel undefined variable: itinerary
I can't seem to find the variable itinerary from my update function in my controller. What seems to be the problem for this?

Error says: Undefined variable: itinerary (View: C:\xampp\htdocs\project_name\resources\views\Agent\edit.blade.php)

AgentsController update function

```<code>public function update(Request $request, $p_id){
    $this->validate($request, [
        'packageName' => 'required',
        'adultPrice' => 'required',
        'childPrice' => 'required',
        'infantPrice' => 'required',
        'excessPrice' => 'required',
        'type' => 'required',
        'inclusions' => 'required',
        'additionalInfo' => 'required',
        'reminders' => 'required',
        'photo' => 'required',
        'tags' => 'required',
        'noOfDays' => 'required',
        'day' => 'required',
        'time' => 'required',
        'destination' => 'required'
    ]);

    $packages = Packages::find($p_id);
    $packages->packageName = $request->input('packageName');
    $packages->adultPrice = $request->input('adultPrice');
    $packages->childPrice = $request->input('childPrice');
    $packages->infantPrice = $request->input('infantPrice');
    $packages->excessPrice = $request->input('excessPrice');
    $packages->type = $request->input('type');
    $packages->inclusions = $request->input('inclusions');
    $packages->additionalInfo = $request->input('additionalInfo');
    $packages->reminders = $request->input('reminders');
    $packages->photo = $request->input('photo');
    $packages->tags = $request->input('tags');
    $packages->save();

    $itinerary = Itinerary::find($p_id);
    if($itinerary->p_id == $packages->p_id){
    $itinerary->noOfDays = $request->input('noOfDays');
    $itinerary->day = $request->input('day');
    $itinerary->time = $request->input('time');
    $itinerary->destination = $request->input('destination');
    $itinerary->save();

    return redirect('Agent/Packages')->with('success', 'Updated');
    }
}
</code>```

edit.blade.php where the error is located

```<code>{{!!Form::open(array('class' => 'form-horizontal', 'method' => 'post', 'action' => array('AgentsController@update', $packages->p_id, $itinerary->p_id)))!!}}
</code>```

Itinerary.php Model

```<code><?php
   namespace App;

   use Illuminate\Database\Eloquent\Model;

   class Itinerary extends Model{
      public $fillable = [
        'p_id',
        'noOfDays',
        'day',
        'time',
        'destination'
   ];

   protected $primaryKey = 'i_id';
   }
?>
</code>```

Edit function

```<code>public function edit($p_id){
   $packages = Packages::find($p_id);
   $itinerary = Itinerary::find($p_id);

   return View::make('\Agent\Edit', ['packages' => $packages, 'itineraries' => $itinerary]);
}
</code>```

答:
The way you pass the data is wrong.

Documentation

There are few ways you can pass. Examples :

1 -
return View::make('Agent.edit', ['packages' => $packages, 'itinerary' => $itinerary]);

2 - return View::make('Agent.edit')->with(['packages' => $packages, 'itinerary' => $itinerary]);

3 - return View::make('Agent.edit')->with('packages', $packages)->with('itinerary', $itinerary);

Title: laravel undefined variable: itinerary

Body:
I can't seem to find the variable itinerary from my update function in my controller. What seems to be the problem for this?

Error says: Undefined variable: itinerary (View: C:\xampp\htdocs\project_name\resources\views\Agent\edit.blade.php)

AgentsController update function

public function update(Request $request, $p_id){
    $this->validate($request, [
        'packageName' => 'required',
        'adultPrice' => 'required',
        'childPrice' => 'required',
        'infantPrice' => 'required',
        'excessPrice' => 'required',
        'type' => 'required',
        'inclusions' => 'required',
        'additionalInfo' => 'required',
        'reminders' => 'required',
        'photo' => 'required',
        'tags' => 'required',
        'noOfDays' => 'required',
        'day' => 'required',
        'time' => 'required',
        'destination' => 'required'
    ]);

    $packages = Packages::find($p_id);
    $packages->packageName = $request->input('packageName');
    $packages->adultPrice = $request->input('adultPrice');
    $packages->childPrice = $request->input('childPrice');
    $packages->infantPrice = $request->input('infantPrice');
    $packages->excessPrice = $request->input('excessPrice');
    $packages->type = $request->input('type');
    $packages->inclusions = $request->input('inclusions');
    $packages->additionalInfo = $request->input('additionalInfo');
    $packages->reminders = $request->input('reminders');
    $packages->photo = $request->input('photo');
    $packages->tags = $request->input('tags');
    $packages->save();

    $itinerary = Itinerary::find($p_id);
    if($itinerary->p_id == $packages->p_id){
    $itinerary->noOfDays = $request->input('noOfDays');
    $itinerary->day = $request->input('day');
    $itinerary->time = $request->input('time');
    $itinerary->destination = $request->input('destination');
    $itinerary->save();

    return redirect('Agent/Packages')->with('success', 'Updated');
    }
}

edit.blade.php where the error is located

{{!!Form::open(array('class' => 'form-horizontal', 'method' => 'post', 'action' => array('AgentsController@update', $packages->p_id, $itinerary->p_id)))!!}}

Itinerary.php Model

<?php
   namespace App;

   use Illuminate\Database\Eloquent\Model;

   class Itinerary extends Model{
      public $fillable = [
        'p_id',
        'noOfDays',
        'day',
        'time',
        'destination'
   ];

   protected $primaryKey = 'i_id';
   }
?>

Edit function

public function edit($p_id){
   $packages = Packages::find($p_id);
   $itinerary = Itinerary::find($p_id);

   return View::make('\Agent\Edit', ['packages' => $packages, 'itineraries' => $itinerary]);
}


问:
CascadeClassifier.load() error in release only
I want to ask about cascadeclassfier load doesn't work in release.
I using Microsoft Visual Studio 2010 and OpenCV 2.4.7.

my code:

```<code>CascadeClassifier cascade;

if(!cascade.load("D:/data/training.xml"))
{
    printf("Error load XML!\n");
    return -1;
}
</code>```

Things i've tried so far:

Tried to specify the path manually using ""

Tried to use / or \ in the path

Tried to give user permission

Tried to call the xml without using absolute path

Tried to use many kind of codes i've found when searching this error

Tried to seperate the xml by creating a new folder for them

Additional Information:

Running in debug mode work 100% perfectly

Running in release while using visual studio trigger a break

Running using the exe created while building only show "Error load XML!"

i really confused right now, so i decided to ask..
Thanks before.

答: I've had similar problems when switch from Debug to Release Mode. I had copy config from Debug to Release and mistake at  Linker > Input > Additional Dependencies. And I had fix this problem by using opencv_world320d.lib for Debug mode and opencv_world320.lib for Release mode.

Body:
I want to ask about cascadeclassfier load doesn't work in release.
I using Microsoft Visual Studio 2010 and OpenCV 2.4.7.

my code:

CascadeClassifier cascade;

if(!cascade.load("D:/data/training.xml"))
{
    printf("Error load XML!\n");
    return -1;
}

Things i've tried so far:

Tried to specify the path manually using ""

Tried to use / or \ in the path

Tried to give user permission

Tried to call the xml without using absolute path

Tried to use many kind of codes i've found when searching this error

Tried to seperate the xml by creating a new folder for them

Additional Information:

Running in debug mode work 100% perfectly

Running in release while using visual studio trigger a break

Running using the exe created while building only show "Error load XML!"

i really confused right now, so i decided to ask..
Thanks before.


问:
Dealing with Views in Phalcon Controllers
I am working on a newly created Phalcon project, and I don't really know how to actually use multiples views.

What is the entry point? I don't really know when each method in the controller is called, under which conditions, etc.

Where is the control flow defined? is it based in the name of the view? or is there a place where you can register them?

答:
The application begins with the routing stage. From there you grab the controller and action from the router, and feed it to the dispatcher. You set the view then call the execute the dispatcher so it access your controller's action. From there you create a new response object and set its contents equal to the view requests, and finally send the response to the client's browser -- both the content and the headers. It's a good idea to do this through Phalcon rather than echoing directly or using PHP's header(), so it's only done at the moment you call $response->send(); This is best practice because it allows you to create tests, such as in phpunit, so you can test for the existence of headers, or content, while moving off to the next response and header without actually sending anything so you can test stuff. Same idea with exit; in code, is best to avoid so you can write tests and move on to the next test without your tests aborting on the first test due to the existence of exit.

As far as how the Phalcon application works, and in what steps, it's much easier to follow the flow by looking at manual bootstrapping:
https://docs.phalconphp.com/en/3.2/application#manual-bootstrapping

At the heart of Phalcon is the DI, the Dependency Injection container. This allows you to create services, and store them on the DI so services can access each other.  You can create your own services and store them under your own name on the DI, there's nothing special about the names used. However depending on the areas of Phalcon you used, certain services on the DI are assumed like "db" for interacting with your database. Note services can be set as either shared or not shared on the DI. Shared means it implements singleton and keeps the object alive for all calls afterwards. If you use getShared, it does a similar thing even if it wasn't initially a shared service. The getShared method is considered bad practice and the Phalcon team is talking about removing the method in future Phalcon versions. Please rely on setShared instead.

Regarding multiple views, you can start with $this->view->disable(); from within the controller. This allows you to disable a view so you don't get any content generated to begin with from within a controller so you can follow how views work from within controllers.

Phalcon assumes every controller has a matching view under /someController/someView followed by whatever extension you registered on the view, which defaults to .volt but can also be set to use .phtml or .php.

These two correspond to:

Phalcon\Mvc\View\Engine\Php and Phalcon\Mvc\View\Engine\Volt

Note that you DON'T specify the extension when looking for a template to render, Phalcon adds this for you

Phalcon also uses a root view template index.volt, if it exists, for all interactions with the view so you can use things like the same doctype for all responses, making your life easier.

Phalcon also offers you partials, so from within a view you can render a partial like breadcrumbs, or a header or footer which you'd otherwise be copy-pasting into each template.  This allows you to manage all pages from the same template so you're not repeating yourself.

As far as which view class you use within Phalcon, there's two main choices:

Phalcon\Mvc\View and Phalcon\Mvc\View\Simple

While similar, Phalcon\Mvc\View gives you a multiple level hierarchy as described before with a main template, and a controller-action based template as well as some other fancy features. As far as Phalcon\Mvc\View\Simple, it's much more lightweight and is a single level.

You should be familiar with hierarchical rendering:

https://docs.phalconphp.com/en/3.2/views#hierarchical-rendering

The idea is with Phalcon\Mvc\View that you have a Main Layout (if this template exists) usually stored in /views/index.volt, which is used on every page so you can toss in your doctypes, the title (which you would set with a variable the view passed in), etc. You'd have a Controller Layout, which would be stored under /views/layouts.myController.volt and used for every action within a controller (if this template exists), finally you'd have the Action Layout which is used for the specific action of the controller in /views/myController/myAction.volt.

There are all types of ways you can break from Phalcon's default behavior. You can do the earlier stated $this->view->disable(); so you can do everything manually yourself so Phalcon doesn't assume anything about the view template. You can also use ->pick to pick which template to use if it's going to be different than the controller and action it's ran in.

You can also return a response object from within a controller and Phalcon will not try to render the templates and use the response object instead.

For example you might want to do:

```<code>return $this->response->redirect('index/index');
</code>```

This would redirect the user's browser to said page. You could also do a forward instead which would be used internally within Phalcon to access a different controller and/or action.

You can config the directory the views are stored with setViewsDir. You can also do this from within the controller itself, or even within the view as late as you want, if you have some exceptions due to a goofy directory structure.

You can do things like use $this->view->setTemplateBefore('common') or $this->view->setTemplateAfter('common'); so you can have intermediate templates.

At the heart of the view hierarchy is <?php echo $this->getContent(); ?> or {{ content() }} if you're using Volt. Even if you're using Volt, it gets parsed by Phalcon and generates the PHP version with $this->getContent(), storing it in your /cache/ directory, before it is executed.

The idea with "template before" is that it's optional if you need another layer of hierarchy between your main template and your controller template. Same idea with "template after" etc. I would advise against using template before and after as they are confusing and partials are better suited for the task.

It all depends on how you want to organize your application structure.

Note you can also swap between your main template to another main template if you need to swap anything major. You could also just toss in an "if" statement into your main template to decide what to do based on some condition, etc.

With all that said, you should be able to read the documentation and make better sense of how to utilize it:

https://docs.phalconphp.com/en/3.2/api/Phalcon_Mvc_View

Body:
The application begins with the routing stage. From there you grab the controller and action from the router, and feed it to the dispatcher. You set the view then call the execute the dispatcher so it access your controller's action. From there you create a new response object and set its contents equal to the view requests, and finally send the response to the client's browser -- both the content and the headers. It's a good idea to do this through Phalcon rather than echoing directly or using PHP's header(), so it's only done at the moment you call $response->send(); This is best practice because it allows you to create tests, such as in phpunit, so you can test for the existence of headers, or content, while moving off to the next response and header without actually sending anything so you can test stuff. Same idea with exit; in code, is best to avoid so you can write tests and move on to the next test without your tests aborting on the first test due to the existence of exit.

As far as how the Phalcon application works, and in what steps, it's much easier to follow the flow by looking at manual bootstrapping:
https://docs.phalconphp.com/en/3.2/application#manual-bootstrapping

At the heart of Phalcon is the DI, the Dependency Injection container. This allows you to create services, and store them on the DI so services can access each other.  You can create your own services and store them under your own name on the DI, there's nothing special about the names used. However depending on the areas of Phalcon you used, certain services on the DI are assumed like "db" for interacting with your database. Note services can be set as either shared or not shared on the DI. Shared means it implements singleton and keeps the object alive for all calls afterwards. If you use getShared, it does a similar thing even if it wasn't initially a shared service. The getShared method is considered bad practice and the Phalcon team is talking about removing the method in future Phalcon versions. Please rely on setShared instead.

Regarding multiple views, you can start with $this->view->disable(); from within the controller. This allows you to disable a view so you don't get any content generated to begin with from within a controller so you can follow how views work from within controllers.

Phalcon assumes every controller has a matching view under /someController/someView followed by whatever extension you registered on the view, which defaults to .volt but can also be set to use .phtml or .php.

These two correspond to:

Phalcon\Mvc\View\Engine\Php and Phalcon\Mvc\View\Engine\Volt

Note that you DON'T specify the extension when looking for a template to render, Phalcon adds this for you

Phalcon also uses a root view template index.volt, if it exists, for all interactions with the view so you can use things like the same doctype for all responses, making your life easier.

Phalcon also offers you partials, so from within a view you can render a partial like breadcrumbs, or a header or footer which you'd otherwise be copy-pasting into each template.  This allows you to manage all pages from the same template so you're not repeating yourself.

As far as which view class you use within Phalcon, there's two main choices:

Phalcon\Mvc\View and Phalcon\Mvc\View\Simple

While similar, Phalcon\Mvc\View gives you a multiple level hierarchy as described before with a main template, and a controller-action based template as well as some other fancy features. As far as Phalcon\Mvc\View\Simple, it's much more lightweight and is a single level.

You should be familiar with hierarchical rendering:

https://docs.phalconphp.com/en/3.2/views#hierarchical-rendering

The idea is with Phalcon\Mvc\View that you have a Main Layout (if this template exists) usually stored in /views/index.volt, which is used on every page so you can toss in your doctypes, the title (which you would set with a variable the view passed in), etc. You'd have a Controller Layout, which would be stored under /views/layouts.myController.volt and used for every action within a controller (if this template exists), finally you'd have the Action Layout which is used for the specific action of the controller in /views/myController/myAction.volt.

There are all types of ways you can break from Phalcon's default behavior. You can do the earlier stated $this->view->disable(); so you can do everything manually yourself so Phalcon doesn't assume anything about the view template. You can also use ->pick to pick which template to use if it's going to be different than the controller and action it's ran in.

You can also return a response object from within a controller and Phalcon will not try to render the templates and use the response object instead.

For example you might want to do:

return $this->response->redirect('index/index');

This would redirect the user's browser to said page. You could also do a forward instead which would be used internally within Phalcon to access a different controller and/or action.

You can config the directory the views are stored with setViewsDir. You can also do this from within the controller itself, or even within the view as late as you want, if you have some exceptions due to a goofy directory structure.

You can do things like use $this->view->setTemplateBefore('common') or $this->view->setTemplateAfter('common'); so you can have intermediate templates.

At the heart of the view hierarchy is <?php echo $this->getContent(); ?> or {{ content() }} if you're using Volt. Even if you're using Volt, it gets parsed by Phalcon and generates the PHP version with $this->getContent(), storing it in your /cache/ directory, before it is executed.

The idea with "template before" is that it's optional if you need another layer of hierarchy between your main template and your controller template. Same idea with "template after" etc. I would advise against using template before and after as they are confusing and partials are better suited for the task.

It all depends on how you want to organize your application structure.

Note you can also swap between your main template to another main template if you need to swap anything major. You could also just toss in an "if" statement into your main template to decide what to do based on some condition, etc.

With all that said, you should be able to read the documentation and make better sense of how to utilize it:

https://docs.phalconphp.com/en/3.2/api/Phalcon_Mvc_View


问:
1 button toggle for multiple texts with id

Hello,

I am trying to make one button to toggle some text, and I want the text to change related to an id.

So 1 button to toggle on/off the text, while the text changes according to a id

Is it possible ?

EDIT :

I have on one side a slideshow with which I can change the image displayed , and on the other side one text about the image current image. I also want to change the text as the same time as the image changes.

I also have a button use for toggle on/off the text and I don't want the text to be displayed when the website load for the first time.

How can text and image change at the same time but the text only be display when the toggle button is hit ?

For the HTML I have :

```<code>  <img class="mySlides" src="img/bouc.jpg" style="width:100%">
  <p class="img-name">BOUC 1</p>
  <div class="txt-div" id="1">
    <p>Text 1</p></p>
  </div>

  <img class="mySlides" src="img/bouc.jpg" style="width:100%">
  <p class="img-name">BOUC 2</p>
  <div class="txt-div" id="2">
    <p>Text 2</p></p>
  </div>

  <button class="chat-button w3-display-left" onclick="plusDivs(-1)"></button>
  <button class="chat-button w3-display-right" onclick="plusDivs(1)"></button>
  <button class="chat-button-txt">Text</button>
</code>```

For the CSS I have :

```<code>.txt-div{
...
display: none;
...
}
</code>```

For the JS I have :

```<code>var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function currentDiv(n) {
  showDivs(slideIndex = n);
}

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName("mySlides");
    var dots = document.getElementsByClassName("img-count");
    var txt = document.getElementsByClassName("txt-div");
    var noms = document.getElementsByClassName("img-name");
  if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length}
  for (i = 0; i < x.length; i++) {
     x[i].style.display = "none";
     dots[i].style.display = "none";
     noms[i].style.display = "none";
  }

  x[slideIndex-1].style.display = "block";
  dots[slideIndex-1].style.display = "block";
  noms[slideIndex-1].style.display = "block";

    $(document).ready(function(){
        $(".chat-button-txt").click(function(){
        $(".txt-div").toggle();
        });
    });
}
</code>```

I don't know how to make the text change as the same time as "x", "dots" and "noms" while only be display when toggle by the "chat-button-txt"

Someone has an idea ?

答:
I found a solution by add anothe class to "mask" the text with the toggle button and the text can change as the same time as images are changing but isn't a "better way" to do so ?

My actual code :

HTML

```<code><div class="cover-txt"></div>
  <img class="mySlides" src="img/bouc.jpg" style="width:100%">
  <p class="img-name">BOUC 1</p>
  <div class="txt-div" id="1">
    <p>Text 1</p>
  </div>

  <img class="mySlides" src="img/bouc.jpg" style="width:100%">
  <p class="img-name">BOUC 2</p>
  <div class="txt-div" id="2">
    <p>Text 2</p>
  </div>

<button class="chat-button w3-display-left" onclick="plusDivs(-1)"></button>
  <button class="chat-button w3-display-right" onclick="plusDivs(1)"></button>
  <button class="chat-button-txt">Text</button>
</code>```

CSS

```<code>.cover-txt{
position: absolute;
background-color: white;
display: block;
top:10%;
left:104%;
width: 22vw;
height: 25vw;
z-index: 999;
}
</code>```

JS

```<code>var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}
function currentDiv(n) {
  showDivs(slideIndex = n);
}

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName("mySlides");
    var dots = document.getElementsByClassName("img-count");
    var txt = document.getElementsByClassName("txt-div");
    var noms = document.getElementsByClassName("img-name");
  if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length}
  for (i = 0; i < x.length; i++) {
     x[i].style.display = "none";
     dots[i].style.display = "none";
     noms[i].style.display = "none";
     txt[i].style.display = "none";
  }

  x[slideIndex-1].style.display = "block";
  dots[slideIndex-1].style.display = "block";
  noms[slideIndex-1].style.display = "block";
  txt[slideIndex-1].style.display = "block";

    $(document).ready(function(){
        $(".chat-button-txt").click(function(){
        $(".cover-txt").toggle();
        });
    });
}
</code>```

I think it's not the best solution but I worked for me. If anyone has something better I'll be glad to read it.

Thank you very much,

Regards,

U

Body:
Hello,

I am trying to make one button to toggle some text, and I want the text to change related to an id.

So 1 button to toggle on/off the text, while the text changes according to a id

Is it possible ?

EDIT :

I have on one side a slideshow with which I can change the image displayed , and on the other side one text about the image current image. I also want to change the text as the same time as the image changes.

I also have a button use for toggle on/off the text and I don't want the text to be displayed when the website load for the first time.

How can text and image change at the same time but the text only be display when the toggle button is hit ?

For the HTML I have :

BOUC 1

Text 1

BOUC 2

Text 2

  <button class="chat-button w3-display-left" onclick="plusDivs(-1)"></button>
  <button class="chat-button w3-display-right" onclick="plusDivs(1)"></button>
  <button class="chat-button-txt">Text</button>

For the CSS I have :

.txt-div{
...
display: none;
...
}

For the JS I have :

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function currentDiv(n) {
  showDivs(slideIndex = n);
}

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName("mySlides");
    var dots = document.getElementsByClassName("img-count");
    var txt = document.getElementsByClassName("txt-div");
    var noms = document.getElementsByClassName("img-name");
  if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length}
  for (i = 0; i < x.length; i++) {
     x[i].style.display = "none";
     dots[i].style.display = "none";
     noms[i].style.display = "none";
  }

  x[slideIndex-1].style.display = "block";
  dots[slideIndex-1].style.display = "block";
  noms[slideIndex-1].style.display = "block";

    $(document).ready(function(){
        $(".chat-button-txt").click(function(){
        $(".txt-div").toggle();
        });
    });
}

I don't know how to make the text change as the same time as "x", "dots" and "noms" while only be display when toggle by the "chat-button-txt"

Someone has an idea ?

Body:
I found a solution by add anothe class to "mask" the text with the toggle button and the text can change as the same time as images are changing but isn't a "better way" to do so ?

My actual code :

HTML

<div class="cover-txt"></div>
  <img class="mySlides" src="img/bouc.jpg" style="width:100%">
  <p class="img-name">BOUC 1</p>
  <div class="txt-div" id="1">
    <p>Text 1</p>
  </div>

  <img class="mySlides" src="img/bouc.jpg" style="width:100%">
  <p class="img-name">BOUC 2</p>
  <div class="txt-div" id="2">
    <p>Text 2</p>
  </div>

<button class="chat-button w3-display-left" onclick="plusDivs(-1)"></button>
  <button class="chat-button w3-display-right" onclick="plusDivs(1)"></button>
  <button class="chat-button-txt">Text</button>

CSS

.cover-txt{
position: absolute;
background-color: white;
display: block;
top:10%;
left:104%;
width: 22vw;
height: 25vw;
z-index: 999;
}

JS

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}
function currentDiv(n) {
  showDivs(slideIndex = n);
}

function showDivs(n) {
    var i;
    var x = document.getElementsByClassName("mySlides");
    var dots = document.getElementsByClassName("img-count");
    var txt = document.getElementsByClassName("txt-div");
    var noms = document.getElementsByClassName("img-name");
  if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length}
  for (i = 0; i < x.length; i++) {
     x[i].style.display = "none";
     dots[i].style.display = "none";
     noms[i].style.display = "none";
     txt[i].style.display = "none";
  }

  x[slideIndex-1].style.display = "block";
  dots[slideIndex-1].style.display = "block";
  noms[slideIndex-1].style.display = "block";
  txt[slideIndex-1].style.display = "block";

    $(document).ready(function(){
        $(".chat-button-txt").click(function(){
        $(".cover-txt").toggle();
        });
    });
}

I think it's not the best solution but I worked for me. If anyone has something better I'll be glad to read it.

Thank you very much,

Regards,

U


问:
Adding to integers in a list which is inside a dictionary
I have a dictionary which houses some integer values in a list:

```<code>d = {"Numbers": [5, 10, 15, 20]}
</code>```

How do I access the integers within the list and add to them all at once? So if I wanted to add 10 on, it would look like this:

```<code>d = {"Numbers": [15, 20, 25, 30]}
</code>```

Thanks for the help!

答:
If the dictionary contains or will contain multiple keys, you can use dictionary comprehension and then list comprehension:</p>

```<code>d = {"Numbers": [5, 10, 15, 20]}
new_d = {a:[i+10 for i in b] for a, b in d.items()}
</code>```

Body:
I have a dictionary which houses some integer values in a list:

d = {"Numbers": [5, 10, 15, 20]}

How do I access the integers within the list and add to them all at once? So if I wanted to add 10 on, it would look like this:

d = {"Numbers": [15, 20, 25, 30]}

Thanks for the help!

Body:
If the dictionary contains or will contain multiple keys, you can use dictionary comprehension and then list comprehension:

d = {"Numbers": [5, 10, 15, 20]}
new_d = {a:[i+10 for i in b] for a, b in d.items()}


问:
How can I properly use a Pandas Dataframe with a multiindex that includes Intervals?
I'm trying to slice into a DataFrame that has a MultiIndex composed of an IntervalIndex and a regular Index. Example code:

```<code>from pandas import Interval as ntv

df = pd.DataFrame.from_records([
   {'id': 1, 'var1': 0.1, 'ntv': ntv(0,10), 'E': 1},
   {'id':2, 'var1': 0.5, 'ntv': ntv(0,12), 'E': 0}
], index=('ntv', 'id'))
</code>```

Looks like this:

```<code>            E  var1
ntv     id
(0, 10] 1   1   0.1
(0, 12] 2   0   0.5
</code>```

What I would like to do is to slice into the DataFrame at a specific value and return all rows that has an interval that contains the value. Ex:

```<code>df.loc[4]
</code>```

should return (trivially)

```<code>    E  var1
id
1   1   0.1
2   0   0.5
</code>```

The problem is I keep getting a TypeError about the index, and the docs show a similar operation (but on a single-level index) that does produce what I'm looking for.

```<code>TypeError: only integer scalar arrays can be converted to a scalar index
</code>```

I've tried many things, nothing seems to work normally. I could include the id column inside the dataframe, but I'd rather keep my index unique, and I would constantly be calling set_index('id').

I feel like either a) I'm missing something about MultiIndexes or b) there is a bug / ambiguity with using an IntervalIndex in a MultiIndex.

答:
This is not really a solution and I don't fully understand but think it may have to do with your interval index not being monotonic (in that you have overlapping intervals).  I guess that could in a sense be considered monotonic so perhaps alternately you could say the overlap means the index is not unique?

Anyway, check out this github issue:

ENH: Implement MultiIndex.is_monotonic_decreasing #17455

And here's an example with your data, but changing the intervals to be non-overlapping (0,6) & (7,12):

```<code>df = pd.DataFrame.from_records([
   {'id': 1, 'var1': 0.1, 'ntv': ntv(0, 6), 'E': 1},
   {'id': 2, 'var1': 0.5, 'ntv': ntv(7,12), 'E': 0}
], index=('ntv', 'id'))
</code>```

Now, loc works OK:

```<code>df.loc[4]

    E  var1
id
1   1   0.1
</code>```

Body:
I'm trying to slice into a DataFrame that has a MultiIndex composed of an IntervalIndex and a regular Index. Example code:

from pandas import Interval as ntv

df = pd.DataFrame.from_records([
   {'id': 1, 'var1': 0.1, 'ntv': ntv(0,10), 'E': 1},
   {'id':2, 'var1': 0.5, 'ntv': ntv(0,12), 'E': 0}
], index=('ntv', 'id'))

Looks like this:

            E  var1
ntv     id
(0, 10] 1   1   0.1
(0, 12] 2   0   0.5

What I would like to do is to slice into the DataFrame at a specific value and return all rows that has an interval that contains the value. Ex:

df.loc[4]

should return (trivially)

    E  var1
id
1   1   0.1
2   0   0.5

The problem is I keep getting a TypeError about the index, and the docs show a similar operation (but on a single-level index) that does produce what I'm looking for.

TypeError: only integer scalar arrays can be converted to a scalar index

I've tried many things, nothing seems to work normally. I could include the id column inside the dataframe, but I'd rather keep my index unique, and I would constantly be calling set_index('id').

I feel like either a) I'm missing something about MultiIndexes or b) there is a bug / ambiguity with using an IntervalIndex in a MultiIndex.

Body:
This is not really a solution and I don't fully understand but think it may have to do with your interval index not being monotonic (in that you have overlapping intervals).  I guess that could in a sense be considered monotonic so perhaps alternately you could say the overlap means the index is not unique?

Anyway, check out this github issue:

ENH: Implement MultiIndex.is_monotonic_decreasing #17455

And here's an example with your data, but changing the intervals to be non-overlapping (0,6) & (7,12):

df = pd.DataFrame.from_records([
   {'id': 1, 'var1': 0.1, 'ntv': ntv(0, 6), 'E': 1},
   {'id': 2, 'var1': 0.5, 'ntv': ntv(7,12), 'E': 0}
], index=('ntv', 'id'))

Now, loc works OK:

df.loc[4]

    E  var1
id
1   1   0.1