问:
ES6 Mixin with generic type in TypeScript
I'm trying to use ES6 Mixin in TypeScript. What I have is as below, and it works perfect with BaseClass.

```<code>class BaseClass {
    public foo() {}
};

interface IMyMixin {
    foo2();
}

let MyMixin = (superclass: typeof BaseClass) => class extends BaseClass implements IMyMixin {
    public foo2() {}
}

class MyBaseClass extends MyMixin(BaseClass) {

}
</code>```

However I can't apply MyMixin on derived class from BaseClass; Meanwhile, I can't make mixin generic either.

Is there a way to make it work for both BaseClass and DerivedClass?

```<code>class DerivedClass extends BaseClass {
    public bar() {}
}

class MyDerivedClass extends MyMixin(DerivedClass) {
    public something() {
// Compile Error: Property 'bar' does not exist on type 'MyDerivedClass'
        this.bar();
    }
}

// Compile Error: 'T' only refers to a type, but is being used as a value here.
let MyMixin = <T extends BaseClass>(superclass: typeof T) => class extends T implements IMyMixin {
    public foo2() {}
}
</code>```

答:
I've found solution from TypeScript/PR#13743, and optimized it with comment from @Maximus.

This piece of code works. The reason is, in MyMixin, T should be a Class (i.e. a constructor), not a type.

```<code>type Constructor<T> = new (...args: any[]) => T;

class BaseClass {
    public foo() { }
};

interface IMyMixin {
    foo2();
}

// `implements IMyMixin` is optional.
let MyMixin = <T extends Constructor<BaseClass>>(superclass: T) => class extends superclass implements IMyMixin {
    public foo2() { }
}

class DerivedClass extends BaseClass {
    public bar() {}
}

class MyDerivedClass extends MyMixin(DerivedClass) {
    public something() {
        this.bar();
        this.foo();
        this.foo2();
    }
}
</code>```

Body:
I'm trying to use ES6 Mixin in TypeScript. What I have is as below, and it works perfect with BaseClass.

class BaseClass {
    public foo() {}
};

interface IMyMixin {
    foo2();
}

let MyMixin = (superclass: typeof BaseClass) => class extends BaseClass implements IMyMixin {
    public foo2() {}
}

class MyBaseClass extends MyMixin(BaseClass) {

}

However I can't apply MyMixin on derived class from BaseClass; Meanwhile, I can't make mixin generic either.

Is there a way to make it work for both BaseClass and DerivedClass?

class DerivedClass extends BaseClass {
    public bar() {}
}

class MyDerivedClass extends MyMixin(DerivedClass) {
    public something() {
// Compile Error: Property 'bar' does not exist on type 'MyDerivedClass'
        this.bar();
    }
}

// Compile Error: 'T' only refers to a type, but is being used as a value here.
let MyMixin = <T extends BaseClass>(superclass: typeof T) => class extends T implements IMyMixin {
    public foo2() {}
}

Body:
I've found solution from TypeScript/PR#13743, and optimized it with comment from @Maximus.

This piece of code works. The reason is, in MyMixin, T should be a Class (i.e. a constructor), not a type.

type Constructor<T> = new (...args: any[]) => T;

class BaseClass {
    public foo() { }
};

interface IMyMixin {
    foo2();
}

// `implements IMyMixin` is optional.
let MyMixin = <T extends Constructor<BaseClass>>(superclass: T) => class extends superclass implements IMyMixin {
    public foo2() { }
}

class DerivedClass extends BaseClass {
    public bar() {}
}

class MyDerivedClass extends MyMixin(DerivedClass) {
    public something() {
        this.bar();
        this.foo();
        this.foo2();
    }
}


来源: stackexchange

问:
Remove lines from a text file which do not contain a certain string with python
I am trying to form a quotes file of a specific user name in a log file.  How do I remove every line that does not contain the specific user name in it?  Or how do I write all the lines which contain this user name to a new file?</p>

答:
Something along this line should suffice:

```<code>newfile = open(newfilename, 'w')
for line in file(filename, 'r'):
    if name in line:
        newfile.write(line)
newfile.close()
</code>```

See :  http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects

f.readlines() returns a list containing all the lines of data in the file.

An alternative approach to reading lines is to loop over the file object. This is memory efficient, fast, and leads to simpler code

```<code>>>> for line in f:
        print line
</code>```

Also you can checkout the use of with keyword. The advantage that the file is properly closed after its suite finishes

```<code>>>> with open(filename, 'r') as f:
...     read_data = f.read()
>>> f.closed
True
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Something along this line should suffice:

newfile = open(newfilename, 'w')
for line in file(filename, 'r'):
    if name in line:
        newfile.write(line)
newfile.close()

See :  http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects

f.readlines() returns a list containing all the lines of data in the file.

An alternative approach to reading lines is to loop over the file object. This is memory efficient, fast, and leads to simpler code

>>> for line in f:
        print line

Also you can checkout the use of with keyword. The advantage that the file is properly closed after its suite finishes

>>> with open(filename, 'r') as f:
...     read_data = f.read()
>>> f.closed
True


问:
How to move cursor to front of line and end of line in textWrangler
Currently I'm using mac OX system and wants to move cursor to front and end of line freely with keyboard alone, is there any way of doing it?

I tried shift + end, ctrl + end, not working.

Thanks!

答:
I tried several methods and find this one works. My system is Mac OS X El Capitan.
It turns out one of the solutions is to config the settings in TextWrangler-> Preference -> Keyboard,  where you can see on the right side there's  " 'Home' and 'End' key behavior".  If you choose "Move cursor to beginning and end of current line", the feature asked in above question can be fulfilled.</p>

ContentLicense: CC BY-SA 3.0


问:
Self executable Jar File not executable after installing Winrar
Here's the deal, I've compiled a few classes into a jar file with a manifest pointing to the main-class. It works just fine on my computer.

I transferred the jar file onto another computer which I'm supposed to give a demonstration tomorrow on and well, here's where things went downhill.

Winrar was not installed, so I installed it in order to extract the folder I had my jar file in. I unknowingly associated winrar with jars which I fixed by changing the default open program with jre7/bin/java.exe. However, the jar file does not self-execute as it did previously. I'm thinking something's up with the registry.

Stackoverflow, what do you think?

答: You need to reset file association for ".jar" files, jar files are not executed by "jre7/bin/java.exe". so what you should have done before choosing default program to "jre7/bin/java.exe" was to simply uninstall WinRAR or remove its association from the WinRAR settings. So now, open start menu, search and open regedit.exe goto HKEY_CLASSES_ROOT/.jar and delete every value excluding "(Default)" who's value data should be "jarfile". the reinstall jre and reboot pc . THAT'S YOUR SOLUTION.</p>


问:
R - ggplot histogram with colors based on range
I've written a function that produces a histogram two vertical bars indicating a range of values. I'd like to modify this function so that the bars within the specified range are a different color.

Heres' my function and a quick demonstration:

```<code>require(ggplot2)
niceHist <- function(data, cutpoint1, cutpoint2, title = "Supply a title, genius") {
  temp_dat = data.frame(Data = data, Col = 0)
  temp_dat = temp_dat[! is.na(temp_dat$Data),]
  temp_dat[temp_dat$Data >= cutpoint1 & temp_dat$Data <= cutpoint2,]$Col = 1
  my_hist = qplot(data) +
    geom_histogram(fill = "forestgreen") +
    geom_vline(xintercept = cutpoint1) +
    geom_vline(xintercept = cutpoint2) +
    ggtitle(paste(title)) +
    theme_minimal() +
    theme(text = element_text(size = 16), axis.line.y = element_line(color = "black", size = 0.5), axis.line.x = element_line(color = "black", size = 0.5))
  my_hist
}
u = rnorm(100)
c1 = mean(u) - sd(u)
c2 = mean(u) + sd(u)
niceHist(u, c1, c2)
</code>```

I've seen a similar question whose accepted solution is not well-suited to my needs because I want to maintain the shape of the original histogram. I'd also prefer not to change the number of bins and, if at all possible, apply the color difference such that a single bar in the histogram can be two colors if the vertical black lines happen to bisect it.

*My main goal is to clearly display how much of the distribution is captured within the supplied range without changing the shape of the distribution. * So an alternative but less desirable solution would be to simply color the background with respect to the range provided. Also, I need my function to return a ggplot object because it will occasionally be further modified using ggplot syntax.

UPDATE:
At the suggestion of a comment, I have tried using scale_fill_gradientn but this doesn't work:

```<code>niceHist <- function(data, cutpoint1, cutpoint2, title = "Supply a title, genius") {
      temp_dat = data.frame(Data = data, Col = 0)
      temp_dat = temp_dat[! is.na(temp_dat$Data),]
      temp_dat[temp_dat$Data >= cutpoint1 & temp_dat$Data <= cutpoint2,]$Col = 1
      my_hist = qplot(data) +
        geom_histogram() +
        scale_fill_gradientn(colours = c("blue", "red", "red", "blue"), values = c(min(data, na.rm = TRUE), cutpoint1, cutpoint2, max(data, na.rm = TRUE))) +
        geom_vline(xintercept = cutpoint1) +
        geom_vline(xintercept = cutpoint2) +
        ggtitle(paste(title)) +
        theme_minimal() +
        theme(text = element_text(size = 16), axis.line.y = element_line(color = "black", size = 0.5), axis.line.x = element_line(color = "black", size = 0.5))
      my_hist
    }
</code>```

答:
My solution is to create the count data.frame and add a factor to indicate the region of bin. for example: </p>

```<code>df <- ggplot_build(niceHist(u,c1,c2))$data[[1]] #recreate the count df
require(dplyr)
df <- df %>% mutate(col=cut(x,c(min(x)-0.001,c1,c2,max(x)+0.001)))
ggplot(df,aes(x,count))+ geom_col(aes(fill=col)) + geom_vline(xintercept = c(c1,c2))
</code>```

Body:
I've written a function that produces a histogram two vertical bars indicating a range of values. I'd like to modify this function so that the bars within the specified range are a different color.

Heres' my function and a quick demonstration:

require(ggplot2)
niceHist <- function(data, cutpoint1, cutpoint2, title = "Supply a title, genius") {
  temp_dat = data.frame(Data = data, Col = 0)
  temp_dat = temp_dat[! is.na(temp_dat$Data),]
  temp_dat[temp_dat$Data >= cutpoint1 & temp_dat$Data <= cutpoint2,]$Col = 1
  my_hist = qplot(data) +
    geom_histogram(fill = "forestgreen") +
    geom_vline(xintercept = cutpoint1) +
    geom_vline(xintercept = cutpoint2) +
    ggtitle(paste(title)) +
    theme_minimal() +
    theme(text = element_text(size = 16), axis.line.y = element_line(color = "black", size = 0.5), axis.line.x = element_line(color = "black", size = 0.5))
  my_hist
}
u = rnorm(100)
c1 = mean(u) - sd(u)
c2 = mean(u) + sd(u)
niceHist(u, c1, c2)

I've seen a similar question whose accepted solution is not well-suited to my needs because I want to maintain the shape of the original histogram. I'd also prefer not to change the number of bins and, if at all possible, apply the color difference such that a single bar in the histogram can be two colors if the vertical black lines happen to bisect it.

*My main goal is to clearly display how much of the distribution is captured within the supplied range without changing the shape of the distribution. * So an alternative but less desirable solution would be to simply color the background with respect to the range provided. Also, I need my function to return a ggplot object because it will occasionally be further modified using ggplot syntax.

UPDATE:
At the suggestion of a comment, I have tried using scale_fill_gradientn but this doesn't work:

niceHist <- function(data, cutpoint1, cutpoint2, title = "Supply a title, genius") {
      temp_dat = data.frame(Data = data, Col = 0)
      temp_dat = temp_dat[! is.na(temp_dat$Data),]
      temp_dat[temp_dat$Data >= cutpoint1 & temp_dat$Data <= cutpoint2,]$Col = 1
      my_hist = qplot(data) +
        geom_histogram() +
        scale_fill_gradientn(colours = c("blue", "red", "red", "blue"), values = c(min(data, na.rm = TRUE), cutpoint1, cutpoint2, max(data, na.rm = TRUE))) +
        geom_vline(xintercept = cutpoint1) +
        geom_vline(xintercept = cutpoint2) +
        ggtitle(paste(title)) +
        theme_minimal() +
        theme(text = element_text(size = 16), axis.line.y = element_line(color = "black", size = 0.5), axis.line.x = element_line(color = "black", size = 0.5))
      my_hist
    }

Body:
My solution is to create the count data.frame and add a factor to indicate the region of bin. for example:

df <- ggplot_build(niceHist(u,c1,c2))$data[[1]] #recreate the count df
require(dplyr)
df <- df %>% mutate(col=cut(x,c(min(x)-0.001,c1,c2,max(x)+0.001)))
ggplot(df,aes(x,count))+ geom_col(aes(fill=col)) + geom_vline(xintercept = c(c1,c2))


问:
How to get IAM Policy Document via boto
I am trying to get the details of a aws IAM Policy via boto to be able to backup or replicate IAM policies via script.
I have searched the docs of boto 2 and 3 but did not find any possibility to get the json data of a configured policy.

What I (successfully) did:

Created a policy via IAM Management console

Assigned it to a role

Used it for creation of ec2 instances via boto

But I cannot find a way to retrieve the associated JSON data ('Policy Document' in Management Console) to get it in boto.

What I tried with boto:

```<code>import boto.iam
REGION_NAME = 'eu-west-1'
iam_conn = boto.iam.connect_to_region(REGION_NAME)
arn = 'arn:myproperlyformattedarn'
p = iam_conn.get_policy(arn)
print p
</code>```

result:

```<code>{
    "get_policy_response": {
        "response_metadata": {
            "request_id": "XXXXX-XXXX-XXXX-XXXX-XXXX"
        },
        "get_policy_result": {
            "policy": {
                "update_date": "2016-04-15T12:51:21Z",
                "create_date": "2016-04-15T12:51:21Z",
                "is_attachable": "true",
                "policy_name": "My_Policy_Name",
                "default_version_id": "v1",
                "attachment_count": "1",
                "path": "/",
                "arn": "arn:aws:iam::123456789:policy/VerticaTest_GetConfigsFromS3",
                "policy_id": "XXXSOMELONGSTRINGXXXX"
            }
        }
    }
}
</code>```

What I am after is something like this (the policy document in Management Console):

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::mybucketname",
                "arn:aws:s3:::mybucketname/*"
            ]
        }
    ]
}
</code>```

答:
Please move to boto3.

Approach this from the policy side: Identify the Policy ARN, Identify the Policy DefaultVersionId using the ARN, Retrieve the PolicyDocument using ARN and DefaultVersionId.

```<code>import boto3
import json

arn = 'arn:aws:iam::aws:policy/AdministratorAccess'

iam = boto3.client('iam')
policy = iam.get_policy(
    PolicyArn = arn
)
policy_version = iam.get_policy_version(
    PolicyArn = arn,
    VersionId = policy['Policy']['DefaultVersionId']
)

print(json.dumps(policy_version['PolicyVersion']['Document']))
print(json.dumps(policy_version['PolicyVersion']['Document']['Statement']))
</code>```

Run this code and pipe the output to "jq ." and you get the following output:

```<code>{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "*",
      "Resource": "*",
      "Effect": "Allow"
    }
  ]
}

[
  {
    "Action": "*",
    "Resource": "*",
    "Effect": "Allow"
  }
]
</code>```

You specifically requested the Actions / Statement in your question.  I printed the 'Document' and 'Statement' properties to show the differences.

http://boto3.readthedocs.io/en/latest/reference/services/iam.html#IAM.Client.get_policy
http://boto3.readthedocs.io/en/latest/reference/services/iam.html#IAM.Client.get_policy_version

Title: How to get IAM Policy Document via boto

Body:
I am trying to get the details of a aws IAM Policy via boto to be able to backup or replicate IAM policies via script.
I have searched the docs of boto 2 and 3 but did not find any possibility to get the json data of a configured policy.

What I (successfully) did:

Created a policy via IAM Management console

Assigned it to a role

Used it for creation of ec2 instances via boto

But I cannot find a way to retrieve the associated JSON data ('Policy Document' in Management Console) to get it in boto.

What I tried with boto:

import boto.iam
REGION_NAME = 'eu-west-1'
iam_conn = boto.iam.connect_to_region(REGION_NAME)
arn = 'arn:myproperlyformattedarn'
p = iam_conn.get_policy(arn)
print p

result:

{
    "get_policy_response": {
        "response_metadata": {
            "request_id": "XXXXX-XXXX-XXXX-XXXX-XXXX"
        },
        "get_policy_result": {
            "policy": {
                "update_date": "2016-04-15T12:51:21Z",
                "create_date": "2016-04-15T12:51:21Z",
                "is_attachable": "true",
                "policy_name": "My_Policy_Name",
                "default_version_id": "v1",
                "attachment_count": "1",
                "path": "/",
                "arn": "arn:aws:iam::123456789:policy/VerticaTest_GetConfigsFromS3",
                "policy_id": "XXXSOMELONGSTRINGXXXX"
            }
        }
    }
}

What I am after is something like this (the policy document in Management Console):

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": [
                "arn:aws:s3:::mybucketname",
                "arn:aws:s3:::mybucketname/*"
            ]
        }
    ]
}

Body:
Please move to boto3.

Approach this from the policy side: Identify the Policy ARN, Identify the Policy DefaultVersionId using the ARN, Retrieve the PolicyDocument using ARN and DefaultVersionId.

import boto3
import json

arn = 'arn:aws:iam::aws:policy/AdministratorAccess'

iam = boto3.client('iam')
policy = iam.get_policy(
    PolicyArn = arn
)
policy_version = iam.get_policy_version(
    PolicyArn = arn,
    VersionId = policy['Policy']['DefaultVersionId']
)

print(json.dumps(policy_version['PolicyVersion']['Document']))
print(json.dumps(policy_version['PolicyVersion']['Document']['Statement']))

Run this code and pipe the output to "jq ." and you get the following output:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "*",
      "Resource": "*",
      "Effect": "Allow"
    }
  ]
}

[
  {
    "Action": "*",
    "Resource": "*",
    "Effect": "Allow"
  }
]

You specifically requested the Actions / Statement in your question.  I printed the 'Document' and 'Statement' properties to show the differences.

http://boto3.readthedocs.io/en/latest/reference/services/iam.html#IAM.Client.get_policy
http://boto3.readthedocs.io/en/latest/reference/services/iam.html#IAM.Client.get_policy_version


问:
Displaying 3 columns of data using bootstrap? Data shows as a row instead
Why are the class="col" classes not causing the data to show as a row containing 3 columns?

https://jsfiddle.net/bobbyrne01/b63g4kpe/1/

Html:

```<code>https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css
<div id="results"></div>
</code>```

Js:

```<code>document.getElementById('results').innerHTML += '<div class="container">';
document.getElementById('results').innerHTML += '<div class="row">';
for (var i = 0; i < 3; i++) {
  document.getElementById('results').innerHTML += '<div class="col">';
  document.getElementById('results').innerHTML += i + ' Col';
}
document.getElementById('results').innerHTML += '</div>';
document.getElementById('results').innerHTML += '</div><br/>';
document.getElementById('results').innerHTML += 'After container';
</code>```

答:
You forgot to include the GRID column correctly. You wrote
. You should write class like col-lg-* or col-md-* or col-sm* inside div tag. Replace these * with number from 1-12. Hope this answer your question and i have provided you the code below.

document.getElementById('results').innerHTML += '
';
document.getElementById('results').innerHTML += '
';
document.getElementById('results').innerHTML += '
';
for (var i = 0; i < 3; i++) {
  document.getElementById('results').innerHTML += '
 Column ' + (i + 1) + '
';
}
document.getElementById('results').innerHTML += '
';
document.getElementById('results').innerHTML += '
';
document.getElementById('results').innerHTML += '

';
document.getElementById('results').innerHTML += 'After container';```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<head>
<body>
   <div id="results"></div>
</body></code>```

Body:
Why are the class="col" classes not causing the data to show as a row containing 3 columns?

https://jsfiddle.net/bobbyrne01/b63g4kpe/1/

Html:

https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css

Js:

document.getElementById('results').innerHTML += '
';
document.getElementById('results').innerHTML += '
';
for (var i = 0; i < 3; i++) {
  document.getElementById('results').innerHTML += '
';
  document.getElementById('results').innerHTML += i + ' Col';
}
document.getElementById('results').innerHTML += '
';
document.getElementById('results').innerHTML += '

';
document.getElementById('results').innerHTML += 'After container';

Body:
You forgot to include the GRID column correctly. You wrote <div class="col">. You should write class like col-lg-* or col-md-* or col-sm* inside div tag. Replace these * with number from 1-12. Hope this answer your question and i have provided you the code below.

document.getElementById('results').innerHTML += '<div class="container">';
document.getElementById('results').innerHTML += '<div class="row">';
document.getElementById('results').innerHTML += '<div class="col-xs-12 col-lg-12">';
for (var i = 0; i < 3; i++) {
  document.getElementById('results').innerHTML += '<div class="col-xs-4 col-lg-4"> Column ' + (i + 1) + '</div>';
}
document.getElementById('results').innerHTML += '</div>';
document.getElementById('results').innerHTML += '</div>';
document.getElementById('results').innerHTML += '</div><br/>';
document.getElementById('results').innerHTML += 'After container';

<head>
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<head>
<body>
   <div id="results"></div>
</body>


问:
Xamarin forms Shadow on Frame in Android
The Frame class in Xamarin Forms is quite limited, and can't allow me to get a shadow behind the Frame. I've made a custom renderer for iOS using this code:

```<code>public class RatingInfoFrameRenderer : FrameRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
    {
        base.OnElementChanged(e);

        Layer.BorderColor = UIColor.White.CGColor;
        Layer.CornerRadius = 10;
        Layer.MasksToBounds = false;
        Layer.ShadowOffset = new CGSize(-2, 2);
        Layer.ShadowRadius = 5;
        Layer.ShadowOpacity = 0.4f;
    }
}
</code>```

Making a similar one on Android is causing me problems, since my knowledge on Android native is kind of limited. Could anyone tell me what to look at, perhaps some good code example? I haven't found anything that looks similar to this.

答:
I was able to get a shadow effect in Xamarin Forms for a box view, I'm pretty sure it can used similarly for a Frame. I got the clue from Android Documentation

I added a new property called HasShadow

```<code>        public static readonly BindableProperty HasShadowProperty =
            BindableProperty.Create("HasShadow", typeof(bool), typeof(ExtendedBoxView), false);

        public bool HasShadow
        {
            get { return (bool)GetValue(HasShadowProperty); }
            set { SetValue(HasShadowProperty, value); }
        }
</code>```

Here's the code for the Renderer in Android

```<code>       public class ExtendedBoxViewRenderer : BoxRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<BoxView> e)
    {
        base.OnElementChanged(e);
        var element = e.NewElement as ExtendedBoxView;

        if (element == null) return;

        if (element.HasShadow)
        {
            ViewGroup.Elevation = 8.0f;
            ViewGroup.TranslationZ = 10.0f;

        }

    }

}
</code>```

And this is how it looks

UPDATE

I found out that this approach causes app crash for older versions of Android. Although I haven't found a way to display Shadows in Android versions prior to Lollipop. This will prevent any app crashes

```<code>    public class ExtendedBoxViewRenderer : BoxRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<BoxView> e)
        {
            base.OnElementChanged(e);
            var element = e.NewElement as ExtendedBoxView;

            if (element == null) return;

            if (element.HasShadow)
            {
//For some reason ViewCompat has issues when running in debug hence the workaround.
#if DEBUG
                double dAndroidVersion;
                if (double.TryParse(Build.VERSION.Release, out dAndroidVersion))
                {
                    if (dAndroidVersion < 21)
                        return;
                }
#else
                ViewCompat.SetElevation(ViewGroup, 8.0f);
                ViewCompat.SetTranslationZ(ViewGroup, 10.0f);
#endif
            }

        }

    }
</code>```

Body:
The Frame class in Xamarin Forms is quite limited, and can't allow me to get a shadow behind the Frame. I've made a custom renderer for iOS using this code:

public class RatingInfoFrameRenderer : FrameRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Frame> e)
    {
        base.OnElementChanged(e);

        Layer.BorderColor = UIColor.White.CGColor;
        Layer.CornerRadius = 10;
        Layer.MasksToBounds = false;
        Layer.ShadowOffset = new CGSize(-2, 2);
        Layer.ShadowRadius = 5;
        Layer.ShadowOpacity = 0.4f;
    }
}

Making a similar one on Android is causing me problems, since my knowledge on Android native is kind of limited. Could anyone tell me what to look at, perhaps some good code example? I haven't found anything that looks similar to this.

Body:
I was able to get a shadow effect in Xamarin Forms for a box view, I'm pretty sure it can used similarly for a Frame. I got the clue from Android Documentation

I added a new property called HasShadow

        public static readonly BindableProperty HasShadowProperty =
            BindableProperty.Create("HasShadow", typeof(bool), typeof(ExtendedBoxView), false);

        public bool HasShadow
        {
            get { return (bool)GetValue(HasShadowProperty); }
            set { SetValue(HasShadowProperty, value); }
        }

Here's the code for the Renderer in Android

       public class ExtendedBoxViewRenderer : BoxRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<BoxView> e)
    {
        base.OnElementChanged(e);
        var element = e.NewElement as ExtendedBoxView;

        if (element == null) return;

        if (element.HasShadow)
        {
            ViewGroup.Elevation = 8.0f;
            ViewGroup.TranslationZ = 10.0f;

        }

    }

}

And this is how it looks

UPDATE

I found out that this approach causes app crash for older versions of Android. Although I haven't found a way to display Shadows in Android versions prior to Lollipop. This will prevent any app crashes

    public class ExtendedBoxViewRenderer : BoxRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<BoxView> e)
        {
            base.OnElementChanged(e);
            var element = e.NewElement as ExtendedBoxView;

            if (element == null) return;

            if (element.HasShadow)
            {
//For some reason ViewCompat has issues when running in debug hence the workaround.
#if DEBUG
                double dAndroidVersion;
                if (double.TryParse(Build.VERSION.Release, out dAndroidVersion))
                {
                    if (dAndroidVersion < 21)
                        return;
                }
#else
                ViewCompat.SetElevation(ViewGroup, 8.0f);
                ViewCompat.SetTranslationZ(ViewGroup, 10.0f);
#endif
            }

        }

    }


问:
Display an image in real device from a computer in Android Application
I want to load an image from an external folder of my system to my android application. I use the following code, but the image is not displaying. When I debugged it, the Bitmap object 'bitmap' is shown as null. How can I solve this problem?

```<code>      ImageView img=(ImageView)findViewById(R.id.myImage);
      String fname="C:/Users/Public/Pictures/Garden.jpg";
      Bitmap bitmap = BitmapFactory.decodeFile(fname);
      img.setImageBitmap(bitmap);
</code>```

My actual need is my andorid application (on real device) should display some images which is stored into one computer. The admin of this application will upload some images to a specific folder in that computer. And the android application will access these images using IP address, and will display these images. If these images should be pushed to sdcard path, then how can i do it at runtime?

Please help me..

Thank you to all..

答:
You can't access files that are on your computer from android (emulator or phone). you have to consider your application as running independently from the rest.

if you really don't want to place your image inside the drawable folder of android (and access it using R.drawable.imagename then you need to push your image onto the sdcard of your phone/emulator and open it using the sdcard path

Body:
I want to load an image from an external folder of my system to my android application. I use the following code, but the image is not displaying. When I debugged it, the Bitmap object 'bitmap' is shown as null. How can I solve this problem?

      ImageView img=(ImageView)findViewById(R.id.myImage);
      String fname="C:/Users/Public/Pictures/Garden.jpg";
      Bitmap bitmap = BitmapFactory.decodeFile(fname);
      img.setImageBitmap(bitmap);

My actual need is my andorid application (on real device) should display some images which is stored into one computer. The admin of this application will upload some images to a specific folder in that computer. And the android application will access these images using IP address, and will display these images. If these images should be pushed to sdcard path, then how can i do it at runtime?

Please help me..

Thank you to all..


问:
This version of the Entity Framework Core Package Manager Console Tools doesn't support these types of projects
After updating an existing project to ASP.NET Core 1.1 and Entity Framework Core 1.1 using this tutorial

I tried to execute "Add-Migration MigrationName" in Package Management Console but got an error:

Startup project 'src\ProjectName' is an ASP.NET Core or .NET Core
  project for Visual Studio 2015. This version of the Entity Framework
  Core Package Manager Console Tools doesn't support these types of
  projects.

I am using VS 2015 Update 3.

Project.json

```<code>{
  "dependencies": {
    "CoursesManagement.DAL": "1.0.0-*",
    "Microsoft.AspNetCore.Diagnostics": "1.1.1",
    "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.1.1",
    "Microsoft.AspNetCore.Mvc": "1.1.2",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.1.1",
    "Microsoft.AspNetCore.Server.Kestrel": "1.1.1",
    "Microsoft.AspNetCore.StaticFiles": "1.1.1",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.1.1",
    "Microsoft.Extensions.Configuration.Json": "1.1.1",
    "Microsoft.Extensions.Logging.Console": "1.1.1",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.1.1",
    "Microsoft.NETCore.App": "1.1.1",
    "Microsoft.EntityFrameworkCore": "1.1.1",
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.1.0",
      "type": "build"
    },
    "Microsoft.EntityFrameworkCore.Design": "1.1.1"
  },

  "tools": {
    "Microsoft.EntityFrameworkCore.Tools": "1.1.0",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.1": {
      "dependencies": {
      },
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "runtimes": {
    "win10-x64": {}
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}
</code>```

global.json

```<code>{
  "projects": [ "src" ],
  "sdk": {
    "version": "1.0.0-preview2-003131"
  }
}
</code>```

答:
As mentioned in this blog,

We’re now encouraging everyone to migrate to MSBuild and csproj from project.json. As I stated above, we will not be supporting any of the new .NET Core tools in Visual Studio 2015. We also won’t be updating the Visual Studio 2015 project.json-based tools.

You are using EFCore.Tools package version 1.1.0 which doesn't support project.json. The tooling for project.json never reached RTM. The suitable preview version to use for EF Core 1.1 packages is EFCore.Tools 1.1.0-preview4-final.

Also as mentioned in other answers, if you want to use powershell commands then you need to install EFCore.Tools package but if you want dotnet ef then you need to install EFCore.Tools.DotNet (version 1.1.0-preview3-final since preview4-final had minor issue).

As noted above, there will not be any updates to project.json-based tools. You can still use above preview package though best option would be to migrate to VS2017 csproj when you can.

Body:
After updating an existing project to ASP.NET Core 1.1 and Entity Framework Core 1.1 using this tutorial

I tried to execute "Add-Migration MigrationName" in Package Management Console but got an error:

Startup project 'src\ProjectName' is an ASP.NET Core or .NET Core
  project for Visual Studio 2015. This version of the Entity Framework
  Core Package Manager Console Tools doesn't support these types of
  projects.

I am using VS 2015 Update 3.

Project.json

{
  "dependencies": {
    "CoursesManagement.DAL": "1.0.0-*",
    "Microsoft.AspNetCore.Diagnostics": "1.1.1",
    "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.1.1",
    "Microsoft.AspNetCore.Mvc": "1.1.2",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.1.1",
    "Microsoft.AspNetCore.Server.Kestrel": "1.1.1",
    "Microsoft.AspNetCore.StaticFiles": "1.1.1",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.1.1",
    "Microsoft.Extensions.Configuration.Json": "1.1.1",
    "Microsoft.Extensions.Logging.Console": "1.1.1",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.1.1",
    "Microsoft.NETCore.App": "1.1.1",
    "Microsoft.EntityFrameworkCore": "1.1.1",
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.1.0",
      "type": "build"
    },
    "Microsoft.EntityFrameworkCore.Design": "1.1.1"
  },

  "tools": {
    "Microsoft.EntityFrameworkCore.Tools": "1.1.0",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.1": {
      "dependencies": {
      },
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "runtimes": {
    "win10-x64": {}
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

global.json

{
  "projects": [ "src" ],
  "sdk": {
    "version": "1.0.0-preview2-003131"
  }
}


问:
Dates and Arithmetic
I'm learning python by myself for almost a month and i was confronted with an exercise that involves "datetime" and arithmetic operators.

First - they asked me to create a code where the users should enter the deadline for their project and the code must tell them how many days they have to complete.

And i did this:

```<code>    import datetime
    today = datetime.date.today()
    delivery_date = input("Tell me your deadline (dd/mm/aa): ")

    print("\n")

    deadline = datetime.datetime.strptime(delivery_date, "%d/%m/%y").date()
    days = delivery_date - today
    print("You have", days.days, "days to finish your project.")
</code>```

But the second part it's kinda tricky.

Second - they are asking me to try to give the answer as a combination of weeks and days and that i will need some math functions to solve this final part.

And i did this:

```<code>    weeks = days // 7
    remainder_days = days % 7
    print("You have", weeks.days, "weeks and", remainder_days.days, "days.")
</code>```

Only this final part fails. In the end i get this error message:

```<code>        remainder_days = days % 7
    TypeError: unsupported operand type(s) for %: 'datetime.timedelta' and 'int'
</code>```

I know that the problem is with the modulus symbol (%) but if they are asking me to give the final result as a combination of weeks and days, it's possible, but i can't see how.

Is any other way with a simple math operation to solve this?

Do i need to put anything in my code?

Can someone help me please?

Thank you

答:
days = delivery_date - today should be days = deadline - today. Also you should call it delta, because it's a time delta, where you can do delta.days to get the number of days. Simply use delta.days later on.

Also delta.days is just a number, so when doing delta.days // 7, you don't want to call .days on the result.

Something like the following should work:

```<code>import datetime
today = datetime.date.today()
delivery_date = input("Tell me your deadline (dd/mm/aa): ")

print("\n")

deadline = datetime.datetime.strptime(delivery_date, "%d/%m/%y").date()
delta = deadline - today
print("You have", delta.days, "days to finish your project.")

weeks = delta.days // 7
remainder_days = delta.days % 7
print("You have", weeks, "weeks and", remainder_days, "days.")
</code>```

By the way the error points you in the right direction: TypeError: unsupported operand type(s) for %: 'datetime.timedelta' and 'int'. It means you have a time delta object, on which you're applying the modulo operator with an integer, and python tells you it's not possible. So you'll need to somehow get an integer out of your time delta.

Title: Dates and Arithmetic

Body:
I'm learning python by myself for almost a month and i was confronted with an exercise that involves "datetime" and arithmetic operators.

First - they asked me to create a code where the users should enter the deadline for their project and the code must tell them how many days they have to complete.

And i did this:

    import datetime
    today = datetime.date.today()
    delivery_date = input("Tell me your deadline (dd/mm/aa): ")

    print("\n")

    deadline = datetime.datetime.strptime(delivery_date, "%d/%m/%y").date()
    days = delivery_date - today
    print("You have", days.days, "days to finish your project.")

But the second part it's kinda tricky.

Second - they are asking me to try to give the answer as a combination of weeks and days and that i will need some math functions to solve this final part.

And i did this:

    weeks = days // 7
    remainder_days = days % 7
    print("You have", weeks.days, "weeks and", remainder_days.days, "days.")

Only this final part fails. In the end i get this error message:

        remainder_days = days % 7
    TypeError: unsupported operand type(s) for %: 'datetime.timedelta' and 'int'

I know that the problem is with the modulus symbol (%) but if they are asking me to give the final result as a combination of weeks and days, it's possible, but i can't see how.

Is any other way with a simple math operation to solve this?

Do i need to put anything in my code?

Can someone help me please?

Thank you

Body:
days = delivery_date - today should be days = deadline - today. Also you should call it delta, because it's a time delta, where you can do delta.days to get the number of days. Simply use delta.days later on.

Also delta.days is just a number, so when doing delta.days // 7, you don't want to call .days on the result.

Something like the following should work:

import datetime
today = datetime.date.today()
delivery_date = input("Tell me your deadline (dd/mm/aa): ")

print("\n")

deadline = datetime.datetime.strptime(delivery_date, "%d/%m/%y").date()
delta = deadline - today
print("You have", delta.days, "days to finish your project.")

weeks = delta.days // 7
remainder_days = delta.days % 7
print("You have", weeks, "weeks and", remainder_days, "days.")

By the way the error points you in the right direction: TypeError: unsupported operand type(s) for %: 'datetime.timedelta' and 'int'. It means you have a time delta object, on which you're applying the modulo operator with an integer, and python tells you it's not possible. So you'll need to somehow get an integer out of your time delta.


问:
Is an OAuth refresh token a valid / secure alternative for a mobile device identifier
Asking as a relative n00b on mobile applications here as I'm primarily a backend developer.

We are building a mobile app and have a business requirement for users' devices to be uniquely identified and registered with the backend (i.e. users can install app but to access services they need to register that device with our backend services and there is a limit of X devices that can be registered simultaneously).

The front end team currently have created a function to extract a unique device ID from the mobile device but we were also told by the security team that device IDs are considered sensitive information and we should not be transmitting this information over the wire.

Putting aside that encryption can be applied to the device ID, I was mulling about alternatives to the device ID altogether. We are using OAuth for authentication and at the end of a valid registration, an OAuth access and refresh token is generated. Since the refresh token is supposed to be long-lived and is stored securely (assumed) client-side, can the refresh token be used as a replacement for the device ID? Would there be any known holes in this strategy? Refresh tokens are supposed to be "long-lived" per the documentation, but how long-lived exactly?

答:
You can configure the life span of the Oauth2 tokens, But this will defeat the purpose of Oauth2. If the device is compromised, What are you going to do about it. You will have to invalidate the tokens.

Using the device ID is the way to go, if it is universally unique or you are sure that there will be no conflicts.

I suggest you to use the device ID and leave the Oauth2 default behavior.


问:
Displaying post format icon next to the title in recent posts
I am creating a theme from scratch, and it's going quite well so far, but I've been wondering if there is a way to display the post format (e.g. standard post, audio, video, image etc.) icon next to a post title when displaying the list of recent posts?

I would like the readers to know right away what kind of post they are about to read / listen to / see..

I know it's possible to format whole posts based on their format, but couldn't find anything regarding the links to them in a widget. I'm thinking it should be possible—if you can get the titles, why couldn't you get the formats and their icons as well?

There definitely IS a way to do it .. somehow, because it's exactly what this plugin does. However, it does it only for one post format, but how to add icons for all of them?

答:
Howli doesn't answer the icon question. I did my homework and wrote some code but if my posts are paginated I don't know how to load the image since its URL changes every time you turn the page.   Here is how it looks the first page of (paginated) post

It's in Spanish but you'll get the idea. After page 1 image link is broken since the png's url changes with pagination and I haven't solved that yet.


问:
SQL Variable not getting set
I might be missing something easy here, as someone relatively new to SQL, I am trying the following query:

```<code>DECLARE @uidd VARCHAR
SELECT @uidd = UID
FROM PRODUCTOBJECT WHERE EMAIL='abc@gmail.com';
SELECT ProductID FROM PRODUCTUIDMAPPING WHERE UID= @uidd;
</code>```

And it is returning zero rows.  What's puzzling is that if do not use variables and run both selects separately, I do get the right row back.

```<code>SELECT UID FROM TABLEA WHERE EMAIL='abc@gmail.com';
</code>```

returns the UID, and then

```<code>SELECT ProductID FROM TABLEB WHERE UID='123456';
</code>```

will return the ProductID value, where '123456' would be the value returned from the first query.

The problem is when combined together, using the variable for some reason it seems @uidd is not being set.  Any reason why ?

I am running this on SQL Server 2008.

答:
Presumably, uuid is longer than one character.  Never use character types in SQL Server without a length.  The default varies by context and may not be correct.

So, this should work:

```<code>DECLARE @uidd VARCHAR(255);

SELECT @uidd = UID
FROM PRODUCTOBJECT
WHERE EMAIL='abc@gmail.com';

SELECT ProductID
FROM PRODUCTUIDMAPPING
WHERE UID= @uidd;
</code>```

Title: SQL Variable not getting set

Body:
I might be missing something easy here, as someone relatively new to SQL, I am trying the following query:

DECLARE @uidd VARCHAR
SELECT @uidd = UID
FROM PRODUCTOBJECT WHERE EMAIL='abc@gmail.com';
SELECT ProductID FROM PRODUCTUIDMAPPING WHERE UID= @uidd;

And it is returning zero rows.  What's puzzling is that if do not use variables and run both selects separately, I do get the right row back.

SELECT UID FROM TABLEA WHERE EMAIL='abc@gmail.com';

returns the UID, and then

SELECT ProductID FROM TABLEB WHERE UID='123456';

will return the ProductID value, where '123456' would be the value returned from the first query.

The problem is when combined together, using the variable for some reason it seems @uidd is not being set.  Any reason why ?

I am running this on SQL Server 2008.

Body:
Presumably, uuid is longer than one character.  Never use character types in SQL Server without a length.  The default varies by context and may not be correct.

So, this should work:

DECLARE @uidd VARCHAR(255);

SELECT @uidd = UID
FROM PRODUCTOBJECT
WHERE EMAIL='abc@gmail.com';

SELECT ProductID
FROM PRODUCTUIDMAPPING
WHERE UID= @uidd;


问:
Making a dictionary from a list
I want to write a function that imports ascii_lowercase and returns a dictionary with the letters of keys as keys and a randomly shuffled version of the keys as values.

for example,

```<code>keys = "abcdefg..."
</code>```

and then you shuffle it and get gydwsk... as an example, and the dictionary should look like

```<code>{'a':'g', 'b':'y', 'c':'d'...}
</code>```

Im not sure where to begin, any help is appreciated.

答:
```<code>import random

def f(keys):
    shuffled = list(keys)
    random.shuffle(shuffled)
    return dict(zip(keys, shuffled))
</code>```

Title: Making a dictionary from a list

Body:
I want to write a function that imports ascii_lowercase and returns a dictionary with the letters of keys as keys and a randomly shuffled version of the keys as values.

for example,

keys = "abcdefg..."

and then you shuffle it and get gydwsk... as an example, and the dictionary should look like

{'a':'g', 'b':'y', 'c':'d'...}

Im not sure where to begin, any help is appreciated.


问:
ASPMVC4 How do I use a ViewModel and dropdown list to get user selection?
I'm trying to use a strongly typed ViewModel rather than a ViewBag to present data in a dropdown list. I want to get the user's selection back.

My controller code looks like this:

```<code>public ActionResult Index()
{
ReportsHelper rh = new ReportsHelper();
List<SecurityProfile> securityProfiles = rh.GetSecurityProfiles();

List<SelectListItem> listItems = new List<SelectListItem>();
foreach (SecurityProfile secProf in securityProfiles)
{
SelectListItem item = new SelectListItem();
item.Value = secProf.SecurityProfileNum.ToString();
item.Text = secProf.SecurityProfileName;
listItems.Add(item);
}

var spvm = new SecurityProfileViewModel();
spvm.listItems = listItems;
return View(spvm);
}
</code>```

My ViewModel looks like this:

```<code>public class SecurityProfileViewModel
{
public IEnumerable<SelectListItem> listItems { get; set; }
}
</code>```

My View looks like this:

```<code>@model ClearWeighWebReporting.ViewModels.SecurityProfileViewModel

@{
ViewBag.Title = "Index";
}

@Html.DropDownListFor(Model.listItems, "--Select One--")
</code>```

The code above doesn't work. I get a build error on the following line of Controller code:

```<code>spvm.listItems = listItems;
</code>```

And I get an error on the following line of View code:

```<code>@Html.DropDownListFor(Model.listItems, "--Select One--")
</code>```

What am I doing wrong?
Furthermore, how do I get the user selection back?

答:
Add a new property to your view model to hold the selected option value.

```<code>public class SecurityProfileViewModel
{
   public int SelectedProfileNum { set;get;}
   public IEnumerable<SelectListItem> listItems { get; set; }
}
</code>```

Now in your view, Use DropDownListFor helper method.

```<code>@Html.DropDownListFor(x=>x.SelectedProfileNum,Model.listItems,"Select--")
</code>```

This will generate the markup for a SELECT Element with name ="SelectedProfileNum"

One suggestion : Try to use PascalCasing when writing C# classes and be consistent. You may rename listItems to  ListItems

Body:
I'm trying to use a strongly typed ViewModel rather than a ViewBag to present data in a dropdown list. I want to get the user's selection back.

My controller code looks like this:

public ActionResult Index()
{
ReportsHelper rh = new ReportsHelper();
List<SecurityProfile> securityProfiles = rh.GetSecurityProfiles();

List<SelectListItem> listItems = new List<SelectListItem>();
foreach (SecurityProfile secProf in securityProfiles)
{
SelectListItem item = new SelectListItem();
item.Value = secProf.SecurityProfileNum.ToString();
item.Text = secProf.SecurityProfileName;
listItems.Add(item);
}

var spvm = new SecurityProfileViewModel();
spvm.listItems = listItems;
return View(spvm);
}

My ViewModel looks like this:

public class SecurityProfileViewModel
{
public IEnumerable<SelectListItem> listItems { get; set; }
}

My View looks like this:

@model ClearWeighWebReporting.ViewModels.SecurityProfileViewModel

@{
ViewBag.Title = "Index";
}

@Html.DropDownListFor(Model.listItems, "--Select One--")

The code above doesn't work. I get a build error on the following line of Controller code:

spvm.listItems = listItems;

And I get an error on the following line of View code:

@Html.DropDownListFor(Model.listItems, "--Select One--")

What am I doing wrong?
Furthermore, how do I get the user selection back?

Body:
Add a new property to your view model to hold the selected option value.

public class SecurityProfileViewModel
{
   public int SelectedProfileNum { set;get;}
   public IEnumerable<SelectListItem> listItems { get; set; }
}

Now in your view, Use DropDownListFor helper method.

@Html.DropDownListFor(x=>x.SelectedProfileNum,Model.listItems,"Select--")

This will generate the markup for a SELECT Element with name ="SelectedProfileNum"

One suggestion : Try to use PascalCasing when writing C# classes and be consistent. You may rename listItems to  ListItems


问:
Bootstrap 3 extra large (xl) columns
In Bootstrap's LESS build can someone please tell me how to add a fifth device size, extra large (col-xl-#)?

答:
https://github.com/shenders13/bootstrap-grid-100cols-with-xl-and-xxl

A CSS file that contains the bootstrap grid with additional xlg ( > 1500px width ) and xxlg ( > 2000 px width) classes. The grid is split into columns with 1/100 width of the parent div.

Title: Bootstrap 3 extra large (xl) columns


答:
```<code>with open('input.txt', 'r') as rfp:
  with open('output.txt', 'w') as wfp:
    for line in rfp:
      if ilikethis(line):
        wfp.write(line)
</code>```

Title: Remove lines from a text file which do not contain a certain string with python

Body: I am trying to form a quotes file of a specific user name in a log file.  How do I remove every line that does not contain the specific user name in it?  Or how do I write all the lines which contain this user name to a new file?


问:
how to get the last day of the month from a given date
I have a column of dates in my dataframe and I'd like to get the last day of the month from the dates
example, if the date is '2017-01-25' I want to get '2017-01-31'
I suppose I can get the month and year number from the dates and use monthrange to figure out the last day of the month but I'm looking for a one line code  </p>

答:
If you have a date d then the simplest way is to use the calendar module to find the number of days in the month:

```<code>datetime.date(d.year, d.month, calendar.monthrange(d.year, d.month)[-1])
</code>```

Alternatively, using only datetime, we just find the first day of the next month and then remove a day:

```<code>datetime.date(d.year + d.month // 12,
              d.month % 12 + 1, 1) - datetime.timedelta(1)
</code>```

You might find the logic clearer if expressed as:

```<code>datetime.date(d.year + (d.month == 12),
              (d.month + 1 if d.month < 12 else 1), 1) - datetime.timedelta(1)
</code>```

Body:
If you have a date d then the simplest way is to use the calendar module to find the number of days in the month:

datetime.date(d.year, d.month, calendar.monthrange(d.year, d.month)[-1])

Alternatively, using only datetime, we just find the first day of the next month and then remove a day:

datetime.date(d.year + d.month // 12,
              d.month % 12 + 1, 1) - datetime.timedelta(1)

You might find the logic clearer if expressed as:

datetime.date(d.year + (d.month == 12),
              (d.month + 1 if d.month < 12 else 1), 1) - datetime.timedelta(1)


答:
This code should work (python version < 3.0):</p>

```<code>import random
keys="abcdefg"
dictionary = {}
shuffled = ''.join(random.sample(keys,len(keys)))
shuffled_iterator = 0
for letter in keys:
  dictionary[letter] = shuffled[shuffled_iterator]
  shuffled_iterator +=1

print dictionary
</code>```

Title: Making a dictionary from a list

Body:
This code should work (python version < 3.0):

import random
keys="abcdefg"
dictionary = {}
shuffled = ''.join(random.sample(keys,len(keys)))
shuffled_iterator = 0
for letter in keys:
  dictionary[letter] = shuffled[shuffled_iterator]
  shuffled_iterator +=1

print dictionary


问:
Need Help in send news letter using PHP mail function
Need your help in over coming the following issues.

i need to send opt-in newsletters to the user. But using "gmail SMTP", i will not be able to send more than 400 mails per day.

Even if i use the mail option given in the shared server, i will not be able to send mails more than 300 mails per day.

Can you please suggest any other way i can handle this issue. Is it possible to use PHP mail functions? are there any limitations in sending the number of mails to the users.

can a server control the mails sent using PHP mail function.

Thanks for reading.

thanks a lot

答:
1- you can buy vps and send many mail

2- you can buy smtp server for many sent

3- you can buy valid ip and set in your pc ... run somethings like postfix and sent mail in this way ...


答:
A one liner. You can use random.sample to avoid the in place reordering nature of random.shuffle. Then combine the shuffled and non-shuffled values using zip, which can be passed directly to the dict constructor to make the new dict.

The use of alc as a shortening for ascii_lowercase is for brevity in the example and is probably a bit too brutal a shortening for most production code.

```<code>>>> from string import ascii_lowercase as alc
>>> from random import sample
>>> dict(zip(alc, sample(alc, len(alc))))
{'b': 'a', 's': 'w', 'v': 'g', 'g': 'n', 'k': 'v', 'c': 'h', 'h': 'j', 'u': 'f', 'd': 'i', 'n': 'p', 'x': 'y', 'r': 'm', 't': 'u', 'o': 's', 'j': 'e', 'e': 'c', 'l': 'b', 'y': 'z', 'q': 'k', 'z': 'd', 'f': 't', 'p': 'r', 'm': 'l', 'i': 'o', 'w': 'x', 'a': 'q'}
</code>```

You will not see them in alphabetical order, but this is expected from an unordered container.

Title: Making a dictionary from a list

Body:
A one liner. You can use random.sample to avoid the in place reordering nature of random.shuffle. Then combine the shuffled and non-shuffled values using zip, which can be passed directly to the dict constructor to make the new dict.

The use of alc as a shortening for ascii_lowercase is for brevity in the example and is probably a bit too brutal a shortening for most production code.

>>> from string import ascii_lowercase as alc
>>> from random import sample
>>> dict(zip(alc, sample(alc, len(alc))))
{'b': 'a', 's': 'w', 'v': 'g', 'g': 'n', 'k': 'v', 'c': 'h', 'h': 'j', 'u': 'f', 'd': 'i', 'n': 'p', 'x': 'y', 'r': 'm', 't': 'u', 'o': 's', 'j': 'e', 'e': 'c', 'l': 'b', 'y': 'z', 'q': 'k', 'z': 'd', 'f': 't', 'p': 'r', 'm': 'l', 'i': 'o', 'w': 'x', 'a': 'q'}

You will not see them in alphabetical order, but this is expected from an unordered container.


答:
Your js is not rendering properly as mentioned by others. I have shown a way to achieve this in the following example. Here I have created divs and appended them as children one after another.

Example Snippet

$(document).ready(function() {
  var res = document.getElementById('results');
  var con = document.createElement('div');
  con.className = 'container-fluid';
  var newdiv = document.createElement('div');
  newdiv.className = 'row';
  res.appendChild(con);
  con.appendChild(newdiv);

  for (var i = 0; i < 3; i++) {
    var con1 = document.createElement('div');
    con1.className = 'col-md-4 col-xs-4';
    newdiv.appendChild(con1);

    var text = document.createTextNode(i + ' Col');
    con1.appendChild(text);
  }
  document.getElementById('results').innerHTML += 'After container';
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id="results">
</div></code>```

Title: Displaying 3 columns of data using bootstrap? Data shows as a row instead

Body:
Why are the class="col" classes not causing the data to show as a row containing 3 columns?

https://jsfiddle.net/bobbyrne01/b63g4kpe/1/

Html:

https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js
https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css

Js:

document.getElementById('results').innerHTML += '
';
document.getElementById('results').innerHTML += '
';
for (var i = 0; i < 3; i++) {
  document.getElementById('results').innerHTML += '
';
  document.getElementById('results').innerHTML += i + ' Col';
}
document.getElementById('results').innerHTML += '
';
document.getElementById('results').innerHTML += '

';
document.getElementById('results').innerHTML += 'After container';

Body:
Your js is not rendering properly as mentioned by others. I have shown a way to achieve this in the following example. Here I have created divs and appended them as children one after another.

Example Snippet

$(document).ready(function() {
  var res = document.getElementById('results');
  var con = document.createElement('div');
  con.className = 'container-fluid';
  var newdiv = document.createElement('div');
  newdiv.className = 'row';
  res.appendChild(con);
  con.appendChild(newdiv);

  for (var i = 0; i < 3; i++) {
    var con1 = document.createElement('div');
    con1.className = 'col-md-4 col-xs-4';
    newdiv.appendChild(con1);

    var text = document.createTextNode(i + ' Col');
    con1.appendChild(text);
  }
  document.getElementById('results').innerHTML += 'After container';
});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id="results">
</div>


问:
Refactoring code in C++
The constructor function for the class route originally contained the following code that checks if an element ("gpx", "rte", etc) exists within a file. Which runs as it should.

```<code>  if (! elementExists(source,"gpx"))
  {
      oss << endl << "no gpx tag";
      constructorReport = oss.str();
      constructorSucceeded = false;
      return;
  }
  if (! elementExists(source,"rte"))
  {
      oss << endl << "no rte tag";
      constructorReport = oss.str();
      constructorSucceeded = false;
      return;
  }
</code>```

I've tried to introduce a function to replace these if statements. The program builds okay.

```<code>void Route::constCheck(string source, string type)
{

    if (! XML_Parser::elementExists(source, type))
    {
        std::ostringstream oss;
        oss << std::endl << "no" << type <<" tag";
        constructorReport = oss.str();
        constructorSucceeded = false;
        return;
    }
}
</code>```

I've changed the gpx file which it checks to produce an error but with my added function it continues as if there is no error.

Any help is appreciated and please let me know if you need more info. I tried to keep the code light per guidelines.

答:
In your original code, you return from the function the first time one of the tests fails, you don't continue trying the other tests.

Now that you've moved the test into a function, there's no way for the caller to know if the test fails, so it will perform all of them, and never return from its function when one of them fails. You need this function to return a boolean that indicates whether it failed.

```<code>bool Route::constCheck(string source, string type)
{

    if (! XML_Parser::elementExists(source, type))
    {
        std::ostringstream oss;
        oss << std::endl << "no" << type <<" tag";
        constructorReport = oss.str();
        constructorSucceeded = false;
        return false;
    }
    return true;
}
</code>```

Then the replacement for your original code would look like:

```<code>if (!constCheck(source, "gpx")) {
    return;
}
if (!constCheck(source, "rte")) {
    return;
}
</code>```

Title: Refactoring code in C++

Body:
The constructor function for the class route originally contained the following code that checks if an element ("gpx", "rte", etc) exists within a file. Which runs as it should.

  if (! elementExists(source,"gpx"))
  {
      oss << endl << "no gpx tag";
      constructorReport = oss.str();
      constructorSucceeded = false;
      return;
  }
  if (! elementExists(source,"rte"))
  {
      oss << endl << "no rte tag";
      constructorReport = oss.str();
      constructorSucceeded = false;
      return;
  }

I've tried to introduce a function to replace these if statements. The program builds okay.

void Route::constCheck(string source, string type)
{

    if (! XML_Parser::elementExists(source, type))
    {
        std::ostringstream oss;
        oss << std::endl << "no" << type <<" tag";
        constructorReport = oss.str();
        constructorSucceeded = false;
        return;
    }
}

I've changed the gpx file which it checks to produce an error but with my added function it continues as if there is no error.

Any help is appreciated and please let me know if you need more info. I tried to keep the code light per guidelines.

Body:
In your original code, you return from the function the first time one of the tests fails, you don't continue trying the other tests.

Now that you've moved the test into a function, there's no way for the caller to know if the test fails, so it will perform all of them, and never return from its function when one of them fails. You need this function to return a boolean that indicates whether it failed.

bool Route::constCheck(string source, string type)
{

    if (! XML_Parser::elementExists(source, type))
    {
        std::ostringstream oss;
        oss << std::endl << "no" << type <<" tag";
        constructorReport = oss.str();
        constructorSucceeded = false;
        return false;
    }
    return true;
}

Then the replacement for your original code would look like:

if (!constCheck(source, "gpx")) {
    return;
}
if (!constCheck(source, "rte")) {
    return;
}


问:
undefined symbol: PySlice_AdjustIndices when importing PyTorch
I am trying to use PyTorch, and I think there is some version of something that isn't lining up.

From what little I can suss out, it seems that there are some functions in the newest version of PyTorch (?) that can't be accessed on my system. I suspect it has something to do with Python version 3.6.1 as opposed to 3.6.0. But I can't figure it out. If anyone has any advice on what I can do to rectify this error:

```<code>/home/ubuntu/nbs/torch_utils.py in <module>()
----> 1 import torch
      2 import torch.nn as nn
      3 import torch.nn.parallel
      4 import torch.utils.data
      5 from torch import optim

/home/ubuntu/anaconda3/lib/python3.6/site-packages/torch/__init__.py in <module>()
     51 sys.setdlopenflags(_dl_flags.RTLD_GLOBAL | _dl_flags.RTLD_NOW)
     52
---> 53 from torch._C import *
     54
     55 __all__ += [name for name in dir(_C)

ImportError: /home/ubuntu/anaconda3/lib/python3.6/site-packages/torch/_C.cpython-36m-x86_64-linux-gnu.so: undefined symbol: PySlice_AdjustIndices
</code>```

Here's the details on my system:

I am running Ubuntu on AWS, Ubuntu 16.04.2 LTS

my Cuda info is Cuda compilation tools, release 8.0, V8.0.61

I have Anaconda, conda 4.3.15

My python version is Python 3.6.0 :: Anaconda custom (64-bit)

Thanks.

答:
I have the same problem, maybe the build is broken for Ubuntu / Python 3.6.

Anyway, until they fix this problem, you can install PyTorch by downgrading one version:

conda install pytorch=0.1.10 torchvision -c soumith

This version runs just fine on all my tests.

Body:
I am trying to use PyTorch, and I think there is some version of something that isn't lining up.

From what little I can suss out, it seems that there are some functions in the newest version of PyTorch (?) that can't be accessed on my system. I suspect it has something to do with Python version 3.6.1 as opposed to 3.6.0. But I can't figure it out. If anyone has any advice on what I can do to rectify this error:

/home/ubuntu/nbs/torch_utils.py in <module>()
----> 1 import torch
      2 import torch.nn as nn
      3 import torch.nn.parallel
      4 import torch.utils.data
      5 from torch import optim

/home/ubuntu/anaconda3/lib/python3.6/site-packages/torch/__init__.py in <module>()
     51 sys.setdlopenflags(_dl_flags.RTLD_GLOBAL | _dl_flags.RTLD_NOW)
     52
---> 53 from torch._C import *
     54
     55 __all__ += [name for name in dir(_C)

ImportError: /home/ubuntu/anaconda3/lib/python3.6/site-packages/torch/_C.cpython-36m-x86_64-linux-gnu.so: undefined symbol: PySlice_AdjustIndices

Here's the details on my system:

I am running Ubuntu on AWS, Ubuntu 16.04.2 LTS

my Cuda info is Cuda compilation tools, release 8.0, V8.0.61

I have Anaconda, conda 4.3.15

My python version is Python 3.6.0 :: Anaconda custom (64-bit)

Thanks.


问:
Fix display value changing on child of flexbox. Inline-block being overridden
I've recently starting using flexbox and this is the first problem I've run into. I want my .wrp class below to remain display: inline-block; but one line seems to disable this value. That line is: flex-direction: column. When I remove that line my .wrp class starts behaving like an inline-block element again but then of course it loses it's flex-direction value. Is there a simple solution that doesn't require restructuring my HTML too much to keep the flex-direction behavior of flexbox but also keep the inline-block behavior on .wrp?

.contr {
  display: flex;
  flex-direction: column; /* this line seems to be breakig my display on .wrp */
  justify-content: center;
  height: 10rem;
  background-color: #eee;
}
.wrp {
  display: inline-block;
  height: 5rem;
  background-color: #ddd;
}
p {
  width: 100%;
  background-color: #ccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="contr">
  <div class="wrp">
    <p>I want this paragraph to stretch to fit it's content. Not full width.</p>
  </div>
</div></code>```

答:
You can't have an inline-block element within a flex. It looks like you may be looking for display: inline-table:

.contr {
  display: flex;
  flex-direction: column; /* this line seems to be breakig my display on .wrp */
  justify-content: center;
  height: 10rem;
  background-color: #eee;
}
.wrp {
  display: inline-table;
  height: 5rem;
  background-color: #ddd;
}
p {
  width: 100%;
  background-color: #ccc;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="contr">
  <div class="wrp">
    <p>I want this paragraph to stretch to fit it's content. Not full width.</p>
  </div>
</div></code>```

Hope this helps! :)

Body:
I've recently starting using flexbox and this is the first problem I've run into. I want my .wrp class below to remain display: inline-block; but one line seems to disable this value. That line is: flex-direction: column. When I remove that line my .wrp class starts behaving like an inline-block element again but then of course it loses it's flex-direction value. Is there a simple solution that doesn't require restructuring my HTML too much to keep the flex-direction behavior of flexbox but also keep the inline-block behavior on .wrp?

.contr {
  display: flex;
  flex-direction: column; /* this line seems to be breakig my display on .wrp */
  justify-content: center;
  height: 10rem;
  background-color: #eee;
}
.wrp {
  display: inline-block;
  height: 5rem;
  background-color: #ddd;
}
p {
  width: 100%;
  background-color: #ccc;
}

I want this paragraph to stretch to fit it's content. Not full width.

Body:
You can't have an inline-block element within a flex. It looks like you may be looking for display: inline-table:

.contr {
  display: flex;
  flex-direction: column; /* this line seems to be breakig my display on .wrp */
  justify-content: center;
  height: 10rem;
  background-color: #eee;
}
.wrp {
  display: inline-table;
  height: 5rem;
  background-color: #ddd;
}
p {
  width: 100%;
  background-color: #ccc;
}

<div class="contr">
  <div class="wrp">
    <p>I want this paragraph to stretch to fit it's content. Not full width.</p>
  </div>
</div>

Hope this helps! :)


问:
Calling external contract in solidity dynamically
I am trying to make a contract have a function that is capable of calling functions of another contract. The key part of my goal is that the contract should not be able to be deployed without any import statements and will not know the name of the contract by default. In other words the user of this contract would input the called contracts data (i.e. address, name) as parameters. What is the best way to accomplish this?</p>

答:
Not sure why this was downvoted.

If I understand the question correctly, you want to deploy the contract without knowledge of the specific details of the contracts it will have to communicate with.

You can greatly simplify this by assuming knowledge of their interfaces.

You can define interfaces without importing contract code. Define the function interfaces and leave the function definitions empty:

```<code>contract WidgetInterface {

   function doSomething() returns(uint) {}
   function somethingElse() returns(bool isTrue) {}

}
</code>```

Use that Interface contract to talk to actual contracts:

```<code>WidgetInterface w = WidgetInterface(actualContractAddress);
</code>```

In my opinion it will usually be possible and advisable to register authorized/valid contracts as you go. Maintain a list of the contracts it can safely talk to, along these lines:

```<code>if(!isAuthorized(actualContractAddress)) throw;
</code>```

where actualContractAddress is supplied by sender and isAuthorized() is a function you have worked out to query an internal registry.

Hope it helps.

Body:
Not sure why this was downvoted.

If I understand the question correctly, you want to deploy the contract without knowledge of the specific details of the contracts it will have to communicate with.

You can greatly simplify this by assuming knowledge of their interfaces.

You can define interfaces without importing contract code. Define the function interfaces and leave the function definitions empty:

contract WidgetInterface {

   function doSomething() returns(uint) {}
   function somethingElse() returns(bool isTrue) {}

}

Use that Interface contract to talk to actual contracts:

WidgetInterface w = WidgetInterface(actualContractAddress);

In my opinion it will usually be possible and advisable to register authorized/valid contracts as you go. Maintain a list of the contracts it can safely talk to, along these lines:

if(!isAuthorized(actualContractAddress)) throw;

where actualContractAddress is supplied by sender and isAuthorized() is a function you have worked out to query an internal registry.

Hope it helps.


问:
Remove lines from a text file which do not contain a certain string with python
I am trying to form a quotes file of a specific user name in a log file.  How do I remove every line that does not contain the specific user name in it?  Or how do I write all the lines which contain this user name to a new file?</p>

答:
```<code>with open(logfile) as f_in:
    lines = [l for l in f_in if username in l]
with open(outfile, 'w') as f_out:
    f_out.writelines(lines)
</code>```

Or if you don't want to store all the lines in memory

```<code>with open(logfile) as f_in:
    lines = (l for l in f_in if username in l)
    with open(outfile, 'w') as f_out:
        f_out.writelines(lines)
</code>```

I sort of like the first one better but for a large file, it might drag.

Body:
with open(logfile) as f_in:
    lines = [l for l in f_in if username in l]
with open(outfile, 'w') as f_out:
    f_out.writelines(lines)

Or if you don't want to store all the lines in memory

with open(logfile) as f_in:
    lines = (l for l in f_in if username in l)
    with open(outfile, 'w') as f_out:
        f_out.writelines(lines)

I sort of like the first one better but for a large file, it might drag.


问:
HTA & Batch Hybrid, passing variables from BATCH section
I'm attempting to write a batch + hta hybrid script that will allow me to pass variables from the batch section of the script to the hta section, so that way I can generate things like the computers model number etc.

This is what I have so far - Batch:

```<code><!-- :: Batch section
    @echo off
    Pushd "%~dp0"
    setlocal

    FOR /F "tokens=2 delims='='" %%A in ('wmic ComputerSystem Get Model /value') do SET model=%%A

    for /F "delims=" %%a in ('mshta.exe "%~F0" "%model%"') do set "HTAreply=%%a"
    echo End of HTA window, reply: "%HTAreply%"
    goto :EOF
    -->
</code>```

As you can see I attempted to use %model% as a parameter, and I tried to use arg1 in my VBScript section to try to use that variable - but it did not work.

So in my hta section, this is my vbscript:

```<code><script language="VBScript">

    MsgBox arg1

</script>
</code>```

Which just opens an empty box.

I've been searching for a while online trying to figure out a way to do this and I cannot figure it out. The way I got around this before was basically creating a batch script that creates a new file which is the hta & batch hybrid, but I want to avoid doing that for simplicity.

Any help would be much appreciated

答:
You can access environment variables in the HTA runtime by using the Wscript.Shell COM object's Environment object.  You can pass data back from HTA to the Batch thread over stdout by using Scripting.FileSystemObject's GetStandardStream method.  Here's a demonstration of both:

```

<p>For what it's worth, you can also access VBScript in a hybrid format using <code>cscript</code> by kludging a pretend .wsf file extension.  The advantage, besides getting rid of the brief flicker of an HTA window appearing and disappearing, is that you can pass script arguments directly without having to access the <code>Environment("Process")</code> scope.</p>

<pre class="lang-js prettyprint-override"><code><!-- : batch portion
@echo off & setlocal

FOR /F "tokens=2 delims==" %%A in ('wmic ComputerSystem Get Model /value') do SET model=%%A

for /F "delims=" %%a in ('cscript /nologo "%~f0?.wsf" "%model%"') do set "VBreply=%%a"
echo End of VB script, reply: "%VBreply%"

goto :EOF

: VBScript -->
<job>
    <script language="VBScript">
        model = WScript.Arguments(0)

        MsgBox model
        Wscript.Echo "response"
    </script>
</job>
</code>```

And hybrid Batch + JScript is even easier.  It's also possible to have both VBScript and JScript code as multiple jobs with the .wsf method.

Body:
I'm attempting to write a batch + hta hybrid script that will allow me to pass variables from the batch section of the script to the hta section, so that way I can generate things like the computers model number etc.

This is what I have so far - Batch:

As you can see I attempted to use %model% as a parameter, and I tried to use arg1 in my VBScript section to try to use that variable - but it did not work.

So in my hta section, this is my vbscript:

Which just opens an empty box.

I've been searching for a while online trying to figure out a way to do this and I cannot figure it out. The way I got around this before was basically creating a batch script that creates a new file which is the hta & batch hybrid, but I want to avoid doing that for simplicity.

Any help would be much appreciated

Body:
You can access environment variables in the HTA runtime by using the Wscript.Shell COM object's Environment object.  You can pass data back from HTA to the Batch thread over stdout by using Scripting.FileSystemObject's GetStandardStream method.  Here's a demonstration of both:

<!-- :: Batch section
@echo off & setlocal
Pushd "%~dp0"

FOR /F "tokens=2 delims==" %%A in ('wmic ComputerSystem Get Model /value') do SET model=%%A

for /F "delims=" %%a in ('mshta.exe "%~f0"') do set "HTAreply=%%a"
echo End of HTA window, reply: "%HTAreply%"
goto :EOF
-->
<script language="VBScript">

    Set Env = CreateObject("Wscript.Shell").Environment("Process")
    Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1)

    MsgBox Env("model")
    StdOut.Write("response")

    Set Env = Nothing
    Set StdOut = Nothing

    close()

</script>

For what it's worth, you can also access VBScript in a hybrid format using cscript by kludging a pretend .wsf file extension.  The advantage, besides getting rid of the brief flicker of an HTA window appearing and disappearing, is that you can pass script arguments directly without having to access the Environment("Process") scope.

<!-- : batch portion
@echo off & setlocal

FOR /F "tokens=2 delims==" %%A in ('wmic ComputerSystem Get Model /value') do SET model=%%A

for /F "delims=" %%a in ('cscript /nologo "%~f0?.wsf" "%model%"') do set "VBreply=%%a"
echo End of VB script, reply: "%VBreply%"

goto :EOF

: VBScript -->
<job>
    <script language="VBScript">
        model = WScript.Arguments(0)

        MsgBox model
        Wscript.Echo "response"
    </script>
</job>

And hybrid Batch + JScript is even easier.  It's also possible to have both VBScript and JScript code as multiple jobs with the .wsf method.


问:
How do I check the order in which Keras' flow_from_directory method processes folders?
When doing transfer learning, I am first feeding the images through the bottom layers of the VGG16 network. I am using a generator function.

```<code>datagen = ImageDataGenerator(1./255)
generator = datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size = 32,
    class_mode=None,
    shuffle=False
)
model.predict_generator(generator, nb_train_samples)
</code>```

I am setting the class mode to none, because I only want the data output. I am setting shuffle = false, because I want to feed the predicted features later here, and match them up with the ground truth category variable:

```<code>train_data = np.lead(open(file_name, 'rb'))
train_labels = np.array([0] * NUMBER_OF_ITEMS_FOR_ITEM1 +
                        [1] * NUMBER_OF_ITEMS_FOR_ITEM2 +...
                        [n-1] * NUMBER_OF_ITEMS_FOR_ITEMN
</code>```

The problem here is that I don't know in which order the files are read. How can I find it out? Or even better yet, how can I just avoid having to guess the correct order? I am asking because I am almost certain that the low prediction accuracy has to do with labels not matching up.

答:
I looked into the source code. I should note that since I posted this question, Keras was updated to version 2.0. So the answer is based on that version.

ImageDataGenerator inherits from DirectoryGenerator. In it, I find the following lines:

```<code>    if not classes:
        classes = []
        for subdir in sorted(os.listdir(directory)):
            if os.path.isdir(os.path.join(directory, subdir)):
                classes.append(subdir)
    self.num_class = len(classes)
    self.class_indices = dict(zip(classes, range(len(classes))))

    def _recursive_list(subpath):
        return sorted(os.walk(subpath, followlinks=follow_links), key=lambda tpl: tpl[0])

    for subdir in classes:
        subpath = os.path.join(directory, subdir)
        for root, _, files in _recursive_list(subpath):
            for fname in files:
                is_valid = False
                for extension in white_list_formats:
                    if fname.lower().endswith('.' + extension):
                        is_valid = True
                        break
                if is_valid:
                    self.samples += 1
    print('Found %d images belonging to %d classes.' % (self.samples, self.num_class))
</code>```

Note line 3 where it says "sorted(os.listdir(direcectory, subdir))". The generator traverses all folders in alphabetical order.

Later on the definition of a _recursive_list uses the same logic on substructures as well.

So the answer is: Folders are processed in alphabetical order which somehow makes sense.

ContentLicense: CC BY-SA 4.0

Body:
When doing transfer learning, I am first feeding the images through the bottom layers of the VGG16 network. I am using a generator function.

datagen = ImageDataGenerator(1./255)
generator = datagen.flow_from_directory(
    train_data_dir,
    target_size=(img_width, img_height),
    batch_size = 32,
    class_mode=None,
    shuffle=False
)
model.predict_generator(generator, nb_train_samples)

I am setting the class mode to none, because I only want the data output. I am setting shuffle = false, because I want to feed the predicted features later here, and match them up with the ground truth category variable:

train_data = np.lead(open(file_name, 'rb'))
train_labels = np.array([0] * NUMBER_OF_ITEMS_FOR_ITEM1 +
                        [1] * NUMBER_OF_ITEMS_FOR_ITEM2 +...
                        [n-1] * NUMBER_OF_ITEMS_FOR_ITEMN

The problem here is that I don't know in which order the files are read. How can I find it out? Or even better yet, how can I just avoid having to guess the correct order? I am asking because I am almost certain that the low prediction accuracy has to do with labels not matching up.

Body:
I looked into the source code. I should note that since I posted this question, Keras was updated to version 2.0. So the answer is based on that version.

ImageDataGenerator inherits from DirectoryGenerator. In it, I find the following lines:

    if not classes:
        classes = []
        for subdir in sorted(os.listdir(directory)):
            if os.path.isdir(os.path.join(directory, subdir)):
                classes.append(subdir)
    self.num_class = len(classes)
    self.class_indices = dict(zip(classes, range(len(classes))))

    def _recursive_list(subpath):
        return sorted(os.walk(subpath, followlinks=follow_links), key=lambda tpl: tpl[0])

    for subdir in classes:
        subpath = os.path.join(directory, subdir)
        for root, _, files in _recursive_list(subpath):
            for fname in files:
                is_valid = False
                for extension in white_list_formats:
                    if fname.lower().endswith('.' + extension):
                        is_valid = True
                        break
                if is_valid:
                    self.samples += 1
    print('Found %d images belonging to %d classes.' % (self.samples, self.num_class))

Note line 3 where it says "sorted(os.listdir(direcectory, subdir))". The generator traverses all folders in alphabetical order.

Later on the definition of a _recursive_list uses the same logic on substructures as well.

So the answer is: Folders are processed in alphabetical order which somehow makes sense.


问:
Python Pandas join or shape data to add two new columns with repeated values
Ok. I have no idea how to actually ask this question but here goes. I have a dataframe like this.

```<code>import pandas as pd

d = {'Product' : ['Product_A','Product_A', 'Product_B', 'Product_B'],'Country' : ["DE", "DE", "DE","DE"],'Billed_Week' : ['201652', '201701', '201652', '201701'],'Billings' : [1116, 9030, 7476, 2859]}
df = pd.DataFrame(d)

sequence = ['Product','Country','Billed_Week','Billings']
df = df.reindex(columns=sequence)
</code>```

output:

```<code>    Product   Country  Billed_Week  Billings
0  Product_A      DE     201652      1116
1  Product_A      DE     201701      9030
2  Product_B      DE     201652      7476
3  Product_B      DE     201701      2859
</code>```

I need to add two more columns "Billed_Week_New" and "Billings_New" where they  have values added in a repeated format based on the grouping of the entire first dataframe. So for the first record of the first dataframe I need to expand by the number of Weeks in the whole grouping. I will just show with the output required.

Output required:

```<code>Product    Country  Billed_Week  Billings   Billed_Week_New   Billings_New
Product_A   DE       201652       1116        201652             1116
Product_A   DE       201652       1116        201701             9030
Product_A   DE       201701       9030        201652             1116
Product_A   DE       201701       9030        201701             9030
Product_B   DE       201652       7476        201652             7476
Product_B   DE       201652       7476        201701             2859
Product_B   DE       201701       2859        201652             7476
Product_B   DE       201701       2859        201701             2859
</code>```

答:
Consider the cross join, returning Cartesian product between columns (all possible combinations between sets on same key(s) here being Product and Country):

```<code>mdf = df.merge(df, on=['Product','Country']).\
      rename(columns = {'Billed_Week_x': 'Billed_Week',
                        'Billings_x': 'Billings',
                        'Billed_Week_x':'Billed_Week_New',
                        'Billings_y':'Billings_New'})
print(mdf)

#      Product Country Billed_Week  Billings Billed_Week_New  Billings_New
# 0  Product_A      DE      201652      1116          201652          1116
# 1  Product_A      DE      201652      1116          201701          9030
# 2  Product_A      DE      201701      9030          201652          1116
# 3  Product_A      DE      201701      9030          201701          9030
# 4  Product_B      DE      201652      7476          201652          7476
# 5  Product_B      DE      201652      7476          201701          2859
# 6  Product_B      DE      201701      2859          201652          7476
# 7  Product_B      DE      201701      2859          201701          2859
</code>```

Body:
Ok. I have no idea how to actually ask this question but here goes. I have a dataframe like this.

import pandas as pd

d = {'Product' : ['Product_A','Product_A', 'Product_B', 'Product_B'],'Country' : ["DE", "DE", "DE","DE"],'Billed_Week' : ['201652', '201701', '201652', '201701'],'Billings' : [1116, 9030, 7476, 2859]}
df = pd.DataFrame(d)

sequence = ['Product','Country','Billed_Week','Billings']
df = df.reindex(columns=sequence)

output:

    Product   Country  Billed_Week  Billings
0  Product_A      DE     201652      1116
1  Product_A      DE     201701      9030
2  Product_B      DE     201652      7476
3  Product_B      DE     201701      2859

I need to add two more columns "Billed_Week_New" and "Billings_New" where they  have values added in a repeated format based on the grouping of the entire first dataframe. So for the first record of the first dataframe I need to expand by the number of Weeks in the whole grouping. I will just show with the output required.

Output required:

Product    Country  Billed_Week  Billings   Billed_Week_New   Billings_New
Product_A   DE       201652       1116        201652             1116
Product_A   DE       201652       1116        201701             9030
Product_A   DE       201701       9030        201652             1116
Product_A   DE       201701       9030        201701             9030
Product_B   DE       201652       7476        201652             7476
Product_B   DE       201652       7476        201701             2859
Product_B   DE       201701       2859        201652             7476
Product_B   DE       201701       2859        201701             2859

Body:
Consider the cross join, returning Cartesian product between columns (all possible combinations between sets on same key(s) here being Product and Country):

mdf = df.merge(df, on=['Product','Country']).\
      rename(columns = {'Billed_Week_x': 'Billed_Week',
                        'Billings_x': 'Billings',
                        'Billed_Week_x':'Billed_Week_New',
                        'Billings_y':'Billings_New'})
print(mdf)

#      Product Country Billed_Week  Billings Billed_Week_New  Billings_New
# 0  Product_A      DE      201652      1116          201652          1116
# 1  Product_A      DE      201652      1116          201701          9030
# 2  Product_A      DE      201701      9030          201652          1116
# 3  Product_A      DE      201701      9030          201701          9030
# 4  Product_B      DE      201652      7476          201652          7476
# 5  Product_B      DE      201652      7476          201701          2859
# 6  Product_B      DE      201701      2859          201652          7476
# 7  Product_B      DE      201701      2859          201701          2859


问:
SQL conditional for a field using multiple subqueries as cases
I am using Proc SQL, but this question should be relevant for all SQL variants. I am trying to populate a field BruceDPOtest with values from two subqueries with if the first query results in blanks--CASE WHEN BruceDPO = INPUT("", 8.) --it fills that blank with another subquery's BruceDPO value:

```<code>THEN (
SELECT SUM(PART_QTY) FROM RSCCParts LEFT JOIN DPO.DPO_PART_ORD_HST AS Total
ON RSCCParts.PartID = STRIP(Total.PART_NO_ID)
WHERE PUT(PROC_DT, YY.) LIKE '%2016%' GROUP BY PART_NO_ID) ELSE BruceDPO END
</code>```

For example, the first query gives the following results;

```<code>Part   DPO

1234   100
1235
</code>```

The second subquery that references data that can populate the second row is run to get:

```<code>Part   DPO

1234   100
1235   999
</code>```

Here is the full code:

```<code>    PROC SQL;
    CREATE VIEW DPOMergeView AS(SELECT *,
        CASE
            WHEN BruceDPO = INPUT("", 8.)  THEN (
        SELECT SUM(PART_QTY) FROM RSCCParts LEFT JOIN DPO.DPO_PART_ORD_HST AS Total
            ON RSCCParts.PartID = STRIP(Total.PART_NO_ID)
        WHERE PUT(PROC_DT, YY.) LIKE '%2016%' GROUP BY PART_NO_ID)
            ELSE BruceDPO
        END
    AS BruceDPOtest
        FROM
            RSCCParts
        LEFT JOIN (SELECT RSCCParts.PartID AS BrucePartID, BruceDPO, Year
            FROM RSCCParts
                LEFT JOIN
                    (SELECT PART_NO_ID AS PartNumber, SUM(PART_QTY) AS BruceDPO, STRIP(YR) AS Year
                        FROM
                            DPO.DPO_PART_HST_MAIN
                        WHERE YR = '2016'
                            GROUP BY PartNumber, Year) AS FQuery
                                ON
                                RSCCParts.PartID = STRIP(FQuery.PartNumber)) AS B
                                ON RSCCParts.PartID = B.BrucePartID);
QUIT;
</code>```

As I run this query, it gets stuck on DATA Step and after 30 minutes, I stopped the query. Am I doing this correctly? If there is a better way to do this please let me know!

答:
Normally I avoid correlated subqueries in SQL since it just makes it feel like you are trying to process the data record by record instead of by combining sets.  But if you did what to use syntax like

```<code>case when (x) then (sub query result) else variable_name end
</code>```

then the subquery needs to return only one value.  Your query

```<code>SELECT SUM(PART_QTY)
FROM RSCCParts LEFT JOIN DPO.DPO_PART_ORD_HST AS Total
ON RSCCParts.PartID = STRIP(Total.PART_NO_ID)
WHERE PUT(PROC_DT, YY.) LIKE '%2016%'
GROUP BY PART_NO_ID
</code>```

looks like it will return multiple observations since you are using a GROUP BY clause.

Shouldn't that subquery look more like

```<code>SELECT SUM(Total.PART_QTY)
FROM DPO.DPO_PART_ORD_HST AS Total
WHERE  RSCCParts.PartID = STRIP(Total.PART_NO_ID)
  AND PUT(PROC_DT, YY.) LIKE '%2016%'
</code>```

Your query has multiple references to RSCCPARTS table so you might need to introduce an alias to each so that you can clarify which one you want to use to get PARTID from to match to PART_NO_ID.

Body:
I am using Proc SQL, but this question should be relevant for all SQL variants. I am trying to populate a field BruceDPOtest with values from two subqueries with if the first query results in blanks--CASE WHEN BruceDPO = INPUT("", 8.) --it fills that blank with another subquery's BruceDPO value:

THEN (
SELECT SUM(PART_QTY) FROM RSCCParts LEFT JOIN DPO.DPO_PART_ORD_HST AS Total
ON RSCCParts.PartID = STRIP(Total.PART_NO_ID)
WHERE PUT(PROC_DT, YY.) LIKE '%2016%' GROUP BY PART_NO_ID) ELSE BruceDPO END

For example, the first query gives the following results;

Part   DPO

1234   100
1235

The second subquery that references data that can populate the second row is run to get:

Part   DPO

1234   100
1235   999

Here is the full code:

    PROC SQL;
    CREATE VIEW DPOMergeView AS(SELECT *,
        CASE
            WHEN BruceDPO = INPUT("", 8.)  THEN (
        SELECT SUM(PART_QTY) FROM RSCCParts LEFT JOIN DPO.DPO_PART_ORD_HST AS Total
            ON RSCCParts.PartID = STRIP(Total.PART_NO_ID)
        WHERE PUT(PROC_DT, YY.) LIKE '%2016%' GROUP BY PART_NO_ID)
            ELSE BruceDPO
        END
    AS BruceDPOtest
        FROM
            RSCCParts
        LEFT JOIN (SELECT RSCCParts.PartID AS BrucePartID, BruceDPO, Year
            FROM RSCCParts
                LEFT JOIN
                    (SELECT PART_NO_ID AS PartNumber, SUM(PART_QTY) AS BruceDPO, STRIP(YR) AS Year
                        FROM
                            DPO.DPO_PART_HST_MAIN
                        WHERE YR = '2016'
                            GROUP BY PartNumber, Year) AS FQuery
                                ON
                                RSCCParts.PartID = STRIP(FQuery.PartNumber)) AS B
                                ON RSCCParts.PartID = B.BrucePartID);
QUIT;

As I run this query, it gets stuck on DATA Step and after 30 minutes, I stopped the query. Am I doing this correctly? If there is a better way to do this please let me know!

Body:
Normally I avoid correlated subqueries in SQL since it just makes it feel like you are trying to process the data record by record instead of by combining sets.  But if you did what to use syntax like

case when (x) then (sub query result) else variable_name end

then the subquery needs to return only one value.  Your query

SELECT SUM(PART_QTY)
FROM RSCCParts LEFT JOIN DPO.DPO_PART_ORD_HST AS Total
ON RSCCParts.PartID = STRIP(Total.PART_NO_ID)
WHERE PUT(PROC_DT, YY.) LIKE '%2016%'
GROUP BY PART_NO_ID

looks like it will return multiple observations since you are using a GROUP BY clause.

Shouldn't that subquery look more like

SELECT SUM(Total.PART_QTY)
FROM DPO.DPO_PART_ORD_HST AS Total
WHERE  RSCCParts.PartID = STRIP(Total.PART_NO_ID)
  AND PUT(PROC_DT, YY.) LIKE '%2016%'

Your query has multiple references to RSCCPARTS table so you might need to introduce an alias to each so that you can clarify which one you want to use to get PARTID from to match to PART_NO_ID.