问:
Is there something wrong with my form?
I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?

I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""

I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.

I tried using

```<code><form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
</code>```

and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?

Form code:

```<code>echo '    <div id="specialsForm"><h3>Interested in this coupon? Email us! </h3>
                                            <form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
                                              Name: <input name="name" type="text" /><br />
                                              Email: <input name="email" type="text" /><br />
                                              Phone Number: <input name="phone" type="text" /><br /><br />
                                              Comment: <br/>
                                              <textarea name="comment" rows="5" cols="30"></textarea><br /><br />
                                              <input type="submit" name="submit" value="Submit Email"/>
                                            </form></div>
                                            <div style="clear:both;"></div><br /><br />';
</code>```

and the vaildator:

```<code>if(isset($_POST['submit'])) {

                                                $errors = array();
                                                if (empty($name)) {
                                                    $errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
                                                }
                                                if (empty($phone) || empty($email)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!is_numeric($phone)) {
                                                    $errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
                                                }
                                                if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
                                                    $errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
                                                }
                                                if ($errors) {
                                                    echo '<p style="font-weight:bold;text-align:center;">There were some errors:</p> ';
                                                    echo '<ul><li>', implode('</li><li>', $errors), '</li></ul><br/>';
                                                } else {
                                                    mail( "email@hotmail.com", "Monthly Specials Email",
                                                        "Name: $name\n".
                                                        "Email: $email\n".
                                                        "Phone Number: $phone\n".
                                                        "Comment: $comment", "From: $email");
                                                    echo'<span id="valid">Message has been sent</span><br/>';
                                                }
}
</code>```

答:
A browser doesn't have to (p)refill a form. Some do for convenience, but you cannot rely on it.

In case you display the form again, you could set the values of the inputs like this:

```<code>$value = isset($_POST['foo']) : $_POST['foo'] : '';
echo '<input type="text" value="'. $value .'" name="foo" />';
</code>```

Of course you should check and sanitize the POSTed data before including it in your HTML to not open up any XSS vulnerabilities.

Title: Is there something wrong with my form?

Body:
I have my form working and all of the errors and everything works.
But if you have an error, it refreshes the page and removes any text that was inserted before the submit button was clicked and you have to re-enter all of the information.
Anyway to fix this?

I think it has something to do with not using $_SERVER["PHP_SELF"] in the action of the form.
Instead I have action=""

I am doing this because the page that needs to be refreshed with the same info has a variable in its url (monthly_specials_info.php?date=Dec10) that was put there from the last page.

I tried using

<form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">

and it produced the right url. but the text was all removed anyway when form was submitted (with errors).. any ideas?

Form code:

echo '

Interested in this coupon? Email us!

                                            <form method="post" action="'.$_SERVER["PHP_SELF"].'?date='.$date.'">
                                              Name: <input name="name" type="text" />

                                              Email: <input name="email" type="text" />

                                              Phone Number: <input name="phone" type="text" />

                                              Comment:

                                              <textarea name="comment" rows="5" cols="30"></textarea>

                                              <input type="submit" name="submit" value="Submit Email"/>
                                            </form>

';

and the vaildator:

if(isset($_POST['submit'])) {

                                                $errors = array();
                                                if (empty($name)) {
                                                    $errors[] = 'ERROR: Missing Name
';
                                                }
                                                if (empty($phone) || empty($email)) {
                                                    $errors[] = 'ERROR: You must insert a phone number or email
';
                                                }
                                                if (!is_numeric($phone)) {
                                                    $errors[] = 'ERROR: You must insert a phone number or email
';
                                                }
                                                if (!preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}/', strtoupper($email))) {
                                                    $errors[] = 'ERROR: Please Insert a valid Email
';
                                                }
                                                if ($errors) {
                                                    echo '
There were some errors:
 ';
                                                    echo '

', implode('

', $errors), '

';
                                                } else {
                                                    mail( "email@hotmail.com", "Monthly Specials Email",
                                                        "Name: $name\n".
                                                        "Email: $email\n".
                                                        "Phone Number: $phone\n".
                                                        "Comment: $comment", "From: $email");
                                                    echo'Message has been sent
';
                                                }
}

Body:
A browser doesn't have to (p)refill a form. Some do for convenience, but you cannot rely on it.

In case you display the form again, you could set the values of the inputs like this:

$value = isset($_POST['foo']) : $_POST['foo'] : '';
echo '<input type="text" value="'. $value .'" name="foo" />';

Of course you should check and sanitize the POSTed data before including it in your HTML to not open up any XSS vulnerabilities.


来源: stackexchange

问:
How can I run protractor e2e tests on skeleton-esnext-webpack without building the app?
I've been using the skeleton navigation skeleton-esnext-webpack environment to run local tests on aurelia. However, sometimes I need to run my tests from a server already set up on the web. I'd like to keep the aurelia plugins intact but not wait so long for the local build to be built and ran since I already have it running elsewhere. The readme doesn't say much about how everything works.

Is there a way to temporarily run my tests while ignoring the local build and setup?

答:
Go the package.json file in the root and modify it as so:

```<code>"e2e": "concurrently --success first --kill-others \"npm run e2e:start\"",
</code>```

You can even keep the original and rename it something else and have that as a local call and rename the above line to run it without building it.

ContentLicense: CC BY-SA 3.0

Body:
Go the package.json file in the root and modify it as so:

"e2e": "concurrently --success first --kill-others \"npm run e2e:start\"",

You can even keep the original and rename it something else and have that as a local call and rename the above line to run it without building it.


问:
Pandas date_range with specific time ranges
I am trying to use pd.date_range() to create a DatetimeIndex that spans over multiple days with a frequency in seconds. However, the time range for each day should be restricted between 05:00:00 and 22:00:00

Something along the lines of (doesn't work of course):

```<code>times_c = pd.date_range(start="2015-01-01",end="2015-01-10",freq="S")
mask_c = ((times_c.time < dt.datetime.strptime("22:00:00", "%H:%M:%S")) | (times_c.time > dt.datetime.strptime("05:00:00","%H:%M:%S")))
times_c = times_c[mask_c]
</code>```

答:
Does this work?   </p>

```<code>times_c = pd.date_range(start="2015-01-01", end="2015-01-10", freq="S")
times_c[(times_c.hour<22) | (times_c.hour>5)]
</code>```

Body:
I am trying to use pd.date_range() to create a DatetimeIndex that spans over multiple days with a frequency in seconds. However, the time range for each day should be restricted between 05:00:00 and 22:00:00

Something along the lines of (doesn't work of course):

times_c = pd.date_range(start="2015-01-01",end="2015-01-10",freq="S")
mask_c = ((times_c.time
 dt.datetime.strptime("05:00:00","%H:%M:%S")))
times_c = times_c[mask_c]

Body:
Does this work?

times_c = pd.date_range(start="2015-01-01", end="2015-01-10", freq="S")
times_c[(times_c.hour<22) | (times_c.hour>5)]


问:
Cesium WMS layer issue
Hi all I am trying to get a WMS layer on my cesium globe.  Below is the code I am using.  When I look at the network tabs I do see the request going through all at 200 and when I use the links on the requests they do work; however, it says their file size is 0kb and I receive this error :

An error occurred in "p": Failed to obtain image tile X: 0 Y: 0 Level: 1.
etc.

```<code>var viewer = new Cesium.Viewer('cesiumContainer');

var provider = new Cesium.WebMapServiceImageryProvider({
       url : url',
       layers : 'bm'
 });

viewer.imageryLayers.addImageryProvider(provider);
</code>```

答:
For me it was a CORS issue.  If you add the filters in
geoserver/webapp/geoserver/WEB-INF/web.xml

```<code><!-- Uncomment following filter to enable CORS -->
   <filter>
        <filter-name>cross-origin</filter-name>
        <filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
    </filter>

<!-- Uncomment following filter to enable CORS -->
    <filter-mapping>
        <filter-name>cross-origin</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</code>```

and add the jetty servlets in geoserver/webapp/geoserver/WEB-INF/lib it will fix this issue.  Download for the servlets is here:
http://repo1.maven.org/maven2/org/eclipse/jetty/jetty-servlets/

See https://gis.stackexchange.com/questions/210109/enabling-cors-in-geoserver-jetty for more info.

Title: Cesium WMS layer issue

Body:
Hi all I am trying to get a WMS layer on my cesium globe.  Below is the code I am using.  When I look at the network tabs I do see the request going through all at 200 and when I use the links on the requests they do work; however, it says their file size is 0kb and I receive this error :

An error occurred in "p": Failed to obtain image tile X: 0 Y: 0 Level: 1.
etc.

var viewer = new Cesium.Viewer('cesiumContainer');

var provider = new Cesium.WebMapServiceImageryProvider({
       url : url',
       layers : 'bm'
 });

viewer.imageryLayers.addImageryProvider(provider);

Body:
For me it was a CORS issue.  If you add the filters in
geoserver/webapp/geoserver/WEB-INF/web.xml

<!-- Uncomment following filter to enable CORS -->
   <filter>
        <filter-name>cross-origin</filter-name>
        <filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
    </filter>

<!-- Uncomment following filter to enable CORS -->
    <filter-mapping>
        <filter-name>cross-origin</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

and add the jetty servlets in geoserver/webapp/geoserver/WEB-INF/lib it will fix this issue.  Download for the servlets is here:
http://repo1.maven.org/maven2/org/eclipse/jetty/jetty-servlets/

See https://gis.stackexchange.com/questions/210109/enabling-cors-in-geoserver-jetty for more info.


问:
VB.net get bitlocker Password ID from Active Directory
I have a VB.net program that I am trying to add a bitlocker lookup tool that will search active directory for the machine name, and display the "Password ID" as well as the "Recovery Password"

So far my script/code works flawlessly for the lookup and displaying the Recovery Password, but I cannot get it to display the Password ID.

I've tried:

```<code>Item.Properties("msFVE-RecoveryGuid")(0)
</code>```

Which returns the error "System.InvalidCastException: Conversion from type 'Byte()' to type 'String' is not valid."

```<code>Item.Properties("msFVE-RecoveryGuid")(0).ToString
</code>```

Which returns "System.Byte[]"

```<code>Item.Properties("msFVE-RecoveryGuid").ToString
</code>```

Which returns "System.DirectoryServices.ResultPropertyValueCollection"

So far in my searching I've only seen C# examples, and I haven't been able to translate.

The same for Recovery Password works however:

```<code>(Item.Properties("msFVE-RecoveryPassword")(0))
</code>```

Here is the larger snippet of what I have for context:

```<code>    Dim RootDSE As New DirectoryEntry("LDAP://RootDSE")
    Dim DomainDN As String = RootDSE.Properties("DefaultNamingContext").Value
    Dim ADsearch As New DirectorySearcher("LDAP://" & DomainDN)

    ADsearch.Filter = ("(&(objectClass=computer)(name=" & MachineName & "))")

    Dim ADresult As SearchResult = ADsearch.FindOne
    Dim ADpath As String = ADresult.Path

    Dim BTsearch As New DirectorySearcher()

    BTsearch.SearchRoot = New DirectoryEntry(ADpath)
    BTsearch.Filter = "(&(objectClass=msFVE-RecoveryInformation))"

    Dim BitLockers As SearchResultCollection = BTsearch.FindAll()

    Dim Item As SearchResult

    Dim longTempstring As String = ""

    For Each Item In BitLockers
        If Item.Properties.Contains("msFVE-RecoveryGuid") Then

            Dim tempstring As String = Item.Properties("msFVE-RecoveryGuid")(0).ToString

            longTempstring = longTempstring & tempstring & vbNewLine
            'ListBox2.Items.Add(Item.Properties("msFVE-RecoveryGuid")(0))

        End If
        If Item.Properties.Contains("msFVE-RecoveryPassword") Then

            ListBox1.Items.Add(Item.Properties("msFVE-RecoveryPassword")(0))

        End If
    Next

    MsgBox(longTempstring)
</code>```

答:
So I figured out that I needed to convert the bytes to hex in order to get them to match what is viewed in the Microsoft Management Console. Once I began doing that the only problem I ran into is that I discovered the indexing of the byte arrays are not in the same order as they are in Active Directory. -- so instead of looping I had to list out each index of the Byte array and sort them to their proper positions so that they match how they show up in AD.

My end function is:

```<code>Function bitread(ByVal GUID As Byte())
    Dim tempVar As String
    tempVar = GUID(3).ToString("X02") & GUID(2).ToString("X02") _
        & GUID(1).ToString("X02") & GUID(0).ToString("X02") & "-" _
        & GUID(5).ToString("X02") & GUID(4).ToString("X02") & "-" _
        & GUID(7).ToString("X02") & GUID(6).ToString("X02") & "-" _
        & GUID(8).ToString("X02") & GUID(9).ToString("X02") & "-" _
        & GUID(10).ToString("X02") & GUID(11).ToString("X02") _
        & GUID(12).ToString("X02") & GUID(13).ToString("X02") _
        & GUID(14).ToString("X02") & GUID(15).ToString("X02")
    Return tempVar
End Function
</code>```

Called with:

```<code>bitread(Item.Properties("msFVE-RecoveryGUID")(0))
</code>```

Body:
I have a VB.net program that I am trying to add a bitlocker lookup tool that will search active directory for the machine name, and display the "Password ID" as well as the "Recovery Password"

So far my script/code works flawlessly for the lookup and displaying the Recovery Password, but I cannot get it to display the Password ID.

I've tried:

Item.Properties("msFVE-RecoveryGuid")(0)

Which returns the error "System.InvalidCastException: Conversion from type 'Byte()' to type 'String' is not valid."

Item.Properties("msFVE-RecoveryGuid")(0).ToString

Which returns "System.Byte[]"

Item.Properties("msFVE-RecoveryGuid").ToString

Which returns "System.DirectoryServices.ResultPropertyValueCollection"

So far in my searching I've only seen C# examples, and I haven't been able to translate.

The same for Recovery Password works however:

(Item.Properties("msFVE-RecoveryPassword")(0))

Here is the larger snippet of what I have for context:

    Dim RootDSE As New DirectoryEntry("LDAP://RootDSE")
    Dim DomainDN As String = RootDSE.Properties("DefaultNamingContext").Value
    Dim ADsearch As New DirectorySearcher("LDAP://" & DomainDN)

    ADsearch.Filter = ("(&(objectClass=computer)(name=" & MachineName & "))")

    Dim ADresult As SearchResult = ADsearch.FindOne
    Dim ADpath As String = ADresult.Path

    Dim BTsearch As New DirectorySearcher()

    BTsearch.SearchRoot = New DirectoryEntry(ADpath)
    BTsearch.Filter = "(&(objectClass=msFVE-RecoveryInformation))"

    Dim BitLockers As SearchResultCollection = BTsearch.FindAll()

    Dim Item As SearchResult

    Dim longTempstring As String = ""

    For Each Item In BitLockers
        If Item.Properties.Contains("msFVE-RecoveryGuid") Then

            Dim tempstring As String = Item.Properties("msFVE-RecoveryGuid")(0).ToString

            longTempstring = longTempstring & tempstring & vbNewLine
            'ListBox2.Items.Add(Item.Properties("msFVE-RecoveryGuid")(0))

        End If
        If Item.Properties.Contains("msFVE-RecoveryPassword") Then

            ListBox1.Items.Add(Item.Properties("msFVE-RecoveryPassword")(0))

        End If
    Next

    MsgBox(longTempstring)

Body:
So I figured out that I needed to convert the bytes to hex in order to get them to match what is viewed in the Microsoft Management Console. Once I began doing that the only problem I ran into is that I discovered the indexing of the byte arrays are not in the same order as they are in Active Directory. -- so instead of looping I had to list out each index of the Byte array and sort them to their proper positions so that they match how they show up in AD.

My end function is:

Function bitread(ByVal GUID As Byte())
    Dim tempVar As String
    tempVar = GUID(3).ToString("X02") & GUID(2).ToString("X02") _
        & GUID(1).ToString("X02") & GUID(0).ToString("X02") & "-" _
        & GUID(5).ToString("X02") & GUID(4).ToString("X02") & "-" _
        & GUID(7).ToString("X02") & GUID(6).ToString("X02") & "-" _
        & GUID(8).ToString("X02") & GUID(9).ToString("X02") & "-" _
        & GUID(10).ToString("X02") & GUID(11).ToString("X02") _
        & GUID(12).ToString("X02") & GUID(13).ToString("X02") _
        & GUID(14).ToString("X02") & GUID(15).ToString("X02")
    Return tempVar
End Function

Called with:

bitread(Item.Properties("msFVE-RecoveryGUID")(0))


问:
JQuery Show() all properties
By default if you specify a speed jQuery adds a weird looking animation where it expands from the left end corner. I want it to just slide down. Is there a way to do that without importing something else like jQuery UI?</p>

答:
```<code> $( "#yourId" ).slideDown( "slow", function() {
    // Animation complete.
 });
</code>```

Or

```<code>$( "#yourId" ).slideDown( "slow" );
</code>```

Or even just

```<code>$( "#yourId" ).slideDown();
</code>```

Look at

http://api.jquery.com/slidedown/

Title: JQuery Show() all properties

Body:
 $( "#yourId" ).slideDown( "slow", function() {
    // Animation complete.
 });

Or

$( "#yourId" ).slideDown( "slow" );

Or even just

$( "#yourId" ).slideDown();

Look at

http://api.jquery.com/slidedown/


问:
Multiple layouts in Ember 2
I need implement next application structure with 3 routes:

```<code>localhost/users
localhost/posts
localhost/settings
</code>```

'users' and 'posts' routes should have basic layout1 with main navbar.
'settings' route should have another layout2 with second navbar.

How can I implement multiple layouts approach with Ember > 2.12?

Can I set a layout name/path for each route or group of routes?

答:
I can think of two possible recommended approaches to this problem. I've used both in different scenarios. You can either:

Use a component to encapsulate each navbar and then present them accordingly in each template

Set the templateName attribute of each route to use the correct template.

The component approach seems to be the easiest/most used in my experience. It also allows you to have differences within your base route template. e.g.:

users.hbs:

```<code>{{layout1}}
<h1>Users<h1>
...
</code>```

posts.hbs:

```<code>{{layout1}}
<h1>Posts</h1>
...
</code>```

While if you use the templateName approach, you are locked into using the same exact template. So, if you need any customization between any page that uses the same layout, you must use a subroute. e.g.:

routes/users.js:

```<code>import Ember from 'ember';

export default Ember.Route.extend({
    templateName: 'layout1'
});
</code>```

routes/posts.js:

```<code>import Ember from 'ember';

export default Ember.Route.extend({
    templateName: 'layout1'
});
</code>```

templates/layout1.hbs:

```<code><nav>...</nav>
{{outlet}}
</code>```

A third possible approach, though I don't necessarily recommend it, is to dynamically replace the navbars in the application.hbs template. The application controller/template have access to a special attribute called currentPath, which you can used to create two computed properties (isLayout1 and isLayout2).

With that, this becomes a viable, though like I said, not necessarily recommended solution:

application.hbs:

```<code>{{#if isLayout1}}
    <nav>layout 1</nav>
{{else}}
    <nav>layout 2</nav>
{{/if}}
{{outlet}}
</code>```

Title: Multiple layouts in Ember 2

Body:
I need implement next application structure with 3 routes:

localhost/users
localhost/posts
localhost/settings

'users' and 'posts' routes should have basic layout1 with main navbar.
'settings' route should have another layout2 with second navbar.

How can I implement multiple layouts approach with Ember > 2.12?

Can I set a layout name/path for each route or group of routes?

Body:
I can think of two possible recommended approaches to this problem. I've used both in different scenarios. You can either:

Use a component to encapsulate each navbar and then present them accordingly in each template

Set the templateName attribute of each route to use the correct template.

The component approach seems to be the easiest/most used in my experience. It also allows you to have differences within your base route template. e.g.:

users.hbs:

{{layout1}}
<h1>Users<h1>
...

posts.hbs:

{{layout1}}
<h1>Posts</h1>
...

While if you use the templateName approach, you are locked into using the same exact template. So, if you need any customization between any page that uses the same layout, you must use a subroute. e.g.:

routes/users.js:

import Ember from 'ember';

export default Ember.Route.extend({
    templateName: 'layout1'
});

routes/posts.js:

import Ember from 'ember';

export default Ember.Route.extend({
    templateName: 'layout1'
});

templates/layout1.hbs:

<nav>...</nav>
{{outlet}}

A third possible approach, though I don't necessarily recommend it, is to dynamically replace the navbars in the application.hbs template. The application controller/template have access to a special attribute called currentPath, which you can used to create two computed properties (isLayout1 and isLayout2).

With that, this becomes a viable, though like I said, not necessarily recommended solution:

application.hbs:

{{#if isLayout1}}
    <nav>layout 1</nav>
{{else}}
    <nav>layout 2</nav>
{{/if}}
{{outlet}}


问:
How to fix "@types/node/index.d.ts is not a module"?
I have installed node type definitions using the following command

```<code>npm install --save-dev @types/node
</code>```

After that, when I try to import the node type definitions using the following statement

```<code>import { Process } from '@types/node';
</code>```

or

```<code>import { Process } from 'node';
</code>```

I get the following error

```<code>[ts] File '<root_path>/node_modules/@types/node/index.d.ts' is not a module.
</code>```

I am sure there is something very basic that I am missing here but I cannot figure out.

Few more things

I am using Windows 8

I am using Visual Studio Code

Here is how my tsconfig.json looks

```<code>{
  "compilerOptions": {
    "target": "es2015",
    "module": "commonjs",
    "outDir": "lib",
    "typeRoots": [
        "node_modules/@typings"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}
</code>```

And here is how my webpackconfig.js looks

```<code>var path = require('path');

module.exports = {
  entry: './ts/handler.ts',
  target: 'node',
  module: {
    loaders: [
      { test: /\.ts(x?)$/, loader: 'ts-loader' },
      { test: /\.json$/, loader: 'json-loader' }
    ]
  },
  resolve: {
    extensions: ['.ts', '.js', '.tsx', '.jsx']
  },
  output: {
    libraryTarget: 'commonjs',
    path: path.join(__dirname, '.webpack'),
    filename: 'handler.js'
  },
};
</code>```

答:
It's because inside the node typing file any module has declared with name node.

If you use

```<code>import { Process } from 'node';
</code>```

TypeScript will try too find a node module or node namespace

Here you can load the complete file using

```<code>import 'node';
</code>```

In your case you want to get only Process from NodeJS namespace :

```<code>import 'NodeJS';
</code>```

Aftert that you just need to call it like this :

```<code>class toto implements NodeJS.Process{

}
</code>```

EDIT :

If you use TypeScript >= 2.0 you should not need to add import in your file, only if you want to "optimize import"

Body:
I have installed node type definitions using the following command

npm install --save-dev @types/node

After that, when I try to import the node type definitions using the following statement

import { Process } from '@types/node';

or

import { Process } from 'node';

I get the following error

[ts] File '<root_path>/node_modules/@types/node/index.d.ts' is not a module.

I am sure there is something very basic that I am missing here but I cannot figure out.

Few more things

I am using Windows 8

I am using Visual Studio Code

Here is how my tsconfig.json looks

{
  "compilerOptions": {
    "target": "es2015",
    "module": "commonjs",
    "outDir": "lib",
    "typeRoots": [
        "node_modules/@typings"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

And here is how my webpackconfig.js looks

var path = require('path');

module.exports = {
  entry: './ts/handler.ts',
  target: 'node',
  module: {
    loaders: [
      { test: /\.ts(x?)$/, loader: 'ts-loader' },
      { test: /\.json$/, loader: 'json-loader' }
    ]
  },
  resolve: {
    extensions: ['.ts', '.js', '.tsx', '.jsx']
  },
  output: {
    libraryTarget: 'commonjs',
    path: path.join(__dirname, '.webpack'),
    filename: 'handler.js'
  },
};

Body:
It's because inside the node typing file any module has declared with name node.

If you use

import { Process } from 'node';

TypeScript will try too find a node module or node namespace

Here you can load the complete file using

import 'node';

In your case you want to get only Process from NodeJS namespace :

import 'NodeJS';

Aftert that you just need to call it like this :

class toto implements NodeJS.Process{

}

EDIT :

If you use TypeScript >= 2.0 you should not need to add import in your file, only if you want to "optimize import"


问:
How do I join an unknown number of rows to another row?
I have this scenario:

Table A:

```<code>---------------
ID| SOME_VALUE|
---------------
1 | 123223    |
2 | 1232ff    |
---------------
</code>```

Table B:

```<code>------------------
ID | KEY | VALUE |
------------------
23 | 1   | 435   |
24 | 1   | 436   |
------------------
</code>```

KEY is a reference to to Table A's ID. Can I somehow join these tables so that I get the following result:

Table C

```<code>-------------------------
ID| SOME_VALUE|    |    |
-------------------------
1 | 123223    |435 |436 |
2 | 1232ff    |    |    |
-------------------------
</code>```

Table C should be able to have any given number of columns depending on how many matching values that are found in Table B.

I hope this enough to explain what I'm after here.

Thanks.

答:
This looks like something a database shouldn't do. Firstly; a table cannot have arbitrary number of columns depending on whatever you'll store. So you will have to put up a maximum number of values anyway. You can get around this by using comma seperated values as value for that cell (or a similar pivot-like solution).

However; if you do have table A and B; i recommend keeping to those two tables; as they seem to be pretty normalised. Should you need a list of b.value given an input a.some_value, the following sql query gives that list.

select b.value from a,b where b.key=a.id a.some_value='INPUT_VALUE';

ContentLicense: CC BY-SA 2.5

Body:
I have this scenario:

Table A:

---------------
ID| SOME_VALUE|
---------------
1 | 123223    |
2 | 1232ff    |
---------------

Table B:

------------------
ID | KEY | VALUE |
------------------
23 | 1   | 435   |
24 | 1   | 436   |
------------------

KEY is a reference to to Table A's ID. Can I somehow join these tables so that I get the following result:

Table C

-------------------------
ID| SOME_VALUE|    |    |
-------------------------
1 | 123223    |435 |436 |
2 | 1232ff    |    |    |
-------------------------

Table C should be able to have any given number of columns depending on how many matching values that are found in Table B.

I hope this enough to explain what I'm after here.

Thanks.


问:
What causes this SoftLayer_Exception_Public error message?
I am seeing the following error message returned from Softlayer when trying to create a new device:

SoftLayer_Exception_Public: Could not obtain network VLAN with id
  1865415. (HTTP 500)

I have successfully created 2 other devices with the same VLAN id but cannot create another one. What does this message mean and what could be causing the exception?

答:
The message means that the vlan doesn't exist in your account.

Probably you are using another credentials or the vlan doesn't exist into your account, please make double check the credentials and the vlan exists into your account.

I understand that you had success with two servers before, but if your are using the same credentials, it's necessary more information like the credentials and the script/code that you tried, in order to dig more into this.

You can submit a ticket for further assistance or provide the script that you tried


问:
How to select rows from array of keys?
I have a table and the primary key is 'unique_identifier'.  I would like to select the rows from a number of keys.  I have an array that contains the keys who's data from the table I would like to select and retrieve all at once. Please set aside security concerns.</p>

```<code> $myArray = array('GMVC0001', 'GMVC0002', 'GMVC0003', 'GMVC0004', 'GMVC0005');

 $sql = "SELECT * FROM tracker WHERE unique_identifier='????????????";
 $result = $mysqli -> query($sql);
 $count = $result -> num_rows;
 if($count > 0){
echo 'count: '.$count;
}else{
echo 'error';
}
</code>```

答:
You can use implode function of PHP and IN operator of SQL.</p>

```<code>$myArray = array('GMVC0001', 'GMVC0002', 'GMVC0003', 'GMVC0004', 'GMVC0005');

 $sql = "SELECT * FROM tracker WHERE unique_identifier in ('" . implode("','", $myArray) ."')";
</code>```

Title: How to select rows from array of keys?

Body:
I have a table and the primary key is 'unique_identifier'.  I would like to select the rows from a number of keys.  I have an array that contains the keys who's data from the table I would like to select and retrieve all at once. Please set aside security concerns.

 $myArray = array('GMVC0001', 'GMVC0002', 'GMVC0003', 'GMVC0004', 'GMVC0005');

 $sql = "SELECT * FROM tracker WHERE unique_identifier='????????????";
 $result = $mysqli -> query($sql);
 $count = $result -> num_rows;
 if($count > 0){
echo 'count: '.$count;
}else{
echo 'error';
}

Body:
You can use implode function of PHP and IN operator of SQL.

$myArray = array('GMVC0001', 'GMVC0002', 'GMVC0003', 'GMVC0004', 'GMVC0005');

 $sql = "SELECT * FROM tracker WHERE unique_identifier in ('" . implode("','", $myArray) ."')";


问:
Error importing mgo driver
I'm trying to use the mgo driver. I run

```<code>go get gopkg.in/mgo.v2
</code>```

To get the package, but get these errors -

```<code># gopkg.in/mgo.v2/internal/scram
/usr/local/go/src/pkg/gopkg.in/mgo.v2/internal/scram/scram.go:86: c.out.Grow undefined (type bytes.Buffer has no field or method Grow)
/usr/local/go/src/pkg/gopkg.in/mgo.v2/internal/scram/scram.go:87: c.authMsg.Grow undefined (type bytes.Buffer has no field or method Grow)
# gopkg.in/mgo.v2/bson
/usr/local/go/src/pkg/gopkg.in/mgo.v2/bson/decode.go:246: k.Convert undefined (type reflect.Value has no field or method Convert)
/usr/local/go/src/pkg/gopkg.in/mgo.v2/bson/encode.go:56: undefined: json.Number
/usr/local/go/src/pkg/gopkg.in/mgo.v2/bson/encode.go:282: undefined: json.Number
</code>```

Should I be doing something else?

答: Update Go to the latest version by going to https://golang.org/dl/. In case you worry about uninstallation of Go, all you need to do is delete the Go folder, that's it. This will most probably solve the problem. But if the problem persists, then send me the screenshot of the errors.</p>

Title: Error importing mgo driver

Body:
I'm trying to use the mgo driver. I run

go get gopkg.in/mgo.v2

To get the package, but get these errors -

# gopkg.in/mgo.v2/internal/scram
/usr/local/go/src/pkg/gopkg.in/mgo.v2/internal/scram/scram.go:86: c.out.Grow undefined (type bytes.Buffer has no field or method Grow)
/usr/local/go/src/pkg/gopkg.in/mgo.v2/internal/scram/scram.go:87: c.authMsg.Grow undefined (type bytes.Buffer has no field or method Grow)
# gopkg.in/mgo.v2/bson
/usr/local/go/src/pkg/gopkg.in/mgo.v2/bson/decode.go:246: k.Convert undefined (type reflect.Value has no field or method Convert)
/usr/local/go/src/pkg/gopkg.in/mgo.v2/bson/encode.go:56: undefined: json.Number
/usr/local/go/src/pkg/gopkg.in/mgo.v2/bson/encode.go:282: undefined: json.Number

Should I be doing something else?


问:
Encapsulating controller logic in rails
I have 2 controllers in rails with different authentications schemes,
but they do almost the same.

What is the best way in rails to encapsulate
the logic of a controller in another class or helper?

Sample:

```<code>def ControllerA < BasicAuthController
  def create
    blablacode
  end
end

def ControllerB < TokenAuthController
  def create
    blablacode
  end
end
</code>```

Whats the proper way to do this? create a model with the code?
Create a helper? other?

答:
Short answer, i choose to create a Helper.

From all the suggestions in the answers

Create a Module:
Seems correct but it didnt feel right to have logic outside
the app directory. This wasnt an external module or library but
something very related to the logic of my app.

Integrate diferents authentications in one controller:
Was a good suggestion but i have to change all the logic of my app.

Create a Helpers:
It seems to me the better solution, i had the code on a helper, and
is inside the app directory, very near from the other logic.

Title: Encapsulating controller logic in rails

Body:
I have 2 controllers in rails with different authentications schemes,
but they do almost the same.

What is the best way in rails to encapsulate
the logic of a controller in another class or helper?

Sample:

def ControllerA < BasicAuthController
  def create
    blablacode
  end
end

def ControllerB < TokenAuthController
  def create
    blablacode
  end
end

Whats the proper way to do this? create a model with the code?
Create a helper? other?


问:
vba target intersect with comments added - object error msg
I have the following piece of code which works really well given what I used it for. In debugging possible outcomes, I found that for example if I try to change the TARGET range by either ADDING or DELETING A ROW , I get a VBA Error:

If I add a row in target-> i get "Object Required" - #424
If I delete a row in target -> I get "Method Undo of Object Application Failed" - #1001 (I know this is due to the fact I am using UNDO to get the old cell value, but don't know how to resolve)

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal target As Range)

Dim newvalue As Variant
Dim oldvalue As Variant
Dim cell As Range
Dim trg As String

' to replace current comment with new one

'If Target.Address = "$A$1" Then
'MsgBox "new value " & newvalue & vbLf & "old value " & oldvalue
'    If ActiveCell.Comment Is Nothing Then
'    ActiveCell.AddComment ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue)
'    Else
'    ActiveCell.Comment.Delete
'    ActiveCell.AddComment ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue)
'    End If

'to append comments to existing comment

On Error GoTo ermess

If Not Application.Intersect(target, Range("A1", "A10")) Is Nothing Then

     For Each cell In target

        Application.EnableEvents = False
        newvalue = cell.Value
        Application.Undo
        oldvalue = cell.Value
        cell.Value = newvalue
        Application.EnableEvents = True
        cell.Interior.ColorIndex = 19

                    If newvalue <> oldvalue Then

                       ' If (Target.Address = "$A$1") Then
                        MsgBox "new value " & newvalue & vbLf & "old value " & oldvalue

                            If cell.Comment Is Nothing Then
                            cell.AddComment ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue & vbNewLine & "Updated: " & Now & vbNewLine & "By: " & Environ("username"))
                            Else
                            With target
                            .Comment.Text Text:=.Comment.Text & vbNewLine & ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue & vbNewLine & "Updated: " & Now _
                            & vbNewLine & "By: " & Environ("username"))
                            End With

                            End If

                        'End If

                    Else
0
                    End If
                    'Set target = Nothing

      Next cell
Else

'to test if not in the target specified
'MsgBox "Not in range"

End If

'Application.EnableEvents = True

Exit Sub
ermess:
MsgBox "VBA Error" & vbLf & Err.Description & vbLf & Err.Number, vbCritical

'Debug.Print
Application.EnableEvents = True

End Sub
</code>```

What I want to do it to reset the range so that the "object required" message is eliminated if possible.

With regards to the "application undo" message -> I know that using this to retrieve a previous value of a cell is not the best method, but it worked for me , so if there is a solution to this tthat would be desired.

I don't want to use "On error resume next" as I want to clean up the code first.

Thanks

答:
I found the solution. For anyone interested I added an if statement which evaluated the target range count (if > 1 then exit the sub)</p>

```<code>Option Explicit

Private Sub worksheet_change(ByVal target As Range)

Dim newvalue As Variant
Dim oldvalue As Variant
Dim rng2 As Range
Dim cell As Range
Dim trg As String

' to replace current comment with new one

'If Target.Address = "$A$1" Then
'MsgBox "new value " & newvalue & vbLf & "old value " & oldvalue
'    If ActiveCell.Comment Is Nothing Then
'    ActiveCell.AddComment ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue)
'    Else
'    ActiveCell.Comment.Delete
'    ActiveCell.AddComment ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue)
'    End If

'to append comments to existing comment

Set rng2 = ActiveSheet.Range("A1:A11")

On Error GoTo ermess

    **If target.Count <= 1 Then 'Exit Sub**

        If Not Application.Intersect(target, rng2) Is Nothing Then

             For Each cell In target

           ' On Error Resume Next
            Application.EnableEvents = False
            newvalue = cell.Value
            Application.Undo
            oldvalue = cell.Value
            cell.Value = newvalue
            'On Error GoTo ExitProc
            Application.EnableEvents = True
            cell.Interior.ColorIndex = 19

           '         If newvalue <> Empty Then

                        If newvalue <> oldvalue Then

                           ' If (Target.Address = "$A$1") Then
                            MsgBox "new value " & newvalue & vbLf & "old value " & oldvalue

                                If cell.Comment Is Nothing Then
                                cell.AddComment ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue & vbNewLine & "Updated: " & Now & vbNewLine & "By: " & Environ("username"))
                                Else
                                With target
                                .Comment.Text Text:=.Comment.Text & vbNewLine & ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue & vbNewLine & "Updated: " & Now _
                                & vbNewLine & "By: " & Environ("username"))
                                End With

                                End If

                            'End If

                        Else
0
                        End If
                        'Set target = Nothing

              '      End If

             Next cell

        End If
    'to test if not in the target specified
    'MsgBox "Not in range"
   ***Else
   Exit Sub
   End If***

 With Application
    .EnableEvents = True
    .ScreenUpdating = True
 End With

Exit Sub
ermess:
MsgBox "VBA Error" & vbLf & Err.Description & vbLf & Err.Number, vbCritical

'Debug.Print

End Sub
</code>```

Body:
I have the following piece of code which works really well given what I used it for. In debugging possible outcomes, I found that for example if I try to change the TARGET range by either ADDING or DELETING A ROW , I get a VBA Error:

If I add a row in target-> i get "Object Required" - #424
If I delete a row in target -> I get "Method Undo of Object Application Failed" - #1001 (I know this is due to the fact I am using UNDO to get the old cell value, but don't know how to resolve)

Option Explicit

Private Sub Worksheet_Change(ByVal target As Range)

Dim newvalue As Variant
Dim oldvalue As Variant
Dim cell As Range
Dim trg As String

' to replace current comment with new one

'If Target.Address = "$A$1" Then
'MsgBox "new value " & newvalue & vbLf & "old value " & oldvalue
'    If ActiveCell.Comment Is Nothing Then
'    ActiveCell.AddComment ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue)
'    Else
'    ActiveCell.Comment.Delete
'    ActiveCell.AddComment ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue)
'    End If

'to append comments to existing comment

On Error GoTo ermess

If Not Application.Intersect(target, Range("A1", "A10")) Is Nothing Then

     For Each cell In target

        Application.EnableEvents = False
        newvalue = cell.Value
        Application.Undo
        oldvalue = cell.Value
        cell.Value = newvalue
        Application.EnableEvents = True
        cell.Interior.ColorIndex = 19

                    If newvalue <> oldvalue Then

                       ' If (Target.Address = "$A$1") Then
                        MsgBox "new value " & newvalue & vbLf & "old value " & oldvalue

                            If cell.Comment Is Nothing Then
                            cell.AddComment ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue & vbNewLine & "Updated: " & Now & vbNewLine & "By: " & Environ("username"))
                            Else
                            With target
                            .Comment.Text Text:=.Comment.Text & vbNewLine & ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue & vbNewLine & "Updated: " & Now _
                            & vbNewLine & "By: " & Environ("username"))
                            End With

                            End If

                        'End If

                    Else
0
                    End If
                    'Set target = Nothing

      Next cell
Else

'to test if not in the target specified
'MsgBox "Not in range"

End If

'Application.EnableEvents = True

Exit Sub
ermess:
MsgBox "VBA Error" & vbLf & Err.Description & vbLf & Err.Number, vbCritical

'Debug.Print
Application.EnableEvents = True

End Sub

What I want to do it to reset the range so that the "object required" message is eliminated if possible.

With regards to the "application undo" message -> I know that using this to retrieve a previous value of a cell is not the best method, but it worked for me , so if there is a solution to this tthat would be desired.

I don't want to use "On error resume next" as I want to clean up the code first.

Thanks

Body:
I found the solution. For anyone interested I added an if statement which evaluated the target range count (if > 1 then exit the sub)

Option Explicit

Private Sub worksheet_change(ByVal target As Range)

Dim newvalue As Variant
Dim oldvalue As Variant
Dim rng2 As Range
Dim cell As Range
Dim trg As String

' to replace current comment with new one

'If Target.Address = "$A$1" Then
'MsgBox "new value " & newvalue & vbLf & "old value " & oldvalue
'    If ActiveCell.Comment Is Nothing Then
'    ActiveCell.AddComment ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue)
'    Else
'    ActiveCell.Comment.Delete
'    ActiveCell.AddComment ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue)
'    End If

'to append comments to existing comment

Set rng2 = ActiveSheet.Range("A1:A11")

On Error GoTo ermess

    **If target.Count <= 1 Then 'Exit Sub**

        If Not Application.Intersect(target, rng2) Is Nothing Then

             For Each cell In target

           ' On Error Resume Next
            Application.EnableEvents = False
            newvalue = cell.Value
            Application.Undo
            oldvalue = cell.Value
            cell.Value = newvalue
            'On Error GoTo ExitProc
            Application.EnableEvents = True
            cell.Interior.ColorIndex = 19

           '         If newvalue <> Empty Then

                        If newvalue <> oldvalue Then

                           ' If (Target.Address = "$A$1") Then
                            MsgBox "new value " & newvalue & vbLf & "old value " & oldvalue

                                If cell.Comment Is Nothing Then
                                cell.AddComment ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue & vbNewLine & "Updated: " & Now & vbNewLine & "By: " & Environ("username"))
                                Else
                                With target
                                .Comment.Text Text:=.Comment.Text & vbNewLine & ("Old Value: " & oldvalue & vbNewLine & "New Value: " & newvalue & vbNewLine & "Updated: " & Now _
                                & vbNewLine & "By: " & Environ("username"))
                                End With

                                End If

                            'End If

                        Else
0
                        End If
                        'Set target = Nothing

              '      End If

             Next cell

        End If
    'to test if not in the target specified
    'MsgBox "Not in range"
   ***Else
   Exit Sub
   End If***

 With Application
    .EnableEvents = True
    .ScreenUpdating = True
 End With

Exit Sub
ermess:
MsgBox "VBA Error" & vbLf & Err.Description & vbLf & Err.Number, vbCritical

'Debug.Print

End Sub


问:
How would I create a new NSWindow via Objective-C?
I would just like to know how to create ("instance") a new NSWindow in a Mac OSX application via it's Objective-C code.</p>

答:
Have you taken a look at the "Creating Windows" section of the NSWindow class reference - it tells you pretty much all you need to know about creating windows programmatically.

Additionally, there's quite a bit of sample code (see the "Related sample code" section at the top of the above link) if you're after examples.


问:
Trapping Powershell Error in a function
I'm having a bit of trouble preventing a certain error message from bubbling up from a function to my main routine's 'Catch'. I would like to have my function react to a particular error, then do something, and continue processing as usual without alerting my main routine that there was an error. Currently, if the file this script is trying to read is in use (being written to), it will write a System.IO.IOException error to my log. But sometimes I expect this error to occur and it isn't an issue and I don't want to fill my log with these type of errors. I would expect from the code below that the checkFileLock function would catch the error, return 0 to the findErrorInFile function, and no error would be caught to my error log.</p>

```<code>Function findErrorsInFile{
    param(
        [string]$dir,
        [string]$file,
        [String]$errorCode
    )
    If((Get-Item $($dir + "`\" + $file)) -is [System.IO.DirectoryInfo]){ #we dont want to look at directories, only files
    }Else{
        If($(checkFileLock -filePath $($dir + "`\" + $file))){
            $reader = New-Object System.IO.StreamReader($($dir + "`\" + $file))
            $content = $reader.ReadToEnd()
            $results = $content | select-string -Pattern $errorCode #if there is no regex match (no matching error code found), then the string $results will be == $null
                If($results){
                    Return 1 #we found the error in the file
                }Else{
                    Return 0 #no error found in the file
                }
        }Else{
            Return 0 #The file was being written to, we will skip it and assume no error. This is rare.
        }
    }
}

Function checkFileLock{
    param(
    [String]$filePath
    )

    try{
        $openFile = New-Object System.IO.FileInfo $filePath
        $testStream = $openFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) #try to open a filestream
        If($testStream){ #If the filestream opens, then it isn't locked
            $testStream.Close() #close the filestream
        }
        return $false #File is not locked
    }

    catch{
        return $true #File is locked
    }
}

#### START MAIN PROCESS ####

Try{

  if($(findErrorsInFile -dir 'somepath' -file 'somefilename' -errorcode 'abc')){
    write-host "found something"
  }else{
    write-host "didn't find anything"
  }
}

Catch{
  $_.Exception.ToString() >> mylogfile.txt
}
</code>```

答:
Use to force a catch

```<code>-ErrorAction Stop
</code>```

use to suppress a error

```<code>[Command with error] | out-null
</code>```

Title: Trapping Powershell Error in a function

Body:
I'm having a bit of trouble preventing a certain error message from bubbling up from a function to my main routine's 'Catch'. I would like to have my function react to a particular error, then do something, and continue processing as usual without alerting my main routine that there was an error. Currently, if the file this script is trying to read is in use (being written to), it will write a System.IO.IOException error to my log. But sometimes I expect this error to occur and it isn't an issue and I don't want to fill my log with these type of errors. I would expect from the code below that the checkFileLock function would catch the error, return 0 to the findErrorInFile function, and no error would be caught to my error log.

Function findErrorsInFile{
    param(
        [string]$dir,
        [string]$file,
        [String]$errorCode
    )
    If((Get-Item $($dir + "`\" + $file)) -is [System.IO.DirectoryInfo]){ #we dont want to look at directories, only files
    }Else{
        If($(checkFileLock -filePath $($dir + "`\" + $file))){
            $reader = New-Object System.IO.StreamReader($($dir + "`\" + $file))
            $content = $reader.ReadToEnd()
            $results = $content | select-string -Pattern $errorCode #if there is no regex match (no matching error code found), then the string $results will be == $null
                If($results){
                    Return 1 #we found the error in the file
                }Else{
                    Return 0 #no error found in the file
                }
        }Else{
            Return 0 #The file was being written to, we will skip it and assume no error. This is rare.
        }
    }
}

Function checkFileLock{
    param(
    [String]$filePath
    )

    try{
        $openFile = New-Object System.IO.FileInfo $filePath
        $testStream = $openFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None) #try to open a filestream
        If($testStream){ #If the filestream opens, then it isn't locked
            $testStream.Close() #close the filestream
        }
        return $false #File is not locked
    }

    catch{
        return $true #File is locked
    }
}

#### START MAIN PROCESS ####

Try{

  if($(findErrorsInFile -dir 'somepath' -file 'somefilename' -errorcode 'abc')){
    write-host "found something"
  }else{
    write-host "didn't find anything"
  }
}

Catch{
  $_.Exception.ToString() >> mylogfile.txt
}

Body:
Use to force a catch

-ErrorAction Stop

use to suppress a error

[Command with error] | out-null


问:
cfloop and query of queries
I have a scenario like below on a page. I have a query being returned from a cfc all_data which has columns, section, state, data. Now the page design looks something like below.

section1 section2 section3 section4 -> select one section to select the state in it

Lets say section1 is selected -> State1 state2 state3 associated with that section need to be displayed -> select one state to see the data related to it.

Say State3 is selected -> related State3 data is shown.

So basically I need 3 cfloops which will accomplish the above. I am doing `

```<code><cfquery name="section" dbtype="query">
 select distinct section from all_data
</cfquery>`
</code>```

for first loop, I loop over 'section' query to display all the sections.

```<code><cfloop query ="section">
    <cfquery name="state" dbtype="query">
    select distinct state from all_data where section = section.section
    </cfquery>
</cfloop>
</code>```

for state display I loop like above. For loop 3 that is the data display I have tried multiple things but nothing seems to work the right way. Is this the right approach. Any insights are appreciated.

答:
do you mean something like this?    </p>

```<code>    <cfloop query ="section">
        <cfquery name="state" dbtype="query">
          select distinct state from all_data where section = section.section;
        </cfquery>
        <cfloop query ="state">
            <cfquery name="getdata" dbtype="query">
              select * from all_data where section = section.section
              and state = state.state;
            </cfquery>
            <cfdump var=#getdata#>
        </cfloop>
    </cfloop>
</code>```

Title: cfloop and query of queries

Body:
I have a scenario like below on a page. I have a query being returned from a cfc all_data which has columns, section, state, data. Now the page design looks something like below.

section1 section2 section3 section4 -> select one section to select the state in it

Lets say section1 is selected -> State1 state2 state3 associated with that section need to be displayed -> select one state to see the data related to it.

Say State3 is selected -> related State3 data is shown.

So basically I need 3 cfloops which will accomplish the above. I am doing `

<cfquery name="section" dbtype="query">
 select distinct section from all_data
</cfquery>`

for first loop, I loop over 'section' query to display all the sections.

<cfloop query ="section">
    <cfquery name="state" dbtype="query">
    select distinct state from all_data where section = section.section
    </cfquery>
</cfloop>

for state display I loop like above. For loop 3 that is the data display I have tried multiple things but nothing seems to work the right way. Is this the right approach. Any insights are appreciated.

Body:
do you mean something like this?

    <cfloop query ="section">
        <cfquery name="state" dbtype="query">
          select distinct state from all_data where section = section.section;
        </cfquery>
        <cfloop query ="state">
            <cfquery name="getdata" dbtype="query">
              select * from all_data where section = section.section
              and state = state.state;
            </cfquery>
            <cfdump var=#getdata#>
        </cfloop>
    </cfloop>


答:
Suppose you have name, roll, email in a table.After completing your sql that you have done you can access every attribute by this way.</p>

```<code>while($row = $result->fetch_assoc()){
  $name = $row["name"];
  $email = $row["email"];
  $roll = $row["roll"];
}
</code>```

Title: How to select rows from array of keys?

Body:
Suppose you have name, roll, email in a table.After completing your sql that you have done you can access every attribute by this way.

while($row = $result->fetch_assoc()){
  $name = $row["name"];
  $email = $row["email"];
  $roll = $row["roll"];
}


问:
Double check my IF AND OR statement
is this logical... If $dirchk1 and $dirchk2 exist or if just $dirchk1 exist continue processing. But if only $dirchk2 exist then process else statement. Thanks in advance

```<code>$dirchk1 = "/temp/files/" . $data[0] . ".doc";
$dirchk2 = "/temp/files/" . $data[1] . ".doc";
    if (is_file($dirchk1) && is_file($dirchk2)) || (is_file($dirchk1)) {
//.. do code
    } else {
    ...// only $dirchk2 exist
    }
</code>```

EDIT: sorry I failed to mention that if $dirchk1 and $dirchk2 DO NOT exist then the else statement should process.

答:
Your else will execute even of both of them does not exist and your if does not check the second condition. So, do it like this:

```<code> if (is_file($dirchk1) && is_file($dirchk2)) || (is_file($dirchk1) && !is_file($dirchk2))
 {
     //.. do code
 }
 elseif((is_file($dirchk2))
 {
    ...// only $dirchk2 exist
 }
</code>```

Title: Double check my IF AND OR statement

Body:
is this logical... If $dirchk1 and $dirchk2 exist or if just $dirchk1 exist continue processing. But if only $dirchk2 exist then process else statement. Thanks in advance

$dirchk1 = "/temp/files/" . $data[0] . ".doc";
$dirchk2 = "/temp/files/" . $data[1] . ".doc";
    if (is_file($dirchk1) && is_file($dirchk2)) || (is_file($dirchk1)) {
//.. do code
    } else {
    ...// only $dirchk2 exist
    }

EDIT: sorry I failed to mention that if $dirchk1 and $dirchk2 DO NOT exist then the else statement should process.

Body:
Your else will execute even of both of them does not exist and your if does not check the second condition. So, do it like this:

 if (is_file($dirchk1) && is_file($dirchk2)) || (is_file($dirchk1) && !is_file($dirchk2))
 {
     //.. do code
 }
 elseif((is_file($dirchk2))
 {
    ...// only $dirchk2 exist
 }


问:
Writing a list comprehension to flatten a nested list
I have a nested list mixed with list and numbers.

```<code>nested = [[1, 2, 3], [4, 5, 6], [7, 8], [9], 10, 11]
</code>```

The nested lists only contain numbers, they'll never contain more lists.

Is it possible to write a list comprehension to make new list from the 'nested' list, producing the following output?

```<code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
</code>```

This was my attempt( code is not working)

```<code>[num if isinstance(item, list) for num in item else item for item in nested]
</code>```

答:
If your list has arbitrary nesting, best to use a recursive function (referring to one of my other answers):

```<code>>>> def flat_gen(x):
...     def iselement(e):
...         return not(isinstance(e, collections.Iterable) and not isinstance(e, str))
...     for el in x:
...         if iselement(el):
...             yield el
...         else:
...             yield from flat_gen(el)
...
>>> nested = [[1,2,3] , [4,5,6] , [7,8] , [9,] , 10 , 11 ]

>>> import collections
>>> list(flat_gen(nested))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
</code>```

If you just have mixed nesting between a simple list or tuple (any iterable container) and non list or tuple objects (i.e., non-iterable objects and iterable containers with no deeper nesting) you can use a generator expression with list:

```<code>>>> import itertools as it
>>> list(it.chain.from_iterable(item if isinstance(item,collections.Iterable) and not isinstance(item, str) else [item] for item in nested))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
</code>```

Body:
I have a nested list mixed with list and numbers.

nested = [[1, 2, 3], [4, 5, 6], [7, 8], [9], 10, 11]

The nested lists only contain numbers, they'll never contain more lists.

Is it possible to write a list comprehension to make new list from the 'nested' list, producing the following output?

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

This was my attempt( code is not working)

[num if isinstance(item, list) for num in item else item for item in nested]

Body:
If your list has arbitrary nesting, best to use a recursive function (referring to one of my other answers):

>>> def flat_gen(x):
...     def iselement(e):
...         return not(isinstance(e, collections.Iterable) and not isinstance(e, str))
...     for el in x:
...         if iselement(el):
...             yield el
...         else:
...             yield from flat_gen(el)
...
>>> nested = [[1,2,3] , [4,5,6] , [7,8] , [9,] , 10 , 11 ]

>>> import collections
>>> list(flat_gen(nested))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

If you just have mixed nesting between a simple list or tuple (any iterable container) and non list or tuple objects (i.e., non-iterable objects and iterable containers with no deeper nesting) you can use a generator expression with list:

>>> import itertools as it
>>> list(it.chain.from_iterable(item if isinstance(item,collections.Iterable) and not isinstance(item, str) else [item] for item in nested))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]


问:
How to SELECT top different value using order by matrics
i have a table like this

i want to get the row of each table that have min responsetime

i have tried this query :

```<code>select tablename,
       index1,
       index2,
       min(responsetime)
from   tableconf
group by tablename
order by responsetime asc
</code>```

but it doesn't give what i want

the output that i want is

```<code>+------------------+------------------+--------+--------------+
|    tablename     |     index1       | index2 | responsetime |
+------------------+------------------+--------+--------------+
| salesorderheader | TotalDue         | NULL   |       6.1555 |
| salesterritory   | Name             | NULL   |     11.66667 |
| store            | BusinessEntityId | Name   |       3.6222 |
| previous         | previous         | NULL   |      5.03333 |
| NONE             | NONE             | NULL   |          5.6 |
+------------------+------------------+--------+--------------+
</code>```

what query i should use for get the output that i want

答:
Select the minimum date per table name. Use an IN clause on these to get the rows:

```<code>select *
from tableconf
where (tablename, responsetime) in
(
  select tablename, min(responsetime)
  from tableconf
  group by tablename
);
</code>```

Body:
i have a table like this

i want to get the row of each table that have min responsetime

i have tried this query :

select tablename,
       index1,
       index2,
       min(responsetime)
from   tableconf
group by tablename
order by responsetime asc

but it doesn't give what i want

the output that i want is

+------------------+------------------+--------+--------------+
|    tablename     |     index1       | index2 | responsetime |
+------------------+------------------+--------+--------------+
| salesorderheader | TotalDue         | NULL   |       6.1555 |
| salesterritory   | Name             | NULL   |     11.66667 |
| store            | BusinessEntityId | Name   |       3.6222 |
| previous         | previous         | NULL   |      5.03333 |
| NONE             | NONE             | NULL   |          5.6 |
+------------------+------------------+--------+--------------+

what query i should use for get the output that i want

Body:
Select the minimum date per table name. Use an IN clause on these to get the rows:

select *
from tableconf
where (tablename, responsetime) in
(
  select tablename, min(responsetime)
  from tableconf
  group by tablename
);


问:
C# coalesce operator
Why the following code returns false?

```<code>public static void Main()
{
    bool? someCondition = true;
    bool someConditionOverride = false;

    bool? result = someCondition ?? someConditionOverride ? false : (bool?)null;

    Console.WriteLine(result);
}
</code>```

I was exprecting the result will be true, since someCondition is not null and ?? operator will return true. However looks like right operand is calculated first and the left part is simply ignored.

Adding brackets fix the confusion:

```<code>bool? result = someCondition ?? (someConditionOverride ? false : (bool?)null)
</code>```

And the result will be true. However I am still curious why left part had been ignored in the first example.

答:
"the left part is simply ignored"? How likely do you really think that is?

Operator precedence dictates that your first version is parsed like so:

```<code>bool? result = (someCondition ?? someConditionOverride)
                   ? false
                   : (bool?)null;
</code>```

someCondition isn't null, and it is true. Therefore, this expression evaluates as true:

```<code>(someCondition ?? someConditionOverride)
</code>```

So we get the ? branch, and the whole expression returns false, just like you told it to.

Adding the brackets that you added completely changes the meaning of the expression. It fixes your confusion, in a limited sense, by bringing the actual meaning of the expression in line with your original intent; but the compiler is never confused. In C#, compiler confuses you.

To reduce my own confusion, I never rely on operator precedence. I parenthesize everything. If I had designed the language, the grammar would require it (unless Eric comes by and tells me why that's actually not such a good idea after all, for some reason that will make perfect sense to me once Eric explains it).

UPDATE: Prediction validated: Eric came by and said that too many people would find it ridiculous to have to parenthesize a + b * c, and if you allow that, there's no reasonable way to define the exceptions. Well, if they won't tolerate being forced to parenthesize everything, they won't, however much I think they should.

Title: C# coalesce operator

Body:
Why the following code returns false?

public static void Main()
{
    bool? someCondition = true;
    bool someConditionOverride = false;

    bool? result = someCondition ?? someConditionOverride ? false : (bool?)null;

    Console.WriteLine(result);
}

I was exprecting the result will be true, since someCondition is not null and ?? operator will return true. However looks like right operand is calculated first and the left part is simply ignored.

Adding brackets fix the confusion:

bool? result = someCondition ?? (someConditionOverride ? false : (bool?)null)

And the result will be true. However I am still curious why left part had been ignored in the first example.

Body:
"the left part is simply ignored"? How likely do you really think that is?

Operator precedence dictates that your first version is parsed like so:

bool? result = (someCondition ?? someConditionOverride)
                   ? false
                   : (bool?)null;

someCondition isn't null, and it is true. Therefore, this expression evaluates as true:

(someCondition ?? someConditionOverride)

So we get the ? branch, and the whole expression returns false, just like you told it to.

Adding the brackets that you added completely changes the meaning of the expression. It fixes your confusion, in a limited sense, by bringing the actual meaning of the expression in line with your original intent; but the compiler is never confused. In C#, compiler confuses you.

To reduce my own confusion, I never rely on operator precedence. I parenthesize everything. If I had designed the language, the grammar would require it (unless Eric comes by and tells me why that's actually not such a good idea after all, for some reason that will make perfect sense to me once Eric explains it).

UPDATE: Prediction validated: Eric came by and said that too many people would find it ridiculous to have to parenthesize a + b * c, and if you allow that, there's no reasonable way to define the exceptions. Well, if they won't tolerate being forced to parenthesize everything, they won't, however much I think they should.


问:
How to get random value from specific ranges of dictionary content
If this way I can get random value from given range:

```<code> int r = ran.Next(1, 4);
 string v;
 if (dict.TryGetValue(r, out v))
 {
    ///...
 }
</code>```

how to properly get random value of <int, string> dictionary content from specific range, for example only from 4 to 6 and 1 and 2 and avoid look for 3:

```<code>Dictionary<int, string> dict = new Dictionary<int, string>()
{
    { 1, "word1" },
    { 2, "word2" },
    { 3, "word3" },
    { 4, "word4" },
    { 5, "word5" },
    { 6, "word6" }
};
</code>```

答:
With this solution you can get a random value within specified ranges without having to iterate the dictionary first.</p>

```<code>void Main()
{
    Dictionary<int, string> dict = new Dictionary<int, string>()
    {
        { 1, "word1" },
        { 2, "word2" },
        { 3, "word3" },
        { 4, "word4" },
        { 5, "word5" },
        { 6, "word6" }
    };
    var randomizer = new Random();
    GetRandomValue(dict, randomizer, new Range(4, 6), new Range(1,2)).Dump();
}

public TValue GetRandomValue<TValue>(IDictionary<int, TValue> dic, Random randomizer, params Range[] ranges)
{
    var range = ranges[randomizer.Next(0, ranges.Length)];
    var key = randomizer.Next(range.From, range.To + 1);
    return dic[key];
}

public class Range
{
    public Range(int @from, int to)
    {
        From = @from;
        To = to;
    }
    public int From {get;set;}
    public int To {get;set;}
}
</code>```

Body:
If this way I can get random value from given range:

 int r = ran.Next(1, 4);
 string v;
 if (dict.TryGetValue(r, out v))
 {
    ///...
 }

how to properly get random value of <int, string> dictionary content from specific range, for example only from 4 to 6 and 1 and 2 and avoid look for 3:

Dictionary<int, string> dict = new Dictionary<int, string>()
{
    { 1, "word1" },
    { 2, "word2" },
    { 3, "word3" },
    { 4, "word4" },
    { 5, "word5" },
    { 6, "word6" }
};

Body:
With this solution you can get a random value within specified ranges without having to iterate the dictionary first.

void Main()
{
    Dictionary<int, string> dict = new Dictionary<int, string>()
    {
        { 1, "word1" },
        { 2, "word2" },
        { 3, "word3" },
        { 4, "word4" },
        { 5, "word5" },
        { 6, "word6" }
    };
    var randomizer = new Random();
    GetRandomValue(dict, randomizer, new Range(4, 6), new Range(1,2)).Dump();
}

public TValue GetRandomValue<TValue>(IDictionary<int, TValue> dic, Random randomizer, params Range[] ranges)
{
    var range = ranges[randomizer.Next(0, ranges.Length)];
    var key = randomizer.Next(range.From, range.To + 1);
    return dic[key];
}

public class Range
{
    public Range(int @from, int to)
    {
        From = @from;
        To = to;
    }
    public int From {get;set;}
    public int To {get;set;}
}


问:
pub get not generating pubspec.lock file
I have a new 2016 MacBook Pro 13-inch, and am trying to get dart and dartium up and running for work. However, when I run pub get in the directory with pubspec.yaml, I do not get a pubspec.lock file, or anything else for that matter.

The packages claim to be downloading, but then after the last package, I receive no further output.

here is the output of pub get

```<code>RMTMACSIERRA01:ui jacob.massengill$ pub get
Resolving dependencies... (10.3s)
+ analyzer 0.25.2+1 (0.30.0+2 available)
+ angular 1.1.2+2
+ angular_ui 0.6.13
+ args 0.12.2+6 (0.13.7 available)
+ async 1.9.0 (1.13.3 available)
+ barback 0.15.2+7 (0.15.2+11 available)
+ browser 0.10.0+2
+ charcode 1.1.1
+ cli_util 0.0.1+2 (0.1.1 available)
+ code_transformers 0.2.9+3 (0.5.1+3 available)
+ collection 1.1.3 (1.14.1 available)
+ convert 1.1.0 (2.0.1 available)
+ crypto 0.9.2+1 (2.0.1 available)
+ csslib 0.13.7+1 (0.14.0 available)
+ dart_config 0.5.0
+ dart_style 0.2.1 (1.0.6 available)
+ dart_to_js_script_rewriter 1.0.1 (1.0.2 available)
+ di 3.3.5+1 (3.3.10 available)
+ glob 1.1.3
+ guinness 0.1.18
+ html 0.12.2+2 (0.13.2 available)
+ html5lib 0.12.1
+ http_multi_server 2.0.3
+ http_parser 2.2.1 (3.1.1 available)
+ initialize 0.6.1+2 (0.6.2+6 available)
+ intl 0.8.10+4 (0.15.0 available)
+ js 0.6.0 (0.6.1 available)
+ logging 0.11.3+1
+ matcher 0.12.0+2 (0.12.1+1 available)
+ meta 1.0.5
+ mime 0.9.3
+ mixpanel 1.0.0
+ mock 0.11.0+4 (0.12.0 available)
+ mockito 0.8.2 (2.0.2 available)
+ observe 0.13.1+3 (0.15.1 available)
+ package_config 0.1.5 (1.0.1 available)
+ path 1.4.1
+ perf_api 0.0.9 (0.1.0 available)
+ petitparser 1.5.3 (1.5.4 available)
+ plugin 0.1.0 (0.2.0 available)
+ pool 1.3.0 (1.3.1 available)
+ pub_semver 1.3.2
+ quiver 0.21.4 (0.25.0 available)
+ route_hierarchical 0.6.2 (0.7.0 available)
+ shelf 0.6.5 (0.6.7+2 available)
+ shelf_static 0.2.4
+ shelf_web_socket 0.0.1+5 (0.2.1 available)
+ smoke 0.3.5 (0.3.6+3 available)
+ source_map_stack_trace 1.0.4 (1.1.4 available)
+ source_maps 0.10.4
+ source_span 1.4.0
+ stack_trace 1.7.3
+ stream_channel 1.3.1 (1.6.1 available)
+ string_scanner 0.1.5 (1.0.2 available)
+ test 0.12.7 (0.12.21 available)
+ typed_data 1.1.3
+ unittest 0.11.7 (0.12.4+1 available)
+ utf 0.9.0+3
+ uuid 0.5.1 (0.5.3 available)
+ watcher 0.9.7 (0.9.7+3 available)
+ web_components 0.11.4 (0.12.5 available)
+ webdriver 1.0.0 (1.2.3 available)
+ when 0.2.0
+ which 0.1.3
+ xml 2.2.3 (2.5.0 available)
+ xml2json 2.0.6 (2.0.8 available)
+ yaml 2.1.10 (2.1.12 available)
Downloading angular 1.1.2+2...
Downloading angular_ui 0.6.13...
Downloading args 0.12.2+6...
Downloading browser 0.10.0+2...
Downloading dart_config 0.5.0...
Downloading dart_to_js_script_rewriter 1.0.1...
Downloading glob 1.1.3...
Downloading guinness 0.1.18...
Downloading js 0.6.0...
Downloading mixpanel 1.0.0...
Downloading mock 0.11.0+4...
Downloading mockito 0.8.2...
Downloading quiver 0.21.4...
Downloading test 0.12.7...
Downloading uuid 0.5.1...
Downloading web_components 0.11.4...
Downloading webdriver 1.0.0...
Downloading xml2json 2.0.6...
Downloading yaml 2.1.10...
Downloading charcode 1.1.1...
Downloading html 0.12.2+2...
Downloading shelf_web_socket 0.0.1+5...
Downloading perf_api 0.0.9...
Downloading pub_semver 1.3.2...
Downloading source_map_stack_trace 1.0.4...
Downloading pool 1.3.0...
Downloading http_multi_server 2.0.3...
Downloading string_scanner 0.1.5...
Downloading source_span 1.4.0...
Downloading http_parser 2.2.1...
Downloading stream_channel 1.3.1...
Downloading route_hierarchical 0.6.2...
Downloading shelf_static 0.2.4...
Downloading convert 1.1.0...
Downloading typed_data 1.1.3...
Downloading matcher 0.12.0+2...
Downloading collection 1.1.3...
Downloading utf 0.9.0+3...
Downloading initialize 0.6.1+2...
Downloading async 1.9.0...
Downloading xml 2.2.3...
Downloading dart_style 0.2.1...
Downloading petitparser 1.5.3...
Downloading mime 0.9.3...
Downloading shelf 0.6.5...
Downloading code_transformers 0.2.9+3...
Downloading cli_util 0.0.1+2...
Downloading which 0.1.3...
Downloading when 0.2.0...
Downloading path 1.4.1...
Downloading crypto 0.9.2+1...
Downloading di 3.3.5+1...
Downloading barback 0.15.2+7...
Downloading html5lib 0.12.1...
Downloading observe 0.13.1+3...
Downloading smoke 0.3.5...
Downloading source_maps 0.10.4...
Downloading logging 0.11.3+1...
Downloading csslib 0.13.7+1...
Downloading stack_trace 1.7.3...
Downloading intl 0.8.10+4...
Downloading meta 1.0.5...
Downloading unittest 0.11.7...
Downloading analyzer 0.25.2+1...
Downloading plugin 0.1.0...
Downloading package_config 0.1.5...
Downloading watcher 0.9.7...
</code>```

and then when I try to run pub build or pub serve,

```<code>no pubspec.lock file found, please run "pub get" first
</code>```

I installed dart 1.15.0 (the version my team uses) via homebrew.

EDIT: my supervisor clone my forked repo, and was able to execute pub get and pub serve without issue, so there doesn't appear to be an issue with the pubspec.yaml file or the repo itself.

答:
After adding pub to the allowed connections in my firewall settings, and performing a hard reboot of my computer, this issue has been resolved. </p>

<p>I believe the issue was caused by pub getting a connection timeout due to the firewall, and failing without warning. </p>

Body:
I have a new 2016 MacBook Pro 13-inch, and am trying to get dart and dartium up and running for work. However, when I run pub get in the directory with pubspec.yaml, I do not get a pubspec.lock file, or anything else for that matter.

The packages claim to be downloading, but then after the last package, I receive no further output.

here is the output of pub get

RMTMACSIERRA01:ui jacob.massengill$ pub get
Resolving dependencies... (10.3s)
+ analyzer 0.25.2+1 (0.30.0+2 available)
+ angular 1.1.2+2
+ angular_ui 0.6.13
+ args 0.12.2+6 (0.13.7 available)
+ async 1.9.0 (1.13.3 available)
+ barback 0.15.2+7 (0.15.2+11 available)
+ browser 0.10.0+2
+ charcode 1.1.1
+ cli_util 0.0.1+2 (0.1.1 available)
+ code_transformers 0.2.9+3 (0.5.1+3 available)
+ collection 1.1.3 (1.14.1 available)
+ convert 1.1.0 (2.0.1 available)
+ crypto 0.9.2+1 (2.0.1 available)
+ csslib 0.13.7+1 (0.14.0 available)
+ dart_config 0.5.0
+ dart_style 0.2.1 (1.0.6 available)
+ dart_to_js_script_rewriter 1.0.1 (1.0.2 available)
+ di 3.3.5+1 (3.3.10 available)
+ glob 1.1.3
+ guinness 0.1.18
+ html 0.12.2+2 (0.13.2 available)
+ html5lib 0.12.1
+ http_multi_server 2.0.3
+ http_parser 2.2.1 (3.1.1 available)
+ initialize 0.6.1+2 (0.6.2+6 available)
+ intl 0.8.10+4 (0.15.0 available)
+ js 0.6.0 (0.6.1 available)
+ logging 0.11.3+1
+ matcher 0.12.0+2 (0.12.1+1 available)
+ meta 1.0.5
+ mime 0.9.3
+ mixpanel 1.0.0
+ mock 0.11.0+4 (0.12.0 available)
+ mockito 0.8.2 (2.0.2 available)
+ observe 0.13.1+3 (0.15.1 available)
+ package_config 0.1.5 (1.0.1 available)
+ path 1.4.1
+ perf_api 0.0.9 (0.1.0 available)
+ petitparser 1.5.3 (1.5.4 available)
+ plugin 0.1.0 (0.2.0 available)
+ pool 1.3.0 (1.3.1 available)
+ pub_semver 1.3.2
+ quiver 0.21.4 (0.25.0 available)
+ route_hierarchical 0.6.2 (0.7.0 available)
+ shelf 0.6.5 (0.6.7+2 available)
+ shelf_static 0.2.4
+ shelf_web_socket 0.0.1+5 (0.2.1 available)
+ smoke 0.3.5 (0.3.6+3 available)
+ source_map_stack_trace 1.0.4 (1.1.4 available)
+ source_maps 0.10.4
+ source_span 1.4.0
+ stack_trace 1.7.3
+ stream_channel 1.3.1 (1.6.1 available)
+ string_scanner 0.1.5 (1.0.2 available)
+ test 0.12.7 (0.12.21 available)
+ typed_data 1.1.3
+ unittest 0.11.7 (0.12.4+1 available)
+ utf 0.9.0+3
+ uuid 0.5.1 (0.5.3 available)
+ watcher 0.9.7 (0.9.7+3 available)
+ web_components 0.11.4 (0.12.5 available)
+ webdriver 1.0.0 (1.2.3 available)
+ when 0.2.0
+ which 0.1.3
+ xml 2.2.3 (2.5.0 available)
+ xml2json 2.0.6 (2.0.8 available)
+ yaml 2.1.10 (2.1.12 available)
Downloading angular 1.1.2+2...
Downloading angular_ui 0.6.13...
Downloading args 0.12.2+6...
Downloading browser 0.10.0+2...
Downloading dart_config 0.5.0...
Downloading dart_to_js_script_rewriter 1.0.1...
Downloading glob 1.1.3...
Downloading guinness 0.1.18...
Downloading js 0.6.0...
Downloading mixpanel 1.0.0...
Downloading mock 0.11.0+4...
Downloading mockito 0.8.2...
Downloading quiver 0.21.4...
Downloading test 0.12.7...
Downloading uuid 0.5.1...
Downloading web_components 0.11.4...
Downloading webdriver 1.0.0...
Downloading xml2json 2.0.6...
Downloading yaml 2.1.10...
Downloading charcode 1.1.1...
Downloading html 0.12.2+2...
Downloading shelf_web_socket 0.0.1+5...
Downloading perf_api 0.0.9...
Downloading pub_semver 1.3.2...
Downloading source_map_stack_trace 1.0.4...
Downloading pool 1.3.0...
Downloading http_multi_server 2.0.3...
Downloading string_scanner 0.1.5...
Downloading source_span 1.4.0...
Downloading http_parser 2.2.1...
Downloading stream_channel 1.3.1...
Downloading route_hierarchical 0.6.2...
Downloading shelf_static 0.2.4...
Downloading convert 1.1.0...
Downloading typed_data 1.1.3...
Downloading matcher 0.12.0+2...
Downloading collection 1.1.3...
Downloading utf 0.9.0+3...
Downloading initialize 0.6.1+2...
Downloading async 1.9.0...
Downloading xml 2.2.3...
Downloading dart_style 0.2.1...
Downloading petitparser 1.5.3...
Downloading mime 0.9.3...
Downloading shelf 0.6.5...
Downloading code_transformers 0.2.9+3...
Downloading cli_util 0.0.1+2...
Downloading which 0.1.3...
Downloading when 0.2.0...
Downloading path 1.4.1...
Downloading crypto 0.9.2+1...
Downloading di 3.3.5+1...
Downloading barback 0.15.2+7...
Downloading html5lib 0.12.1...
Downloading observe 0.13.1+3...
Downloading smoke 0.3.5...
Downloading source_maps 0.10.4...
Downloading logging 0.11.3+1...
Downloading csslib 0.13.7+1...
Downloading stack_trace 1.7.3...
Downloading intl 0.8.10+4...
Downloading meta 1.0.5...
Downloading unittest 0.11.7...
Downloading analyzer 0.25.2+1...
Downloading plugin 0.1.0...
Downloading package_config 0.1.5...
Downloading watcher 0.9.7...

and then when I try to run pub build or pub serve,

no pubspec.lock file found, please run "pub get" first

I installed dart 1.15.0 (the version my team uses) via homebrew.

EDIT: my supervisor clone my forked repo, and was able to execute pub get and pub serve without issue, so there doesn't appear to be an issue with the pubspec.yaml file or the repo itself.

Body:
After adding pub to the allowed connections in my firewall settings, and performing a hard reboot of my computer, this issue has been resolved.

I believe the issue was caused by pub getting a connection timeout due to the firewall, and failing without warning.


问:
What is the proper way to handle several automatic redirects?
I have a website that basically allows customers to build a cart with an item that can be configured. A user will pick an item, and they'll be prompted to pick the first option they want, they get sent to the second step where they pick their second option, etc.

The number of steps and the number of options are variable, as they are defined by the client. Usually the item only has 2-3 steps with 5-10 options. However, in order to make it faster for the customer, if there is only one option available for the given step, it will automatically be chosen and the user will be sent to the next step.

A client decided to set up an item with 10+ steps with only one option for each step. This results in the entire process automatically choosing everything. FireFox doesn't like this, as it gives the error

Firefox has detected that the server
  is redirecting the request for this
  address in a way that will never
  complete.

(I haven't checked IE or Chrome, although it probably gives similar errors).

What's the best way to fix this?

Right now the process is basically

User picks item

User picks option if there is more than one option available. Otherwise the website does step 3 itself.

POST to add the option to the cart

Redirect to Page.aspx?step=#

Repeat step 2-4 as many times as necessary

Is there any change I can make to the code or page so that FireFox doesn't think I'm in an endless loop?

答:
I am surprised that you get an endless redirect error if # is different each time, but either way, this doesn't seem like the best architecture. Basically, if the code decides a step can be done automatically, it instantly redirects to the same page with the new step number?

Why don't you just have your code do that without redirecting, increment the page number in the server code as needed, and show them the right step directly, without having to redirect?

Whatever is happening when you POST at each step I would think you can accomplish just as easily in code without actually having to do a new post.


问:
Pandas date_range with specific time ranges
I am trying to use pd.date_range() to create a DatetimeIndex that spans over multiple days with a frequency in seconds. However, the time range for each day should be restricted between 05:00:00 and 22:00:00

Something along the lines of (doesn't work of course):

```<code>times_c = pd.date_range(start="2015-01-01",end="2015-01-10",freq="S")
mask_c = ((times_c.time < dt.datetime.strptime("22:00:00", "%H:%M:%S")) | (times_c.time > dt.datetime.strptime("05:00:00","%H:%M:%S")))
times_c = times_c[mask_c]
</code>```

答:
Let's try this.

```<code>times_c[((times_c.hour >= 5) & (times_c.hour < 22)) | ((times_c.hour == 22) &(times_c.minute == 0) & (times_c.second == 0))]
</code>```

Let's get all time times greater than hour 5 and less than 22, then get that edge case of 22 with zero minutes and zero seconds.

Body:
I am trying to use pd.date_range() to create a DatetimeIndex that spans over multiple days with a frequency in seconds. However, the time range for each day should be restricted between 05:00:00 and 22:00:00

Something along the lines of (doesn't work of course):

times_c = pd.date_range(start="2015-01-01",end="2015-01-10",freq="S")
mask_c = ((times_c.time
 dt.datetime.strptime("05:00:00","%H:%M:%S")))
times_c = times_c[mask_c]

Body:
Let's try this.

times_c[((times_c.hour >= 5) & (times_c.hour < 22)) | ((times_c.hour == 22) &(times_c.minute == 0) & (times_c.second == 0))]

Let's get all time times greater than hour 5 and less than 22, then get that edge case of 22 with zero minutes and zero seconds.


问:
How are these two Breadth First Search problems different from each other
Below are two breadth first search traversal problems.

Problem 1 : 317 - Shortest Distance From All Buildings

The solution for this problem is to do a breadth first search traversal from each building, and record the distance to the reachable cells from it.
The shortest distance would be the cell that is reachable from each of the buildings, and have the cumulative shortest distance over distance to reach that cell from each building.

Problem 2 : 296 - Best Meeting Point

I find this problem to be exactly the same as previous, except that there are no 2, that is, obstacles here. Why is there a different solution however?

I am trying to understand the difference between the two problems, and why the solution of the first problem won't work for the second. Does Manhattan distance have anything to do with it?

EDIT : Based on SimMac's answer below, I have tried to update the Manhattan and Travelling distance starting from the building at (0,1). The input as well as Manhattan and Travelling distance are below. SimMac, could you please validate these.

```<code>Input
0 - 1 - 2 - 0 - 1
|   |   |   |   |
0 - 2 - 0 - 0 - 0
|   |   |   |   |
0 - 0 - 0 - 0 - 1

Manhattan distance
1 - source - INF - 8 -   9
|      |     |     |     |
2 -   INF -  6 -   7 -   8
|      |     |     |     |
3 -    4 -   5 -   6 -   7

Travelling Distance
1-   source- INF - INF - INF
|      |     |     |     |
2 -   INF - INF - INF - INF
|      |     |     |     |
3 -   INF - INF - INF - INF
</code>```

答:
You can use first algorithm for second problem, but it isn't neccessary.

You already mentioned the Manhattan distance. Instead of doing a BFS to calculate the distance between two points, you can now simply calculate the Manhattan distance and use this value. Because the manhattan distance between two points (x1, y1), (x2, y2) is simply the absolute difference of x1 and x2 plus the absolute difference of y1 and y2, it is much faster to calculate the distance this way.

You can't use the Manhattan distance on the first problem, because you may have a situation like this:

```<code>0 - 1 - 2 - 0 - 1
|   |   |   |   |
0 - 2 - 0 - 0 - 0
|   |   |   |   |
0 - 0 - 0 - 0 - 1
</code>```

You can easily see how the traveling distance from the building at (0,1) to any point not in the rightmost column differs from the Manhattan distance.

Let's draw the traveling distances from the building to every other field:

```<code>1 - x - + - 8 - 9
|   |   |   |   |
2 - + - 6 - 7 - 8
|   |   |   |   |
3 - 4 - 5 - 6 - 7
</code>```

The Manhattan distance would look like this (it isn't affected by the obstacles):

```<code>1 - x - + - 2 - 3
|   |   |   |   |
2 - + - 2 - 3 - 4
|   |   |   |   |
3 - 2 - 3 - 4 - 5
</code>```

Body:
Below are two breadth first search traversal problems.

Problem 1 : 317 - Shortest Distance From All Buildings

The solution for this problem is to do a breadth first search traversal from each building, and record the distance to the reachable cells from it.
The shortest distance would be the cell that is reachable from each of the buildings, and have the cumulative shortest distance over distance to reach that cell from each building.

Problem 2 : 296 - Best Meeting Point

I find this problem to be exactly the same as previous, except that there are no 2, that is, obstacles here. Why is there a different solution however?

I am trying to understand the difference between the two problems, and why the solution of the first problem won't work for the second. Does Manhattan distance have anything to do with it?

EDIT : Based on SimMac's answer below, I have tried to update the Manhattan and Travelling distance starting from the building at (0,1). The input as well as Manhattan and Travelling distance are below. SimMac, could you please validate these.

Input
0 - 1 - 2 - 0 - 1
|   |   |   |   |
0 - 2 - 0 - 0 - 0
|   |   |   |   |
0 - 0 - 0 - 0 - 1

Manhattan distance
1 - source - INF - 8 -   9
|      |     |     |     |
2 -   INF -  6 -   7 -   8
|      |     |     |     |
3 -    4 -   5 -   6 -   7

Travelling Distance
1-   source- INF - INF - INF
|      |     |     |     |
2 -   INF - INF - INF - INF
|      |     |     |     |
3 -   INF - INF - INF - INF

Body:
You can use first algorithm for second problem, but it isn't neccessary.

You already mentioned the Manhattan distance. Instead of doing a BFS to calculate the distance between two points, you can now simply calculate the Manhattan distance and use this value. Because the manhattan distance between two points (x1, y1), (x2, y2) is simply the absolute difference of x1 and x2 plus the absolute difference of y1 and y2, it is much faster to calculate the distance this way.

You can't use the Manhattan distance on the first problem, because you may have a situation like this:

0 - 1 - 2 - 0 - 1
|   |   |   |   |
0 - 2 - 0 - 0 - 0
|   |   |   |   |
0 - 0 - 0 - 0 - 1

You can easily see how the traveling distance from the building at (0,1) to any point not in the rightmost column differs from the Manhattan distance.

Let's draw the traveling distances from the building to every other field:

1 - x - + - 8 - 9
|   |   |   |   |
2 - + - 6 - 7 - 8
|   |   |   |   |
3 - 4 - 5 - 6 - 7

The Manhattan distance would look like this (it isn't affected by the obstacles):

1 - x - + - 2 - 3
|   |   |   |   |
2 - + - 2 - 3 - 4
|   |   |   |   |
3 - 2 - 3 - 4 - 5