问:
VB - Reference a resource in a command prompt command
When using the eventvwr command line command you can pass an exported XML file to it using /v:"path to file"

I'm trying to do this using visual studio.

Right now I'm trying

```<code>Process.Start("CMD", "/C eventvwr " + Servername + " /v:" +
</code>```

And that's where I get stuck.  I need it to pull in the xml file as a file and not the contents.  I currently have the xml file pulled in as a resource under project->properties->files.

Any help would be appreciated if this is at all possible.

Thank you.

答:
You can use:

```<code>Dim xmlText as String = Properties.File
Dim path as String = "c:\temp\file.xml"; //or Path.GetTempPath() + "file.xml"
File.WriteAllText(path, xmlText)
</code>```

Then:

```<code>Process.Start("CMD", "/C eventvwr " + Servername + " /v:" + path)
</code>```

Body:
When using the eventvwr command line command you can pass an exported XML file to it using /v:"path to file"

I'm trying to do this using visual studio.

Right now I'm trying

Process.Start("CMD", "/C eventvwr " + Servername + " /v:" +

And that's where I get stuck.  I need it to pull in the xml file as a file and not the contents.  I currently have the xml file pulled in as a resource under project->properties->files.

Any help would be appreciated if this is at all possible.

Thank you.

Body:
You can use:

Dim xmlText as String = Properties.File
Dim path as String = "c:\temp\file.xml"; //or Path.GetTempPath() + "file.xml"
File.WriteAllText(path, xmlText)

Then:

Process.Start("CMD", "/C eventvwr " + Servername + " /v:" + path)


来源: stackexchange

问:
Show a div tag only if a person is logged in
I was trying to incorporate a functionality in my ASP.NET such that  a DIV tag which contains the Profile Navigation Menu  should only be visible if a person is logged in.
I know the condition on how to if the person is logged in or not but wanted to know the method to toggle the div tag on/off based on person's logged in status.

```<code>if(loggedin==yes)
{
//?
}
</code>```

Thanks

答: If you make it a server tag by adding the runat="server" then you can use divid.Visable=false to not display it</p>

ContentLicense: CC BY-SA 2.5

Body:
I was trying to incorporate a functionality in my ASP.NET such that  a DIV tag which contains the Profile Navigation Menu  should only be visible if a person is logged in.
I know the condition on how to if the person is logged in or not but wanted to know the method to toggle the div tag on/off based on person's logged in status.

if(loggedin==yes)
{
//?
}

Thanks


问:
Recursion condensing concentric circles by 10% while staying relative to center
The right circle is not using recursion but I want the recursive one(left) to look similar. Might be to little code will provide more if needed. It's the equation to keep the condensing circles stick to the center that i'm struggling with. Thank you any help would be appreciated.</p>

```<code>// Initial attempt
      if (diameter >= 20) {
        double newDiameter = diameter * .9;
        drawCircles(newDiameter, xCorner += deltaDiameter * 2, yCorner += deltaDiameter * 2, g2);
    }

 // Working code
    if (diameter >= 20) {
        double newDiameter = diameter - deltaDiameter;
        drawCircles(newDiameter, xCorner += (deltaDiameter / 2), yCorner +=
       (deltaDiameter / 2), g2);
    }
</code>```

答:
Since xCorner and yCorner are the upper left coordinates, new coordinates are to be calculated properly. Please try putting in this piece of code, I will add more info into the answer soon. This is assuming your initial diameter=255; xCorner=0; yCorner=10 and deltaDiameter=10

This is the approximation diagram of how the calculation is done.

```<code>if (diameter >= 20) {
    double newDiameter = diameter - deltaDiameter;
    // System.out.println(xCorner + 255);
    drawCircles(newDiameter, xCorner += (1.414 * 0.5 * deltaDiameter), yCorner += (1.414 * 0.5 * deltaDiameter), g2);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The right circle is not using recursion but I want the recursive one(left) to look similar. Might be to little code will provide more if needed. It's the equation to keep the condensing circles stick to the center that i'm struggling with. Thank you any help would be appreciated.

// Initial attempt
      if (diameter >= 20) {
        double newDiameter = diameter * .9;
        drawCircles(newDiameter, xCorner += deltaDiameter * 2, yCorner += deltaDiameter * 2, g2);
    }

 // Working code
    if (diameter >= 20) {
        double newDiameter = diameter - deltaDiameter;
        drawCircles(newDiameter, xCorner += (deltaDiameter / 2), yCorner +=
       (deltaDiameter / 2), g2);
    }

Body:
Since xCorner and yCorner are the upper left coordinates, new coordinates are to be calculated properly. Please try putting in this piece of code, I will add more info into the answer soon. This is assuming your initial diameter=255; xCorner=0; yCorner=10 and deltaDiameter=10

This is the approximation diagram of how the calculation is done.

if (diameter >= 20) {
    double newDiameter = diameter - deltaDiameter;
    // System.out.println(xCorner + 255);
    drawCircles(newDiameter, xCorner += (1.414 * 0.5 * deltaDiameter), yCorner += (1.414 * 0.5 * deltaDiameter), g2);
}


问:
Does Facebook Messenger Bot provide information about the channel where the message was originated?
I'm having a problem with the lite version of messenger (android only)

This version of the application does not support bot messages with templates or buttons (including the get_started button)

In my case this is an example:

I could not find a parameter in the webhooks to provide the user's platform.
So I have to ask the user: do you use the lite version?
And then set a different flow.

But this means that I must also give the possibility to disable the lite mode when browsing from the web or from the non-lite application (to guarantee a better user experience)

Does Facebook Messenger Bot provide information about the channel where the message was originated ?

答:
One way to identify where message event originates from is to use the payloads. You can specify a unique payload when setting up your bot and check what you receive to react on. get_started, persistent_menu, quick_replies have a payload field that you can set.

```<code>{
  "get_started":{
    "payload":"<GET_STARTED_PAYLOAD>"
  }
}
</code>```

Body:
One way to identify where message event originates from is to use the payloads. You can specify a unique payload when setting up your bot and check what you receive to react on. get_started, persistent_menu, quick_replies have a payload field that you can set.

{
  "get_started":{
    "payload":"<GET_STARTED_PAYLOAD>"
  }
}


问:
Why is my django urlpattern not resolving?
So I'm creating a small ecommerce website for a friend and cannot work out why the url won't resolve itself.

For the sake of simplicity whilst making the website I'm using a product called "number 1". It has a slug field of "number-1" and on the product page clicking on the product takes a user to "/shop/number-1"

My url pattern for this is:

```<code>url(r'^<slug:url>', views.item, name='products')
</code>```

with the view:

```<code>def item(request, url=""):
    products = product.objects.get(url=url)
    return render(request, 'shop\product.html', {'products', products})
</code>```

As far as I can tell this should render my product.html template but instead it returns a 404 and I'm not sure why?

If it helps I have other views, such as product types set within the same views and they work fine so as far as I can tell its that the slug:url isn't being used in the views.item, or the view isn't getting the context properly.

Also I'm on django 1.11.7 for this project.

答:
Please change url pattern to:</p>

```<code>url(r'^?P<url>[\w-]+', views.item, name='products')
</code>```

Body:
So I'm creating a small ecommerce website for a friend and cannot work out why the url won't resolve itself.

For the sake of simplicity whilst making the website I'm using a product called "number 1". It has a slug field of "number-1" and on the product page clicking on the product takes a user to "/shop/number-1"

My url pattern for this is:

url(r'^<slug:url>', views.item, name='products')

with the view:

def item(request, url=""):
    products = product.objects.get(url=url)
    return render(request, 'shop\product.html', {'products', products})

As far as I can tell this should render my product.html template but instead it returns a 404 and I'm not sure why?

If it helps I have other views, such as product types set within the same views and they work fine so as far as I can tell its that the slug:url isn't being used in the views.item, or the view isn't getting the context properly.

Also I'm on django 1.11.7 for this project.

Body:
Please change url pattern to:

url(r'^?P<url>[\w-]+', views.item, name='products')


问:
Why am I getting different results if my css is typed into head or linked to .css file?
I am a beginner and have the following problem:

When I insert css directly into the head of my .html file, I get a great result:
typed into the head

But when I link my .css file into the head, the very first word ("Holy") does not show up properly, as follows:
Linked into the Head

I have looked it over to ensure the css is the same whether pasted or linked, and I am currently at a loss. Any insight would be greatly appreciated. Thanks in advance.

This is the css:

```<code><span class="holy"></span>
<span class="waiving"></span>
<span class="american"></span>
<span class="flag"></span>
<span class="batman"></span>

<style>
  .holy {
    background-color: red;
    color: white;
  }
  .waiving {
    background-color: white;
    color: blue;
  }
  .american {
    background-color: blue;
    color: white;
  }
  .flag {
    background-color: white;
    color: red;
  }
  .batman {
    background-color: black;
    color: yellow;
  }
</style>
</code>```

This is is how I linked it when only the First "Holy" does not work:

```<code><!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="batman_with_css.css">
</head>

<body>
  <span class="holy">Holy</span>
  <span class="waiving">Waiving</span>
  <span class="american">American</span>
  <span class="flag">Flag</span>
  <span class="batman">Batman!!!</span>
  <br>
  <img src="https://i.pinimg.com/736x/af/7b/d3/af7bd3df85c1397456084b29e3729269--keaton-batman-batman-car.jpg">

</body>
<html>
</code>```

And this is the html file with the css in the head where everyything including the first word "Holy" does work:

```<code><!DOCTYPE html>
<html>
<head>
  <span class="holy"></span>
  <span class="waiving"></span>
  <span class="american"></span>
  <span class="flag"></span>
  <span class="batman"></span>

  <style>
    .holy {
      background-color: red;
      color: white;
    }
    .waiving {
      background-color: white;
      color: blue;
    }
    .american {
      background-color: blue;
      color: white;
    }
    .flag {
      background-color: white;
      color: red;
    }
    .batman {
      background-color: black;
      color: yellow;
    }
  </style>

</head>
<body>
  <span class="holy">Holy</span>
  <span class="waiving">Waiving</span>
  <span class="american">American</span>
  <span class="Flag">Flag</span>
  <span class="batman">Batman!!!</span>
  <br>
  <img src="https://i.pinimg.com/736x/af/7b/d3/af7bd3df85c1397456084b29e3729269--keaton-batman-batman-car.jpg">
</body>
</html>
</code>```

答:
You're not supposed to put in HTML code in stylesheets, which you did by adding those span elements at the top.

Change your CSS file so it looks like this.....

```<code>  .holy {
background-color: red;
color: white;
}
.waiving {
background-color: white;
color: blue;
}
.american {
background-color: blue;
color: white;
}
.flag {
background-color: white;
color: red;
}
.batman {
background-color: black;
color: yellow;
}
</code>```

Body:
I am a beginner and have the following problem:

When I insert css directly into the head of my .html file, I get a great result:
typed into the head

But when I link my .css file into the head, the very first word ("Holy") does not show up properly, as follows:
Linked into the Head

I have looked it over to ensure the css is the same whether pasted or linked, and I am currently at a loss. Any insight would be greatly appreciated. Thanks in advance.

This is the css:

This is is how I linked it when only the First "Holy" does not work:

<!DOCTYPE html>

  <link rel="stylesheet" href="batman_with_css.css">

  Holy
  Waiving
  American
  Flag
  Batman!!!

And this is the html file with the css in the head where everyything including the first word "Holy" does work:

<!DOCTYPE html>

  Holy
  Waiving
  American
  Flag
  Batman!!!

Body:
You're not supposed to put in HTML code in stylesheets, which you did by adding those span elements at the top.

Change your CSS file so it looks like this.....

  .holy {
background-color: red;
color: white;
}
.waiving {
background-color: white;
color: blue;
}
.american {
background-color: blue;
color: white;
}
.flag {
background-color: white;
color: red;
}
.batman {
background-color: black;
color: yellow;
}


答:
You can set the div to runat="server", and then access it as a variable in your code-behind page and set Visible to false.

That is, you'd have something like:

```<code><div id="myDiv" runat="server">
</code>```

And then in your CS file:

```<code>if (!loggedIn)
{
    myDiv.Visible = false;
}
</code>```

Title: Show a div tag only if a person is logged in

Body:
You can set the div to runat="server", and then access it as a variable in your code-behind page and set Visible to false.

That is, you'd have something like:

<div id="myDiv" runat="server">

And then in your CS file:

if (!loggedIn)
{
    myDiv.Visible = false;
}


问:
How to simplify the default implementation of a kotlin function

The following code, I always feel a bit long-winded.

```<code>//judging employee's salary level,  and set a default implemention of the function:whether it > amount
fun paidMore(amount: Int, employee: Employee,
     predicate: (Int, Employee) -> Boolean = { amount, employee -> employee.salary > amount }
): Boolean = predicate(amount, employee)
</code>```

I think I can simplify the code like this：

```<code>fun paidMore(amount: Int, employee: Employee,
      predicate: (Int, Employee) -> Boolean = employee.salary > amount
): Boolean = predicate(amount, employee)
</code>```

Of course, I am self-righteous. It can not run.

```<code>//This code is treated as a Boolean expression, not a function.
employee.salary > amount
</code>```

why? what should I do to simplify the code?

答:
Oh,yeah.I simplified a bit of code.

```<code>fun paidMore(amount: Int, employee: Employee,
                     predicate: (Int, Employee) -> Boolean = { _, _ -> employee.salary > amount }
        ): Boolean = predicate(amount, employee)
</code>```

now,I simplified the code again

```<code>import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import kotlin.test.assertFalse
import kotlin.test.assertTrue

object ClosureSpec : Spek({
    describe("Test, add a default implementation to the function") {
        data class Employee(val name: String, val salary: Int) //the model used to test

        fun paidMore(amount: Int, employee: Employee,
                     predicate: (Int) -> Boolean = { _ -> employee.salary > amount }
        ): Boolean = predicate(amount)

        it("judging employee's salary level") {
            fun isHighPaid(employee: Employee): Boolean = paidMore(100, employee)
            fun isHighPaid2(employee: Employee): Boolean = paidMore(100, employee) {amount ->
                employee.salary > amount * 2
            }

            val employee = Employee("yuri", 101)
            assertTrue(isHighPaid(employee))
            assertFalse(isHighPaid2(employee))

            assertTrue(isHighPaid2(Employee("peter", 201)))
            assertFalse(isHighPaid2(Employee("jerry", 200)))
        }
    }

})
</code>```

or else

```<code>import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import kotlin.test.assertFalse
import kotlin.test.assertTrue

object ClosureSpec : Spek({
    describe("Test, add a default implementation to the function") {
        data class Employee(val name: String, val salary: Int) //the model used to test

        //judging employee's salary level
        fun Employee.paidMore(amount: Int, predicate: (Int) -> Boolean = {
            this.salary > it
        }): Boolean = predicate(amount)

        on("use the default implementation") {
            val amount = 100
            fun Employee.isHighPaid() = paidMore(amount)

            it("should all be passed") {
                assertTrue(Employee("Alice", amount + 1).isHighPaid())
                assertFalse(Employee("Alice", amount - 1).isHighPaid())
            }
        }

        on("override the default implementation") {
            val amount = 100
            fun Employee.isHighPaid() = paidMore(amount) {
                this.salary > it * 2
            }

            it("should all be passed") {
                assertTrue(Employee("Bob", amount * 2 + 1).isHighPaid())
                assertFalse(Employee("Bob", amount * 2 - 1).isHighPaid())
            }
        }
    }
})
</code>```

Which one is better? something else? Looking forward to your good idea

Body:
The following code, I always feel a bit long-winded.

//judging employee's salary level,  and set a default implemention of the function:whether it > amount
fun paidMore(amount: Int, employee: Employee,
     predicate: (Int, Employee) -> Boolean = { amount, employee -> employee.salary > amount }
): Boolean = predicate(amount, employee)

I think I can simplify the code like this：

fun paidMore(amount: Int, employee: Employee,
      predicate: (Int, Employee) -> Boolean = employee.salary > amount
): Boolean = predicate(amount, employee)

Of course, I am self-righteous. It can not run.

//This code is treated as a Boolean expression, not a function.
employee.salary > amount

why? what should I do to simplify the code?

Body:
Oh,yeah.I simplified a bit of code.

fun paidMore(amount: Int, employee: Employee,
                     predicate: (Int, Employee) -> Boolean = { _, _ -> employee.salary > amount }
        ): Boolean = predicate(amount, employee)

now,I simplified the code again

import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import kotlin.test.assertFalse
import kotlin.test.assertTrue

object ClosureSpec : Spek({
    describe("Test, add a default implementation to the function") {
        data class Employee(val name: String, val salary: Int) //the model used to test

        fun paidMore(amount: Int, employee: Employee,
                     predicate: (Int) -> Boolean = { _ -> employee.salary > amount }
        ): Boolean = predicate(amount)

        it("judging employee's salary level") {
            fun isHighPaid(employee: Employee): Boolean = paidMore(100, employee)
            fun isHighPaid2(employee: Employee): Boolean = paidMore(100, employee) {amount ->
                employee.salary > amount * 2
            }

            val employee = Employee("yuri", 101)
            assertTrue(isHighPaid(employee))
            assertFalse(isHighPaid2(employee))

            assertTrue(isHighPaid2(Employee("peter", 201)))
            assertFalse(isHighPaid2(Employee("jerry", 200)))
        }
    }

})

or else

import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import kotlin.test.assertFalse
import kotlin.test.assertTrue

object ClosureSpec : Spek({
    describe("Test, add a default implementation to the function") {
        data class Employee(val name: String, val salary: Int) //the model used to test

        //judging employee's salary level
        fun Employee.paidMore(amount: Int, predicate: (Int) -> Boolean = {
            this.salary > it
        }): Boolean = predicate(amount)

        on("use the default implementation") {
            val amount = 100
            fun Employee.isHighPaid() = paidMore(amount)

            it("should all be passed") {
                assertTrue(Employee("Alice", amount + 1).isHighPaid())
                assertFalse(Employee("Alice", amount - 1).isHighPaid())
            }
        }

        on("override the default implementation") {
            val amount = 100
            fun Employee.isHighPaid() = paidMore(amount) {
                this.salary > it * 2
            }

            it("should all be passed") {
                assertTrue(Employee("Bob", amount * 2 + 1).isHighPaid())
                assertFalse(Employee("Bob", amount * 2 - 1).isHighPaid())
            }
        }
    }
})

Which one is better? something else? Looking forward to your good idea


问:
How Do I show a users Email address from MYSQL?

I'm trying to get it where, when the user goes to their profile, it will show them their email address. I have it where it shows their username by using $_SESSION['username'] but when I try that for the EMAIL address it doesn't work. Any Ideas on how I can get it to SELECT the email address from the Database? Thank You In Advance!! :)

It's showing their current Email address: and then the code.
Here's my PHP:

Includes/config.php is getting the DATABASE INFO.

```<code><?php require('includes/config.php');

//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php?action=login'); }

 ?>
</code>```

Includes/config.php

```<code><?php
ob_start();
session_start();

//set timezone
date_default_timezone_set('Europe/London');

//database credentials
define('DBHOST','localhost');
define('DBUSER','xxxxx');
define('DBPASS','xxxxx');
define('DBNAME','bigfellamembers');

//application address
define('DIR','http://xxxxxxxxxxx.com');
define('SITEEMAIL','noreply@domain.com');

try {

    //create PDO connection
    $db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch(PDOException $e) {
    //show error
    echo '<p class="bg-danger">'.$e->getMessage().'</p>';
    exit;
}

//include the user class, pass in the database connection
include('classes/user.php');
include('classes/phpmailer/mail.php');
$user = new User($db);
?>
</code>```

Here's my database table.

Heres: some of my HTML:

```<code>   <!-- row -->
                <div class="row">
                    <div class="col-md-12">
                        <div class="white-box">
                            <div class="user-bg"><img width="100%" alt="user" src="login-bg.jpg">
                                <div class="overlay-box">
                                    <div class="user-content">
                                        <a href="javascript:void(0)"><img src="uploads/<?php echo $_SESSION['username']; ?>.jpg" class="thumb-lg img-circle" alt="img"></a>
                                         <h4 class="text-white">Current Username: <?php echo $_SESSION['username']; ?> </h4>
                                        <h5 class="text-white">Current Email Address:    <?php  echo $_SESSION['email']; ?>

                                   </div>
                                </div>
                            </div>
</code>```

答:
If you haven’t set the email within the SESSION then you can’t try and grab it like that.

You’ll need to use a MySQL query (research PDO) to grab the email from the database based on some criteria (e.g username).

Body:
I'm trying to get it where, when the user goes to their profile, it will show them their email address. I have it where it shows their username by using $_SESSION['username'] but when I try that for the EMAIL address it doesn't work. Any Ideas on how I can get it to SELECT the email address from the Database? Thank You In Advance!! :)

It's showing their current Email address: and then the code.
Here's my PHP:

Includes/config.php is getting the DATABASE INFO.

<?php require('includes/config.php');

//if not logged in redirect to login page
if(!$user->is_logged_in()){ header('Location: login.php?action=login'); }

 ?>

Includes/config.php

<?php
ob_start();
session_start();

//set timezone
date_default_timezone_set('Europe/London');

//database credentials
define('DBHOST','localhost');
define('DBUSER','xxxxx');
define('DBPASS','xxxxx');
define('DBNAME','bigfellamembers');

//application address
define('DIR','http://xxxxxxxxxxx.com');
define('SITEEMAIL','noreply@domain.com');

try {

    //create PDO connection
    $db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch(PDOException $e) {
    //show error
    echo '
'.$e->getMessage().'
';
    exit;
}

//include the user class, pass in the database connection
include('classes/user.php');
include('classes/phpmailer/mail.php');
$user = new User($db);
?>

Here's my database table.

Heres: some of my HTML:

                                        <img src="uploads/<?php echo $_SESSION['username']; ?>.jpg" class="thumb-lg img-circle" alt="img">

Current Username: <?php echo $_SESSION['username']; ?>

Current Email Address:    <?php  echo $_SESSION['email']; ?>


问:
Deploy .NET app to Azure using another server database
Is possible to deploy my .NET application to azure using as connection string another server MySQL database?

I created an application in .NET MVC. It connects to my private server MySQL Database. The application works fine. However, when I deployed it to Azure server, it doesn't working.

When I try to publish, I don't have MySQL as datasource:

When I run it in Azure server, I get the error:

```<code>    [MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.]
   MySql.Data.MySqlClient.NativeDriver.Open() +1228
   MySql.Data.MySqlClient.Driver.Open() +22
   MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings) +218
   MySql.Data.MySqlClient.MySqlPool.GetPooledConnection() +287
   MySql.Data.MySqlClient.MySqlPool.TryToGetDriver() +93
   MySql.Data.MySqlClient.MySqlPool.GetConnection() +65
   MySql.Data.MySqlClient.MySqlConnection.Open() +566
   System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +41
</code>```

My connectionstring:

```<code>    <connectionStrings>
    <add name="myEntities" connectionString="metadata=res://*/Models.MyModel.csdl|res://*/Models.MyModel.ssdl|res://*/Models.MyModel.msl;provider=MySql.Data.MySqlClient;provider connection string="server=myServer;user id=userName;password=Password;database=myDB"" providerName="System.Data.EntityClient" />
  </connectionStrings>
</code>```

Does anyone know how to fix it?

Thanks

答: You can certainly connect to a MySQL server from an MVC web app. Your MySQL server can be hosted in Azure, AWS, or any other hosting provider that lets you connect to your database remotely. However, making database calls outside of your Azure data enter will cause a delay due to network latency.</p>

Body:
Is possible to deploy my .NET application to azure using as connection string another server MySQL database?

I created an application in .NET MVC. It connects to my private server MySQL Database. The application works fine. However, when I deployed it to Azure server, it doesn't working.

When I try to publish, I don't have MySQL as datasource:

When I run it in Azure server, I get the error:

    [MySqlException (0x80004005): Unable to connect to any of the specified MySQL hosts.]
   MySql.Data.MySqlClient.NativeDriver.Open() +1228
   MySql.Data.MySqlClient.Driver.Open() +22
   MySql.Data.MySqlClient.Driver.Create(MySqlConnectionStringBuilder settings) +218
   MySql.Data.MySqlClient.MySqlPool.GetPooledConnection() +287
   MySql.Data.MySqlClient.MySqlPool.TryToGetDriver() +93
   MySql.Data.MySqlClient.MySqlPool.GetConnection() +65
   MySql.Data.MySqlClient.MySqlConnection.Open() +566
   System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) +41

My connectionstring:

    <connectionStrings>
    <add name="myEntities" connectionString="metadata=res://*/Models.MyModel.csdl|res://*/Models.MyModel.ssdl|res://*/Models.MyModel.msl;provider=MySql.Data.MySqlClient;provider connection string="server=myServer;user id=userName;password=Password;database=myDB"" providerName="System.Data.EntityClient" />
  </connectionStrings>

Does anyone know how to fix it?

Thanks


问:
Python: import variable from main file at package module
i try to use a complex structure in flask restfull, my structure is the following:

```<code>main.py
-models
-- __init__.py
--modelA.py
-resources
--__init__.py
--resourceA.py
</code>```

I have a variable in main.py and i need this variable in models.modelA and i need also models.modelA in resources.resourceA. At this point everything is ok. When i start my app, i get the following error:

```<code>Traceback (most recent call last):
  File "main.py", line 12, in <module>
    from resources.resourceA import functionA
  File "/var/www/project/resources/resourceA.py", line 11, in <module>
    from models.modelA import *
  File "/var/www/project/models/modelA.py", line 8, in <module>
    from main import mainvariable
  File "/var/www/project/main.py", line 12, in <module>
    from resources.resourceA import functionA
ImportError: cannot import name functionA
</code>```

I hope your help

答:
What you basically have here is called a circular import. As the traceback states, your main module is importing functionA from resources.resourceA. And resourceA is importing models.modelA which is in turn trying to import main which again requires resources.resourceA.

Unless a particular order is resolved, python interpreter cannot understand how to resolve the modules. You can however solve this problem in an easier way.

If the models.modelA doesn't require a module level import for main, you can shift the import to the function / class scope where you need its imports.

See here for more on circular imports.

Body:
i try to use a complex structure in flask restfull, my structure is the following:

main.py
-models
-- __init__.py
--modelA.py
-resources
--__init__.py
--resourceA.py

I have a variable in main.py and i need this variable in models.modelA and i need also models.modelA in resources.resourceA. At this point everything is ok. When i start my app, i get the following error:

Traceback (most recent call last):
  File "main.py", line 12, in <module>
    from resources.resourceA import functionA
  File "/var/www/project/resources/resourceA.py", line 11, in <module>
    from models.modelA import *
  File "/var/www/project/models/modelA.py", line 8, in <module>
    from main import mainvariable
  File "/var/www/project/main.py", line 12, in <module>
    from resources.resourceA import functionA
ImportError: cannot import name functionA

I hope your help


问:
Mxnet - Understanding weight shape for Dense Layer
I am understanding Mxnet framework. While following this Linear Regression article I see the following piece of code which is creating a Dense Layer:

```<code>net = gluon.nn.Dense(1, in_units=2) # input dimension= 2, output dimension = 1
</code>```

but why does print(net.weight) give shape as Parameter dense4_weight (shape=(1, 2), dtype=None)

Shouldn't the shape be (2, 1)?

According to my understanding:

```<code>input = Shape(n, 2) where n is number of samples
output = Shape(n, 1)
</code>```

so the weight matrix should be Shape(2, 1) for the matrix multiplication, isn't it?

What am I missing here?

答: This is just due to internal implementation. You can think of it as weight matrix is transposed before multiplication.</p>

Body:
I am understanding Mxnet framework. While following this Linear Regression article I see the following piece of code which is creating a Dense Layer:

net = gluon.nn.Dense(1, in_units=2) # input dimension= 2, output dimension = 1

but why does print(net.weight) give shape as Parameter dense4_weight (shape=(1, 2), dtype=None)

Shouldn't the shape be (2, 1)?

According to my understanding:

input = Shape(n, 2) where n is number of samples
output = Shape(n, 1)

so the weight matrix should be Shape(2, 1) for the matrix multiplication, isn't it?

What am I missing here?


问:
How to set TextField changes in to state using MaterialUI and Redux?
Using React / Redux and MaterialUI I set up a component which needs to check your location or get the lat/lng based upon the address you put in.

When clicking on a button I would like the address, typed in to a TextField to be checked on a webservice.

However I can not seem to get the value of the TextField to the webservice using the button.

So I tried to set the value immediately in the props (of the state).
This works, but I do get an error:

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa).

This code is like this:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Field, reduxForm } from 'redux-form'
import TextField from 'material-ui/TextField';
import IconButton from 'material-ui/IconButton';
import PlaceIcon from 'material-ui-icons/Place';
import SearchIcon from 'material-ui-icons/Search';

import { getLocationByAddress, getLocationByLatLng } from '../actions';

/**
 * Location Search, Lets the user search for his location and coordinates
 * @class LocationSearch
 * @extends React.Component
 */
class LocationSearch extends Component {

    /**
     * getLocationByLatLng: uses navigator.geolocation to get the current position of the user

     * then requests the information from a back-end service to retrieve full location data.
     */
    getLocationByLatLng () {

        let options = {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        };

        navigator.geolocation.getCurrentPosition(function (pos) {
            console.log(pos.coords);

        }, function(err){
            console.warn(`ERROR(${err.code}): ${err.message}`);
        }, options)
    }

    /**
     * getLocationByAddress: uses address to request full location data from back-end service
     */
    getLocationByAddress = (e) => {
        /*
        console.log(e);
        e.preventDefault();
         */

        this.props.getLocationByAddress(this.props.location.address);
    };

    keepVal = ({target}) => {

        this.props.location.address = target.value;

    };

    render () {

        const { location } = this.props;

        return (

                <IconButton onClick={this.getLocationByLatLng} color="primary" className={'locationSearch_locationBtn'} aria-label="">
                    <PlaceIcon fontSize={35} />
                </IconButton>
                  <TextField
                      value={location.address}
                      placeholder={'Voer uw locatie in'}
                      margin={'normal'}
                      className={'locationSearch_input'}
                      onChange={this.keepVal}
                  />
                  <IconButton onClick={this.getLocationByAddress} color="primary" className={'locationSearch_searchBtn'} aria-label="">
                      <SearchIcon fontSize={35} />
                  </IconButton>

        );
    }

}

function mapStateToProps (state) {
    return {
        location: state.location
    }
}

export default connect(mapStateToProps, {getLocationByAddress, getLocationByLatLng})(LocationSearch)```
</div>
</div>
</p>

<p>So because I do not want any errors I also looked into changing the state just for the location address.
So I created a new action setLocationAddress and that should go to the reducer and change the state just for the address, but thats silly to do on every change, as the value is already there... no need to change it.</p>

<p>Thus I used a form to do this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>getLocationByAddress = (e) => {
    e.preventDefault();
    const { target } = e;
    this.props.getLocationByAddress(target['locationInput'].value);
};

render () {

    const { location } = this.props;

    return (
        <div className={'locationSearch'}>

            <IconButton onClick={this.getLocationByLatLng} color="primary" className={'locationSearch_locationBtn'} aria-label="">
                <PlaceIcon fontSize={35} />
            </IconButton>
            <form onSubmit={this.getLocationByAddress}>
                <TextField
                    name={'locationInput'}
                    value={location.address}
                    placeholder={'Voer uw locatie in'}
                    margin={'normal'}
                    className={'locationSearch_input'}
                />
                <IconButton color="primary" className={'locationSearch_searchBtn'} aria-label="">
                    <SearchIcon fontSize={35} />
                </IconButton>
            </form>
        </div>
    );
}</code>```

But again this naggy message:

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa)

So how do I do this?
Any help would be appreciated.

答:
See the code for the controlled component in the TextField demo.  In the code, the value prop is pulled from state and onChange is set to a function that updates state.

```<code>   <div>
    <TextField id="standard-name" label="Name" value={name} onChange={handleChange} />
    <TextField id="standard-uncontrolled" label="Uncontrolled" defaultValue="foo" />
  </div>
</code>```

You're actually pretty close.  You've mapped state to your location prop and you've set value={location.address}, but onChange is assigned to this.keepVal which attempts to update props, which is no good.

Since you're using Redux, you need to dispatch an action in keepVal that will update state.location.address with event.target.value.  This will ensure that the component value is populated from state and that changes from fired onChange events update the store.

Body:
Using React / Redux and MaterialUI I set up a component which needs to check your location or get the lat/lng based upon the address you put in.

When clicking on a button I would like the address, typed in to a TextField to be checked on a webservice.

However I can not seem to get the value of the TextField to the webservice using the button.

So I tried to set the value immediately in the props (of the state).
This works, but I do get an error:

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa).

This code is like this:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Field, reduxForm } from 'redux-form'
import TextField from 'material-ui/TextField';
import IconButton from 'material-ui/IconButton';
import PlaceIcon from 'material-ui-icons/Place';
import SearchIcon from 'material-ui-icons/Search';

import { getLocationByAddress, getLocationByLatLng } from '../actions';

/**
 * Location Search, Lets the user search for his location and coordinates
 * @class LocationSearch
 * @extends React.Component
 */
class LocationSearch extends Component {

    /**
     * getLocationByLatLng: uses navigator.geolocation to get the current position of the user

     * then requests the information from a back-end service to retrieve full location data.
     */
    getLocationByLatLng () {

        let options = {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        };

        navigator.geolocation.getCurrentPosition(function (pos) {
            console.log(pos.coords);

        }, function(err){
            console.warn(`ERROR(${err.code}): ${err.message}`);
        }, options)
    }

    /**
     * getLocationByAddress: uses address to request full location data from back-end service
     */
    getLocationByAddress = (e) => {
        /*
        console.log(e);
        e.preventDefault();
         */

        this.props.getLocationByAddress(this.props.location.address);
    };

    keepVal = ({target}) => {

        this.props.location.address = target.value;

    };

    render () {

        const { location } = this.props;

        return (

                <IconButton onClick={this.getLocationByLatLng} color="primary" className={'locationSearch_locationBtn'} aria-label="">
                    <PlaceIcon fontSize={35} />
                </IconButton>
                  <TextField
                      value={location.address}
                      placeholder={'Voer uw locatie in'}
                      margin={'normal'}
                      className={'locationSearch_input'}
                      onChange={this.keepVal}
                  />
                  <IconButton onClick={this.getLocationByAddress} color="primary" className={'locationSearch_searchBtn'} aria-label="">
                      <SearchIcon fontSize={35} />
                  </IconButton>

        );
    }

}

function mapStateToProps (state) {
    return {
        location: state.location
    }
}

export default connect(mapStateToProps, {getLocationByAddress, getLocationByLatLng})(LocationSearch)

So because I do not want any errors I also looked into changing the state just for the location address.
So I created a new action setLocationAddress and that should go to the reducer and change the state just for the address, but thats silly to do on every change, as the value is already there... no need to change it.

Thus I used a form to do this:

getLocationByAddress = (e) => {
    e.preventDefault();
    const { target } = e;
    this.props.getLocationByAddress(target['locationInput'].value);
};

render () {

    const { location } = this.props;

    return (

            <IconButton onClick={this.getLocationByLatLng} color="primary" className={'locationSearch_locationBtn'} aria-label="">
                <PlaceIcon fontSize={35} />
            </IconButton>
            <form onSubmit={this.getLocationByAddress}>
                <TextField
                    name={'locationInput'}
                    value={location.address}
                    placeholder={'Voer uw locatie in'}
                    margin={'normal'}
                    className={'locationSearch_input'}
                />
                <IconButton color="primary" className={'locationSearch_searchBtn'} aria-label="">
                    <SearchIcon fontSize={35} />
                </IconButton>
            </form>

    );
}

But again this naggy message:

Warning: A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa)

So how do I do this?
Any help would be appreciated.

Body:
See the code for the controlled component in the TextField demo.  In the code, the value prop is pulled from state and onChange is set to a function that updates state.

   <div>
    <TextField id="standard-name" label="Name" value={name} onChange={handleChange} />
    <TextField id="standard-uncontrolled" label="Uncontrolled" defaultValue="foo" />
  </div>

You're actually pretty close.  You've mapped state to your location prop and you've set value={location.address}, but onChange is assigned to this.keepVal which attempts to update props, which is no good.

Since you're using Redux, you need to dispatch an action in keepVal that will update state.location.address with event.target.value.  This will ensure that the component value is populated from state and that changes from fired onChange events update the store.

ContentLicense: CC BY-SA 4.0


问:
How can I store rnorm output from a loop in a separate vector?
I need to store the output into a separate vector so that I can plot the data (years against reproduction_rate). At the moment it only stores the final year and not years 1:20. Is there a way to use grep/regex to store the output values into one external vector instead of copying and pasting from the console?

```<code>N <- 1000
years <- 1:20
storage <- ()
for (year in years)  {
  reproduction_rate <- rnorm(n=1, mean=1, sd=0.4)+N
  phrase <- paste("In year", year, "the population rate was", reproduction_rate)
  print(paste("In year", year, "the population rate was", reproduction_rate))
  storage <- (reproduction_rate)
}
</code>```

答:
If you can forgo the printing,

```<code>storage <- rnorm(n=20, mean=1, sd=0.4)+N
</code>```

will work.  Otherwise,

```<code>storage <- numeric(length(years))
for (i in seq_along(years)) {
    storage[i] <- rnorm(...)
    print("stuff",years[i],...)
}
</code>```

As long as you set the seed appropriately, and don't run any other commands in between that call the random number generator, you're guaranteed to get exactly the same answers whether you pick the random numbers all at once or one at a time.
All at once:

```<code>N <- 1000
nyear <- 20
years <- 1:nyear
set.seed(101)
storage1 <- rnorm(n=nyear, mean=1, sd=0.4)+N
for (i in seq_along(years)) {
   print(paste("year",years[i],": reproduction=",storage1[i]))
}
</code>```

One at a time:

```<code>set.seed(101)
storage2 <- numeric(nyear)
for (i in seq_along(years)) {
   storage2[i] <- rnorm(1,mean=1,sd=0.4)+N
   print(paste("year",years[i],": reproduction=",storage2[i]))
}
</code>```

Compare:

```<code>all.equal(storage1,storage2)  ## TRUE
</code>```

Body:
I need to store the output into a separate vector so that I can plot the data (years against reproduction_rate). At the moment it only stores the final year and not years 1:20. Is there a way to use grep/regex to store the output values into one external vector instead of copying and pasting from the console?

N <- 1000
years <- 1:20
storage <- ()
for (year in years)  {
  reproduction_rate <- rnorm(n=1, mean=1, sd=0.4)+N
  phrase <- paste("In year", year, "the population rate was", reproduction_rate)
  print(paste("In year", year, "the population rate was", reproduction_rate))
  storage <- (reproduction_rate)
}

Body:
If you can forgo the printing,

storage <- rnorm(n=20, mean=1, sd=0.4)+N

will work.  Otherwise,

storage <- numeric(length(years))
for (i in seq_along(years)) {
    storage[i] <- rnorm(...)
    print("stuff",years[i],...)
}

As long as you set the seed appropriately, and don't run any other commands in between that call the random number generator, you're guaranteed to get exactly the same answers whether you pick the random numbers all at once or one at a time.
All at once:

N <- 1000
nyear <- 20
years <- 1:nyear
set.seed(101)
storage1 <- rnorm(n=nyear, mean=1, sd=0.4)+N
for (i in seq_along(years)) {
   print(paste("year",years[i],": reproduction=",storage1[i]))
}

One at a time:

set.seed(101)
storage2 <- numeric(nyear)
for (i in seq_along(years)) {
   storage2[i] <- rnorm(1,mean=1,sd=0.4)+N
   print(paste("year",years[i],": reproduction=",storage2[i]))
}

Compare:

all.equal(storage1,storage2)  ## TRUE


问:
How do I use reduce() to mimic the capabilities of forEach()?
I'm trying to accomplish a task with reduce() that I know how to do with forEach().  Unfortunately I'm not sure how to structure the syntax and I can't find a good example.

Example 1) In this code I use forEach() to insert the word species into the first index of each array.

"use strict";

var creatureArray;

creatureArray = [
  ['zombie', 30, 1, 'bite', 0, 5],
  ['skeleton', 10, 2, 'sword', 1, 10],
  ['orc', 15, 4, 'club', 1, 7]
];

creatureArray.forEach(function(value, index, array) {
  array[index].unshift('species');
});

console.log(creatureArray);```
</div>
</div>
</p>

<p><strong>Example 2)</strong> In this code I try to accomplish something similar using <code>.reduce()</code>.  However I know that I'm missing a piece of syntax. I can't figure out how to apply the updated array to the accumulator which is then returned as an object.  Thanks so much for any help!</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>"use strict";

var creatureArray, creatureObject;

creatureArray = [
  ['zombie', 30, 1, 'bite', 0, 5],
  ['skeleton', 10, 2, 'sword', 1, 10],
  ['orc', 15, 4, 'club', 1, 7]
];

creatureObject = creatureArray.reduce(function(accumulator, currentValue, index, array) {
  array[index].unshift('species');
  //what goes here?
  return accumulator;
}, {});

console.log(creatureObject);</code>```

答:
Here is how you can do accomplish it.

"use strict";

var creatureArray, creatureObject;

creatureArray = [
  ['zombie', 30, 1, 'bite', 0, 5],
  ['skeleton', 10, 2, 'sword', 1, 10],
  ['orc', 15, 4, 'club', 1, 7]
];

creatureObject = creatureArray.reduce((accumulator, currentValue) => {
  return [...accumulator, ['species', ...currentValue]];
}, []);

console.log(creatureObject);```
</div>
</div>
</p>

<p>The <code>...</code> syntax above is called the Spread Operator.</p>

<p>When applied it expands the elements of the array into the new array created by the enclosing <code>[</code> and <code>]</code>, placing each element from the old array as a top level element into the new array. This results in a flat array instead of a nested array. E.g <code>[[1, 2]]</code> -> <code>[[1, 2]]</code>, but <code>[...[1, 2]]</code> -> <code>[1, 2]</code>.
This is highly useful because it enables both simple concatenation as well as insertion of top level elements either before or after the expanded array.</p>

<p>Consider:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>"use strict";

const names = ['Linus', 'Jane', 'David'];

const withJakeAppended = [...names, 'Jake'];

const withJakePrepended = ['Jake', ...names];

[names, withJakeAppended, withJakePrepended].forEach(xs => console.log(xs));</code>```

As you can see, when we spread an Array it is not modified, so the pleasant syntax also enables improved ergonomics for immutable, value oriented programming.

Even better, ... works with Sets and Maps as well. In fact, it works any Iterable object, including ones we can create ourselves.

I might add that using the fourth argument to either Array.prototype.forEach or Array.prototype.forEach is a poor practice that should be avoided.

Note if you need to do this in a browser without ES2015 support, you can write

"use strict";

var creatureArray, creatureObject;

creatureArray = [
  ['zombie', 30, 1, 'bite', 0, 5],
  ['skeleton', 10, 2, 'sword', 1, 10],
  ['orc', 15, 4, 'club', 1, 7]
];

creatureObject = creatureArray.reduce(function (accumulator, currentValue) {

  return accumulator.concat([['species'].concat(currentValue)]);
}, []);

console.log(creatureObject);```

Body:
I'm trying to accomplish a task with reduce() that I know how to do with forEach().  Unfortunately I'm not sure how to structure the syntax and I can't find a good example.

Example 1) In this code I use forEach() to insert the word species into the first index of each array.

"use strict";

var creatureArray;

creatureArray = [
  ['zombie', 30, 1, 'bite', 0, 5],
  ['skeleton', 10, 2, 'sword', 1, 10],
  ['orc', 15, 4, 'club', 1, 7]
];

creatureArray.forEach(function(value, index, array) {
  array[index].unshift('species');
});

console.log(creatureArray);

Example 2) In this code I try to accomplish something similar using .reduce().  However I know that I'm missing a piece of syntax. I can't figure out how to apply the updated array to the accumulator which is then returned as an object.  Thanks so much for any help!

"use strict";

var creatureArray, creatureObject;

creatureArray = [
  ['zombie', 30, 1, 'bite', 0, 5],
  ['skeleton', 10, 2, 'sword', 1, 10],
  ['orc', 15, 4, 'club', 1, 7]
];

creatureObject = creatureArray.reduce(function(accumulator, currentValue, index, array) {
  array[index].unshift('species');
  //what goes here?
  return accumulator;
}, {});

console.log(creatureObject);

Body:
Here is how you can do accomplish it.

"use strict";

var creatureArray, creatureObject;

creatureArray = [
  ['zombie', 30, 1, 'bite', 0, 5],
  ['skeleton', 10, 2, 'sword', 1, 10],
  ['orc', 15, 4, 'club', 1, 7]
];

creatureObject = creatureArray.reduce((accumulator, currentValue) => {
  return [...accumulator, ['species', ...currentValue]];
}, []);

console.log(creatureObject);

The ... syntax above is called the Spread Operator.

When applied it expands the elements of the array into the new array created by the enclosing [ and ], placing each element from the old array as a top level element into the new array. This results in a flat array instead of a nested array. E.g [[1, 2]] -> [[1, 2]], but [...[1, 2]] -> [1, 2].
This is highly useful because it enables both simple concatenation as well as insertion of top level elements either before or after the expanded array.

Consider:

"use strict";

const names = ['Linus', 'Jane', 'David'];

const withJakeAppended = [...names, 'Jake'];

const withJakePrepended = ['Jake', ...names];

[names, withJakeAppended, withJakePrepended].forEach(xs => console.log(xs));

As you can see, when we spread an Array it is not modified, so the pleasant syntax also enables improved ergonomics for immutable, value oriented programming.

Even better, ... works with Sets and Maps as well. In fact, it works any Iterable object, including ones we can create ourselves.

I might add that using the fourth argument to either Array.prototype.forEach or Array.prototype.forEach is a poor practice that should be avoided.

Note if you need to do this in a browser without ES2015 support, you can write

"use strict";

var creatureArray, creatureObject;

creatureArray = [
  ['zombie', 30, 1, 'bite', 0, 5],
  ['skeleton', 10, 2, 'sword', 1, 10],
  ['orc', 15, 4, 'club', 1, 7]
];

creatureObject = creatureArray.reduce(function (accumulator, currentValue) {

  return accumulator.concat([['species'].concat(currentValue)]);
}, []);

console.log(creatureObject);


问:
Count Frequency based on Bit Flag
```<code>SELECT

              ROW_NUMBER() OVER (PARTITION BY dicei.IsLocked ORDER BY DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded)
             ,DocumentInstance.PK_DocumentInstance
             ,DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded
             ,dicei.IsLocked

FROM         DocumentInstance INNER JOIN
                      DocumentInstanceChapter ON DocumentInstance.PK_DocumentInstance = DocumentInstanceChapter.FK_DocumentInstance INNER JOIN
                      DocumentInstanceChapter AS DocumentInstanceChapter_1 ON
                      DocumentInstanceChapter.PK_DocumentInstanceChapter = DocumentInstanceChapter_1.FK_DocumentInstanceChapter INNER JOIN
                      DocumentInstanceChapterExpanded ON
                      DocumentInstanceChapter_1.PK_DocumentInstanceChapter = DocumentInstanceChapterExpanded.FK_DocumentInstanceChapter INNER JOIN
                      DocumentInstanceChapterExpanded AS DocumentInstanceChapterExpanded_1 ON
                      DocumentInstanceChapter.PK_DocumentInstanceChapter = DocumentInstanceChapterExpanded_1.FK_DocumentInstanceChapter INNER JOIN
                      DocumentInstanceChapterExpandedItem AS dicei ON
                      DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded = dicei.FK_DocumentInstanceChapterExpanded
WHERE     (DocumentInstance.PK_DocumentInstance = 455)
 AND DocumentInstanceChapterExpanded_1.PK_DocumentInstanceChapterExpanded = 50730
</code>```

As you can see the picture what i wanted to do was add a Column which would indicate

```<code>**Result Expected**
ExpandeditemKey IsLocked     StatusColumn
50797               0         Mixed
50797               0         Mixed
50797               1         Mixed
50797               1         Mixed
50797               1         Mixed
50798               1         Lock
50798               1         Lock
50798               1         Lock

If it contains 0 and 1 'Mixed'
If it contains 1 only  'Lock'
If it contains 0 only  'Unlock'
</code>```

it does not necessary need to be string column, i tried using OverBy Clause if i can used Partition by for the Islock Bit Field but was not able to
Thanks for having a look.

答:
I suggest usng MIN/MAX as window functions, then you can add a case expression that works across a partition. e.g.

```<code>SELECT
      ROW_NUMBER() OVER (PARTITION BY dicei.IsLocked ORDER BY DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded)
    , DocumentInstance.PK_DocumentInstance
    , DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded
    , dicei.IsLocked
    , case when dicei.isLockedMin <> dicei.isLockedMax then 'Mixed'
           when dicei.isLockedMax = 0 then 'Unlocked'
           else 'Locked'
      end StatusColumn
FROM DocumentInstance
INNER JOIN DocumentInstanceChapter ON DocumentInstance.PK_DocumentInstance = DocumentInstanceChapter.FK_DocumentInstance
INNER JOIN DocumentInstanceChapter AS documentinstancechapter_1 ON DocumentInstanceChapter.PK_DocumentInstanceChapter = documentinstancechapter_1.FK_DocumentInstanceChapter
INNER JOIN DocumentInstanceChapterExpanded ON documentinstancechapter_1.PK_DocumentInstanceChapter = DocumentInstanceChapterExpanded.FK_DocumentInstanceChapter
INNER JOIN DocumentInstanceChapterExpanded AS documentinstancechapterexpanded_1 ON DocumentInstanceChapter.PK_DocumentInstanceChapter = documentinstancechapterexpanded_1.FK_DocumentInstanceChapter
INNER JOIN (
      select d.*
            , min(d.IsLocked) over(partition by d.FK_DocumentInstanceChapterExpanded) isLockedMin
            , max(d.IsLocked) over(partition by d.FK_DocumentInstanceChapterExpanded) isLockedMax
      from DocumentInstanceChapterExpandedItem d
      ) AS dicei ON DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded = dicei.FK_DocumentInstanceChapterExpanded
WHERE (DocumentInstance.PK_DocumentInstance = 455)
AND documentinstancechapterexpanded_1.PK_DocumentInstanceChapterExpanded = 50730
</code>```

edit, due to the bit column, case expressions were needed:

```<code>            , min(case when d.IsLocked = 1 then 1 else 0 end) over(partition by d.FK_DocumentInstanceChapterExpanded) isLockedMin
            , max(case when d.IsLocked = 1 then 1 else 0 end) over(partition by d.FK_DocumentInstanceChapterExpanded) isLockedMax
</code>```

Title: Count Frequency based on Bit Flag

Body:
SELECT

              ROW_NUMBER() OVER (PARTITION BY dicei.IsLocked ORDER BY DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded)
             ,DocumentInstance.PK_DocumentInstance
             ,DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded
             ,dicei.IsLocked

FROM         DocumentInstance INNER JOIN
                      DocumentInstanceChapter ON DocumentInstance.PK_DocumentInstance = DocumentInstanceChapter.FK_DocumentInstance INNER JOIN
                      DocumentInstanceChapter AS DocumentInstanceChapter_1 ON
                      DocumentInstanceChapter.PK_DocumentInstanceChapter = DocumentInstanceChapter_1.FK_DocumentInstanceChapter INNER JOIN
                      DocumentInstanceChapterExpanded ON
                      DocumentInstanceChapter_1.PK_DocumentInstanceChapter = DocumentInstanceChapterExpanded.FK_DocumentInstanceChapter INNER JOIN
                      DocumentInstanceChapterExpanded AS DocumentInstanceChapterExpanded_1 ON
                      DocumentInstanceChapter.PK_DocumentInstanceChapter = DocumentInstanceChapterExpanded_1.FK_DocumentInstanceChapter INNER JOIN
                      DocumentInstanceChapterExpandedItem AS dicei ON
                      DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded = dicei.FK_DocumentInstanceChapterExpanded
WHERE     (DocumentInstance.PK_DocumentInstance = 455)
 AND DocumentInstanceChapterExpanded_1.PK_DocumentInstanceChapterExpanded = 50730

As you can see the picture what i wanted to do was add a Column which would indicate

**Result Expected**
ExpandeditemKey IsLocked     StatusColumn
50797               0         Mixed
50797               0         Mixed
50797               1         Mixed
50797               1         Mixed
50797               1         Mixed
50798               1         Lock
50798               1         Lock
50798               1         Lock

If it contains 0 and 1 'Mixed'
If it contains 1 only  'Lock'
If it contains 0 only  'Unlock'

it does not necessary need to be string column, i tried using OverBy Clause if i can used Partition by for the Islock Bit Field but was not able to
Thanks for having a look.

Body:
I suggest usng MIN/MAX as window functions, then you can add a case expression that works across a partition. e.g.

SELECT
      ROW_NUMBER() OVER (PARTITION BY dicei.IsLocked ORDER BY DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded)
    , DocumentInstance.PK_DocumentInstance
    , DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded
    , dicei.IsLocked
    , case when dicei.isLockedMin <> dicei.isLockedMax then 'Mixed'
           when dicei.isLockedMax = 0 then 'Unlocked'
           else 'Locked'
      end StatusColumn
FROM DocumentInstance
INNER JOIN DocumentInstanceChapter ON DocumentInstance.PK_DocumentInstance = DocumentInstanceChapter.FK_DocumentInstance
INNER JOIN DocumentInstanceChapter AS documentinstancechapter_1 ON DocumentInstanceChapter.PK_DocumentInstanceChapter = documentinstancechapter_1.FK_DocumentInstanceChapter
INNER JOIN DocumentInstanceChapterExpanded ON documentinstancechapter_1.PK_DocumentInstanceChapter = DocumentInstanceChapterExpanded.FK_DocumentInstanceChapter
INNER JOIN DocumentInstanceChapterExpanded AS documentinstancechapterexpanded_1 ON DocumentInstanceChapter.PK_DocumentInstanceChapter = documentinstancechapterexpanded_1.FK_DocumentInstanceChapter
INNER JOIN (
      select d.*
            , min(d.IsLocked) over(partition by d.FK_DocumentInstanceChapterExpanded) isLockedMin
            , max(d.IsLocked) over(partition by d.FK_DocumentInstanceChapterExpanded) isLockedMax
      from DocumentInstanceChapterExpandedItem d
      ) AS dicei ON DocumentInstanceChapterExpanded.PK_DocumentInstanceChapterExpanded = dicei.FK_DocumentInstanceChapterExpanded
WHERE (DocumentInstance.PK_DocumentInstance = 455)
AND documentinstancechapterexpanded_1.PK_DocumentInstanceChapterExpanded = 50730

edit, due to the bit column, case expressions were needed:

            , min(case when d.IsLocked = 1 then 1 else 0 end) over(partition by d.FK_DocumentInstanceChapterExpanded) isLockedMin
            , max(case when d.IsLocked = 1 then 1 else 0 end) over(partition by d.FK_DocumentInstanceChapterExpanded) isLockedMax


问:
The problem: found a tab character that violate intendation
```<code>./run-bot
Running bot 22496
Error parsing ./shittybot.yml: YAML::XS::Load Error: The problem:

    found a tab character that violate intendation

was found at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 201
        Config::Any::_load('Config::Any', 'HASH(0x8de4708)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 94
        Config::Any::load_files('Config::Any', 'HASH(0x8de4708)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 104
        Config::JFDI::Source::Loader::_load_files('Config::JFDI::Source::Loader=HASH(0x85e1d48)', 'ARRAY(0x8de4f48)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 62
        Config::JFDI::Source::Loader::read('Config::JFDI::Source::Loader=HASH(0x85e1d48)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 153
        Config::JFDI::load('Config::JFDI=HASH(0x85e67c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 140
        Config::JFDI::config('Config::JFDI=HASH(0x85e67c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 131
        Config::JFDI::get('Config::JFDI=HASH(0x85e67c0)') called at bot.pl line 32
</code>```

How do I fix this?

EDIT:  I fixed indentation I think, but now I get this error:

```<code>Error parsing ./shittybot.yml: YAML::XS::Load Error: The problem:

    found character that cannot start any token

was found at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 201
        Config::Any::_load('Config::Any', 'HASH(0xa3da738)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 94
        Config::Any::load_files('Config::Any', 'HASH(0xa3da738)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 104
        Config::JFDI::Source::Loader::_load_files('Config::JFDI::Source::Loader=HASH(0x9bd7d48)', 'ARRAY(0xa3daf78)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 62
        Config::JFDI::Source::Loader::read('Config::JFDI::Source::Loader=HASH(0x9bd7d48)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 153
        Config::JFDI::load('Config::JFDI=HASH(0x9bdc7c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 140
        Config::JFDI::config('Config::JFDI=HASH(0x9bdc7c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 131
        Config::JFDI::get('Config::JFDI=HASH(0x9bdc7c0)') called at bot.pl line 32
</code>```

答:
With your pastebin file.

```<code>apv@cassidy[421]~/>perl -MYAML::XS=LoadFile -le 'LoadFile(+shift)' S1tuACcg.txt
             YAML::XS::Load Error: The problem:

    found a tab character that violate intendation

was found at document: 1, line: 8, column: 1
while scanning a plain scalar at line: 7, column: 18
apv@cassidy[422]~/>perl -lne 'print "TAB!" if /\t/' S1tuACcg.txt
TAB!
TAB!
TAB!
apv@cassidy[423]~/>perl -pi -e 's/\t/        /' S1tuACcg.txt
apv@cassidy[424]~/>perl -MYAML::XS=LoadFile -le \
   'LoadFile(+shift) and print "OK!"' S1tuACcg.txt
OK!
</code>```

I suspect that if you upgrade your YAML::XS (mine’s 0.34), you’ll see the better error feedback my example shows.

Body:
./run-bot
Running bot 22496
Error parsing ./shittybot.yml: YAML::XS::Load Error: The problem:

    found a tab character that violate intendation

was found at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 201
        Config::Any::_load('Config::Any', 'HASH(0x8de4708)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 94
        Config::Any::load_files('Config::Any', 'HASH(0x8de4708)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 104
        Config::JFDI::Source::Loader::_load_files('Config::JFDI::Source::Loader=HASH(0x85e1d48)', 'ARRAY(0x8de4f48)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 62
        Config::JFDI::Source::Loader::read('Config::JFDI::Source::Loader=HASH(0x85e1d48)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 153
        Config::JFDI::load('Config::JFDI=HASH(0x85e67c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 140
        Config::JFDI::config('Config::JFDI=HASH(0x85e67c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 131
        Config::JFDI::get('Config::JFDI=HASH(0x85e67c0)') called at bot.pl line 32

How do I fix this?

EDIT:  I fixed indentation I think, but now I get this error:

Error parsing ./shittybot.yml: YAML::XS::Load Error: The problem:

    found character that cannot start any token

was found at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 201
        Config::Any::_load('Config::Any', 'HASH(0xa3da738)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/Any.pm line 94
        Config::Any::load_files('Config::Any', 'HASH(0xa3da738)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 104
        Config::JFDI::Source::Loader::_load_files('Config::JFDI::Source::Loader=HASH(0x9bd7d48)', 'ARRAY(0xa3daf78)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI/Source/Loader.pm line 62
        Config::JFDI::Source::Loader::read('Config::JFDI::Source::Loader=HASH(0x9bd7d48)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 153
        Config::JFDI::load('Config::JFDI=HASH(0x9bdc7c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 140
        Config::JFDI::config('Config::JFDI=HASH(0x9bdc7c0)') called at /usr/local/lib/perl5/site_perl/5.10.1/Config/JFDI.pm line 131
        Config::JFDI::get('Config::JFDI=HASH(0x9bdc7c0)') called at bot.pl line 32

Body:
With your pastebin file.

apv@cassidy[421]~/>perl -MYAML::XS=LoadFile -le 'LoadFile(+shift)' S1tuACcg.txt
             YAML::XS::Load Error: The problem:

    found a tab character that violate intendation

was found at document: 1, line: 8, column: 1
while scanning a plain scalar at line: 7, column: 18
apv@cassidy[422]~/>perl -lne 'print "TAB!" if /\t/' S1tuACcg.txt
TAB!
TAB!
TAB!
apv@cassidy[423]~/>perl -pi -e 's/\t/        /' S1tuACcg.txt
apv@cassidy[424]~/>perl -MYAML::XS=LoadFile -le \
   'LoadFile(+shift) and print "OK!"' S1tuACcg.txt
OK!

I suspect that if you upgrade your YAML::XS (mine’s 0.34), you’ll see the better error feedback my example shows.


问:
Inconsistent time series given equal spacing in matplotlib
I'm plotting a stacked line chart from a pandas dataframe. The data was collected irregularly over the course of two days. In the image below, you can see that the time change between equal intervals varies (~7 hours to ~36 hours between equally spaced intervals). I don't want this to happen, I want points on the graph to be stretched and squeezed appropriately such that time scales linearly with the x-axis. How can I do this?

The data was read in as follows:

```<code>df = pd.read_csv("filepath", index_col=0)
df = df.T
</code>```

Above, I had to transpose the dataframe for the pandas stacked line plot to work as I wanted it to. The plot was produced as follows:

```<code>plot = df.plot.area(rot=90)
plot.axhline(y=2450, color="black")
</code>```

In response to ImportanceOfBeingErnest, here is a minimal, complete, and verifiable example:

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as mpl

dateTimeIndex = ["04.12.17 23:03", "05.12.17 00:09", "05.12.17 21:44", "05.12.17 22:34", "08.12.17 16:23"]

d = {'one' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex),
     'two' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex),
     'three' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex)}

df = pd.DataFrame(d)

plot = df.plot.area(rot=90)
</code>```

Here is what the dataframe looks like (random values will vary):

```<code>                one       three     two
04.12.17 23:03  0.472832  0.283329  0.739657
05.12.17 00:09  3.166099  1.065015  0.561079
05.12.17 21:44  0.209190  0.674236  0.143453
05.12.17 22:34  1.275056  0.764328  0.650507
08.12.17 16:23  0.764038  0.265599  0.342435
</code>```

and the plot produced:

As you can tell, the dateTimeIndex entries are rather random but they are given equal spacing on the x-axis. I don't mind if the tick marks coincide with the data points. I only want time to scale linearly. How can this be achieved?

答:
Whats happening above is pandas is just using the strings as the x-ticks.  You need to make the dateTimeIndex a datetime object:

```<code>dateTimeIndex = pd.to_datetime( ["04.12.17 23:03", "05.12.17 00:09",
                "05.12.17 21:44", "05.12.17 22:34", "08.12.17 16:23"])

d = {'one' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex),
     'two' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex),
     'three' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex)}

df = pd.DataFrame(d)
plot = df.plot.area(rot=90)
</code>```

Body:
I'm plotting a stacked line chart from a pandas dataframe. The data was collected irregularly over the course of two days. In the image below, you can see that the time change between equal intervals varies (~7 hours to ~36 hours between equally spaced intervals). I don't want this to happen, I want points on the graph to be stretched and squeezed appropriately such that time scales linearly with the x-axis. How can I do this?

The data was read in as follows:

df = pd.read_csv("filepath", index_col=0)
df = df.T

Above, I had to transpose the dataframe for the pandas stacked line plot to work as I wanted it to. The plot was produced as follows:

plot = df.plot.area(rot=90)
plot.axhline(y=2450, color="black")

In response to ImportanceOfBeingErnest, here is a minimal, complete, and verifiable example:

import numpy as np
import pandas as pd
import matplotlib.pyplot as mpl

dateTimeIndex = ["04.12.17 23:03", "05.12.17 00:09", "05.12.17 21:44", "05.12.17 22:34", "08.12.17 16:23"]

d = {'one' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex),
     'two' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex),
     'three' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex)}

df = pd.DataFrame(d)

plot = df.plot.area(rot=90)

Here is what the dataframe looks like (random values will vary):

                one       three     two
04.12.17 23:03  0.472832  0.283329  0.739657
05.12.17 00:09  3.166099  1.065015  0.561079
05.12.17 21:44  0.209190  0.674236  0.143453
05.12.17 22:34  1.275056  0.764328  0.650507
08.12.17 16:23  0.764038  0.265599  0.342435

and the plot produced:

As you can tell, the dateTimeIndex entries are rather random but they are given equal spacing on the x-axis. I don't mind if the tick marks coincide with the data points. I only want time to scale linearly. How can this be achieved?

Body:
Whats happening above is pandas is just using the strings as the x-ticks.  You need to make the dateTimeIndex a datetime object:

dateTimeIndex = pd.to_datetime( ["04.12.17 23:03", "05.12.17 00:09",
                "05.12.17 21:44", "05.12.17 22:34", "08.12.17 16:23"])

d = {'one' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex),
     'two' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex),
     'three' : pd.Series(abs(np.random.randn(5)), index=dateTimeIndex)}

df = pd.DataFrame(d)
plot = df.plot.area(rot=90)


问:
Apply math to a member of a list in python
I am trying to keep track of some numbers in a list, but I am unable to edit members of said list. When I try subtracting from it I am given the error "unsupported operand type(s) for -=: 'list' and 'int'"

```<code>with open("prices.txt") as f:
        seatCapacity = []
        for line in f:
            line = [int(i) for i in line[10:].split()]
            seatCapacity.append(line)

seatCapacity[seat] -= 1
</code>```

seatCapacity[seat] displays a number correctly so I'm not certain what I'm doing wrong.

Edit:
Some examples of output are

```<code>print(seatCapacity)
</code>```

output:

```<code>[[150], [120], [200], [80], [120], [80]]
</code>```

and

```<code>print(seatCapacity[seat])
</code>```

output:

```<code>[150]
</code>```

答:
seatCapacity[seat] displays a number correctly so I'm not certain what I'm doing wrong.

Actually, not according to the output you posted. If it's correct that print(seatCapacity[seat]) displays [150], then seatCapacity[seat] is in fact a list. Note the brackets that make the difference between [150], which represents a list, and 150, which represents an integer.

The reason this is happening is that you set line to a list during your loop.

```<code>line = [int(i) for i in line[10:].split()]
</code>```

What this does is take the current line of the file, for example

```<code>"something 10 20 30 40"
</code>```

strips off the first 10 characters

```<code>"10 20 30 40"
</code>```

splits it into a list of individual whitespace-separated pieces

```<code>["10", "20", "30", "40"]
</code>```

then iterates over each of those pieces (i) and converts it to an integer (int(i)), recombining the results into a list.

```<code>[10, 20, 30, 40]
</code>```

That list is what gets appended to seatCapacity in the next line.

If you want to append an integer, instead of a list, you would have to do something to get the integer you want out of that list. For example, use list[0] if you always want the first thing in the list, or list[-1] if you always want the last one. Or, if you know that there will always be one number on each line (not counting the first 10 characters), you can just convert that string to a line directly, using something like int(line[10:].strip()). (strip() removes whitespace from the beginning and end. It may be optional depending on the content of your file.)

Body:
I am trying to keep track of some numbers in a list, but I am unable to edit members of said list. When I try subtracting from it I am given the error "unsupported operand type(s) for -=: 'list' and 'int'"

with open("prices.txt") as f:
        seatCapacity = []
        for line in f:
            line = [int(i) for i in line[10:].split()]
            seatCapacity.append(line)

seatCapacity[seat] -= 1

seatCapacity[seat] displays a number correctly so I'm not certain what I'm doing wrong.

Edit:
Some examples of output are

print(seatCapacity)

output:

[[150], [120], [200], [80], [120], [80]]

and

print(seatCapacity[seat])

output:

[150]

Body:
seatCapacity[seat] displays a number correctly so I'm not certain what I'm doing wrong.

Actually, not according to the output you posted. If it's correct that print(seatCapacity[seat]) displays [150], then seatCapacity[seat] is in fact a list. Note the brackets that make the difference between [150], which represents a list, and 150, which represents an integer.

The reason this is happening is that you set line to a list during your loop.

line = [int(i) for i in line[10:].split()]

What this does is take the current line of the file, for example

"something 10 20 30 40"

strips off the first 10 characters

"10 20 30 40"

splits it into a list of individual whitespace-separated pieces

["10", "20", "30", "40"]

then iterates over each of those pieces (i) and converts it to an integer (int(i)), recombining the results into a list.

[10, 20, 30, 40]

That list is what gets appended to seatCapacity in the next line.

If you want to append an integer, instead of a list, you would have to do something to get the integer you want out of that list. For example, use list[0] if you always want the first thing in the list, or list[-1] if you always want the last one. Or, if you know that there will always be one number on each line (not counting the first 10 characters), you can just convert that string to a line directly, using something like int(line[10:].strip()). (strip() removes whitespace from the beginning and end. It may be optional depending on the content of your file.)


问:
how to reload the Table view data when tap on UILabel(UITapGestureRecognizer)
I am new to objective c, and i am very interested in learn new technologies.

I have a UITapGestureRecognizer on a label. I am using 2 label ,when i tap on label1 load some data Tableview and when I tap on label 2 i want to change the Tableview.

I didn't find any solution for my requirement. so anyone help me .

suggest me guy's how to change the TableView data when tap on UILabel.

答:
You can do this like following way:

Way 1:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   ..
   ..
   ..
   // Here is your stuff for cell

   UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
   [lbl1 setText:@"Label"];
   [lbl1 setUserInteractionEnabled:YES];
   [cell.contentView addSubview:lbl1];
   UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self    action:@selector(tapAction:)];
   tap.tag = [NSIndexPath row];
   [tap setNumberOfTapsRequired:1];
   [lbl addGestureRecognizer:tap];
   ...
}

- (void)tapAction:(id)sender {
  switch(((UITapGestureRecognizer *)sender).view.tag) {
     case 0:
          // code for first TableView
          break;
     case 1:
         // code for second TableView

         break;
      ....
     }
}
</code>```

Way 2:

in cellForRowAtIndexPath: method:

```<code> UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
tap.tag = [NSIndexPath row];
...
</code>```

Handler method:

```<code>- (void)tapAction:(id)sender
{
 switch(((UITapGestureRecognizer *)sender).tag)
{
case 0:

NSLog(@"Tap action 1");

break;
case 1:

NSLog(@"tap action 2");

break;

..... }
</code>```

Body:
You can do this like following way:

Way 1:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   ..
   ..
   ..
   // Here is your stuff for cell

   UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
   [lbl1 setText:@"Label"];
   [lbl1 setUserInteractionEnabled:YES];
   [cell.contentView addSubview:lbl1];
   UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self    action:@selector(tapAction:)];
   tap.tag = [NSIndexPath row];
   [tap setNumberOfTapsRequired:1];
   [lbl addGestureRecognizer:tap];
   ...
}

- (void)tapAction:(id)sender {
  switch(((UITapGestureRecognizer *)sender).view.tag) {
     case 0:
          // code for first TableView
          break;
     case 1:
         // code for second TableView

         break;
      ....
     }
}

Way 2:

in cellForRowAtIndexPath: method:

 UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
tap.tag = [NSIndexPath row];
...

Handler method:

- (void)tapAction:(id)sender
{
 switch(((UITapGestureRecognizer *)sender).tag)
{
case 0:

NSLog(@"Tap action 1");

break;
case 1:

NSLog(@"tap action 2");

break;

..... }


问:
Concatenate variable number of element string values via XPath 1.0?
I'm trying to use XPath 1.0 to select all of the text within these li elements, except for the last one with class="detailCrumb".

I'd like my result to look like:

```<code>Home Photography Memory Cards & Accessories Memory Cards
</code>```

These breadcrumbs will be dynamic based on the level of the site I'm at, so I can't specify positional requests, such as li[4]. How can I achieve this?

```<code><div class="breadcrums-cont">
    <ul id="breadcrumbs" ">
        <li class="first">Home</li>
        <li>Photography</li>
        <li>Memory Cards & Accessories</li>
        <li>Memory Cards</li>
        <li class="detailCrumb">SanDisk Extreme Pro</li>
    </ul>
</div>
</code>```

答:
XPath 1.0

The usual answer is that you can concatenate a fixed number of items:

```<code>concat(//ul[@id="breadcrumbs"]/li[not(@class="detailCrumb")][1], ' ',
       //ul[@id="breadcrumbs"]/li[not(@class="detailCrumb")][2], ' ',
       //ul[@id="breadcrumbs"]/li[not(@class="detailCrumb")][3])
</code>```

To concatenate a variable number of items, as @splash58 has said (+1), you'll have to use string concatenation facilities of the language calling XPath – XPath 1.0 alone cannot do it.

However, if you start with the string value of the entire list and then take away the unwanted string,

```<code>normalize-space(
   substring-before(//ul[@id="breadcrumbs"],
                    //ul[@id="breadcrumbs"]/li[@class="detailCrumb"]))
</code>```

then you can achieve your requested result:

```<code>Home Photography Memory Cards & Accessories Memory Cards
</code>```

XPath 2.0

You can join a variable number of items in XPath via string-join():

```<code>string-join(//ul[@id="breadcrumbs"]/li[not(@class="detailCrumb")], ' ')
</code>```

returns

```<code>Home Photography Memory Cards & Accessories Memory Cards
</code>```

as requested.

Body:
I'm trying to use XPath 1.0 to select all of the text within these li elements, except for the last one with class="detailCrumb".

I'd like my result to look like:

Home Photography Memory Cards & Accessories Memory Cards

These breadcrumbs will be dynamic based on the level of the site I'm at, so I can't specify positional requests, such as li[4]. How can I achieve this?

Home

Photography

Memory Cards & Accessories

Memory Cards

SanDisk Extreme Pro

Body:
XPath 1.0

The usual answer is that you can concatenate a fixed number of items:

concat(//ul[@id="breadcrumbs"]/li[not(@class="detailCrumb")][1], ' ',
       //ul[@id="breadcrumbs"]/li[not(@class="detailCrumb")][2], ' ',
       //ul[@id="breadcrumbs"]/li[not(@class="detailCrumb")][3])

To concatenate a variable number of items, as @splash58 has said (+1), you'll have to use string concatenation facilities of the language calling XPath – XPath 1.0 alone cannot do it.

However, if you start with the string value of the entire list and then take away the unwanted string,

normalize-space(
   substring-before(//ul[@id="breadcrumbs"],
                    //ul[@id="breadcrumbs"]/li[@class="detailCrumb"]))

then you can achieve your requested result:

Home Photography Memory Cards & Accessories Memory Cards

XPath 2.0

You can join a variable number of items in XPath via string-join():

string-join(//ul[@id="breadcrumbs"]/li[not(@class="detailCrumb")], ' ')

returns

Home Photography Memory Cards & Accessories Memory Cards

as requested.


问:
ffmpeg concat produces DTS out of order errors
I'm following the documentation on how to concatenate files with ffmpeg but during the process I'm seeing lots of warning and the output video stops after the first chunk but the audio keeps on playing.

This is the command I'm using to concatenate the files:

```<code>ffmpeg -f concat -i mylist.txt -c copy output.webm
</code>```

This are the warnings I'm seeing:

```<code>[concat @ 0x7fee11822a00] DTS 0 < 2500 out of order
[webm @ 0x7fee11011000] Non-monotonous DTS in output stream 0:0; previous: 2500, current: 0; changing to 2500. This may result in incorrect timestamps in the output file.
</code>```

The video files are coming from an external source. My current solution is to re-encode every file separately to mp4 and then to concatenate them together and then to re-encode the complete file back to webm. That, of cause, that takes some significant time but I can't find another solution.

答:
The following is a method for solving the "DTS out of order" error when concatenating a group of mp4 video files. It also avoids re-encoding them.

Although you will typically still see the "out of order" error message reported in the console window during processing, the concatenation will nevertheless succeed (and without loss of sync).

Run this code in a batch file. I wrote it on a machine running Windows 7.

```<code>::  *** Concatenate .MP4 files : Stream Copy ***

    ::  You can't concatenate .mp4 files. You have to convert them to an
    ::  intermediate format that can be concatenated, such as .mpg:
    ::
    ::    1. Convert the .mp4 videos to .mpg, using ffmpeg.
    ::    2. Then run a file level concatenation command on
    ::       the .mpg files, to create a combined .mpg file.
    ::    3. Convert the concatenated .mpg file to .mp4,
    ::       using ffmpeg.

    ::  If the mp4 files contain a h264 stream, use the .TS format (MPEG-TS)
    ::  as the intermediate format (instead of .MPG)

    ::  Convert the .MP4 files to intermediate .TS
    ffmpeg -i input1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts input1.ts
    ffmpeg -i input2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts input2.ts
    ffmpeg -i input3.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts input3.ts
    ffmpeg -i input4.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts input4.ts
    ffmpeg -i input5.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts input5.ts

    ::  MP4 Options
    SET options=-bsf:a aac_adtstoasc -movflags faststart

    ::  Concatenate the TS files & Convert the output back to MP4
    ffmpeg -i "concat:input1.ts|input2.ts|input3.ts|input4.ts|input5.ts" -c copy -video_track_timescale 25 %options% -f mp4 -threads 1 output.mp4

    ::  Report
    echo.  &  ffmpeg  -i input1.mp4 -f nul
    echo.  &  ffmpeg  -i input1.ts  -f nul
    echo.  &  ffmpeg  -i output.mp4 -f nul
</code>```

Body:
I'm following the documentation on how to concatenate files with ffmpeg but during the process I'm seeing lots of warning and the output video stops after the first chunk but the audio keeps on playing.

This is the command I'm using to concatenate the files:

ffmpeg -f concat -i mylist.txt -c copy output.webm

This are the warnings I'm seeing:

[concat @ 0x7fee11822a00] DTS 0 < 2500 out of order
[webm @ 0x7fee11011000] Non-monotonous DTS in output stream 0:0; previous: 2500, current: 0; changing to 2500. This may result in incorrect timestamps in the output file.

The video files are coming from an external source. My current solution is to re-encode every file separately to mp4 and then to concatenate them together and then to re-encode the complete file back to webm. That, of cause, that takes some significant time but I can't find another solution.

Body:
The following is a method for solving the "DTS out of order" error when concatenating a group of mp4 video files. It also avoids re-encoding them.

Although you will typically still see the "out of order" error message reported in the console window during processing, the concatenation will nevertheless succeed (and without loss of sync).

Run this code in a batch file. I wrote it on a machine running Windows 7.

::  *** Concatenate .MP4 files : Stream Copy ***

    ::  You can't concatenate .mp4 files. You have to convert them to an
    ::  intermediate format that can be concatenated, such as .mpg:
    ::
    ::    1. Convert the .mp4 videos to .mpg, using ffmpeg.
    ::    2. Then run a file level concatenation command on
    ::       the .mpg files, to create a combined .mpg file.
    ::    3. Convert the concatenated .mpg file to .mp4,
    ::       using ffmpeg.

    ::  If the mp4 files contain a h264 stream, use the .TS format (MPEG-TS)
    ::  as the intermediate format (instead of .MPG)

    ::  Convert the .MP4 files to intermediate .TS
    ffmpeg -i input1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts input1.ts
    ffmpeg -i input2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts input2.ts
    ffmpeg -i input3.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts input3.ts
    ffmpeg -i input4.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts input4.ts
    ffmpeg -i input5.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts input5.ts

    ::  MP4 Options
    SET options=-bsf:a aac_adtstoasc -movflags faststart

    ::  Concatenate the TS files & Convert the output back to MP4
    ffmpeg -i "concat:input1.ts|input2.ts|input3.ts|input4.ts|input5.ts" -c copy -video_track_timescale 25 %options% -f mp4 -threads 1 output.mp4

    ::  Report
    echo.  &  ffmpeg  -i input1.mp4 -f nul
    echo.  &  ffmpeg  -i input1.ts  -f nul
    echo.  &  ffmpeg  -i output.mp4 -f nul