问:
"Runtime error 13 - Type mismatch" when parsing date from a text cell
I'm importing a .csv file from another program into Excel. The date format is text, formatted as follows :
mm/dd/yy or
07/03/17
The imported file is very unstructured, with more than just dates in the first field.

I want to write 2017-07-03 into the cell (2,13)

Here is the code I'm using

```<code>ActiveSheet.Cells(2, 13).Select
ActiveCell.FormulaR1C1 = "=IF(LEN(RC[-12]))=8, _  'How I identify date
20&MID((RC[-12]),7,2)&" - "&                      'To get 2017 4 digit Year
MID((RC[-12]),1,2)&" - "&                         'To extract 2 digit month
MID((RC[-12]),4,2)),"""")"                        'To extract 2 digit day
</code>```

This gives me Runtime error 13 - Type mismatch.
I think that my code is causing the error by mixing values and text, but I cannot see where.

答:
You haven't appropriately closed your strings with double quotes for each line. Using the continuation character _ doesn't allow you to break a string in the middle. You can do this if you properly concatenate:

```<code>ActiveCell.FormulaR1C1 = "=IF(LEN(RC[-12]))=8," & _       'How I identify date
                         "20&MID((RC[-12]),7,2)&" - " & _ 'To get 2017 4 digit Year
                         "MID((RC[-12]),1,2)&" - " & _    'To extract 2 digit month
                         "MID((RC[-12]),4,2)),"""")"      'To extract 2 digit day
</code>```

(Your code will be far more readable if you take the time to indent continued lines in the fashion shown above. You can more quickly and easily pick out the destination variable and the assignment if you follow this format.)

Body:
I'm importing a .csv file from another program into Excel. The date format is text, formatted as follows :
mm/dd/yy or
07/03/17
The imported file is very unstructured, with more than just dates in the first field.

I want to write 2017-07-03 into the cell (2,13)

Here is the code I'm using

ActiveSheet.Cells(2, 13).Select
ActiveCell.FormulaR1C1 = "=IF(LEN(RC[-12]))=8, _  'How I identify date
20&MID((RC[-12]),7,2)&" - "&                      'To get 2017 4 digit Year
MID((RC[-12]),1,2)&" - "&                         'To extract 2 digit month
MID((RC[-12]),4,2)),"""")"                        'To extract 2 digit day

This gives me Runtime error 13 - Type mismatch.
I think that my code is causing the error by mixing values and text, but I cannot see where.

Body:
You haven't appropriately closed your strings with double quotes for each line. Using the continuation character _ doesn't allow you to break a string in the middle. You can do this if you properly concatenate:

ActiveCell.FormulaR1C1 = "=IF(LEN(RC[-12]))=8," & _       'How I identify date
                         "20&MID((RC[-12]),7,2)&" - " & _ 'To get 2017 4 digit Year
                         "MID((RC[-12]),1,2)&" - " & _    'To extract 2 digit month
                         "MID((RC[-12]),4,2)),"""")"      'To extract 2 digit day

(Your code will be far more readable if you take the time to indent continued lines in the fashion shown above. You can more quickly and easily pick out the destination variable and the assignment if you follow this format.)


来源: stackexchange

问:
Identity Server - multiple STS
I have two groups of api applications (group 1: api11, api12; group 2: api21, api22) that are used by two different groups od javascript applications (group 1 and group 2). Each api group has different domain and use different instance of Identity Server (also each identity server has different domain). Business requirement is that user logged in to any application from group 1 can use any app from this group but can't use app or api from group 2.

Under the hood both api1 and api2 often needs to talk to the same microservices. What I want to achive is to make microservices accessible with access tokens issued from any of the identity servers (used by group 1 or group 2 app). Is there any way to achieve this? For one identity server I can use UseIdentityServerBearerTokenAuthentication but as argument I can pass only one Authority there.

答:
So I think this should be possible although whether you really want to do it or not is another question! I haven't tried this but you'd need to do something along the lines of:

Use the same signing certificate from both IdentityServers

To validate your JWTs, use the Microsoft extension "UseJwtBearerAuthentication" instead of using the IdentityServer validator (which is set with the UseIdentityServerAuthentication extension not UseIdentityServerBearerTokenAuthentication - the latter is IdentityServer3 I think). IdentityServer uses the Microsoft validator under the hood anyway, code and docs:

Our authentication middleware serves the same purpose as the above middleware (in fact it uses the Microsoft JWT middleware internally)

The reason for using the Microsoft validator directly is that now you can avoid setting the authority when you set it up, this would normally be used to validate the "iss" (issuer) as part of validating the JWT. Instead you can configure multiple valid issuers (i.e. your two IdentityServers) and point the validator directly at the signing cert that you are using in step 1:

```<code>var tokenValidationParameters = new TokenValidationParameters
{
    ValidateIssuerSigningKey = true,
    ValidateIssuer = true,
    ValidIssuers = new[]
    {
        "http://my_first_IdentityServer/",
        "http://my_second_IdentityServer/"
    },
    IssuerSigningKey = new X509SecurityKey(new X509Certificate2(certLocation))
};

app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
    Audience = "http://localhost:5001/",
    AutomaticAuthenticate = true,
    TokenValidationParameters = tokenValidationParameters
});
</code>```

The above is adapted from the article here. As it says in the article, you could equally (and preferably) use a certificate store rather than a cert file.

Btw, we're obviously talking authentication here, how you authorise users across the APIs will no doubt add extra complexity.

ContentLicense: CC BY-SA 3.0

Title: Identity Server - multiple STS

Body:
So I think this should be possible although whether you really want to do it or not is another question! I haven't tried this but you'd need to do something along the lines of:

Use the same signing certificate from both IdentityServers

To validate your JWTs, use the Microsoft extension "UseJwtBearerAuthentication" instead of using the IdentityServer validator (which is set with the UseIdentityServerAuthentication extension not UseIdentityServerBearerTokenAuthentication - the latter is IdentityServer3 I think). IdentityServer uses the Microsoft validator under the hood anyway, code and docs:

Our authentication middleware serves the same purpose as the above middleware (in fact it uses the Microsoft JWT middleware internally)

The reason for using the Microsoft validator directly is that now you can avoid setting the authority when you set it up, this would normally be used to validate the "iss" (issuer) as part of validating the JWT. Instead you can configure multiple valid issuers (i.e. your two IdentityServers) and point the validator directly at the signing cert that you are using in step 1:

var tokenValidationParameters = new TokenValidationParameters
{
    ValidateIssuerSigningKey = true,
    ValidateIssuer = true,
    ValidIssuers = new[]
    {
        "http://my_first_IdentityServer/",
        "http://my_second_IdentityServer/"
    },
    IssuerSigningKey = new X509SecurityKey(new X509Certificate2(certLocation))
};

app.UseJwtBearerAuthentication(new JwtBearerOptions()
{
    Audience = "http://localhost:5001/",
    AutomaticAuthenticate = true,
    TokenValidationParameters = tokenValidationParameters
});

The above is adapted from the article here. As it says in the article, you could equally (and preferably) use a certificate store rather than a cert file.

Btw, we're obviously talking authentication here, how you authorise users across the APIs will no doubt add extra complexity.


问:
Reference - How do I handle Namespaces (Tags and Attributes with a Colon in their Name) in SimpleXML?
This question is intended as a reference to answer a particularly common question, which might take different forms:

I have an XML document which contains multiple namespaces; how do I parse it with SimpleXML?

My XML has a colon (":") in the tag name, how do I access it with SimpleXML?

How do I access attributes in my XML file when they have a colon in their name?

If your question has been closed as a duplicate of this, it may not be identical to these examples, but this page should tell you what you need to know.

Here is an illustrative example:

```<code>$xml =
    <<<XML
    <?xml version="1.0" encoding="utf-8"?>
    <document xmlns="http://example.com" xmlns:ns2="https://namespaces.example.org/two" xmlns:seq="urn:example:sequences">
        <list type="short">
            <ns2:item seq:position="1">A thing</ns2:item>
            <ns2:item seq:position="2">Another thing</ns2:item>
        </list>
    </document>
    XML;
$sx = simplexml_load_string($xml);
</code>```

This code will not work; why not?

```<code>foreach ( $sx->list->ns2:item as $item ) {
    echo 'Position: ' . $item['seq:position'] . "\n";
    echo 'Item: ' . (string)$item . "\n";
}
</code>```

The first problem is that ->ns2:item is invalid syntax; but changing it to this doesn't work either:

```<code>foreach ( $sx->list->{'ns2:item'} as $item ) { ... }
</code>```

Why not, and what should you use instead?

答:
What are XML namespaces?

A colon (:) in a tag or attribute name means that the element or attribute is in an XML namespace. Namespaces are a way of combining different XML formats / standards in one document, and keeping track of which names come from which format. The colon, and the part before it, aren't really part of the tag / attribute name, they just indicate which namespace it's in.

An XML namespace has a namespace identifier, which is identified by a URI (a URL or URN). The URI doesn't point at anything, it's just a way for someone to "own" the namespace. For instance, the SOAP standard uses the namespace http://www.w3.org/2003/05/soap-envelope and an OpenDocument file uses (among others) urn:oasis:names:tc:opendocument:xmlns:meta:1.0. The example in the question uses the namespaces http://example.com and https://namespaces.example.org/two.

Within a document, or a section of a document, a namespace is given a local prefix, which is the part you see before the colon. For instance, in different documents, the SOAP namespace might be given the local prefix soap:, SOAP:, SOAP-ENV:, env:, or just ns1:. These names are linked back to the identifier of the namespace using a special xmlns attribute, e.g. xmlns:soap="http://www.w3.org/2003/05/soap-envelope". The choice of prefix in a particular document is completely arbitrary, and could change each time it was generated without changing the meaning.

Finally, there is a default namespace in each document, or section of a document, which is the namespace used for elements with no prefix. It is defined by an xmlns attribute with no :, e.g. xmlns="http://www.w3.org/2003/05/soap-envelope". In the example above, <list> is in the default namespace, which is defined as http://example.com.

Somewhat peculiarly, un-prefixed attributes are never in the default namespace, but in a kind of "void namespace", which the standard doesn't clearly define. See: XML Namespaces and Unprefixed Attributes

SimpleXML gives me an empty object; what's wrong?

If you use print_r, var_dump, or similar "dump structure" functions on a SimpleXML object with namespaces in, some of the contents will not display. It is still there, and can be accessed as described below.

How do you access namespaces in SimpleXML?

SimpleXML provides two main methods for using namespaces:

The ->children() method allows you to access child elements in a particular namespace. It effectively switches your object to look at that namespace, until you call it again to switch back, or to another namespace.

The ->attributes() method works in a similar way, but allows you to access attributes in a particular namespace.

For instance, the example above might become:

define('XMLNS_EG1', 'http://example.com');
define('XMLNS_EG2', 'https://namespaces.example.org/two');
define('XMLNS_SEQ', 'urn:example:sequences');

foreach ( $sx->children(XMLNS_EG1)->list->children(XMLNS_EG2)->item as $item ) {
    echo 'Position: ' . $item->attributes(XMLNS_SEQ)->position . "\n";
    echo 'Item: ' . (string)$item . "\n";
}
```
<p>You can also select the <em>initial</em> namespace when you first parse the XML, using the <code>$namespace_or_prefix</code> parameter, which is the fourth parameter to <code>simplexml_load_string</code>, <code>simplexml_load_file</code>, or <code>new SimpleXMLElement</code>.</p>
<p>For instance, if we created the object this way, we wouldn't need the <code>->children(XMLNS_EG1)</code> call to access the <code>list</code> element:</p>
<pre class="lang-php prettyprint-override"><code>$sx = simplexml_load_string($xml, null, 0, XMLNS_EG1);
</code>```

(Note that if the root element uses a default namespace rather than a prefix, SimpleXML will select it automatically; but since you can't predict which namespace will be the default in future, it's best to always include the $namespace_or_prefix parameter or initial ->children() call.)

Short-hand (not recommended)

As a short-hand, you can also pass the methods the local alias of the namespace, by giving the second parameter as true. Remember that this prefix could change at any time, for instance, a generator might assign prefixes ns1, ns2, etc, and assign them in a different order if the code changes slightly. Relying on the full namespace URIs is always the best approach.

Using this short-hand, the code would become:

```<code>foreach ( $sx->list->children('ns2', true)->item as $item ) {
    echo 'Position: ' . $item->attributes('seq', true)->position . "\n";
    echo 'Item: ' . (string)$item . "\n";
}
</code>```

(This short-hand was added in PHP 5.2, and you may see really old examples using a more long-winded version using $sx->getNamespaces to get a list of prefix-identifier pairs. This is the worst of both worlds, as you're still hard-coding the prefix rather than the identifier.)

ContentLicense: CC BY-SA 4.0

Body:
This question is intended as a reference to answer a particularly common question, which might take different forms:

I have an XML document which contains multiple namespaces; how do I parse it with SimpleXML?

My XML has a colon (":") in the tag name, how do I access it with SimpleXML?

How do I access attributes in my XML file when they have a colon in their name?

If your question has been closed as a duplicate of this, it may not be identical to these examples, but this page should tell you what you need to know.

Here is an illustrative example:

$xml =
    <<<XML
    <?xml version="1.0" encoding="utf-8"?>
    <document xmlns="http://example.com" xmlns:ns2="https://namespaces.example.org/two" xmlns:seq="urn:example:sequences">
        <list type="short">
            <ns2:item seq:position="1">A thing</ns2:item>
            <ns2:item seq:position="2">Another thing</ns2:item>
        </list>
    </document>
    XML;
$sx = simplexml_load_string($xml);

This code will not work; why not?

foreach ( $sx->list->ns2:item as $item ) {
    echo 'Position: ' . $item['seq:position'] . "\n";
    echo 'Item: ' . (string)$item . "\n";
}

The first problem is that ->ns2:item is invalid syntax; but changing it to this doesn't work either:

foreach ( $sx->list->{'ns2:item'} as $item ) { ... }

Why not, and what should you use instead?

Body:
What are XML namespaces?

A colon (:) in a tag or attribute name means that the element or attribute is in an XML namespace. Namespaces are a way of combining different XML formats / standards in one document, and keeping track of which names come from which format. The colon, and the part before it, aren't really part of the tag / attribute name, they just indicate which namespace it's in.

An XML namespace has a namespace identifier, which is identified by a URI (a URL or URN). The URI doesn't point at anything, it's just a way for someone to "own" the namespace. For instance, the SOAP standard uses the namespace http://www.w3.org/2003/05/soap-envelope and an OpenDocument file uses (among others) urn:oasis:names:tc:opendocument:xmlns:meta:1.0. The example in the question uses the namespaces http://example.com and https://namespaces.example.org/two.

Within a document, or a section of a document, a namespace is given a local prefix, which is the part you see before the colon. For instance, in different documents, the SOAP namespace might be given the local prefix soap:, SOAP:, SOAP-ENV:, env:, or just ns1:. These names are linked back to the identifier of the namespace using a special xmlns attribute, e.g. xmlns:soap="http://www.w3.org/2003/05/soap-envelope". The choice of prefix in a particular document is completely arbitrary, and could change each time it was generated without changing the meaning.

Finally, there is a default namespace in each document, or section of a document, which is the namespace used for elements with no prefix. It is defined by an xmlns attribute with no :, e.g. xmlns="http://www.w3.org/2003/05/soap-envelope". In the example above, <list> is in the default namespace, which is defined as http://example.com.

Somewhat peculiarly, un-prefixed attributes are never in the default namespace, but in a kind of "void namespace", which the standard doesn't clearly define. See: XML Namespaces and Unprefixed Attributes

SimpleXML gives me an empty object; what's wrong?

If you use print_r, var_dump, or similar "dump structure" functions on a SimpleXML object with namespaces in, some of the contents will not display. It is still there, and can be accessed as described below.

How do you access namespaces in SimpleXML?

SimpleXML provides two main methods for using namespaces:

The ->children() method allows you to access child elements in a particular namespace. It effectively switches your object to look at that namespace, until you call it again to switch back, or to another namespace.

The ->attributes() method works in a similar way, but allows you to access attributes in a particular namespace.

For instance, the example above might become:

define('XMLNS_EG1', 'http://example.com');
define('XMLNS_EG2', 'https://namespaces.example.org/two');
define('XMLNS_SEQ', 'urn:example:sequences');

foreach ( $sx->children(XMLNS_EG1)->list->children(XMLNS_EG2)->item as $item ) {
    echo 'Position: ' . $item->attributes(XMLNS_SEQ)->position . "\n";
    echo 'Item: ' . (string)$item . "\n";
}

You can also select the initial namespace when you first parse the XML, using the $namespace_or_prefix parameter, which is the fourth parameter to simplexml_load_string, simplexml_load_file, or new SimpleXMLElement.

For instance, if we created the object this way, we wouldn't need the ->children(XMLNS_EG1) call to access the list element:

$sx = simplexml_load_string($xml, null, 0, XMLNS_EG1);

(Note that if the root element uses a default namespace rather than a prefix, SimpleXML will select it automatically; but since you can't predict which namespace will be the default in future, it's best to always include the $namespace_or_prefix parameter or initial ->children() call.)

Short-hand (not recommended)

As a short-hand, you can also pass the methods the local alias of the namespace, by giving the second parameter as true. Remember that this prefix could change at any time, for instance, a generator might assign prefixes ns1, ns2, etc, and assign them in a different order if the code changes slightly. Relying on the full namespace URIs is always the best approach.

Using this short-hand, the code would become:

foreach ( $sx->list->children('ns2', true)->item as $item ) {
    echo 'Position: ' . $item->attributes('seq', true)->position . "\n";
    echo 'Item: ' . (string)$item . "\n";
}

(This short-hand was added in PHP 5.2, and you may see really old examples using a more long-winded version using $sx->getNamespaces to get a list of prefix-identifier pairs. This is the worst of both worlds, as you're still hard-coding the prefix rather than the identifier.)


问:
CMD error filename/directory error
I used to program batch files for work but I quit since a long time, now I'm back on the job and there seemed to be a bit of a problem.
I try to edit txt files using CMD commands on a batch file:

e.g. echo hello >> *.txt

the thing is I want to add the text to all the txt files in that directory and I remember the * represented all the files in that directory with the same extension unless it's used as *.* then it includes all the files, but now all it does is just writes this error on cmd:

The filename, directory name, or volume label syntax is incorrect.

Can anyone can give a little help?

答:
You can use a FOR /F loop with a DIR command to iterate the full paths and pass those over to the redirection append >> to echo to the text files accordingly.

Example FOR Loop

Be sure to change the value of the Folder= variable to be the directory you need to append to the files with the ECHO command.

Confirmed working batch script example

```<code>@ECHO ON
SET Folder=C:\MyFolder
CD /D "%Folder%"
FOR /F "TOKENS=*" %%A IN ('DIR /B /A-D "%Folder%\*.txt"') DO ECHO HELLO>>%%~fA
PAUSE
EXIT
</code>```

Further Resources

DIR

FOR /F

In addition, substitution of FOR variable references has been
  enhanced. You can now use the following optional syntax:

```<code>%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string
</code>```

Title: CMD error filename/directory error

Body:
You can use a FOR /F loop with a DIR command to iterate the full paths and pass those over to the redirection append >> to echo to the text files accordingly.

Example FOR Loop

Be sure to change the value of the Folder= variable to be the directory you need to append to the files with the ECHO command.

Confirmed working batch script example

@ECHO ON
SET Folder=C:\MyFolder
CD /D "%Folder%"
FOR /F "TOKENS=*" %%A IN ('DIR /B /A-D "%Folder%\*.txt"') DO ECHO HELLO>>%%~fA
PAUSE
EXIT

Further Resources

DIR

FOR /F

In addition, substitution of FOR variable references has been
  enhanced. You can now use the following optional syntax:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string


问:
How to do MySQL bulk insert using stored procedure?
I'm exclusively using Stored Procedures when doing database operations with MySQL. There is a need to insert thousands of records periodically. Is there a way to pass a collection as a parameter to stored procedure? If there is, how does the stored procedure go about inserting the received parameter as one bulk insert?</p>

答:
My understanding of stored procedures is that the parameters cannot contain any code that will be executable commands like INSERT DELETE UPDATE only variables. So you cannot pass a whole INSERT comand to a stored procedure. Hence store procedures give protection from SQL injection. Here is the excellent and very Turing like explanation of the rationale for the separation of commands and parameters in stored procedures by @Polynomials https://security.stackexchange.com/questions/25684/how-can-i-explain-sql-injection-without-technical-jargon/25710#25710

So batch inserts will either be LOAD DATA INFILE as @O. Jones said in comments above or an INSERT stored procedure where you use the language of your choice to iterate the population of the parameters insert by insert.


问:
A tool to find projects erroneously referenced by dll in Visual Studio 2008 solutions
I have a Visual Studio 2008 solution containing a lot of projects with references to each other.

I didn't create the solution, and a lot of references that could be made by project are actually made by dll (referencing the dll of the /bin/Debug folder of the project). This is of course a problem since it creates weird behaviour when you clean or rebuild the solution, like the compiler complaining about dll versions not being OK.

I don't seem to be able to spot easily which projects are erroneously referenced by dll, so my only option now seems to look into the references from each .csproj files to spot the errors and correct them.

The problem is that my source control holds around 100 solutions with the same potential issues, each one containing tens of projects. Doing it manually may take a lot of time, so I was wondering if there is any tool out there that can rebuild references and dependencies easily?

答:
A tool such as ReSharper by Jet Brains may be what you're looking for.

This will allow you to see which references in your projects are not being used. (and more)

ContentLicense: CC BY-SA 2.5


问:
Is it possible to use one sql query to iterate through hierarchical table till NULL
For example i have table that looks like this:

```<code>| ID (This is primary key) | parent (this refers to other rows in this table) |
|--------------------------|--------------------------------------------------|
| 1                        | NULL                                             |
| 2                        | 3                                                |
| 3                        | 1                                                |
</code>```

Is it possible to have ONE mysql query which would return me all hierarchy of parents till it hits NULL?

For example if i would ask for row 2 parents, i want to get row 2, then row 3 and row 1. And if i would ask for row 3 parents, i want to get row 3 and row 1.

(By the way, I want my table to have multiple rows with NULL parents).

Is this possible, if yes how to do it?

答:
You can't do this easily until MySQL 8.0 recursive queries.

I did a presentation Recursive Query Throwdown in MySQL 8.0 for the Percona Live conference in April 2017, showing how to do this.

You can also see:

My older presentation Models for Hierarchical Data

My answer to What is the most efficient/elegant way to parse a flat table into a tree?

My book SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming

Body:
For example i have table that looks like this:

| ID (This is primary key) | parent (this refers to other rows in this table) |
|--------------------------|--------------------------------------------------|
| 1                        | NULL                                             |
| 2                        | 3                                                |
| 3                        | 1                                                |

Is it possible to have ONE mysql query which would return me all hierarchy of parents till it hits NULL?

For example if i would ask for row 2 parents, i want to get row 2, then row 3 and row 1. And if i would ask for row 3 parents, i want to get row 3 and row 1.

(By the way, I want my table to have multiple rows with NULL parents).

Is this possible, if yes how to do it?


问:
on calling new created controller function it navigates to 404 error page
in yii2 advanced template site Controller is working fine. When calling a function in new controller it is navigating to 404 error page.

I created model using model generator and create a crude for the model.

This is my controller

```<code> namespace backend\Controllers;

    use Yii;
    use common\models\PackageTable;
    use common\models\PackageTableSearch;
    use yii\web\Controller;
    use yii\web\NotFoundHttpException;
    use yii\filters\VerbFilter;

    /**
     * PackageTableController implements the CRUD actions for PackageTable model.
     */
    class PackageTableController extends Controller
    {
        /**
         * @inheritdoc
         */
        public function behaviors()
        {
            return [
                'verbs' => [
                    'class' => VerbFilter::className(),
                    'actions' => [
                        'delete' => ['POST'],
                    ],
                ],
            ];
        }

        /**
         * Lists all PackageTable models.
         * @return mixed
         */
        public function actionIndex()
        {
            $searchModel = new PackageTableSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

            return $this->render('index', [
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider,
            ]);
        }

        /**
         * Displays a single PackageTable model.
         * @param integer $id
         * @return mixed
         */
        public function actionView($id)
        {
            return $this->render('view', [
                'model' => $this->findModel($id),
            ]);
        }

        /**
         * Creates a new PackageTable model.
         * If creation is successful, the browser will be redirected to the 'view' page.
         * @return mixed
         */
        public function actionCreate()
        {
            $model = new PackageTable();

            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->package_id]);
            } else {
                return $this->render('create', [
                    'model' => $model,
                ]);
            }
        }

        /**
         * Updates an existing PackageTable model.
         * If update is successful, the browser will be redirected to the 'view' page.
         * @param integer $id
         * @return mixed
         */
        public function actionUpdate($id)
        {
            $model = $this->findModel($id);

            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->package_id]);
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        }

        /**
         * Deletes an existing PackageTable model.
         * If deletion is successful, the browser will be redirected to the 'index' page.
         * @param integer $id
         * @return mixed
         */
        public function actionDelete($id)
        {
            $this->findModel($id)->delete();

            return $this->redirect(['index']);
        }

        /**
         * Finds the PackageTable model based on its primary key value.
         * If the model is not found, a 404 HTTP exception will be thrown.
         * @param integer $id
         * @return PackageTable the loaded model
         * @throws NotFoundHttpException if the model cannot be found
         */
        protected function findModel($id)
        {
            if (($model = PackageTable::findOne($id)) !== null) {
                return $model;
            } else {
                throw new NotFoundHttpException('The requested page does not exist.');
            }
        }
    }
</code>```

This is my model

```<code>    <?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "package_table".
 *
 * @property integer $package_id
 * @property string $package_name
 * @property string $description
 * @property integer $amount
 * @property integer $status
 * @property string $created_on
 * @property string $updated_on
 */
class PackageTable extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'package_table';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['package_name', 'description', 'amount', 'status'], 'required'],
            [['description'], 'string'],
            [['amount', 'status'], 'integer'],
            [['created_on', 'updated_on'], 'safe'],
            [['package_name'], 'string', 'max' => 250],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'package_id' => 'Package ID',
            'package_name' => 'Package Name',
            'description' => 'Description',
            'amount' => 'Amount',
            'status' => 'Status',
            'created_on' => 'Created On',
            'updated_on' => 'Updated On',
        ];
    }
}
</code>```

This is my model search

```<code> <?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\PackageTable;

/**
 * PackageTableSearch represents the model behind the search form about `common\models\PackageTable`.
 */
class PackageTableSearch extends PackageTable
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['package_id', 'amount', 'status'], 'integer'],
            [['package_name', 'description', 'created_on', 'updated_on'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = PackageTable::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'package_id' => $this->package_id,
            'amount' => $this->amount,
            'status' => $this->status,
            'created_on' => $this->created_on,
            'updated_on' => $this->updated_on,
        ]);

        $query->andFilterWhere(['like', 'package_name', $this->package_name])
            ->andFilterWhere(['like', 'description', $this->description]);

        return $dataProvider;
    }
}
</code>```

答:
Although php namespaces are case-insensitive, autoloader in your case is likely case-sensitive.

At the top of your controller namespace mentioned as

```<code> namespace backend/Controllers;
</code>```

but in advanced template all directories are in lower case. So try to change this line to

```<code> namespace backend/controllers;
</code>```

Body:
in yii2 advanced template site Controller is working fine. When calling a function in new controller it is navigating to 404 error page.

I created model using model generator and create a crude for the model.

This is my controller

 namespace backend\Controllers;

    use Yii;
    use common\models\PackageTable;
    use common\models\PackageTableSearch;
    use yii\web\Controller;
    use yii\web\NotFoundHttpException;
    use yii\filters\VerbFilter;

    /**
     * PackageTableController implements the CRUD actions for PackageTable model.
     */
    class PackageTableController extends Controller
    {
        /**
         * @inheritdoc
         */
        public function behaviors()
        {
            return [
                'verbs' => [
                    'class' => VerbFilter::className(),
                    'actions' => [
                        'delete' => ['POST'],
                    ],
                ],
            ];
        }

        /**
         * Lists all PackageTable models.
         * @return mixed
         */
        public function actionIndex()
        {
            $searchModel = new PackageTableSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

            return $this->render('index', [
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider,
            ]);
        }

        /**
         * Displays a single PackageTable model.
         * @param integer $id
         * @return mixed
         */
        public function actionView($id)
        {
            return $this->render('view', [
                'model' => $this->findModel($id),
            ]);
        }

        /**
         * Creates a new PackageTable model.
         * If creation is successful, the browser will be redirected to the 'view' page.
         * @return mixed
         */
        public function actionCreate()
        {
            $model = new PackageTable();

            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->package_id]);
            } else {
                return $this->render('create', [
                    'model' => $model,
                ]);
            }
        }

        /**
         * Updates an existing PackageTable model.
         * If update is successful, the browser will be redirected to the 'view' page.
         * @param integer $id
         * @return mixed
         */
        public function actionUpdate($id)
        {
            $model = $this->findModel($id);

            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->package_id]);
            } else {
                return $this->render('update', [
                    'model' => $model,
                ]);
            }
        }

        /**
         * Deletes an existing PackageTable model.
         * If deletion is successful, the browser will be redirected to the 'index' page.
         * @param integer $id
         * @return mixed
         */
        public function actionDelete($id)
        {
            $this->findModel($id)->delete();

            return $this->redirect(['index']);
        }

        /**
         * Finds the PackageTable model based on its primary key value.
         * If the model is not found, a 404 HTTP exception will be thrown.
         * @param integer $id
         * @return PackageTable the loaded model
         * @throws NotFoundHttpException if the model cannot be found
         */
        protected function findModel($id)
        {
            if (($model = PackageTable::findOne($id)) !== null) {
                return $model;
            } else {
                throw new NotFoundHttpException('The requested page does not exist.');
            }
        }
    }

This is my model

    <?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "package_table".
 *
 * @property integer $package_id
 * @property string $package_name
 * @property string $description
 * @property integer $amount
 * @property integer $status
 * @property string $created_on
 * @property string $updated_on
 */
class PackageTable extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'package_table';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['package_name', 'description', 'amount', 'status'], 'required'],
            [['description'], 'string'],
            [['amount', 'status'], 'integer'],
            [['created_on', 'updated_on'], 'safe'],
            [['package_name'], 'string', 'max' => 250],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'package_id' => 'Package ID',
            'package_name' => 'Package Name',
            'description' => 'Description',
            'amount' => 'Amount',
            'status' => 'Status',
            'created_on' => 'Created On',
            'updated_on' => 'Updated On',
        ];
    }
}

This is my model search

 <?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\PackageTable;

/**
 * PackageTableSearch represents the model behind the search form about `common\models\PackageTable`.
 */
class PackageTableSearch extends PackageTable
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['package_id', 'amount', 'status'], 'integer'],
            [['package_name', 'description', 'created_on', 'updated_on'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = PackageTable::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'package_id' => $this->package_id,
            'amount' => $this->amount,
            'status' => $this->status,
            'created_on' => $this->created_on,
            'updated_on' => $this->updated_on,
        ]);

        $query->andFilterWhere(['like', 'package_name', $this->package_name])
            ->andFilterWhere(['like', 'description', $this->description]);

        return $dataProvider;
    }
}

Body:
Although php namespaces are case-insensitive, autoloader in your case is likely case-sensitive.

At the top of your controller namespace mentioned as

 namespace backend/Controllers;

but in advanced template all directories are in lower case. So try to change this line to

 namespace backend/controllers;


问:
Python - Num1 1 not defined
```<code>def to_numbers():
  num1 = str(raw_input('Enter a string number?\n'))

for value in num1:
  try:
    print '%s as an int is %d' % (str(value), int(value))
  except ValueError, ex:
    print '"%s" cannot be converted to an int: %s' % (value, ex)
</code>```

Was wondering if I can code this correctly. Received num1 not defined error.

答:
You need to return num1 in the function to_numbers (otherwise, you cannot use this value outsize of to_numbers). Then you need to call to_numbers in order to define num1, as follows:

```<code>def to_numbers():
    num1 = str(raw_input('Enter a string number?\n'))
    return num1

num1=to_numbers()
for value in num1:
    try:
        print '%s as an int is %d' % (str(value), int(value))
    except ValueError, ex:
        print '"%s" cannot be converted to an int: %s' % (value, ex)
</code>```

Title: Python - Num1 1 not defined

Body:
def to_numbers():
  num1 = str(raw_input('Enter a string number?\n'))

for value in num1:
  try:
    print '%s as an int is %d' % (str(value), int(value))
  except ValueError, ex:
    print '"%s" cannot be converted to an int: %s' % (value, ex)

Was wondering if I can code this correctly. Received num1 not defined error.

Body:
You need to return num1 in the function to_numbers (otherwise, you cannot use this value outsize of to_numbers). Then you need to call to_numbers in order to define num1, as follows:

def to_numbers():
    num1 = str(raw_input('Enter a string number?\n'))
    return num1

num1=to_numbers()
for value in num1:
    try:
        print '%s as an int is %d' % (str(value), int(value))
    except ValueError, ex:
        print '"%s" cannot be converted to an int: %s' % (value, ex)


答: You have to insert tabs so the for is inside the function. Else, you just have a function which reads a value and a for outside of it, which cannot access to num1.

Title: Python - Num1 1 not defined


答:
Here is how I would do it:

```<code>import java.io.*;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {

        try {

            PrintWriter requests = new PrintWriter("requests.txt");
            PrintWriter responses = new PrintWriter("responses.txt");
            PrintWriter currentLog = null;

            Scanner s = new Scanner(new File("log.txt"));
            while (s.hasNextLine()) {
                String line = s.nextLine();
                if (line.startsWith("Request from"))
                    currentLog = requests;
                else if (line.startsWith("Response from"))
                    currentLog = responses;
                else if (currentLog != null)
                    currentLog.println(line);
            }

            requests.close();
            responses.close();
            s.close();
        } catch (IOException ioex) {
            // handle exception...
        }
    }
}
</code>```

Given log.txt

```<code>Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************
2010-12-14 12:42:13.724 [ 6796] 1111111111111111
2010-12-14 12:42:13.724 [ 6796]22222222222

Response from Centercord.
2010-12-14 12:42:21.802 [ 5960] 11111111111111
2010-12-14 12:42:21.802 [ 5960]  ffffffffffffffffffffffffffff
2010-12-14 12:42:21.802 [ 5960]  tttttttttttttttttttttttttttt

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************
</code>```

It produces, requests.txt

```<code>2010-12-14 12:42:13.724 [ 6796] ****************************
2010-12-14 12:42:13.724 [ 6796] 1111111111111111
2010-12-14 12:42:13.724 [ 6796]22222222222

2010-12-14 12:42:13.724 [ 6796] ****************************
</code>```

...and responses.txt

```<code>2010-12-14 12:42:21.802 [ 5960] 11111111111111
2010-12-14 12:42:21.802 [ 5960]  ffffffffffffffffffffffffffff
2010-12-14 12:42:21.802 [ 5960]  tttttttttttttttttttttttttttt
</code>```

Title: Parsing a log file in Java

Body:
All,

I have a log file with the below content.

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************
2010-12-14 12:42:13.724 [ 6796] 1111111111111111
2010-12-14 12:42:13.724 [ 6796]22222222222

Response from Centercord.
2010-12-14 12:42:21.802 [ 5960] 11111111111111
2010-12-14 12:42:21.802 [ 5960]  ffffffffffffffffffffffffffff
2010-12-14 12:42:21.802 [ 5960]  tttttttttttttttttttttttttttt

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************

I need to create two log files one is for storing all the Request details and the other one is for storing all the Response details. How can I parse this and prepare two log files?.

I need the below answer.

Log 1:

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************
2010-12-14 12:42:13.724 [ 6796] 1111111111111111
2010-12-14 12:42:13.724 [ 6796]22222222222

2010-12-14 12:42:13.724 [ 6796] ****************************

Log 2:

Response from Centercord.
2010-12-14 12:42:21.802 [ 5960] 11111111111111
2010-12-14 12:42:21.802 [ 5960]  ffffffffffffffffffffffffffff
2010-12-14 12:42:21.802 [ 5960]  tttttttttttttttttttttttttttt

Regards,
Kanagaraj

Body:
Here is how I would do it:

import java.io.*;
import java.util.Scanner;

public class Test {

    public static void main(String[] args) {

        try {

            PrintWriter requests = new PrintWriter("requests.txt");
            PrintWriter responses = new PrintWriter("responses.txt");
            PrintWriter currentLog = null;

            Scanner s = new Scanner(new File("log.txt"));
            while (s.hasNextLine()) {
                String line = s.nextLine();
                if (line.startsWith("Request from"))
                    currentLog = requests;
                else if (line.startsWith("Response from"))
                    currentLog = responses;
                else if (currentLog != null)
                    currentLog.println(line);
            }

            requests.close();
            responses.close();
            s.close();
        } catch (IOException ioex) {
            // handle exception...
        }
    }
}

Given log.txt

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************
2010-12-14 12:42:13.724 [ 6796] 1111111111111111
2010-12-14 12:42:13.724 [ 6796]22222222222

Response from Centercord.
2010-12-14 12:42:21.802 [ 5960] 11111111111111
2010-12-14 12:42:21.802 [ 5960]  ffffffffffffffffffffffffffff
2010-12-14 12:42:21.802 [ 5960]  tttttttttttttttttttttttttttt

Request from Centercord.
2010-12-14 12:42:13.724 [ 6796] ****************************

It produces, requests.txt

2010-12-14 12:42:13.724 [ 6796] ****************************
2010-12-14 12:42:13.724 [ 6796] 1111111111111111
2010-12-14 12:42:13.724 [ 6796]22222222222

2010-12-14 12:42:13.724 [ 6796] ****************************

...and responses.txt

2010-12-14 12:42:21.802 [ 5960] 11111111111111
2010-12-14 12:42:21.802 [ 5960]  ffffffffffffffffffffffffffff
2010-12-14 12:42:21.802 [ 5960]  tttttttttttttttttttttttttttt


问:
IIS URL Rewrite - IIS 7
I am new to using IIS Url Rewrite. I installed it and set up a rule using IIS, but nothing happens when I try to access a url in my localhost. Below is what IIS put in my web.config. When I access this url mysite/srcc_development_2012/login/default.aspx, based on the rule I set up it should redirect to google, but it does not work. What am I missing?</p>

```<code>    <rewrite>
        <rules>
            <rule name="SRCC" patternSyntax="Wildcard" stopProcessing="true">
                <match url="mysite/srcc_development_2012/*" />
                <action type="Redirect" url="http://www.google.com" />
                <conditions logicalGrouping="MatchAny">
                </conditions>
            </rule>
        </rules>
    </rewrite>
</code>```

答:
The below one should work :

But make sure you add this rule to the login folder.

```<code><rule name="redirect" stopProcessing="true">
      <match url=".*" />
      <action type="Redirect" url="https://google.com" />
</rule>
</code>```

Title: IIS URL Rewrite - IIS 7

Body:
I am new to using IIS Url Rewrite. I installed it and set up a rule using IIS, but nothing happens when I try to access a url in my localhost. Below is what IIS put in my web.config. When I access this url mysite/srcc_development_2012/login/default.aspx, based on the rule I set up it should redirect to google, but it does not work. What am I missing?

    <rewrite>
        <rules>
            <rule name="SRCC" patternSyntax="Wildcard" stopProcessing="true">
                <match url="mysite/srcc_development_2012/*" />
                <action type="Redirect" url="http://www.google.com" />
                <conditions logicalGrouping="MatchAny">
                </conditions>
            </rule>
        </rules>
    </rewrite>

Body:
The below one should work :

But make sure you add this rule to the login folder.

<rule name="redirect" stopProcessing="true">
      <match url=".*" />
      <action type="Redirect" url="https://google.com" />
</rule>


问:
Mongoose Error while performing delete
I am running into following error but I unable to completely grasp the understanding behind the error.

```<code>CastError: Cast to ObjectId failed for value "XYZ" at path "_id" for model "Partner"
</code>```

I have my schema defined as following

```<code>var partnerList = new Schema (
    {
        partnerName: String,
        supportedProducts: [String]
    },
    {
        collection: 'partnerList'
    }
);

module.exports = mongoose.model('Partner', partnerList);
</code>```

The functionality of my delete function

```<code>delete: function (req, res) {
    var removePartner = req.params.partnerName;
    var promise = Partner.findByIdAndRemove(removePartner).exec();
    promise.then(function removePartner(val) {
        console.log('partner value removed');
        res.send(val);
    }).catch(function catchError(err){
        console.error(err);
        throw err;
    });
}
</code>```

I am trying to making a request to my node app service using
localhost:8443/data/XYZ, where i am passing the value 'XYZ' as the parameter. This value is used to delete the appropriate object from the database.

答:
Basically the error means that whatever you pass as your "XYZ" url param is not a valid ObjectId.

Guessing from your code you use the "partner name" (probably some arbitrary string) instead of the database id of the partner. However findByIdAndRemove() requires you to specify an ObjectId as it uses this to identify which document to delete:

```<code>Model.findByIdAndRemove(id, [options], [callback])
</code>```

Your delete API call could then look something like this: http://localhost:8443/data/59558ccd7acc4dd63ea88988. However for this the client needs to know the ObjectId of the partner.

So you have to either use the ObjectId of a partner in the URL, or use remove() to implement your custom delete query instead, for example like this (if name is the property you use to store your partner names):

```<code>Partner.remove({ name: partnerName }).exec();
</code>```

Be careful however that this might remove multiple documents if your partner name is not unique, as remove will delete all documents matching the query.

In order to prevent this you can also use findOneAndRemove() using the same query. This would only remove one document at a time. If there are multiple partners with the same name it would remove the first one (depending on your sort order).

Title: Mongoose Error while performing delete

Body:
I am running into following error but I unable to completely grasp the understanding behind the error.

CastError: Cast to ObjectId failed for value "XYZ" at path "_id" for model "Partner"

I have my schema defined as following

var partnerList = new Schema (
    {
        partnerName: String,
        supportedProducts: [String]
    },
    {
        collection: 'partnerList'
    }
);

module.exports = mongoose.model('Partner', partnerList);

The functionality of my delete function

delete: function (req, res) {
    var removePartner = req.params.partnerName;
    var promise = Partner.findByIdAndRemove(removePartner).exec();
    promise.then(function removePartner(val) {
        console.log('partner value removed');
        res.send(val);
    }).catch(function catchError(err){
        console.error(err);
        throw err;
    });
}

I am trying to making a request to my node app service using
localhost:8443/data/XYZ, where i am passing the value 'XYZ' as the parameter. This value is used to delete the appropriate object from the database.

Body:
Basically the error means that whatever you pass as your "XYZ" url param is not a valid ObjectId.

Guessing from your code you use the "partner name" (probably some arbitrary string) instead of the database id of the partner. However findByIdAndRemove() requires you to specify an ObjectId as it uses this to identify which document to delete:

Model.findByIdAndRemove(id, [options], [callback])

Your delete API call could then look something like this: http://localhost:8443/data/59558ccd7acc4dd63ea88988. However for this the client needs to know the ObjectId of the partner.

So you have to either use the ObjectId of a partner in the URL, or use remove() to implement your custom delete query instead, for example like this (if name is the property you use to store your partner names):

Partner.remove({ name: partnerName }).exec();

Be careful however that this might remove multiple documents if your partner name is not unique, as remove will delete all documents matching the query.

In order to prevent this you can also use findOneAndRemove() using the same query. This would only remove one document at a time. If there are multiple partners with the same name it would remove the first one (depending on your sort order).


问:
Writing multiple json objects to a json file
I have a list of json objects that I would like to write to a json file. Example of my data is as follows:

```<code>    {
    "_id": "abc",
    "resolved": false,
    "timestamp": "2017-04-18T04:57:41 366000",
    "timestamp_utc": {
        "$date": 1492509461366
    },
    "sessionID": "abc",
    "resHeight": 768,

    "time_bucket": ["2017-year", "2017-04-month", "2017-16-week", "2017-04-18-day", "2017-04-18 16-hour"],
    "referrer": "Standalone",
    "g_event_id": "abc",

    "user_agent": "abc"
    "_id": "abc",
} {
    "_id": "abc",
    "resolved": false,
    "timestamp": "2017-04-18T04:57:41 366000",
    "timestamp_utc": {
        "$date": 1492509461366
    },
    "sessionID": "abc",
    "resHeight": 768,

    "time_bucket": ["2017-year", "2017-04-month", "2017-16-week", "2017-04-18-day", "2017-04-18 16-hour"],
    "referrer": "Standalone",
    "g_event_id": "abc",

    "user_agent": "abc"
}
</code>```

I would like to wirte this to a json file. Here's the code that I am using for this purpose:

```<code>with open("filename", 'w') as outfile1:
    for row in data:
        outfile1.write(json.dumps(row))
</code>```

But this gives me a file with only 1 long row of data. I would like to have a row for each json object in my original data. I know there are some other StackOverflow questions that are trying to address somewhat similar situation (by externally inserting '\n' etc.), but it hasn't worked in my case for some reason. I believe there has to be a pythonic way to do this.

How do I achieve this?

答:
The format of the file you are trying to create is called JSON lines.

It seems, you are asking why the jsons are not separated with a newline. Because write method does not append the newline.

If you want implicit newlines you should better use print function:

```<code>with open("filename", 'w') as outfile1:
    for row in data:
       print(json.dumps(row), file=outfile1)
</code>```

Body:
I have a list of json objects that I would like to write to a json file. Example of my data is as follows:

    {
    "_id": "abc",
    "resolved": false,
    "timestamp": "2017-04-18T04:57:41 366000",
    "timestamp_utc": {
        "$date": 1492509461366
    },
    "sessionID": "abc",
    "resHeight": 768,

    "time_bucket": ["2017-year", "2017-04-month", "2017-16-week", "2017-04-18-day", "2017-04-18 16-hour"],
    "referrer": "Standalone",
    "g_event_id": "abc",

    "user_agent": "abc"
    "_id": "abc",
} {
    "_id": "abc",
    "resolved": false,
    "timestamp": "2017-04-18T04:57:41 366000",
    "timestamp_utc": {
        "$date": 1492509461366
    },
    "sessionID": "abc",
    "resHeight": 768,

    "time_bucket": ["2017-year", "2017-04-month", "2017-16-week", "2017-04-18-day", "2017-04-18 16-hour"],
    "referrer": "Standalone",
    "g_event_id": "abc",

    "user_agent": "abc"
}

I would like to wirte this to a json file. Here's the code that I am using for this purpose:

with open("filename", 'w') as outfile1:
    for row in data:
        outfile1.write(json.dumps(row))

But this gives me a file with only 1 long row of data. I would like to have a row for each json object in my original data. I know there are some other StackOverflow questions that are trying to address somewhat similar situation (by externally inserting '\n' etc.), but it hasn't worked in my case for some reason. I believe there has to be a pythonic way to do this.

How do I achieve this?

Body:
The format of the file you are trying to create is called JSON lines.

It seems, you are asking why the jsons are not separated with a newline. Because write method does not append the newline.

If you want implicit newlines you should better use print function:

with open("filename", 'w') as outfile1:
    for row in data:
       print(json.dumps(row), file=outfile1)


答:
Do you mean this?

```<code> if(frequency==0):
 time.sleep(length)
</code>```

You need to indent the block after the if

```<code> if(frequency==0):
     time.sleep(length)
</code>```

Title: What's wrong with "time.sleep(length)"?

Body:
What is the problem by line 84? I've got this error:

SyntaxError: time.sleep(length)

What's wrong with my code?

    import time
    import RPi.GPIO as GPIO
    GPIO.setmode(GPIO.BCM)

    buzzer_pin = 17
    sensor_pin = 18

    GPIO.setup(sensor_pin, GPIO.IN)
    GPIO.setup(buzzer_pin, GPIO.IN)
    GPIO.setup(buzzer_pin, GPIO.OUT)

    notes = {
     'B0' : 31,
     'C1' : 33, 'CS1' : 35,
     'D1' : 37, 'DS1' : 39,
     'EB1' : 39,
     'E1' : 41,
     'F1' : 44, 'FS1' : 46,
     'G1' : 49, 'GS1' : 52,
     'A1' : 55, 'AS1' : 58,
     'BB1' : 58,
     'B1' : 62,
     'C2' : 65, 'CS2' : 69,
     'D2' : 73, 'DS2' : 78,
     'EB2' : 78,
     'E2' : 82,
     'F2' : 87, 'FS2' : 93,
     'G2' : 98, 'GS2' : 104,
     'A2' : 110, 'AS2' : 117,
     'BB2' : 123,
     'B2' : 123,
     'C3' : 131, 'CS3' : 139,
     'D3' : 147, 'DS3' : 156,
     'EB3' : 156,
     'E3' : 165,
     'F3' : 175, 'FS3' : 185,
     'G3' : 196, 'GS3' : 208,
     'A3' : 220, 'AS3' : 233,
     'BB3' : 233,
     'B3' : 247,
     'C4' : 262, 'CS4' : 277,
     'D4' : 294, 'DS4' : 311,
     'EB4' : 311,
     'E4' : 330,
     'F4' : 349, 'FS4' : 370,
     'G4' : 392, 'GS4' : 415,
     'A4' : 440, 'AS4' : 466,
     'BB4' : 466,
     'B4' : 494,
     'C5' : 523, 'CS5' : 554,
     'D5' : 587, 'DS5' : 622,
     'EB5' : 622,
     'E5' : 659,
     'F5' : 698, 'FS5' : 740,
     'G5' : 784, 'GS5' : 831,
     'A5' : 880, 'AS5' : 932,
     'BB5' : 932,
     'B5' : 988,
     'C6' : 1047, 'CS6' : 1109,
     'D6' : 1175, 'DS6' : 1245,
     'EB6' : 1245,
     'E6' : 1319,
     'F6' : 1397, 'FS6' : 1480,
     'G6' : 1568, 'GS6' : 1661,
     'A6' : 1760, 'AS6' : 1865,
     'BB6' : 1865,
     'B6' : 1976,
     'C7' : 2093, 'CS7' : 2217,
     'D7' : 2349, 'DS7' : 2489,
     'EB7' : 2489,
     'E7' : 2637,
     'F7' : 2794, 'FS7' : 2960,
     'G7' : 3136, 'GS7' : 3322,
     'A7' : 3520, 'AS7' : 3729,

     'BB7' : 3729,
     'B7' : 3951,
     'C8' : 4186, 'CS8' : 4435,
     'D8' : 4699, 'DS8' : 4978
    }

    def buzz(frequency, length):

     if(frequency==0):
     time.sleep(length)
     return
     period = 1.0 / frequency
     delayValue = period / 2
     numCycles = int(length * frequency)

     for i in range(numCycles):
     GPIO.output(buzzer_pin, True)
     time.sleep(delayValue)
     GPIO.output(buzzer_pin, False)
     time.sleep(delayValue)

    def play():
     buzz(notes['A3'], 0.5)
     buzz(notes['A3'], 0.5)
     buzz(notes['A3'], 0.5)
     buzz(notes['F3'], 0.35)
     buzz(notes['C4'], 0.15)
     buzz(notes['A3'], 0.5)
     buzz(notes['F3'], 0.35)
     buzz(notes['C4'], 0.15)
     buzz(notes['A3'], 1.0)

    while True:
     if GPIO.input(sensor_pin):
     print("Ses Alarmi!")
     play()
     time.sleep(0.5)

Body:
Do you mean this?

 if(frequency==0):
 time.sleep(length)

You need to indent the block after the if

 if(frequency==0):
     time.sleep(length)


问:
Flask Internal Server Error 500
Internal Server Error  The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.</p>

答:
@Alih81, you are a man of extremely few words.  I'm guessing you are using Flask and have a bug in your code.  All you are seeing in the browser is Internal Server Error ....  Flask does this for security reasons (don't want to show hackers anything about your code).

But Flask isn't showing you any useful info elsewhere.  Try setting the environment variable FLASK_DEBUG=1 before invoking your Flask server.  If using GAE, do dev_appsever.py app.yaml --env_var FLASK_DEBUG=1.

Title: Flask Internal Server Error 500


问:
Performing an SOAP Request to a service that requires NTLM Auth IIB
I am developing an operation in which i have to perform a SOAP request to a SQL reporting service, i already have gotten the WSDL to invoke the soap req and i built the Outputroot needed, but when i invoke the Service with the following authorization parameters:

```<code>    SET OutputRoot.Properties.IdentitySourceType        = 'usernameAndPassword';
    SET OutputRoot.Properties.IdentitySourceToken       = 'User';
    SET OutputRoot.Properties.IdentitySourcePassword    = 'Password';
    SET OutputRoot.Properties.IdentitySourceIssuedBy    = 'Domain';
</code>```

I get the following message from the traces

2017-07-01 20:45:18.789668    19826   UserTrace   BIP3719I: Node 'SubflowSUB.SOAP Request Operation' sending SOAP request via transport 'HTTP' ('gg20154') for operation 'Operation' of type 'request-response'. See subsequent messages for success or failure messages relating to this request, and for any transport-specific messages.No action required.

2017-07-01 20:45:18.792716    19826   UserTrace   BIP3633I: Node 'SubflowSUB.SOAP Request Operation' sending HTTP data to URL '/ReportServer/ReportExec2005.asmx' at host 'gg20154' (port 80). The broker is sending data via HTTP to a remote server at host 'gg20154' (port 80) using URL '/ReportServer/ReportExec2005.asmx'. See subsequent messages for success or failure messages relating to this request. No action required.

2017-07-01 20:45:18.794458    19826   UserTrace   BIP3634I: Node 'SubflowSUB.SOAP Request Operation' received HTTP data from host 'gg20154' with status code of 401. The broker has received data via HTTP from a remote server at host 'gg20154' with an HTTP status code of 401. Status codes beginning with a 2 indicate success; others imply errors in either client or server. No action required.

I am using the correct credentials because i have seen how is loaded on soapui when invoking the service directly but when it is invoked by IIB it throws a 401 does anyone have had this kind of issue? and how to solve it?.

Thank you in advance guys.

答:
For credentials with basic authentication you should create a security profile with basic default and assign the user and password to this profile using the mqsisetdbparms command. With this in the SOAP Request flow in the BAR generation you have to assign the security profile created:

```<code>mqsisetdbparms $BRKCORP -n NAME_CRED -u <user> -p <password>
mqsicreateconfigurableservice $BRKCORP -c SecurityProfiles -o SEG_NAME_CRED -n "propagation,idToPropagateToTransport,transportPropagationConfig" -v "TRUE,STATIC ID,NAME_CRED"
</code>```

Body:
I am developing an operation in which i have to perform a SOAP request to a SQL reporting service, i already have gotten the WSDL to invoke the soap req and i built the Outputroot needed, but when i invoke the Service with the following authorization parameters:

    SET OutputRoot.Properties.IdentitySourceType        = 'usernameAndPassword';
    SET OutputRoot.Properties.IdentitySourceToken       = 'User';
    SET OutputRoot.Properties.IdentitySourcePassword    = 'Password';
    SET OutputRoot.Properties.IdentitySourceIssuedBy    = 'Domain';

I get the following message from the traces

2017-07-01 20:45:18.789668    19826   UserTrace   BIP3719I: Node 'SubflowSUB.SOAP Request Operation' sending SOAP request via transport 'HTTP' ('gg20154') for operation 'Operation' of type 'request-response'. See subsequent messages for success or failure messages relating to this request, and for any transport-specific messages.No action required.

2017-07-01 20:45:18.792716    19826   UserTrace   BIP3633I: Node 'SubflowSUB.SOAP Request Operation' sending HTTP data to URL '/ReportServer/ReportExec2005.asmx' at host 'gg20154' (port 80). The broker is sending data via HTTP to a remote server at host 'gg20154' (port 80) using URL '/ReportServer/ReportExec2005.asmx'. See subsequent messages for success or failure messages relating to this request. No action required.

2017-07-01 20:45:18.794458    19826   UserTrace   BIP3634I: Node 'SubflowSUB.SOAP Request Operation' received HTTP data from host 'gg20154' with status code of 401. The broker has received data via HTTP from a remote server at host 'gg20154' with an HTTP status code of 401. Status codes beginning with a 2 indicate success; others imply errors in either client or server. No action required.

I am using the correct credentials because i have seen how is loaded on soapui when invoking the service directly but when it is invoked by IIB it throws a 401 does anyone have had this kind of issue? and how to solve it?.

Thank you in advance guys.

Body:
For credentials with basic authentication you should create a security profile with basic default and assign the user and password to this profile using the mqsisetdbparms command. With this in the SOAP Request flow in the BAR generation you have to assign the security profile created:

mqsisetdbparms $BRKCORP -n NAME_CRED -u <user> -p <password>
mqsicreateconfigurableservice $BRKCORP -c SecurityProfiles -o SEG_NAME_CRED -n "propagation,idToPropagateToTransport,transportPropagationConfig" -v "TRUE,STATIC ID,NAME_CRED"


答: It is not possible to get the hierarchy from a single query in mysql using the structure you have chosen to represent your tree. You could switch to oracle (have a google for "oracle connect by") or use a different structure for your data (adjacency list) or run an indeterminant number of queries.</p>

Title: Is it possible to use one sql query to iterate through hierarchical table till NULL

Body:
For example i have table that looks like this:

| ID (This is primary key) | parent (this refers to other rows in this table) |
|--------------------------|--------------------------------------------------|
| 1                        | NULL                                             |
| 2                        | 3                                                |
| 3                        | 1                                                |

Is it possible to have ONE mysql query which would return me all hierarchy of parents till it hits NULL?

For example if i would ask for row 2 parents, i want to get row 2, then row 3 and row 1. And if i would ask for row 3 parents, i want to get row 3 and row 1.

(By the way, I want my table to have multiple rows with NULL parents).

Is this possible, if yes how to do it?


问:
Is it possible use UINavigationController but hide its navigation bar (replace it with customized toolbar) and go back button
I hope to switch between 2 UIViewController using UINavigationController. (AUIViewController, BUIViewController relate to UIView AView,BView)

AView has an UIButton, BView has an UIButton also.
If I press the button on AView, it will push BViewController and display BView.
If I press the button on BView, BViewController will pop and go back AUIViewController.

I hope to use UINavigationController's navigation function but hide its 'go back' bar and navigation bar, only use 2 buttons to tell UINaviationController what it needs to do.
Is it possible?

答:
to hide UINavigationController's navigation bar:

```<code>[self.navigationController setNavigationBarHidden:YES];
</code>```

To push a view controller from a button:

```<code>- (void)pushNextViewController {
    NextViewController *page = [[NextViewController alloc] initWithNibName:nil bundle:nil];
    [self.navigationController pushViewController:page animated:YES];
}
</code>```

To pop a view controller back one:

```<code>- (void)popToLastViewController {
    [self.navigationController popViewControllerAnimated:YES];
}
</code>```

Body:
to hide UINavigationController's navigation bar:

[self.navigationController setNavigationBarHidden:YES];

To push a view controller from a button:

- (void)pushNextViewController {
    NextViewController *page = [[NextViewController alloc] initWithNibName:nil bundle:nil];
    [self.navigationController pushViewController:page animated:YES];
}

To pop a view controller back one:

- (void)popToLastViewController {
    [self.navigationController popViewControllerAnimated:YES];
}


问:
Combinations from different groups in a specific order
I have a list of parameters that each accept a specific range of inputs. I am working on creating a test that creates every possible valid input. Furthermore, each group is optional (can be skipped entirely), so the combination lengths don't necessarily have to be the same length of the list.

Input

```<code>List<string[]> temp = new List<string[]>
{
    // The order of these groups is important
    new string[] { "a", "b", "c" },
    new string[] { "d", "e" },
    new string[] { "f", "g", "h" }
};
</code>```

Constraints

0 or 1 item per group (a string[] above)

Order of the List<T> must be preserved

Valid Combinations

a, e, f

a, d, g

c, e, f

b, g

c, f

Invalid Combinations

a, b, f (a and b are from the same group - not allowed)

a, f, d (wrong order - d must come before f)

So far, I have gone back to my library where I have a Combinations LINQ method.

```<code>public static class IEnumerableExtensions
{
    // Can be used to get all permutations at a certain level
    // Source: http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n#1898744
    public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
    {
        return k == 0 ? new[] { new T[0] } :
          elements.SelectMany((e, i) =>
            elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c)));
    }
}
</code>```

In the past I have only used this on single sequence to do things like generate every permutation of URL segments. But I am struggling with its usage on a nested list with the constraints of one per group and in a specific order.

I know I can solve this particular puzzle by doing 3 nested loops and using lists to track which items were already used, but I don't know in advance how many items will be in the List<T>, so that won't work in the general case.

How can I get all of the valid combinations of the above input?

I would prefer LINQ, but will accept any solution that solves this problem.

答:
Using some extension functions,

```<code>public static IEnumerable<T> Prepend<T>(this IEnumerable<T> rest, params T[] first) => first.Concat(rest);
public static IEnumerable<T> AsSingleton<T>(this T source) {
    yield return source;
}
</code>```

You can write

```<code>public static IEnumerable<IEnumerable<T>> ParametersWithEmpty<T>(this IEnumerable<IEnumerable<T>> ParmLists) {
    if (ParmLists.Count() == 0)
        yield break; // empty
    else {
        var rest = ParametersWithEmpty(ParmLists.Skip(1));
        foreach (var p in ParmLists.First()) {
            yield return p.AsSingleton(); // p.Concat(empty)
            foreach (var r in rest)
                yield return r.Prepend(p); // p.Concat(r)
        }
        foreach (var r in rest)
            yield return r; // empty.Concat(r)
    }
}
</code>```

You can call it like this:

```<code>var ans = temp.ParametersWithEmpty();
</code>```

To include all the levels in the results, you must skip the empty cases implicit in the above code:

```<code>public static IEnumerable<IEnumerable<T>> Parameters<T>(this IEnumerable<IEnumerable<T>> ParmLists) {
    if (ParmLists.Count() == 1)
        foreach (var p in ParmLists.First())
            yield return p.AsSingleton();
    else {
        var rest = Parameters(ParmLists.Skip(1));
        foreach (var p in ParmLists.First()) {
            foreach (var r in rest)
                yield return r.Prepend(p);
        }
    }
}
</code>```

Finally, here is an alternative version that may make it somewhat clearer as it outputs the sequence as if each parameter list is preceded by empty, but also returns the all empty sequence in the answer.

```<code>public static IEnumerable<IEnumerable<T>> ParametersWithEmpty2<T>(this IEnumerable<IEnumerable<T>> ParmLists) {
    if (ParmLists.Count() == 0)
        yield return Enumerable.Empty<T>();
    else {
        var rest = ParametersWithEmpty2(ParmLists.Skip(1));
        foreach (var r in rest)
            yield return r; // empty.Concat(r)
        foreach (var p in ParmLists.First()) {
            foreach (var r in rest)
                yield return r.Prepend(p); // p.Concat(r)
        }
    }
}
</code>```

Body:
I have a list of parameters that each accept a specific range of inputs. I am working on creating a test that creates every possible valid input. Furthermore, each group is optional (can be skipped entirely), so the combination lengths don't necessarily have to be the same length of the list.

Input

List<string[]> temp = new List<string[]>
{
    // The order of these groups is important
    new string[] { "a", "b", "c" },
    new string[] { "d", "e" },
    new string[] { "f", "g", "h" }
};

Constraints

0 or 1 item per group (a string[] above)

Order of the List<T> must be preserved

Valid Combinations

a, e, f

a, d, g

c, e, f

b, g

c, f

Invalid Combinations

a, b, f (a and b are from the same group - not allowed)

a, f, d (wrong order - d must come before f)

So far, I have gone back to my library where I have a Combinations LINQ method.

public static class IEnumerableExtensions
{
    // Can be used to get all permutations at a certain level
    // Source: http://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n#1898744
    public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
    {
        return k == 0 ? new[] { new T[0] } :
          elements.SelectMany((e, i) =>
            elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c)));
    }
}

In the past I have only used this on single sequence to do things like generate every permutation of URL segments. But I am struggling with its usage on a nested list with the constraints of one per group and in a specific order.

I know I can solve this particular puzzle by doing 3 nested loops and using lists to track which items were already used, but I don't know in advance how many items will be in the List<T>, so that won't work in the general case.

How can I get all of the valid combinations of the above input?

I would prefer LINQ, but will accept any solution that solves this problem.

Body:
Using some extension functions,

public static IEnumerable<T> Prepend<T>(this IEnumerable<T> rest, params T[] first) => first.Concat(rest);
public static IEnumerable<T> AsSingleton<T>(this T source) {
    yield return source;
}

You can write

public static IEnumerable<IEnumerable<T>> ParametersWithEmpty<T>(this IEnumerable<IEnumerable<T>> ParmLists) {
    if (ParmLists.Count() == 0)
        yield break; // empty
    else {
        var rest = ParametersWithEmpty(ParmLists.Skip(1));
        foreach (var p in ParmLists.First()) {
            yield return p.AsSingleton(); // p.Concat(empty)
            foreach (var r in rest)
                yield return r.Prepend(p); // p.Concat(r)
        }
        foreach (var r in rest)
            yield return r; // empty.Concat(r)
    }
}

You can call it like this:

var ans = temp.ParametersWithEmpty();

To include all the levels in the results, you must skip the empty cases implicit in the above code:

public static IEnumerable<IEnumerable<T>> Parameters<T>(this IEnumerable<IEnumerable<T>> ParmLists) {
    if (ParmLists.Count() == 1)
        foreach (var p in ParmLists.First())
            yield return p.AsSingleton();
    else {
        var rest = Parameters(ParmLists.Skip(1));
        foreach (var p in ParmLists.First()) {
            foreach (var r in rest)
                yield return r.Prepend(p);
        }
    }
}

Finally, here is an alternative version that may make it somewhat clearer as it outputs the sequence as if each parameter list is preceded by empty, but also returns the all empty sequence in the answer.

public static IEnumerable<IEnumerable<T>> ParametersWithEmpty2<T>(this IEnumerable<IEnumerable<T>> ParmLists) {
    if (ParmLists.Count() == 0)
        yield return Enumerable.Empty<T>();
    else {
        var rest = ParametersWithEmpty2(ParmLists.Skip(1));
        foreach (var r in rest)
            yield return r; // empty.Concat(r)
        foreach (var p in ParmLists.First()) {
            foreach (var r in rest)
                yield return r.Prepend(p); // p.Concat(r)
        }
    }
}


问:
php switching to server connection if localhost failed
I'm trying to write a script that connects to an online server if localhost connection failed or inaccessible. I have the script below that connects to a localhost database and if it's not accessible then reroute to a server connection. The script somehow fails to work and I just don't know why. Anyone has any suggestions?</p>

```<code><?php
  $DB_HOST = 'localhost';
  $DB_USER = 'root';
  $DB_PASS = '';
  $DB_NAME = 'admin';

  $DB_CON_A = new PDO("mysql:host={$DB_HOST}", $DB_USER, $DB_PASS);

  if(!$DB_CON_A) {
    die($DB_CON_A);
    $DB_HOST = 'www.xyz.com';
    $DB_USER = 'admin';
    $DB_PASS = '1235kasK';
    $DB_NAME = 'admin';
  }

  try {
    $DB_CON_A = new PDO("mysql:host={$DB_HOST}; dbname={$DB_NAME}", $DB_USER, $DB_PASS);
    $DB_CON_A->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }

  catch(PDOException $e){
    echo $e->getMessage();
  }
</code>```

答:
Here is my solution for those who's looking for one:</p>

```<code>    <?php
      function ping($DB_HOST) {
        exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($DB_HOST)), $res, $rval);
        return $rval === 0;
      }

      $DB_HOST = 'www.xyz.com';
      $connected = ping($DB_HOST);

      if ($connected) {
        $DB_HOST = 'www.xyz.com';
        $DB_USER = 'user';
        $DB_PASS = 'pass';
        $DB_NAME = 'accounts';
      } else {
          $DB_HOST = 'localhost';
          $DB_USER = 'root';
          $DB_PASS = '';
          $DB_NAME = 'accounts';
      }

      // Create database if not exists
      $DB_CON_C = new PDO("mysql:host={$DB_HOST}", $DB_USER, $DB_PASS);
      $DB_CON_C->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $DB_CON_C->query("CREATE DATABASE IF NOT EXISTS $DB_NAME");
      $DB_CON_C->query("USE $DB_NAME");

      try {
        $DB_CON_C = new PDO("mysql:host={$DB_HOST}; dbname={$DB_NAME}", $DB_USER, $DB_PASS);
        $DB_CON_C->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      }

      catch(PDOException $e){
        echo $e->getMessage();
      }
    ?>
</code>```

Body:
I'm trying to write a script that connects to an online server if localhost connection failed or inaccessible. I have the script below that connects to a localhost database and if it's not accessible then reroute to a server connection. The script somehow fails to work and I just don't know why. Anyone has any suggestions?

<?php
  $DB_HOST = 'localhost';
  $DB_USER = 'root';
  $DB_PASS = '';
  $DB_NAME = 'admin';

  $DB_CON_A = new PDO("mysql:host={$DB_HOST}", $DB_USER, $DB_PASS);

  if(!$DB_CON_A) {
    die($DB_CON_A);
    $DB_HOST = 'www.xyz.com';
    $DB_USER = 'admin';
    $DB_PASS = '1235kasK';
    $DB_NAME = 'admin';
  }

  try {
    $DB_CON_A = new PDO("mysql:host={$DB_HOST}; dbname={$DB_NAME}", $DB_USER, $DB_PASS);
    $DB_CON_A->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }

  catch(PDOException $e){
    echo $e->getMessage();
  }

Body:
Here is my solution for those who's looking for one:

    <?php
      function ping($DB_HOST) {
        exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($DB_HOST)), $res, $rval);
        return $rval === 0;
      }

      $DB_HOST = 'www.xyz.com';
      $connected = ping($DB_HOST);

      if ($connected) {
        $DB_HOST = 'www.xyz.com';
        $DB_USER = 'user';
        $DB_PASS = 'pass';
        $DB_NAME = 'accounts';
      } else {
          $DB_HOST = 'localhost';
          $DB_USER = 'root';
          $DB_PASS = '';
          $DB_NAME = 'accounts';
      }

      // Create database if not exists
      $DB_CON_C = new PDO("mysql:host={$DB_HOST}", $DB_USER, $DB_PASS);
      $DB_CON_C->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $DB_CON_C->query("CREATE DATABASE IF NOT EXISTS $DB_NAME");
      $DB_CON_C->query("USE $DB_NAME");

      try {
        $DB_CON_C = new PDO("mysql:host={$DB_HOST}; dbname={$DB_NAME}", $DB_USER, $DB_PASS);
        $DB_CON_C->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      }

      catch(PDOException $e){
        echo $e->getMessage();
      }
    ?>


问:
Git on Windows: What do the crlf settings mean?
I don't understand the complexities related to CrLf settings in git: core.autocrlf, core.safecrlf

I'm developing a cross-platform project in a team and would like both Windows and Linux developers to be able to work together without git marking files as modified just because of line ending style.

What do the various settings mean? What would be the consequences of choosing any of the options? And what would be the best solution for my case?

Yes, I'm aware of this question and the answers there were not insightful, thus not helpful.

答:
FYI., By default, Line ending in Windows will take CRLF and Linux will take LF.
Please find the below table for clear understanding.

╔═══════════════╦══════════════╦══════════════╦══════════════╗
║ core.autocrlf ║    false     ║    input     ║    true      ║
║               ║ Win => Unix  ║ Win => Unix  ║ Win => Unix  ║
╠═══════════════╬══════════════╬══════════════╬══════════════╣
║   git commit  ║ LF => LF     ║ LF => LF     ║ LF => LF     ║
║               ║ CR => CR     ║ CR => CR     ║ CR => CR     ║
║               ║ CRLF => CRLF ║ *CRLF => LF  ║ *CRLF => LF  ║
╠═══════════════╬══════════════╬══════════════╬══════════════╣
║  git checkout ║ LF => LF     ║ LF => LF     ║ *LF => CRLF  ║
║               ║ CR => CR     ║ CR => CR     ║ CR => CR     ║
║               ║ CRLF => CRLF ║ CRLF => CRLF ║ CRLF => CRLF ║
╚═══════════════╩══════════════╩══════════════╩══════════════╝```

In the above tabular information, the symbol * highlights the differences between Windows and Unix. At a glance, below is the CLRF information based on the OS platforms:

For Windows users

If windows users working with cross-platform projects, It MUST be core.autocrlf=true for Windows machines and core.autocrlf=input for Unix machines.

If windows users work with Only Windows projects, It can be both core.autocrlf=true or core.autocrlf=false. But core.autocrlf=input will result in issues in this case.

For Unix users (Linux / Mac OS)

If Unix users working with cross-platform projects, It MUST be core.autocrlf=true for Windows machines and core.autocrlf=input for Unix machines.

If Unix users work with Only Unix projects, It can be both core.autocrlf=input or core.autocrlf=false. But core.autocrlf=true will result in issues in this case.

For same OS users

For a pure Windows project or pure Unix project, it can be core.autocrlf=false.

Body:
FYI., By default, Line ending in Windows will take CRLF and Linux will take LF.
Please find the below table for clear understanding.

╔═══════════════╦══════════════╦══════════════╦══════════════╗
║ core.autocrlf ║    false     ║    input     ║    true      ║
║               ║ Win => Unix  ║ Win => Unix  ║ Win => Unix  ║
╠═══════════════╬══════════════╬══════════════╬══════════════╣
║   git commit  ║ LF => LF     ║ LF => LF     ║ LF => LF     ║
║               ║ CR => CR     ║ CR => CR     ║ CR => CR     ║
║               ║ CRLF => CRLF ║ *CRLF => LF  ║ *CRLF => LF  ║
╠═══════════════╬══════════════╬══════════════╬══════════════╣
║  git checkout ║ LF => LF     ║ LF => LF     ║ *LF => CRLF  ║
║               ║ CR => CR     ║ CR => CR     ║ CR => CR     ║
║               ║ CRLF => CRLF ║ CRLF => CRLF ║ CRLF => CRLF ║
╚═══════════════╩══════════════╩══════════════╩══════════════╝

In the above tabular information, the symbol * highlights the differences between Windows and Unix. At a glance, below is the CLRF information based on the OS platforms:

For Windows users

If windows users working with cross-platform projects, It MUST be core.autocrlf=true for Windows machines and core.autocrlf=input for Unix machines.

If windows users work with Only Windows projects, It can be both core.autocrlf=true or core.autocrlf=false. But core.autocrlf=input will result in issues in this case.

For Unix users (Linux / Mac OS)

If Unix users working with cross-platform projects, It MUST be core.autocrlf=true for Windows machines and core.autocrlf=input for Unix machines.

If Unix users work with Only Unix projects, It can be both core.autocrlf=input or core.autocrlf=false. But core.autocrlf=true will result in issues in this case.

For same OS users

For a pure Windows project or pure Unix project, it can be core.autocrlf=false.


问:
GUI's with Docker
Im trying to run a GUI within Docker and trying to following the below link.

```<code>http://wiki.ros.org/docker/Tutorials/GUI#The_safer_way
</code>```

Using this link, Im trying to implement the the_safer_way method but get the following error in my MAC.

```<code>Ps-MacBook-Pro:~ p$ docker run -it \
>     --user=$USER \
>     --env="DISPLAY" \
>     --volume="/etc/group:/etc/group:ro" \
>     --volume="/etc/passwd:/etc/passwd:ro" \
>     --volume="/etc/shadow:/etc/shadow:ro" \
>     --volume="/etc/sudoers.d:/etc/sudoers.d:ro" \
>     --volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" \
>     osrf/ros:indigo-desktop-full \
>     rqt
docker: Error response from daemon: Mounts denied:
The path /etc/sudoers.d
is not shared from OS X and is not known to Docker.
You can configure shared paths from Docker -> Preferences... -> File Sharing.
See https://docs.docker.com/docker-for-mac/osxfs/#namespaces for more info.
</code>```

答:
On MacOS, which doesn't normally have an X server, you have to do a little more than on a Linux system, as described by Using GUI's with Docker.

The article Running GUI’s with Docker on Mac OS X has brief instructions on how to do this, while Bring Linux apps to the Mac Desktop with Docker has more comprehensive instructions, but to summarise:

Install socat so you can create a connection between the docker container that runs a graphical application and the X window system on our OS X host operating system using:

```<code>> brew install socat
> socat TCP-LISTEN:6000,reuseaddr,fork UNIX-CLIENT:\"$DISPLAY\"
</code>```

Install the Xquartz, the X Window System on the OS X operating system using:

```<code>> brew install xquartz
</code>```

Log out and then back in again.

Open Xquartz:

```<code>> open -a Xquartz
</code>```

On the X11 Preferences window, select the Security tab and ensure the allow connections from network clients is ticked.

Get the IP adress of the host OS:

```<code>> ifconfig en0
en0:
…
inet 192.168.0.235 netmask 0xffffff00 broadcast 192.168.199.255
…
</code>```

Finally set the DISPLAY environment variable to this IP address followed by :0 when running the docker container:

```<code>> docker run -e DISPLAY=192.168.0.235:0 gns3/xeyes
</code>```

From a comment by BMitch

Title: GUI's with Docker

Body:
Im trying to run a GUI within Docker and trying to following the below link.

http://wiki.ros.org/docker/Tutorials/GUI#The_safer_way

Using this link, Im trying to implement the the_safer_way method but get the following error in my MAC.

Ps-MacBook-Pro:~ p$ docker run -it \
>     --user=$USER \
>     --env="DISPLAY" \
>     --volume="/etc/group:/etc/group:ro" \
>     --volume="/etc/passwd:/etc/passwd:ro" \
>     --volume="/etc/shadow:/etc/shadow:ro" \
>     --volume="/etc/sudoers.d:/etc/sudoers.d:ro" \
>     --volume="/tmp/.X11-unix:/tmp/.X11-unix:rw" \
>     osrf/ros:indigo-desktop-full \
>     rqt
docker: Error response from daemon: Mounts denied:
The path /etc/sudoers.d
is not shared from OS X and is not known to Docker.
You can configure shared paths from Docker -> Preferences... -> File Sharing.
See https://docs.docker.com/docker-for-mac/osxfs/#namespaces for more info.

Body:
On MacOS, which doesn't normally have an X server, you have to do a little more than on a Linux system, as described by Using GUI's with Docker.

The article Running GUI’s with Docker on Mac OS X has brief instructions on how to do this, while Bring Linux apps to the Mac Desktop with Docker has more comprehensive instructions, but to summarise:

Install socat so you can create a connection between the docker container that runs a graphical application and the X window system on our OS X host operating system using:

> brew install socat
> socat TCP-LISTEN:6000,reuseaddr,fork UNIX-CLIENT:\"$DISPLAY\"

Install the Xquartz, the X Window System on the OS X operating system using:

> brew install xquartz

Log out and then back in again.

Open Xquartz:

> open -a Xquartz

On the X11 Preferences window, select the Security tab and ensure the allow connections from network clients is ticked.

Get the IP adress of the host OS:

> ifconfig en0
en0:
…
inet 192.168.0.235 netmask 0xffffff00 broadcast 192.168.199.255
…

Finally set the DISPLAY environment variable to this IP address followed by :0 when running the docker container:

> docker run -e DISPLAY=192.168.0.235:0 gns3/xeyes

From a comment by BMitch


问:
Ruby Hash Whitelist Filter
I am trying to figure out how I can filter out key and value pairs from one filter into another

For example I want to take this hash

```<code>x = { "one" => "one", "two" => "two", "three" => "three"}

y = x.some_function

y == { "one" => "one", "two" => "two"}
</code>```

Thanks for your help

EDIT: should probably mention that in this example, I want it to behave as a whitelist filter. That is, I know what I want, not what I don't want.

答:
I'd use a lambda to filter. This will both allow you to write complex filtering logic & make it easy to test it. The fact that the filtering logic is extracted will allow to reuse it in other contexts. </p>

<p>ex: </p>

```<code>x = { "one" => "one", "two" => "two", "three" => "three"}

matcher = ->(key,value) {
  # FILTERING LOGIC HERE
   !key[/three/]
}

x.select(&matcher) == { "one" => "one", "two" => "two"}
</code>```

Title: Ruby Hash Whitelist Filter

Body:
I am trying to figure out how I can filter out key and value pairs from one filter into another

For example I want to take this hash

x = { "one" => "one", "two" => "two", "three" => "three"}

y = x.some_function

y == { "one" => "one", "two" => "two"}

Thanks for your help

EDIT: should probably mention that in this example, I want it to behave as a whitelist filter. That is, I know what I want, not what I don't want.

Body:
I'd use a lambda to filter. This will both allow you to write complex filtering logic & make it easy to test it. The fact that the filtering logic is extracted will allow to reuse it in other contexts.

ex:

x = { "one" => "one", "two" => "two", "three" => "three"}

matcher = ->(key,value) {
  # FILTERING LOGIC HERE
   !key[/three/]
}

x.select(&matcher) == { "one" => "one", "two" => "two"}


问:
SQL Server equivalent to MySQL's EXPLAIN
I was reading an SQL tutorial which used the keyword EXPLAIN to see how a query is executed. I tried it in SQL Server 2008 with no success.

How do I get the equivalent result?

答:
Be aware that Microsoft added an EXPLAIN command to TSQL syntax in SQL 2012, however it only applies to Azure SQL Data Warehouse and Parallel Data Warehouse - so not the regular RDBMS product.

It provides an execution plan in XML format, and helpfully shows the parts of the plan that will be distributed across the warehouse nodes.

Source:
TSQL EXPLAIN


问:
Android: Has anyone encountered the localhost HttpClient Connection Refused error?
I was just wondering if anyone solved this problem. Googling gives tons of posts having this question but not one with a proper reply. I tried literally every combination of the following two pieces of code with and without proxy:

```<code>/*********** URL METHOD ***************/
//URLConnection conn = aURL.openConnection();
//conn.connect();
//InputStream is = conn.getInputStream();

/*********** HTTP METHOD ***************/
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(urlString);
HttpResponse resp = client.execute(get);

InputStream is = resp.getEntity().getContent();
</code>```

I am trying to connect to a site on my intranet (its not localhost). I've tried the following:

Setting Proxy inside Eclipse settings

Setting my own localhost and writing a small php script that takes the url, connects to it and then gets the file from the intranet site - This works from the Browser though! It does not work when I use the 10.0.2.2 IP address

Any thoughts?

答:
You should check out this :
http://developer.android.com/guide/appendix/faq/commontasks.html#localhostalias

(use the alias "10.0.2.2" instead of "localhost" or "127.0.0.1")

Body:
I was just wondering if anyone solved this problem. Googling gives tons of posts having this question but not one with a proper reply. I tried literally every combination of the following two pieces of code with and without proxy:

/*********** URL METHOD ***************/
//URLConnection conn = aURL.openConnection();
//conn.connect();
//InputStream is = conn.getInputStream();

/*********** HTTP METHOD ***************/
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(urlString);
HttpResponse resp = client.execute(get);

InputStream is = resp.getEntity().getContent();

I am trying to connect to a site on my intranet (its not localhost). I've tried the following:

Setting Proxy inside Eclipse settings

Setting my own localhost and writing a small php script that takes the url, connects to it and then gets the file from the intranet site - This works from the Browser though! It does not work when I use the 10.0.2.2 IP address

Any thoughts?