问:
Access Docker API on Windows via Named Pipes
According to the Docker for Windows FAQ, " clients can connect to the Docker Engine through a named pipe: npipe:////./pipe/docker_engine"

I have been trying to connect to the API via named pipes to no avail:

```<code>public class DockerNamedPipeTest
{
    private const string PIPE_PATH = "docker_engine";

    public void Test()
    {
        using (NamedPipeClientStream pipeClient =
            new NamedPipeClientStream(
                ".",
                PIPE_PATH,
                PipeDirection.InOut,
                PipeOptions.WriteThrough,
                TokenImpersonationLevel.Impersonation))
        {
            pipeClient.Connect(30);
            Send(pipeClient);
            Receive(pipeClient);
        }
    }

    public void Send(NamedPipeClientStream pipeClient)
    {
        if (pipeClient.IsConnected)
        {
            byte[] buffer = Encoding.UTF8.GetBytes("GET /containers/json");
            pipeClient.Write(buffer, 0, buffer.Length);
            pipeClient.WaitForPipeDrain();
            pipeClient.Flush();
        }
    }

    public void Receive(NamedPipeClientStream pipeClient)
    {
        string result = string.Empty;

        if (pipeClient.IsConnected && pipeClient.CanRead)
        {
            do
            {
                byte b = (byte)pipeClient.ReadByte();   //  <-- Hangs here
                result += Convert.ToChar(b).ToString();
            }
            while (!pipeClient.IsMessageComplete);
        }

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

Can anyone tell me what I am doing wrong?

答:
Microsoft's .NET client library for Docker supports named pipes, have you looked at that?

Here's an example:

```<code>using Docker.DotNet;
DockerClient client = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine"))
 .CreateClient();
</code>```

Body:
According to the Docker for Windows FAQ, " clients can connect to the Docker Engine through a named pipe: npipe:////./pipe/docker_engine"

I have been trying to connect to the API via named pipes to no avail:

public class DockerNamedPipeTest
{
    private const string PIPE_PATH = "docker_engine";

    public void Test()
    {
        using (NamedPipeClientStream pipeClient =
            new NamedPipeClientStream(
                ".",
                PIPE_PATH,
                PipeDirection.InOut,
                PipeOptions.WriteThrough,
                TokenImpersonationLevel.Impersonation))
        {
            pipeClient.Connect(30);
            Send(pipeClient);
            Receive(pipeClient);
        }
    }

    public void Send(NamedPipeClientStream pipeClient)
    {
        if (pipeClient.IsConnected)
        {
            byte[] buffer = Encoding.UTF8.GetBytes("GET /containers/json");
            pipeClient.Write(buffer, 0, buffer.Length);
            pipeClient.WaitForPipeDrain();
            pipeClient.Flush();
        }
    }

    public void Receive(NamedPipeClientStream pipeClient)
    {
        string result = string.Empty;

        if (pipeClient.IsConnected && pipeClient.CanRead)
        {
            do
            {
                byte b = (byte)pipeClient.ReadByte();   //  <-- Hangs here
                result += Convert.ToChar(b).ToString();
            }
            while (!pipeClient.IsMessageComplete);
        }

        Console.WriteLine(result);
    }
}

Can anyone tell me what I am doing wrong?

Body:
Microsoft's .NET client library for Docker supports named pipes, have you looked at that?

Here's an example:

using Docker.DotNet;
DockerClient client = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine"))
 .CreateClient();


来源: stackexchange

问:
getting error on sql query in asp.net using c#
I am using this sql query in c#

```<code>select t.testname,t.totalque,r.testdate,r.score
from test t, result r
where t.testid=r.testid
  and r.login='vsdep980'
</code>```

but it shows an error that is

invalid column name 'vsdep980'

now here vsdep980 is the value which is stored in the column login but why it shows this type of error.

now my code is

```<code>SqlCommand cmd = new SqlCommand("select t.testname,t.totalque,r.testdate,r.score from test t, result r where t.testid=r.testid and r.login=vsdep980", con);
con.Open();
int c = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
if (c > 0)
{
    Response.Write("<br><br><h1 class='head1'> You have not given any quiz</h1>");
    Response.End();
}
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
DataTable dt = ds.Tables[0];
DataRow dr = null;
Response.Write("<table border='1' align='center'><tr class='style2'><td width='300'>Test Name </td><td> Total<br> Question </td><td> Date </td><td> Score </td></tr>");
foreach (DataRow dr1 in dt.Rows)
{
    dr = dr1;
    Response.Write("<tr class='style8'><td> "+dr[0]+" </td><td align='center'> "+dr[1]+" </td><td align='center'> "+dr[2]+" </td><td align='center'>"+dr[3]+" </td></tr>");
}
Response.Write("</table>");
</code>```

image of error msg

Please help me.

Thanks.

答:
1- Do not use old joins.

Bad habits to kick : using old-style JOINs

2- Use parameters in your query.

A parameterized query is a query in which placeholders are used for parameters and the parameter values are supplied at execution time. The most important reason to use parameterized queries is to avoid SQL injection attacks.

Your query should be:

```<code>SqlCommand cmd = new SqlCommand("select t.testname,t.totalque,r.testdate,r.score
from test t, result r where t.testid=r.testid and r.login='vsdep980'", con);
</code>```

You miss quote '', so the vsdep980 will act as a column instead of a value.

And your query should be like:

```<code>SELECT T.testname,
       T.totalque,
       R.testdate,
       R.score
FROM test T JOIN result R ON T.testid = R.testid -- Use the new style instead
WHERE R.login = 'vsdep980';
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using this sql query in c#

select t.testname,t.totalque,r.testdate,r.score
from test t, result r
where t.testid=r.testid
  and r.login='vsdep980'

but it shows an error that is

invalid column name 'vsdep980'

now here vsdep980 is the value which is stored in the column login but why it shows this type of error.

now my code is

SqlCommand cmd = new SqlCommand("select t.testname,t.totalque,r.testdate,r.score from test t, result r where t.testid=r.testid and r.login=vsdep980", con);
con.Open();
int c = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
if (c > 0)
{
    Response.Write("

 You have not given any quiz
");
    Response.End();
}
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds);
DataTable dt = ds.Tables[0];
DataRow dr = null;
Response.Write("

Test Name 	 Total
 Question 	 Date 	 Score
");
foreach (DataRow dr1 in dt.Rows)
{
    dr = dr1;
    Response.Write("
 "+dr[0]+" 	 "+dr[1]+" 	 "+dr[2]+" 	"+dr[3]+"
");
}
Response.Write("
");

image of error msg

Please help me.

Thanks.

Body:
1- Do not use old joins.

Bad habits to kick : using old-style JOINs

2- Use parameters in your query.

A parameterized query is a query in which placeholders are used for parameters and the parameter values are supplied at execution time. The most important reason to use parameterized queries is to avoid SQL injection attacks.

Your query should be:

SqlCommand cmd = new SqlCommand("select t.testname,t.totalque,r.testdate,r.score
from test t, result r where t.testid=r.testid and r.login='vsdep980'", con);

You miss quote '', so the vsdep980 will act as a column instead of a value.

And your query should be like:

SELECT T.testname,
       T.totalque,
       R.testdate,
       R.score
FROM test T JOIN result R ON T.testid = R.testid -- Use the new style instead
WHERE R.login = 'vsdep980';

ContentLicense: CC BY-SA 4.0


问:
What's the syntax for using facts in Ansible Tower?
I'm using Ansible Tower trying to create a Smart Inventory based on some Ansible Facts.

What's the syntax required to access the "facts" in a Smart Inventory?

答:
The Ansible Tower documentation is a little mysterious for the: Smart Inventory -> Smart Host Filter -> Dynamic Host.

Ansible Facts: The "Key" button (aka legend/help) in Ansible Tower suggests to use the term "facts" to access Ansible Facts.  This is wrong, you need to use "ansible_facts" to access facts.

Examples:

Access the facts: ansible_facts.ansible_lsb__major_release:"7"

Using Numbers in facts: Numeric values need to be quoted (see above)

Double underscores to represent a json 'dot'.

Variables:

Variables appear to be stored as an escaped JSON text in a singular field.

Smart Inventory of 'Active' Servers: "variables:active".

This does a search across ALL fields in the variables, no current way to do the following: "variables.openstack__vm_state:active"


问:
Could not find com.android.tools.build:gradle:2.3.3
I am getting this error during gradle build in android studio. And I am unable to figure out what I am missing.

Error:Could not find com.android.tools.build:gradle:2.3.3. Searched in the
    following locations:
    file:/C:/Program Files/Android/Android
    Studio/gradle/m2repository/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom

    file:/C:/Program Files/Android/Android
    Studio/gradle/m2repository/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.jar

    https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom

    https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.jar

Here is my build.gradlefile configuration

```<code>`
all sub-projects/modules.
    allprojects {
        repositories {
            jcenter()
            maven {
                url "https://maven.google.com"
            }
            maven {
                url 'https://jitpack.io'
            }
        }
    }

    buildscript {
        dependencies {
            classpath 'com.android.tools.build:gradle:2.3.3'
        }
        repositories {
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
        }
    }

    ext {
        supportlib_version = '26.0.2'
        gps_version = '11.2.0'
    }

    //Ensure that all dependencies use the same version of the Android Support library
    subprojects {
        project.configurations.all {
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'com.android.support'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "$supportlib_version"
                }
                if (details.requested.group == 'com.google.android.gms'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "$gps_version"
                }
            }
        }
    }

    allprojects {
        repositories {
            jcenter()
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
        }
    }
`
</code>```

Could you help me what am I missing?

答:
You need to use the right version of the gradle and gradle plugin

If you are using plugin 2.2.3 you should use gradle 2.14.1+.
If you updated your Android Studio, you should use plugin version 3.0.0+ with gradle 4.1+.

Please, take a lok at documentation:

https://developer.android.com/studio/releases/gradle-plugin.html

Gradle plugin: build.gradle project file

Gradle: gradle-wrapper.properties file

Body:
I am getting this error during gradle build in android studio. And I am unable to figure out what I am missing.

Error:Could not find com.android.tools.build:gradle:2.3.3. Searched in the
    following locations:
    file:/C:/Program Files/Android/Android
    Studio/gradle/m2repository/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom

    file:/C:/Program Files/Android/Android
    Studio/gradle/m2repository/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.jar

    https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.pom

    https://maven.google.com/com/android/tools/build/gradle/2.3.3/gradle-2.3.3.jar

Here is my build.gradlefile configuration

`
all sub-projects/modules.
    allprojects {
        repositories {
            jcenter()
            maven {
                url "https://maven.google.com"
            }
            maven {
                url 'https://jitpack.io'
            }
        }
    }

    buildscript {
        dependencies {
            classpath 'com.android.tools.build:gradle:2.3.3'
        }
        repositories {
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
        }
    }

    ext {
        supportlib_version = '26.0.2'
        gps_version = '11.2.0'
    }

    //Ensure that all dependencies use the same version of the Android Support library
    subprojects {
        project.configurations.all {
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'com.android.support'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "$supportlib_version"
                }
                if (details.requested.group == 'com.google.android.gms'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "$gps_version"
                }
            }
        }
    }

    allprojects {
        repositories {
            jcenter()
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
        }
    }
`

Could you help me what am I missing?


问:
Azure continuous webjob fails in some cases
I have a continuous webjob that is running on azure that after a larger deployment 8 hours ago gets the status never finished in some cases and in other cases completed the job.
I have enabled all logging I could find and have been spending quite a few hours trying to figure out what the problem is.

The only log error information I seem to be able to find is from the job_log which states:

[11/15/2017 14:46:23 > e553e5: ERR ] Unhandled Exception: Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (404) Not Found. ---> System.Net.WebException: The remote server returned an error: (404) Not Found.
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Shared.Protocol.HttpResponseParsers.ProcessExpectedStatusCodeNoException[T](HttpStatusCode expectedStatusCode, HttpStatusCode actualStatusCode, T retVal, StorageCommandBase1 cmd, Exception ex) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\Common\Shared\Protocol\HttpResponseParsers.Common.cs:line 50
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Blob.CloudBlob.<DeleteBlobImpl>b__33(RESTCommand1 cmd, HttpWebResponse resp, Exception ex, OperationContext ctx) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlob.cs:line 3349
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndGetResponse[T](IAsyncResult getResponseResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 299
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of inner exception stack trace ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndExecuteAsync[T](IAsyncResult result) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 50
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Blob.CloudBlob.EndDelete(IAsyncResult asyncResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlob.cs:line 1729
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.<>c__DisplayClass4.b__3(IAsyncResult ar) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Util\AsyncExtensions.cs:line 114
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Protocols.PersistentQueueWriter1.<DeleteAsync>d__6.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Loggers.CompositeFunctionInstanceLogger.<DeleteLogFunctionStartedAsync>d__e.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.<TryExecuteAsync>d__1.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Executors.TriggeredFunctionExecutor1.d__0.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Timers.BackgroundExceptionDispatcher.<>c__DisplayClass1.b__0()
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ThreadHelper.ThreadStart()

Can anyone give me some ideas on how to debug this, because I am out of ideas.

My webjobs main looks like this:

```<code> static void Main()
    {
         var host = new JobHost();

        var config = new JobHostConfiguration();
        config.Queues.MaxPollingInterval = new TimeSpan(0,0,0,30);
        config.Queues.MaxDequeueCount = 3;
        // The following code ensures that the WebJob will be running continuously
        host.RunAndBlock();
    }
</code>```

and the processqueuemessage looks like:

```<code> public static void ProcessQueueMessage([QueueTrigger("importqueue")] string msg)
    {
        try
        {
            WorkerWebJobCore wwjc = new WorkerWebJobCore();
            wwjc.RunCore(msg, TableStorageAccessResources.ImportQueue,
                TableStorageAccessResources.TableStorageDataOneId,
                TableStorageAccessResources.TableStorageDataOnePassword);
        }
        catch (Exception e)
        {
            CommunicatorLog.Log.LogError("WebJobWorker","WebJobWorker","Error in processing queue message","ERRWJWF01");
        }
    }
</code>```

So I have a catch around everything, therefore I don't get how it can fail?

Thanks in advance.

答:
My guess would be that something is either messing with your queue or with the files in the storage itself.

Looks like it tries to delete files that are no longer there. Or maybe something "larger" is being deleted.

Upon looking deeper into it, it might also be an issue with how you deploy your WebJob. Maybe there is a difference sometimes when you deploy? Take a look at these:

Azure Web Job-The remote server returned 404

https://github.com/Azure/azure-webjobs-sdk/issues/922

Azure WebJob QueueTrigger message is not deleted from queue

https://github.com/Azure/azure-webjobs-sdk/issues/645

Body:
I have a continuous webjob that is running on azure that after a larger deployment 8 hours ago gets the status never finished in some cases and in other cases completed the job.
I have enabled all logging I could find and have been spending quite a few hours trying to figure out what the problem is.

The only log error information I seem to be able to find is from the job_log which states:

[11/15/2017 14:46:23 > e553e5: ERR ] Unhandled Exception: Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (404) Not Found. ---> System.Net.WebException: The remote server returned an error: (404) Not Found.
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Shared.Protocol.HttpResponseParsers.ProcessExpectedStatusCodeNoException[T](HttpStatusCode expectedStatusCode, HttpStatusCode actualStatusCode, T retVal, StorageCommandBase1 cmd, Exception ex) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\Common\Shared\Protocol\HttpResponseParsers.Common.cs:line 50
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Blob.CloudBlob.<DeleteBlobImpl>b__33(RESTCommand1 cmd, HttpWebResponse resp, Exception ex, OperationContext ctx) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlob.cs:line 3349
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndGetResponse[T](IAsyncResult getResponseResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 299
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of inner exception stack trace ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.EndExecuteAsync[T](IAsyncResult result) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 50
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Blob.CloudBlob.EndDelete(IAsyncResult asyncResult) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlob.cs:line 1729
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.WindowsAzure.Storage.Core.Util.AsyncExtensions.<>c__DisplayClass4.b__3(IAsyncResult ar) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Util\AsyncExtensions.cs:line 114
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Protocols.PersistentQueueWriter1.<DeleteAsync>d__6.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Loggers.CompositeFunctionInstanceLogger.<DeleteLogFunctionStartedAsync>d__e.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.<TryExecuteAsync>d__1.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Executors.TriggeredFunctionExecutor1.d__0.MoveNext()
  [11/15/2017 14:46:23 > e553e5: ERR ] --- End of stack trace from previous location where exception was thrown ---
  [11/15/2017 14:46:23 > e553e5: ERR ] at Microsoft.Azure.WebJobs.Host.Timers.BackgroundExceptionDispatcher.<>c__DisplayClass1.b__0()
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
  [11/15/2017 14:46:23 > e553e5: ERR ] at System.Threading.ThreadHelper.ThreadStart()

Can anyone give me some ideas on how to debug this, because I am out of ideas.

My webjobs main looks like this:

 static void Main()
    {
         var host = new JobHost();

        var config = new JobHostConfiguration();
        config.Queues.MaxPollingInterval = new TimeSpan(0,0,0,30);
        config.Queues.MaxDequeueCount = 3;
        // The following code ensures that the WebJob will be running continuously
        host.RunAndBlock();
    }

and the processqueuemessage looks like:

 public static void ProcessQueueMessage([QueueTrigger("importqueue")] string msg)
    {
        try
        {
            WorkerWebJobCore wwjc = new WorkerWebJobCore();
            wwjc.RunCore(msg, TableStorageAccessResources.ImportQueue,
                TableStorageAccessResources.TableStorageDataOneId,
                TableStorageAccessResources.TableStorageDataOnePassword);
        }
        catch (Exception e)
        {
            CommunicatorLog.Log.LogError("WebJobWorker","WebJobWorker","Error in processing queue message","ERRWJWF01");
        }
    }

So I have a catch around everything, therefore I don't get how it can fail?

Thanks in advance.


答:
The query has to use single quotes while specifying the filter text i.e vsdep980.

Edit: Looking at the code I saw that the command is executed using ExecuteScalar. ExecuteScalar executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

Since the first column is testname it'll return a string that cannot be converted to an integer. Rethink what you want to do with the return value and change it accordingly

Title: getting error on sql query in asp.net using c#


问:
A Tool for Comparing Result Sets From Stored Procedures Across Multiple Databases - SQL Server 2008
We are updating numerous stored procedures that touch nearly every transaction in our database.  What I'm wondering is if there is a tool out there where we could have it run the two stored procedures on multiple databases and compare the results sets, not only on if the data is the same, but also compare if the returning data has the same attributes (field returns 1 and it is an Integer for one stored procedure, but it is a Bit in the other).

Currently, I am logging into a remote database, running the stored procedures and pasting the results in Excel.  Then, I run a Macro to see if the data matches.

I'd like to find a tool that I could set up to log in, run the stored procedures and do the compare without my doing it manually.

答:
Not sure if you truly mean "across multiple databases" or "across multiple servers".  If its a server you'll need to add linked servers.

The stored proc below will compare the output resultset of 2 stored procedures, or 2 statements. Doesn't need to know the schema of the result set, but the 2 input statements must have identical schemas.  It will return 0 rows if the output is the same.  This solution uses openrowset command in SQL Server.
Here is some sample usage of the Stored proc

```<code>    -- Sample Usage, works for both Queries and Stored Procs
    DECLARE @SQL_SP1 VARCHAR(MAX)
    DECLARE @SQL_SP2 VARCHAR(MAX)

    -- Compare results of 2 Stored Procs
    SET @SQL_SP1 = 'EXEC SomeDB.dbo.[usp_GetWithTheProgram_OLD] 100, ''SomeParamX'''
    SET @SQL_SP1 = 'EXEC SomeDB.dbo.[usp_GetWithTheProgram_NEW] 50, ''SomeParamX'''
    EXEC utlCompareStatementResults @SQL_SP1, @SQL_SP2

    -- Compare just 2 SQL Statements
    SET @SQL_SP1 = 'SELECT * FROM SomeDB.dbo.Table1 WHERE CreatedOn > ''2016-05-08'''
    SET @SQL_SP1 = 'SELECT * FROM SomeDB.dbo.Table1 WHERE CreatedOn > ''2016-06-11'''
    EXEC utlCompareStatementResults @SQL_SP1, @SQL_SP2
</code>```

The SP requires the following prerequisites because it uses openrowset, which may not be ideal for a production environment.

```<code>   -- Code uses openrowset so needs some special permissions
   EXEC sp_configure 'show advanced options', 1
   EXEC sp_configure 'ad hoc distributed queries', 1
   EXEC sp_serveroption @@SERVERNAME, 'DATA ACCESS', TRUE
</code>```

Here is the code for the stored proc.

```<code>==================================================================================
    --== SUMMARY utlCompareStatementResults
    --==    Compares output of 2 queries or stored procs
    --==    - requires sp_configure 'show advanced options', 1
    --==    - requires sp_configure 'ad hoc distributed queries', 1
    --==    - maybe requires EXEC sp_serveroption @@SERVERNAME, 'DATA ACCESS', TRUE
    --==    - requires the RecordSet Output to have Unique ColumnNames (no duplicate columns)
    --==    - requires references in straight SQL to be fully qualified [dbname].[schema].[objects] but not within an SP
    --==    - requires references SP call to be fully qualifed [dbname].[schema].[spname] but not objects with the SP
    --== OUTPUT
    --==    Differences are returned
    --==    If there is no recordset returned, then theres no differences
    --==    However if you are comparing 2 empty recordsets, it doesn't mean anything
    --== USAGE
    --==   DECLARE @SQL_SP1 VARCHAR(MAX)
    --==   DECLARE @SQL_SP2 VARCHAR(MAX)
    --==   -- Compare just 2 SQL Statements
    --==   SET @SQL_SP1 = 'SELECT * FROM SomeDB.dbo.Table1 WHERE CreatedOn > ''2016-05-08'''
    --==   SET @SQL_SP1 = 'SELECT * FROM SomeDB.dbo.Table1 WHERE CreatedOn > ''2016-06-11'''
    --==   EXEC utlCompareStatementResults @SQL_SP1, @SQL_SP2
    --==
    --==   -- Compare results of 2 Stored Procs
    --==   SET @SQL_SP1 = 'EXEC SomeDB.dbo.[usp_GetWithTheProgram_OLD] 100, ''SomeParamX'''
    --==   SET @SQL_SP1 = 'EXEC SomeDB.dbo.[usp_GetWithTheProgram_NEW] 50, ''SomeParamX'''
    --==   EXEC utlCompareStatementResults @SQL_SP1, @SQL_SP2
    --==================================================================================
    CREATE PROCEDURE utlCompareStatementResults
       @SQL_SP1 VARCHAR(MAX),
       @SQL_SP2 VARCHAR(MAX)
    AS
    BEGIN
        DECLARE @TABLE1 VARCHAR(200)
        DECLARE @TABLE2 VARCHAR(200)
        DECLARE @SQL_OPENROWSET VARCHAR(MAX)
        DECLARE @CONNECTION VARCHAR(100)

        SET @CONNECTION = 'server='+@@SERVERNAME+';Trusted_Connection=yes'

        SET @SQL_SP1 = REPLACE(@SQL_SP1, '''','''''')
        SET @SQL_SP2 = REPLACE(@SQL_SP2, '''','''''')

        SET @TABLE1 = '#' + SUBSTRING(CONVERT(VARCHAR(250),NEWID()), 1, 8)
        SET @TABLE2 = '#' + SUBSTRING(CONVERT(VARCHAR(250),NEWID()), 1, 8)

        SET @SQL_OPENROWSET =
        'SELECT * ' + ' ' +
        'INTO ' + @TABLE1 + ' ' +
        'FROM OPENROWSET(''SQLNCLI'', ' + '''' + @CONNECTION + '''' +
                        ',''' + @SQL_SP1 +'''); ' +
        'SELECT * ' + ' ' +
        'INTO ' + @TABLE2 + ' ' +
        'FROM OPENROWSET(''SQLNCLI'', ' + '''' + @CONNECTION + '''' +
                        ',''' + @SQL_SP2 +'''); ' +
        '(SELECT * FROM ' + @TABLE1 + ' EXCEPT SELECT * FROM ' + @TABLE2 + ') '  +
        ' UNION ALL ' +
        '(SELECT * FROM ' + @TABLE2 + ' EXCEPT SELECT * FROM ' + @TABLE1 + '); ' +
        'DROP TABLE ' + @TABLE1 + '; ' +
        'DROP TABLE ' + @TABLE2 + '; '
        PRINT @SQL_OPENROWSET
        EXEC (@SQL_OPENROWSET)
        PRINT 'DifferenceCount: ' + CONVERT(VARCHAR(100), @@ROWCOUNT)
    END
</code>```

Body:
Not sure if you truly mean "across multiple databases" or "across multiple servers".  If its a server you'll need to add linked servers.

The stored proc below will compare the output resultset of 2 stored procedures, or 2 statements. Doesn't need to know the schema of the result set, but the 2 input statements must have identical schemas.  It will return 0 rows if the output is the same.  This solution uses openrowset command in SQL Server.
Here is some sample usage of the Stored proc

    -- Sample Usage, works for both Queries and Stored Procs
    DECLARE @SQL_SP1 VARCHAR(MAX)
    DECLARE @SQL_SP2 VARCHAR(MAX)

    -- Compare results of 2 Stored Procs
    SET @SQL_SP1 = 'EXEC SomeDB.dbo.[usp_GetWithTheProgram_OLD] 100, ''SomeParamX'''
    SET @SQL_SP1 = 'EXEC SomeDB.dbo.[usp_GetWithTheProgram_NEW] 50, ''SomeParamX'''
    EXEC utlCompareStatementResults @SQL_SP1, @SQL_SP2

    -- Compare just 2 SQL Statements
    SET @SQL_SP1 = 'SELECT * FROM SomeDB.dbo.Table1 WHERE CreatedOn > ''2016-05-08'''
    SET @SQL_SP1 = 'SELECT * FROM SomeDB.dbo.Table1 WHERE CreatedOn > ''2016-06-11'''
    EXEC utlCompareStatementResults @SQL_SP1, @SQL_SP2

The SP requires the following prerequisites because it uses openrowset, which may not be ideal for a production environment.

   -- Code uses openrowset so needs some special permissions
   EXEC sp_configure 'show advanced options', 1
   EXEC sp_configure 'ad hoc distributed queries', 1
   EXEC sp_serveroption @@SERVERNAME, 'DATA ACCESS', TRUE

Here is the code for the stored proc.

==================================================================================
    --== SUMMARY utlCompareStatementResults
    --==    Compares output of 2 queries or stored procs
    --==    - requires sp_configure 'show advanced options', 1
    --==    - requires sp_configure 'ad hoc distributed queries', 1
    --==    - maybe requires EXEC sp_serveroption @@SERVERNAME, 'DATA ACCESS', TRUE
    --==    - requires the RecordSet Output to have Unique ColumnNames (no duplicate columns)
    --==    - requires references in straight SQL to be fully qualified [dbname].[schema].[objects] but not within an SP
    --==    - requires references SP call to be fully qualifed [dbname].[schema].[spname] but not objects with the SP
    --== OUTPUT
    --==    Differences are returned
    --==    If there is no recordset returned, then theres no differences
    --==    However if you are comparing 2 empty recordsets, it doesn't mean anything
    --== USAGE
    --==   DECLARE @SQL_SP1 VARCHAR(MAX)
    --==   DECLARE @SQL_SP2 VARCHAR(MAX)
    --==   -- Compare just 2 SQL Statements
    --==   SET @SQL_SP1 = 'SELECT * FROM SomeDB.dbo.Table1 WHERE CreatedOn > ''2016-05-08'''
    --==   SET @SQL_SP1 = 'SELECT * FROM SomeDB.dbo.Table1 WHERE CreatedOn > ''2016-06-11'''
    --==   EXEC utlCompareStatementResults @SQL_SP1, @SQL_SP2
    --==
    --==   -- Compare results of 2 Stored Procs
    --==   SET @SQL_SP1 = 'EXEC SomeDB.dbo.[usp_GetWithTheProgram_OLD] 100, ''SomeParamX'''
    --==   SET @SQL_SP1 = 'EXEC SomeDB.dbo.[usp_GetWithTheProgram_NEW] 50, ''SomeParamX'''
    --==   EXEC utlCompareStatementResults @SQL_SP1, @SQL_SP2
    --==================================================================================
    CREATE PROCEDURE utlCompareStatementResults
       @SQL_SP1 VARCHAR(MAX),
       @SQL_SP2 VARCHAR(MAX)
    AS
    BEGIN
        DECLARE @TABLE1 VARCHAR(200)
        DECLARE @TABLE2 VARCHAR(200)
        DECLARE @SQL_OPENROWSET VARCHAR(MAX)
        DECLARE @CONNECTION VARCHAR(100)

        SET @CONNECTION = 'server='+@@SERVERNAME+';Trusted_Connection=yes'

        SET @SQL_SP1 = REPLACE(@SQL_SP1, '''','''''')
        SET @SQL_SP2 = REPLACE(@SQL_SP2, '''','''''')

        SET @TABLE1 = '#' + SUBSTRING(CONVERT(VARCHAR(250),NEWID()), 1, 8)
        SET @TABLE2 = '#' + SUBSTRING(CONVERT(VARCHAR(250),NEWID()), 1, 8)

        SET @SQL_OPENROWSET =
        'SELECT * ' + ' ' +
        'INTO ' + @TABLE1 + ' ' +
        'FROM OPENROWSET(''SQLNCLI'', ' + '''' + @CONNECTION + '''' +
                        ',''' + @SQL_SP1 +'''); ' +
        'SELECT * ' + ' ' +
        'INTO ' + @TABLE2 + ' ' +
        'FROM OPENROWSET(''SQLNCLI'', ' + '''' + @CONNECTION + '''' +
                        ',''' + @SQL_SP2 +'''); ' +
        '(SELECT * FROM ' + @TABLE1 + ' EXCEPT SELECT * FROM ' + @TABLE2 + ') '  +
        ' UNION ALL ' +
        '(SELECT * FROM ' + @TABLE2 + ' EXCEPT SELECT * FROM ' + @TABLE1 + '); ' +
        'DROP TABLE ' + @TABLE1 + '; ' +
        'DROP TABLE ' + @TABLE2 + '; '
        PRINT @SQL_OPENROWSET
        EXEC (@SQL_OPENROWSET)
        PRINT 'DifferenceCount: ' + CONVERT(VARCHAR(100), @@ROWCOUNT)
    END


问:
merging datastreams of two different types in Flink or any other system
I want to use Flink for a remote patient monitoring case scenario which includes various sensors like gyroscope, accelerometer, ECG Stream, HR rate stream, RR rate etc. So in this case scenario it's not possible that we should have the same data type or input rate etc, but still I want to detect arrhythmia or other medical condition which involves doing CEP on these multiple sensors

What I know is that ,If I want to perform some complex event processing on these sensors,  then I have 2 options that needs to be done before the CEP

Join  diff streams

merge  diff streams

Earlier I was performing a join based upon timestamps of sensors, but it does not result in joining all the events as diff streams can have diff rates and different timestamps in microseconds, so it will be a rare case such that the timestamps are exactly equal.

So I would like to go with option # 2 i.e performing a merge before doing CEP. for doing this, I have found on Flink documentation, that I can merge the two streams  but they should have same data type, I  tried to do the same but I am unsuccessful as I got following error

```<code>  Exception in thread "main" java.lang.IllegalArgumentException: Cannot union streams of different types: GenericType<org.carleton.cep.monitoring.latest.Events.RRIntervalStreamEvent> and GenericType<org.carleton.cep.monitoring.latest.Events.qrsIntervalStreamEvent>
    at org.apache.flink.streaming.api.datastream.DataStream.union(DataStream.java:217)
</code>```

Now let's see how I tried to perform a merge. So basically I had two stream classes, their attributes are as follows

RRIntervalStreamEvent Stream

```<code>public Integer Sensor_id;
public Long time;
public Integer RRInterval;
</code>```

qrsIntervalStreamEvent Stream

```<code>public Integer Sensor_id;
public Long time;
public Integer qrsInterval;
</code>```

Both of these streams have generators classes which also sends the events at in same data types at the specified rate.Below is code by which I tried to merge them.

```<code>// getting qrs interval stream
   DataStream<qrsIntervalStreamEvent> qrs_stream_raw = envrionment.
                    addSource(new Qrs_interval_Gen(input_rate_qrs_S,Total_Number_Of_Events_in_qrs)).name("qrs stream");

// getting RR interval stream
 DataStream<RRIntervalStreamEvent> rr_stream_raw = envrionment.
                         addSource(new RR_interval_Gen(input_rate_rr_S,Total_Number_Of_Events_in_RR)).name("RR stream");

//merging both streams
 DataStream<Tuple3<Integer,Long,Integer>> mergedStream;
            mergedStream = rr_stream_raw.union(new DataStream[]{qrs_stream_raw});
</code>```

I have to use new DataStream[] as just using qrs_stream_raw was resulting in error as shown below.

Can someone please give me an idea about

how should I merge these two streams?

how should I merge more than two streams?

is there some engine which can merge more than two streams having different structures, if yes which  engine should I use

答:
As pointed out by Alex, we can use the same data type of both the streams and can join them in Flink, another option is to use Siddhi or Flink-Siddhi extension. But I want to do everything in Flink only

So here are couple of changes I made in my program to make it work

Step # 1: made both of my generator classes to return common type

```<code>public class RR_interval_Gen extends RichParallelSourceFunction<Tuple3<Integer,Long, Integer>>
</code>```

step# 2: made both of stream generators to have Tuple types and then merged 2 streams.

```<code> // getting qrs interval stream
    DataStream<Tuple3<Integer,Long,Integer>> qrs_stream_raw = envrionment.
            addSource(new Qrs_interval_Gen(input_rate_qrs_S,Total_Number_Of_Events_in_qrs)).name("qrs stream");

    // getting RR interval stream
         DataStream<Tuple3<Integer,Long,Integer>> rr_stream_raw = envrionment.
                 addSource(new RR_interval_Gen(input_rate_rr_S,Total_Number_Of_Events_in_RR)).name("RR stream");

         //merging both streams
    DataStream<Tuple3<Integer,Long,Integer>> mergedStream = rr_stream_raw.union(qrs_stream_raw);
</code>```

Body:
I want to use Flink for a remote patient monitoring case scenario which includes various sensors like gyroscope, accelerometer, ECG Stream, HR rate stream, RR rate etc. So in this case scenario it's not possible that we should have the same data type or input rate etc, but still I want to detect arrhythmia or other medical condition which involves doing CEP on these multiple sensors

What I know is that ,If I want to perform some complex event processing on these sensors,  then I have 2 options that needs to be done before the CEP

Join  diff streams

merge  diff streams

Earlier I was performing a join based upon timestamps of sensors, but it does not result in joining all the events as diff streams can have diff rates and different timestamps in microseconds, so it will be a rare case such that the timestamps are exactly equal.

So I would like to go with option # 2 i.e performing a merge before doing CEP. for doing this, I have found on Flink documentation, that I can merge the two streams  but they should have same data type, I  tried to do the same but I am unsuccessful as I got following error

  Exception in thread "main" java.lang.IllegalArgumentException: Cannot union streams of different types: GenericType<org.carleton.cep.monitoring.latest.Events.RRIntervalStreamEvent> and GenericType<org.carleton.cep.monitoring.latest.Events.qrsIntervalStreamEvent>
    at org.apache.flink.streaming.api.datastream.DataStream.union(DataStream.java:217)

Now let's see how I tried to perform a merge. So basically I had two stream classes, their attributes are as follows

RRIntervalStreamEvent Stream

public Integer Sensor_id;
public Long time;
public Integer RRInterval;

qrsIntervalStreamEvent Stream

public Integer Sensor_id;
public Long time;
public Integer qrsInterval;

Both of these streams have generators classes which also sends the events at in same data types at the specified rate.Below is code by which I tried to merge them.

// getting qrs interval stream
   DataStream<qrsIntervalStreamEvent> qrs_stream_raw = envrionment.
                    addSource(new Qrs_interval_Gen(input_rate_qrs_S,Total_Number_Of_Events_in_qrs)).name("qrs stream");

// getting RR interval stream
 DataStream<RRIntervalStreamEvent> rr_stream_raw = envrionment.
                         addSource(new RR_interval_Gen(input_rate_rr_S,Total_Number_Of_Events_in_RR)).name("RR stream");

//merging both streams
 DataStream<Tuple3<Integer,Long,Integer>> mergedStream;
            mergedStream = rr_stream_raw.union(new DataStream[]{qrs_stream_raw});

I have to use new DataStream[] as just using qrs_stream_raw was resulting in error as shown below.

Can someone please give me an idea about

how should I merge these two streams?

how should I merge more than two streams?

is there some engine which can merge more than two streams having different structures, if yes which  engine should I use

Body:
As pointed out by Alex, we can use the same data type of both the streams and can join them in Flink, another option is to use Siddhi or Flink-Siddhi extension. But I want to do everything in Flink only

So here are couple of changes I made in my program to make it work

Step # 1: made both of my generator classes to return common type

public class RR_interval_Gen extends RichParallelSourceFunction<Tuple3<Integer,Long, Integer>>

step# 2: made both of stream generators to have Tuple types and then merged 2 streams.

 // getting qrs interval stream
    DataStream<Tuple3<Integer,Long,Integer>> qrs_stream_raw = envrionment.
            addSource(new Qrs_interval_Gen(input_rate_qrs_S,Total_Number_Of_Events_in_qrs)).name("qrs stream");

    // getting RR interval stream
         DataStream<Tuple3<Integer,Long,Integer>> rr_stream_raw = envrionment.
                 addSource(new RR_interval_Gen(input_rate_rr_S,Total_Number_Of_Events_in_RR)).name("RR stream");

         //merging both streams
    DataStream<Tuple3<Integer,Long,Integer>> mergedStream = rr_stream_raw.union(qrs_stream_raw);


问:
Quagga Javascript Barcode Scanner
Is there a way to scan Code 39 and UPC at the same time without changing the barcode type from the options? I tried adding both of them to active barcodes list. Still without changing the option to UPC or Code 39, it is not scanning</p>

答:
I left you some questions with the details you should have given so people can help you more easily but I'll try to answer what I think that your question is. Not sure.

I think you ask why you need to set the reader engine before reading a barcode. I just read the docs for a minute and it is answered there:

Inside the decoder section:

"The most important property is readers which takes an array of types of barcodes which should be decoded during the session.

(...)

Why are not all types activated by default? Simply because one
  should explicitly define the set of barcodes for their use-case. More
  decoders means more possible clashes, or false-positives. One should
  take care of the order the readers are given, since some might return
  a value even though it is not the correct type (EAN-13 vs. UPC-A).

The multiple property tells the decoder if it should continue decoding
  after finding a valid barcode. If multiple is set to true, the results
  will be returned as an array of result objects. Each object in the
  array will have a box, and may have a codeResult depending on the
  success of decoding the individual box."

You need to use a config like this one with several readers:

```<code>{
  readers: [
    'code_39_reader',
    'code_39_vin_reader',
    'upc_reader',
    'upc_e_reader'
  ]
  multiple: false
}
</code>```

Title: Quagga Javascript Barcode Scanner

Body:
I left you some questions with the details you should have given so people can help you more easily but I'll try to answer what I think that your question is. Not sure.

I think you ask why you need to set the reader engine before reading a barcode. I just read the docs for a minute and it is answered there:

Inside the decoder section:

"The most important property is readers which takes an array of types of barcodes which should be decoded during the session.

(...)

Why are not all types activated by default? Simply because one
  should explicitly define the set of barcodes for their use-case. More
  decoders means more possible clashes, or false-positives. One should
  take care of the order the readers are given, since some might return
  a value even though it is not the correct type (EAN-13 vs. UPC-A).

The multiple property tells the decoder if it should continue decoding
  after finding a valid barcode. If multiple is set to true, the results
  will be returned as an array of result objects. Each object in the
  array will have a box, and may have a codeResult depending on the
  success of decoding the individual box."

You need to use a config like this one with several readers:

{
  readers: [
    'code_39_reader',
    'code_39_vin_reader',
    'upc_reader',
    'upc_e_reader'
  ]
  multiple: false
}


问:
Matlab to calculate a spectral line parameter for each layer
I need to calculate a parameter defined as x,( this is defined in my code below) for the given spectral lines in each layer. My atmospheric profile has 10 layers. I know how to calculate x for just one layer. Then I get 5 values for x corresponding to each spectral line ( or wavelength) .
Suppose I want to do this for all 10 layers. Then my output should have 10 rows and 5 columns , size should be (10,5) , 10 represent number of the layer and 5 represent the spectral line. Any suggestion would be greatly appreciated

```<code>wl=[100 200 300 400 500]; %5 wavelengths, 5 spectral lines
br=[0.12 0.56 0.45 0.67 0.89]; % broadening parameter for each wavelength

p=[1 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 ];    % pressure for 10 layers

T=[101 102 103 104 105 106 107 108 109 110];   % temperature for 10 layers

%suppose I want to caculate a parameter, x for all the layers
% x is defined as,( wavelength*br*T)/p
%when I do the calculation for the first layer,I have to consider all the
%wavelengths , all the broadening parameters and only the first value of
%pressure and only the first value of temperature

 for i=1:5;
     x(i)= (wl(i)*br(i)*T(1))/p(1);
 end
% x is the x parameter for all the wavelengths in the first layer
%Now I want to calculate the x parameter for all the wavelengths in all 10
%layers
%my output should have 10 rows for 10 layers and  5 columns , size= (10,5)
</code>```

Body:
I need to calculate a parameter defined as x,( this is defined in my code below) for the given spectral lines in each layer. My atmospheric profile has 10 layers. I know how to calculate x for just one layer. Then I get 5 values for x corresponding to each spectral line ( or wavelength) .
Suppose I want to do this for all 10 layers. Then my output should have 10 rows and 5 columns , size should be (10,5) , 10 represent number of the layer and 5 represent the spectral line. Any suggestion would be greatly appreciated

wl=[100 200 300 400 500]; %5 wavelengths, 5 spectral lines
br=[0.12 0.56 0.45 0.67 0.89]; % broadening parameter for each wavelength

p=[1 0.9 0.8 0.7 0.6 0.5 0.4 0.3 0.2 0.1 ];    % pressure for 10 layers

T=[101 102 103 104 105 106 107 108 109 110];   % temperature for 10 layers

%suppose I want to caculate a parameter, x for all the layers
% x is defined as,( wavelength*br*T)/p
%when I do the calculation for the first layer,I have to consider all the
%wavelengths , all the broadening parameters and only the first value of
%pressure and only the first value of temperature

 for i=1:5;
     x(i)= (wl(i)*br(i)*T(1))/p(1);
 end
% x is the x parameter for all the wavelengths in the first layer
%Now I want to calculate the x parameter for all the wavelengths in all 10
%layers
%my output should have 10 rows for 10 layers and  5 columns , size= (10,5)

Body:
you don't need loops for this case

>> (T./p)'*(wl.*br)

ans =

   1.0e+05 *

    0.0121    0.1131    0.1364    0.2707    0.4495
    0.0136    0.1269    0.1530    0.3037    0.5043
    0.0155    0.1442    0.1738    0.3451    0.5729
    0.0178    0.1664    0.2006    0.3982    0.6611
    0.0210    0.1960    0.2362    0.4690    0.7788
    0.0254    0.2374    0.2862    0.5682    0.9434
    0.0321    0.2996    0.3611    0.7169    1.1904
    0.0432    0.4032    0.4860    0.9648    1.6020
    0.0654    0.6104    0.7358    1.4606    2.4253
    0.1320    1.2320    1.4850    2.9480    4.8950


问:
Pre checking/selecting radio button in IE7
I have a page with radio button which need to be prefilled on page load ...my code works perfectly in firefox , IE8 and IE7 in IE8 but when I am trying IE7 pure environment ...radio button is not prefilled whereas disable the radio works perfectly ....
   any help will be appreciated.

Thanks!

edit1: code

```<code>main.disable = function($cntrl, flag){
    if($cntrl.attr('type')=== "radio"){
       var ctrls = document.getElementByName($cntrl.attr('name'));
       for(var idx = 0 ; idx < ctrls.length; idx++){
            ctrls[idx].disabled = flag;
      }
   else{
       $cntrl.disabled = flag;
}
};
main.getControlById = function(id, context){
  if(id.search("{") > 0){
    id = main.fillTem(id, context);
}

return $(document.getElementById(id));
};

behave.addRule("abc","Enable/disable aa", function(){
var $ab = main.getControlById(a.ab, this);

        if( supp !== undefined && supp !== null){
            if(supp.ab === 'A' || supp.A === 'N'){
               main.disable($ab, false);
}
else{
   main.disable($ab, false);
}
}

else{
main.disable($ab, false);
}
});
</code>```

答:
I suspect that you're running your code before the page has finished rendering. IE7 is slower at rendering pages than IE8.

If you JS code is before your HTML and you're not using $(document).ready(function() { .... }) to invoke it then the cart is before the horse.

Body:
I have a page with radio button which need to be prefilled on page load ...my code works perfectly in firefox , IE8 and IE7 in IE8 but when I am trying IE7 pure environment ...radio button is not prefilled whereas disable the radio works perfectly ....
   any help will be appreciated.

Thanks!

edit1: code

main.disable = function($cntrl, flag){
    if($cntrl.attr('type')=== "radio"){
       var ctrls = document.getElementByName($cntrl.attr('name'));
       for(var idx = 0 ; idx < ctrls.length; idx++){
            ctrls[idx].disabled = flag;
      }
   else{
       $cntrl.disabled = flag;
}
};
main.getControlById = function(id, context){
  if(id.search("{") > 0){
    id = main.fillTem(id, context);
}

return $(document.getElementById(id));
};

behave.addRule("abc","Enable/disable aa", function(){
var $ab = main.getControlById(a.ab, this);

        if( supp !== undefined && supp !== null){
            if(supp.ab === 'A' || supp.A === 'N'){
               main.disable($ab, false);
}
else{
   main.disable($ab, false);
}
}

else{
main.disable($ab, false);
}
});

ContentLicense: CC BY-SA 2.5


问:
How to convert the string into ASCII Values in array and add those elements in Swift?
How to convert this string "RAHUL" into ASCII Values in array and adding all the elements of array.</p>

```<code>var myString: String = "RAHUL"

for scalar in myString.unicodeScalars
{
    print(scalar.value)
    var num = scalar.value
}
</code>```

答:
Just convert the num to a Int and add them to an array:

```<code>var myString: String = "RAHUL"
var asciiArray = [Int]()

for scalar in myString.unicodeScalars
{
    var num = Int(scalar.value)
    asciiArray.append(num)
}

print(asciiArray)    //Prints [82, 65, 72, 85, 76]
</code>```

Body:
How to convert this string "RAHUL" into ASCII Values in array and adding all the elements of array.

var myString: String = "RAHUL"

for scalar in myString.unicodeScalars
{
    print(scalar.value)
    var num = scalar.value
}

Body:
Just convert the num to a Int and add them to an array:

var myString: String = "RAHUL"
var asciiArray = [Int]()

for scalar in myString.unicodeScalars
{
    var num = Int(scalar.value)
    asciiArray.append(num)
}

print(asciiArray)    //Prints [82, 65, 72, 85, 76]


问:
Oracle: problems to insert simbol '&'
Im trying to insert the next query in Oracle SQL Developer

```<code>insert into table1 (specialString) values ("&&test");
</code>```

but The SQL ask me for a var value

how can I solve this?

答:
or... SET SCAN OFF, which tell's sql developer's statement/script engines to not do replacements for &'s

```<code>clear screen
drop table so;
set scan off
CREATE TABLE SO (WORDS VARCHAR2(256));
INSERT INTO SO VALUES ('&&test');
select * from so;
</code>```

Title: Oracle: problems to insert simbol '&'

Body:
Im trying to insert the next query in Oracle SQL Developer

insert into table1 (specialString) values ("&&test");

but The SQL ask me for a var value

how can I solve this?

Body:
or... SET SCAN OFF, which tell's sql developer's statement/script engines to not do replacements for &'s

clear screen
drop table so;
set scan off
CREATE TABLE SO (WORDS VARCHAR2(256));
INSERT INTO SO VALUES ('&&test');
select * from so;


问:
setting alert on custom metric in Application Insights
I need to set an alert on custom metric in Application Insights. For testing, I sent custom metric from a console app and then in Azure portal, set the alert on that custom metric. but when we will move the app to production, how we can make it work. I assume , during installation, we will need to set the alerts but I will be sending the custom metric through my application, so how I will set alert on that metric in the beginning which does not exists yet. </p>

答: John is correct. This is a desired behavior aimed at preventing customers from making an error when specifying the name of a metric and thus configuring and relying on an alert that will never fire.</p>


问:
Android Studio Coding Convention & Possible Context Error?
Right now I'm trying to become more familiar with Android development. Of course, I am using Android Studio to do this. As a project, I am writing an application to handle streaming from a URL with the MediaPlayer class.

I got this functional and does exactly what I need it to do. However, I did not want my MainActivity to be cluttered with methods and variables that could be stored in their own classes.

I have a couple questions about this:

Is it conventional to do this? Or should I keep all code and methods inside of their respective Activities, or is it conventional to move them to their own class, and access them from whichever Activity needs it?

I am having issues getting the MediaPlayer to work correctly when moving it to another class. I read that I must give the methods Context when calling that method. So I called the method using my object with Context passed, as you will see below.

I am fairly new to this sort of development, so tips, good habits, and helpful hints are always welcome.

Here is my MainActivity that calls the methods I put in the Streaming class:

```<code>public class MainActivity extends AppCompatActivity {

    Streaming stream = new Streaming(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    stream.updateSeekBar();
    stream.onPlayClick();
    stream.onDrag();

}
</code>```

You can see here, all of those methods I called:

```<code>public class Streaming extends AppCompatActivity {

private SeekBar musicSeek;
private TextView currentTime;
private TextView totalTime;
private ImageButton play_pause;
private Handler seekHandler = new Handler();
private MediaPlayer mp = new MediaPlayer();
Context context;
Utilities util = new Utilities();

//Default Constructor
public Streaming(){}
//Contructor
public Streaming(Context context){
    this.context = context;
}
//Method to run the runnable to update the seekbar
public void updateSeekBar(){
    seekHandler.postDelayed(mUpdateTimeTask, 100);
}

public void prepareStreaming() throws IOException {
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mp.setDataSource("http://tricountynaz.net/media/audio/2017-11-08-The%20Compassion%20of%20the%20Christ.mp3");
    mp.prepare();
}

public void startStreaming(){
    mp.start();
}

public void pauseStreaming(){
    mp.pause();
}

//Runnable to update the seekbar with the current position.
private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        int totalDuration = mp.getDuration();
        int currentPosition = (mp.getCurrentPosition());

        //Displaying Total Duration time
        totalTime = (TextView)((Activity)context).findViewById(R.id.totalTime);
        totalTime.setText(util.milliSecondsToTimer(totalDuration));
        // Displaying time completed playing
        currentTime = (TextView)((Activity)context).findViewById(R.id.currentTime);
        currentTime.setText(util.milliSecondsToTimer(currentPosition));
        //Set the bars total duration, based on the song duration (converted to seconds)
        musicSeek = (SeekBar)((Activity)context).findViewById(R.id.music_seek);
        musicSeek.setMax(totalDuration/1000);
        // Updating progress bar
        musicSeek.setProgress(mp.getCurrentPosition()/1000);

        // Running this thread after 100 milliseconds
        seekHandler.postDelayed(this, 100);
    }
};

//What happens when the user interacts with the button
public void onPlayClick (){
    play_pause = (ImageButton)((Activity)context).findViewById(R.id.playButton);
    play_pause.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            play_pause.setImageResource(R.drawable.ic_pause_name);

            try {
                prepareStreaming();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (mp.isPlaying()) {
                pauseStreaming();
                play_pause.setImageResource(R.drawable.ic_play_name);

            } else {
                //mediaPlayer.start();
                startStreaming();
            }
        }
    });
}

//Handles when the user interacts with the seekbar
public void onDrag(){
    musicSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            if(b) {
                //seeks to the current position of the slider when the user (b) interacts.
                mp.seekTo(i*1000);
                musicSeek.setProgress(i);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });}
</code>```

You will notice a Utilities class. This, at the moment, only holds a method to convert to seconds so I can update a TextView Item of the current progress of the MP3 being streamed.

The specific errors I am receiving are NullPointerException coming from the onDrag method. I cannot seem to understand why.

Sorry if this is a duplicate, I could not seem to find this anywhere else.

EDIT I did change my onDrag method a little:

```<code>//Handles when the user interacts with the seekbar
public void onDrag(){
    musicSeek = (SeekBar)((Activity)context).findViewById(R.id.music_seek);
    musicSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            if(b) {
                //seeks to the current position of the slider when the user (b) interacts.
                mp.seekTo(i*1000);
                musicSeek.setProgress(i);
            }
        }
</code>```

This did fix the nullPointerException, except now I get this errors in the log:

```<code>E/MediaPlayerNative: Attempt to call getDuration in wrong state: mPlayer=0x0, mCurrentState=0
</code>```

EDIT 2 I think I resolved my issue. Upon researching my most recent error, I had come to realize I never called my MediaPlayer in my MainActivity, therefore nothing was being loaded and nothing streamed. Here is where I found part of my solution.

Still running into issues with my playbutton not working and stream starting automatically, but this is a small problem and can be fixed easily I think. However, I would still be interested in knowing if there is something "wrong" with my code.

答:
Is it conventional to do this? Or should I keep all code and methods inside of their respective Activities, or is it conventional to move them to their own class, and access them from whichever Activity needs it?

Definitely use general software engineering principles and best practices. Design classes that are focused and serve a specific purpose. You should look at the new Architecture Components library. This has tools that allow you to create "life cycle aware" classes. These classes can be responsible for handling lifecycle events for their own resources rather than polluting the Activity with managing resources.

Comment

Generally, you should not initialize fields of an Activity class outside of the activity lifecycle. This can cause problems when you depend on resources which are available only at certain times in the lifecycle, such as views. In this case, initializing the Streaming object inline with its declaration probably won't cause any problems. Still it is best to get into the habit of treating onCreate() as the "constructor" and do all initializing in this method instead.

Body:
Right now I'm trying to become more familiar with Android development. Of course, I am using Android Studio to do this. As a project, I am writing an application to handle streaming from a URL with the MediaPlayer class.

I got this functional and does exactly what I need it to do. However, I did not want my MainActivity to be cluttered with methods and variables that could be stored in their own classes.

I have a couple questions about this:

Is it conventional to do this? Or should I keep all code and methods inside of their respective Activities, or is it conventional to move them to their own class, and access them from whichever Activity needs it?

I am having issues getting the MediaPlayer to work correctly when moving it to another class. I read that I must give the methods Context when calling that method. So I called the method using my object with Context passed, as you will see below.

I am fairly new to this sort of development, so tips, good habits, and helpful hints are always welcome.

Here is my MainActivity that calls the methods I put in the Streaming class:

public class MainActivity extends AppCompatActivity {

    Streaming stream = new Streaming(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    stream.updateSeekBar();
    stream.onPlayClick();
    stream.onDrag();

}

You can see here, all of those methods I called:

public class Streaming extends AppCompatActivity {

private SeekBar musicSeek;
private TextView currentTime;
private TextView totalTime;
private ImageButton play_pause;
private Handler seekHandler = new Handler();
private MediaPlayer mp = new MediaPlayer();
Context context;
Utilities util = new Utilities();

//Default Constructor
public Streaming(){}
//Contructor
public Streaming(Context context){
    this.context = context;
}
//Method to run the runnable to update the seekbar
public void updateSeekBar(){
    seekHandler.postDelayed(mUpdateTimeTask, 100);
}

public void prepareStreaming() throws IOException {
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mp.setDataSource("http://tricountynaz.net/media/audio/2017-11-08-The%20Compassion%20of%20the%20Christ.mp3");
    mp.prepare();
}

public void startStreaming(){
    mp.start();
}

public void pauseStreaming(){
    mp.pause();
}

//Runnable to update the seekbar with the current position.
private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        int totalDuration = mp.getDuration();
        int currentPosition = (mp.getCurrentPosition());

        //Displaying Total Duration time
        totalTime = (TextView)((Activity)context).findViewById(R.id.totalTime);
        totalTime.setText(util.milliSecondsToTimer(totalDuration));
        // Displaying time completed playing
        currentTime = (TextView)((Activity)context).findViewById(R.id.currentTime);
        currentTime.setText(util.milliSecondsToTimer(currentPosition));
        //Set the bars total duration, based on the song duration (converted to seconds)
        musicSeek = (SeekBar)((Activity)context).findViewById(R.id.music_seek);
        musicSeek.setMax(totalDuration/1000);
        // Updating progress bar
        musicSeek.setProgress(mp.getCurrentPosition()/1000);

        // Running this thread after 100 milliseconds
        seekHandler.postDelayed(this, 100);
    }
};

//What happens when the user interacts with the button
public void onPlayClick (){
    play_pause = (ImageButton)((Activity)context).findViewById(R.id.playButton);
    play_pause.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            play_pause.setImageResource(R.drawable.ic_pause_name);

            try {
                prepareStreaming();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (mp.isPlaying()) {
                pauseStreaming();
                play_pause.setImageResource(R.drawable.ic_play_name);

            } else {
                //mediaPlayer.start();
                startStreaming();
            }
        }
    });
}

//Handles when the user interacts with the seekbar
public void onDrag(){
    musicSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            if(b) {
                //seeks to the current position of the slider when the user (b) interacts.
                mp.seekTo(i*1000);
                musicSeek.setProgress(i);
            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });}

You will notice a Utilities class. This, at the moment, only holds a method to convert to seconds so I can update a TextView Item of the current progress of the MP3 being streamed.

The specific errors I am receiving are NullPointerException coming from the onDrag method. I cannot seem to understand why.

Sorry if this is a duplicate, I could not seem to find this anywhere else.

EDIT I did change my onDrag method a little:

//Handles when the user interacts with the seekbar
public void onDrag(){
    musicSeek = (SeekBar)((Activity)context).findViewById(R.id.music_seek);
    musicSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            if(b) {
                //seeks to the current position of the slider when the user (b) interacts.
                mp.seekTo(i*1000);
                musicSeek.setProgress(i);
            }
        }

This did fix the nullPointerException, except now I get this errors in the log:

E/MediaPlayerNative: Attempt to call getDuration in wrong state: mPlayer=0x0, mCurrentState=0

EDIT 2 I think I resolved my issue. Upon researching my most recent error, I had come to realize I never called my MediaPlayer in my MainActivity, therefore nothing was being loaded and nothing streamed. Here is where I found part of my solution.

Still running into issues with my playbutton not working and stream starting automatically, but this is a small problem and can be fixed easily I think. However, I would still be interested in knowing if there is something "wrong" with my code.


问:
Simple Rails Conditional Statement
Pretty simple I'm sure... but I can't figure out why it wouldn't work.

```<code><tr<% if film.viewed == true %> class="viewed"<% end %>>
</code>```

The film.viewed is a boolean but its not rendering the class if its true. Probably a syntax error. Any help? Also is there an easier way to write this without opening and closing? I tried using:

```<code><tr<% if film.viewed == true puts class=\"viewed\" end %>>
</code>```

Again probably a syntax error. I'm coming from PHP so I'm still learning.

Thanks.

答:
I think this is easer to read:</p>

```<code><%= content_tag(:tr, "", :class => film.viewed? ? "viewed" : nil) %>
</code>```

Title: Simple Rails Conditional Statement

Body:
Pretty simple I'm sure... but I can't figure out why it wouldn't work.

<tr<% if film.viewed == true %> class="viewed"<% end %>>

The film.viewed is a boolean but its not rendering the class if its true. Probably a syntax error. Any help? Also is there an easier way to write this without opening and closing? I tried using:

<tr<% if film.viewed == true puts class=\"viewed\" end %>>

Again probably a syntax error. I'm coming from PHP so I'm still learning.

Thanks.

Body:
I think this is easer to read:

<%= content_tag(:tr, "", :class => film.viewed? ? "viewed" : nil) %>


问:
convert each words into one list dataframe
I have a dataframe df:

Suppose a,b,c,d,e,f,g,h,j is a word ,not a single letter.

```<code>cate  word
apple [['a','b'],['c','d','e']]
pen   [['f','g','h'],['j']]
</code>```

I want to get one list in word column.So the expected output should be word_list =[u'a b c d e',u'f g h j']

However,when I use the following code:

```<code>word_list =[]

for line in df['word']:
    for word in line:
        word_list.append(word)
</code>```

So the output is not what I expected.

答:
flatten then list then join it

```<code>df.word=df.word.apply(lambda x : ' '.join(sum(x,[])))

df
Out[847]:
    cate       word
0  apple  a b c d e
1    pen    f g h j

df.word.tolist()
Out[848]: ['a b c d e', 'f g h j']
</code>```

Data input :

```<code>df = pd.DataFrame({"cate": ['apple','pen'],'word':[[['a','b'],['c','d','e']],[['f','g','h'],['j']]]})
</code>```

Body:
I have a dataframe df:

Suppose a,b,c,d,e,f,g,h,j is a word ,not a single letter.

cate  word
apple [['a','b'],['c','d','e']]
pen   [['f','g','h'],['j']]

I want to get one list in word column.So the expected output should be word_list =[u'a b c d e',u'f g h j']

However,when I use the following code:

word_list =[]

for line in df['word']:
    for word in line:
        word_list.append(word)

So the output is not what I expected.

Body:
flatten then list then join it

df.word=df.word.apply(lambda x : ' '.join(sum(x,[])))

df
Out[847]:
    cate       word
0  apple  a b c d e
1    pen    f g h j

df.word.tolist()
Out[848]: ['a b c d e', 'f g h j']

Data input :

df = pd.DataFrame({"cate": ['apple','pen'],'word':[[['a','b'],['c','d','e']],[['f','g','h'],['j']]]})


问:
Raise OnPropertyChanged in an async method
In my WPF application I have a method in my view model that

should run asynchronously

change the content of the button from "Connect" to "Cancel" to "Cancelling" depending on whether cancel has been pressed or not.

The cancelling itself is working but the content of the button is not updated.
This is an excerpt of my code:

```<code>public async void Execute(object parameter)
{
    if (cts == null)
    {
        cts = new CancellationTokenSource();
        OnPropertyChanged(nameof(Name));
        await ConnectDevice(self.CurrentScannedDevice, cts.Token);
        cts = null;
        OnPropertyChanged(nameof(Name));
    }
    else
    {
        cts.Cancel();
        OnPropertyChanged(nameof(Name));
    }
 }
private CancellationTokenSource cts;

public string Name { get // bound to the content of the button
    {
        return cts == null
            ? "Connect Device"
            : cts.IsCancellationRequested
                ? "Cancelling Connecting To Device"
                : "Cancel Connecting To Device";
    }
}
private async Task ConnectDevice(object currentScannedDevice, CancellationToken ct)
{
  //...
}
</code>```

XAML

```<code><Button
    HorizontalAlignment="Left"
    Command="{Binding Path=ScanCommand}"
    Content="{Binding Path=Name}" />
</code>```

答:
I found the reason.

In the "real" code, the Execute method lives in the command class ScanCommandImpl. The property for this ICommand class looked like this:

```<code> public ICommand ScanCommand => new ScanCommandImpl();
</code>```

It somehow recreated the ScanCommandImpl, so the variables for cts changed along the way.

Initializing it from the constructor fixed the problem.

Body:
In my WPF application I have a method in my view model that

should run asynchronously

change the content of the button from "Connect" to "Cancel" to "Cancelling" depending on whether cancel has been pressed or not.

The cancelling itself is working but the content of the button is not updated.
This is an excerpt of my code:

public async void Execute(object parameter)
{
    if (cts == null)
    {
        cts = new CancellationTokenSource();
        OnPropertyChanged(nameof(Name));
        await ConnectDevice(self.CurrentScannedDevice, cts.Token);
        cts = null;
        OnPropertyChanged(nameof(Name));
    }
    else
    {
        cts.Cancel();
        OnPropertyChanged(nameof(Name));
    }
 }
private CancellationTokenSource cts;

public string Name { get // bound to the content of the button
    {
        return cts == null
            ? "Connect Device"
            : cts.IsCancellationRequested
                ? "Cancelling Connecting To Device"
                : "Cancel Connecting To Device";
    }
}
private async Task ConnectDevice(object currentScannedDevice, CancellationToken ct)
{
  //...
}

XAML

<Button
    HorizontalAlignment="Left"
    Command="{Binding Path=ScanCommand}"
    Content="{Binding Path=Name}" />

Body:
I found the reason.

In the "real" code, the Execute method lives in the command class ScanCommandImpl. The property for this ICommand class looked like this:

 public ICommand ScanCommand => new ScanCommandImpl();

It somehow recreated the ScanCommandImpl, so the variables for cts changed along the way.

Initializing it from the constructor fixed the problem.


问:
MySQL concurrent insert causing deadlock outside of (explicit) transaction
I am attempting to debug the following scenario: There are 2 concurrent processes, inserting exactly the same row into a table with a unique constraint. This is done outside of an explicit transaction (though I assume InnoDB handles this as a single statement w/ auto commit internally?)

Schema as follows:

```<code>CREATE TABLE locks (
    id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    lock_uid varchar(255) NOT NULL,
    count smallint(6) NOT NULL,
    processor_id varchar(255) DEFAULT NULL,
    created_at timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
    updated_at timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
    PRIMARY KEY (id),
    UNIQUE INDEX locks_lock_uid_unique (lock_uid)
)
</code>```

As you can see there is unique index on the lock_uid to prevent multiple rows with the same value being in the table.

Commands being run (for context, these are taken from general query log for complete sanity, there are no other statements on either thread outside of a collation command):

Thread 1:

```<code>insert into `locks` (`lock_uid`, `count`, `processor_id`, `created_at`, `updated_at`)
values ('11161567', '0', NULL, '2017-11-07 10:46:36', '2017-11-07 10:46:36')
</code>```

Thread 2:

```<code>insert into `locks` (`lock_uid`, `count`, `processor_id`, `created_at`, `updated_at`)
values ('11161567', '0', NULL, '2017-11-07 10:46:36', '2017-11-07 10:46:36')
</code>```

This resulted in the following deadlock:

```<code>LATEST DETECTED DEADLOCK
------------------------
2017-11-07 10:46:36 0x2ac88f791700
*** (1) TRANSACTION:
TRANSACTION 6089510736, ACTIVE 0 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 4 lock struct(s), heap size 1136, 4 row lock(s), undo log entries 1
MySQL thread id 177584962, OS thread handle 47059008030464, query id 13109086103 ec2-34-232-58-13.compute-1.amazonaws.com 34.232.58.13 appserver update
insert into `locks` (`lock_uid`, `count`, `processor_id`, `created_at`, `updated_at`) values ('11161567', '0', NULL, '2017-11-07 10:46:36', '2017-11-07 10:46:36')
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 6403 page no 4 n bits 176 index locks_lock_uid_unique of table `core`.`locks` trx id 6089510736 lock_mode X locks gap before rec insert intention waiting
Record lock, heap no 107 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
0: len 30; hex 636865636b6f75745265636f7665727950726f636573735f313131363137; asc 111617; (total 32 bytes);
1: len 8; hex 0000000003266637; asc      &f7;;

*** (2) TRANSACTION:
TRANSACTION 6089510734, ACTIVE 0 sec inserting
mysql tables in use 1, locked 1
4 lock struct(s), heap size 1136, 5 row lock(s), undo log entries 1
MySQL thread id 177584971, OS thread handle 47040888903424, query id 13109086092 ec2-34-237-3-244.compute-1.amazonaws.com 34.237.3.244 appserver update
insert into `locks` (`lock_uid`, `count`, `processor_id`, `created_at`, `updated_at`) values ('11161567', '0', NULL, '2017-11-07 10:46:36', '2017-11-07 10:46:36')
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 6403 page no 4 n bits 176 index locks_lock_uid_unique of table `core`.`locks` trx id 6089510734 lock mode S
Record lock, heap no 104 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
0: len 30; hex 636865636b6f75745265636f7665727950726f636573735f313131363135; asc 111615; (total 32 bytes);
1: len 8; hex 0000000003266632; asc      &f2;;

Record lock, heap no 105 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
0: len 30; hex 636865636b6f75745265636f7665727950726f636573735f313131363135; asc 111615; (total 32 bytes);
1: len 8; hex 0000000003266634; asc      &f4;;

Record lock, heap no 107 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
0: len 30; hex 636865636b6f75745265636f7665727950726f636573735f313131363137; asc 111617; (total 32 bytes);
1: len 8; hex 0000000003266637; asc      &f7;;

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 6403 page no 4 n bits 176 index locks_lock_uid_unique of table `core`.`locks` trx id 6089510734 lock_mode X locks gap before rec insert intention waiting
Record lock, heap no 107 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
0: len 30; hex 636865636b6f75745265636f7665727950726f636573735f313131363137; asc 111617; (total 32 bytes);
1: len 8; hex 0000000003266637; asc      &f7;;

*** WE ROLL BACK TRANSACTION (2)
</code>```

I have read similar answers (e.g. MySQL locking in Duplicate Key Error), but I can't quite understand what's happening in this case. The explanation doesn't match the deadlock output.

Why does this deadlock occur on 2 inserts outside a transaction?

Why does the T2 already hold S locks, before requesting X, where as the identical T1 does not?

答:
Why does this deadlock occur on 2 inserts outside a transaction?

It still has a transaction
https://dev.mysql.com/doc/refman/5.7/en/innodb-autocommit-commit-rollback.html

In InnoDB, all user activity occurs inside a transaction. If
  autocommit mode is enabled, each SQL statement forms a single
  transaction on its own

So your single queries can be treated as short-lived transactions

Why does the T2 already hold S locks, before requesting X, where as the identical T1 does not?

It has. This is just how the function printing the latest deadlock information works :-)
It would not print the locks held by the first transaction. You can check it yourself by simulating a simple deadlock from 2 parallel mysql sessions.
And here’s the code:

https://github.com/mysql/mysql-server/blob/5.7/storage/innobase/lock/lock0lock.cc#L7236

```<code>DeadlockChecker::notify(const lock_t* lock) const
{
    ut_ad(lock_mutex_own());

    start_print();

    print("\n*** (1) TRANSACTION:\n");

    print(m_wait_lock->trx, 3000);

    print("*** (1) WAITING FOR THIS LOCK TO BE GRANTED:\n");

    print(m_wait_lock);

    print("*** (2) TRANSACTION:\n");

    print(lock->trx, 3000);

    print("*** (2) HOLDS THE LOCK(S):\n");

    print(lock);

    /* It is possible that the joining transaction was granted its
    lock when we rolled back some other waiting transaction. */

    if (m_start->lock.wait_lock != 0) {
        print("*** (2) WAITING FOR THIS LOCK TO BE GRANTED:\n");

        print(m_start->lock.wait_lock);
    }

    DBUG_PRINT("ib_lock", ("deadlock detected"));
}
</code>```

The explanation doesn't match the deadlock output

It's fairly close to what appears to be happening in your case.
Here’s a simulation:

Preparation:

```<code>create table test (id int primary key, val int not null unique) engine=innodb;
insert into test values (1, 1), (2, 2), (3, 3);
</code>```

Now lets open 3 shells and run the follow command:

```<code>1> begin;
2> begin;
3> begin;
</code>```

and then

```<code>1>insert into test values (1, 1);
2>insert into test values (1, 1); (will hang)
3>insert into test values (1, 1); (will hang)
</code>```

and now

```<code>1>rollback
2>would produce: ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction
3>would produce: Query OK, 1 row affected

1>show engine innodb status;
...
------------------------
LATEST DETECTED DEADLOCK
------------------------
2017-11-15 23:21:47 0x700000d95000
*** (1) TRANSACTION:
TRANSACTION 2336, ACTIVE 8 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 4 lock struct(s), heap size 1136, 2 row lock(s)
MySQL thread id 8, OS thread handle 123145316831232, query id 58 localhost 127.0.0.1 root update
insert into test values (1, 1)
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 26 page no 3 n bits 72 index PRIMARY of table `test`.`test` trx id 2336 lock_mode X insert intention waiting
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** (2) TRANSACTION:
TRANSACTION 2335, ACTIVE 13 sec inserting
mysql tables in use 1, locked 1
4 lock struct(s), heap size 1136, 2 row lock(s)
MySQL thread id 5, OS thread handle 123145316552704, query id 57 localhost root update
insert into test values (1, 1)
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 26 page no 3 n bits 72 index PRIMARY of table `test`.`test` trx id 2335 lock mode S
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 26 page no 3 n bits 72 index PRIMARY of table `test`.`test` trx id 2335 lock_mode X insert intention waiting
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** WE ROLL BACK TRANSACTION (2)
</code>```

As you can see it’s close to your outcome

Body:
I am attempting to debug the following scenario: There are 2 concurrent processes, inserting exactly the same row into a table with a unique constraint. This is done outside of an explicit transaction (though I assume InnoDB handles this as a single statement w/ auto commit internally?)

Schema as follows:

CREATE TABLE locks (
    id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
    lock_uid varchar(255) NOT NULL,
    count smallint(6) NOT NULL,
    processor_id varchar(255) DEFAULT NULL,
    created_at timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
    updated_at timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
    PRIMARY KEY (id),
    UNIQUE INDEX locks_lock_uid_unique (lock_uid)
)

As you can see there is unique index on the lock_uid to prevent multiple rows with the same value being in the table.

Commands being run (for context, these are taken from general query log for complete sanity, there are no other statements on either thread outside of a collation command):

Thread 1:

insert into `locks` (`lock_uid`, `count`, `processor_id`, `created_at`, `updated_at`)
values ('11161567', '0', NULL, '2017-11-07 10:46:36', '2017-11-07 10:46:36')

Thread 2:

insert into `locks` (`lock_uid`, `count`, `processor_id`, `created_at`, `updated_at`)
values ('11161567', '0', NULL, '2017-11-07 10:46:36', '2017-11-07 10:46:36')

This resulted in the following deadlock:

LATEST DETECTED DEADLOCK
------------------------
2017-11-07 10:46:36 0x2ac88f791700
*** (1) TRANSACTION:
TRANSACTION 6089510736, ACTIVE 0 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 4 lock struct(s), heap size 1136, 4 row lock(s), undo log entries 1
MySQL thread id 177584962, OS thread handle 47059008030464, query id 13109086103 ec2-34-232-58-13.compute-1.amazonaws.com 34.232.58.13 appserver update
insert into `locks` (`lock_uid`, `count`, `processor_id`, `created_at`, `updated_at`) values ('11161567', '0', NULL, '2017-11-07 10:46:36', '2017-11-07 10:46:36')
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 6403 page no 4 n bits 176 index locks_lock_uid_unique of table `core`.`locks` trx id 6089510736 lock_mode X locks gap before rec insert intention waiting
Record lock, heap no 107 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
0: len 30; hex 636865636b6f75745265636f7665727950726f636573735f313131363137; asc 111617; (total 32 bytes);
1: len 8; hex 0000000003266637; asc      &f7;;

*** (2) TRANSACTION:
TRANSACTION 6089510734, ACTIVE 0 sec inserting
mysql tables in use 1, locked 1
4 lock struct(s), heap size 1136, 5 row lock(s), undo log entries 1
MySQL thread id 177584971, OS thread handle 47040888903424, query id 13109086092 ec2-34-237-3-244.compute-1.amazonaws.com 34.237.3.244 appserver update
insert into `locks` (`lock_uid`, `count`, `processor_id`, `created_at`, `updated_at`) values ('11161567', '0', NULL, '2017-11-07 10:46:36', '2017-11-07 10:46:36')
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 6403 page no 4 n bits 176 index locks_lock_uid_unique of table `core`.`locks` trx id 6089510734 lock mode S
Record lock, heap no 104 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
0: len 30; hex 636865636b6f75745265636f7665727950726f636573735f313131363135; asc 111615; (total 32 bytes);
1: len 8; hex 0000000003266632; asc      &f2;;

Record lock, heap no 105 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
0: len 30; hex 636865636b6f75745265636f7665727950726f636573735f313131363135; asc 111615; (total 32 bytes);
1: len 8; hex 0000000003266634; asc      &f4;;

Record lock, heap no 107 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
0: len 30; hex 636865636b6f75745265636f7665727950726f636573735f313131363137; asc 111617; (total 32 bytes);
1: len 8; hex 0000000003266637; asc      &f7;;

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 6403 page no 4 n bits 176 index locks_lock_uid_unique of table `core`.`locks` trx id 6089510734 lock_mode X locks gap before rec insert intention waiting
Record lock, heap no 107 PHYSICAL RECORD: n_fields 2; compact format; info bits 32
0: len 30; hex 636865636b6f75745265636f7665727950726f636573735f313131363137; asc 111617; (total 32 bytes);
1: len 8; hex 0000000003266637; asc      &f7;;

*** WE ROLL BACK TRANSACTION (2)

I have read similar answers (e.g. MySQL locking in Duplicate Key Error), but I can't quite understand what's happening in this case. The explanation doesn't match the deadlock output.

Why does this deadlock occur on 2 inserts outside a transaction?

Why does the T2 already hold S locks, before requesting X, where as the identical T1 does not?

Body:
Why does this deadlock occur on 2 inserts outside a transaction?

It still has a transaction
https://dev.mysql.com/doc/refman/5.7/en/innodb-autocommit-commit-rollback.html

In InnoDB, all user activity occurs inside a transaction. If
  autocommit mode is enabled, each SQL statement forms a single
  transaction on its own

So your single queries can be treated as short-lived transactions

Why does the T2 already hold S locks, before requesting X, where as the identical T1 does not?

It has. This is just how the function printing the latest deadlock information works :-)
It would not print the locks held by the first transaction. You can check it yourself by simulating a simple deadlock from 2 parallel mysql sessions.
And here’s the code:

https://github.com/mysql/mysql-server/blob/5.7/storage/innobase/lock/lock0lock.cc#L7236

DeadlockChecker::notify(const lock_t* lock) const
{
    ut_ad(lock_mutex_own());

    start_print();

    print("\n*** (1) TRANSACTION:\n");

    print(m_wait_lock->trx, 3000);

    print("*** (1) WAITING FOR THIS LOCK TO BE GRANTED:\n");

    print(m_wait_lock);

    print("*** (2) TRANSACTION:\n");

    print(lock->trx, 3000);

    print("*** (2) HOLDS THE LOCK(S):\n");

    print(lock);

    /* It is possible that the joining transaction was granted its
    lock when we rolled back some other waiting transaction. */

    if (m_start->lock.wait_lock != 0) {
        print("*** (2) WAITING FOR THIS LOCK TO BE GRANTED:\n");

        print(m_start->lock.wait_lock);
    }

    DBUG_PRINT("ib_lock", ("deadlock detected"));
}

The explanation doesn't match the deadlock output

It's fairly close to what appears to be happening in your case.
Here’s a simulation:

Preparation:

create table test (id int primary key, val int not null unique) engine=innodb;
insert into test values (1, 1), (2, 2), (3, 3);

Now lets open 3 shells and run the follow command:

1> begin;
2> begin;
3> begin;

and then

1>insert into test values (1, 1);
2>insert into test values (1, 1); (will hang)
3>insert into test values (1, 1); (will hang)

and now

1>rollback
2>would produce: ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction
3>would produce: Query OK, 1 row affected

1>show engine innodb status;
...
------------------------
LATEST DETECTED DEADLOCK
------------------------
2017-11-15 23:21:47 0x700000d95000
*** (1) TRANSACTION:
TRANSACTION 2336, ACTIVE 8 sec inserting
mysql tables in use 1, locked 1
LOCK WAIT 4 lock struct(s), heap size 1136, 2 row lock(s)
MySQL thread id 8, OS thread handle 123145316831232, query id 58 localhost 127.0.0.1 root update
insert into test values (1, 1)
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 26 page no 3 n bits 72 index PRIMARY of table `test`.`test` trx id 2336 lock_mode X insert intention waiting
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** (2) TRANSACTION:
TRANSACTION 2335, ACTIVE 13 sec inserting
mysql tables in use 1, locked 1
4 lock struct(s), heap size 1136, 2 row lock(s)
MySQL thread id 5, OS thread handle 123145316552704, query id 57 localhost root update
insert into test values (1, 1)
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 26 page no 3 n bits 72 index PRIMARY of table `test`.`test` trx id 2335 lock mode S
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 26 page no 3 n bits 72 index PRIMARY of table `test`.`test` trx id 2335 lock_mode X insert intention waiting
Record lock, heap no 1 PHYSICAL RECORD: n_fields 1; compact format; info bits 0
 0: len 8; hex 73757072656d756d; asc supremum;;

*** WE ROLL BACK TRANSACTION (2)

As you can see it’s close to your outcome