问:
After updatet documentDB sdk .net to 1.10.0 or latest method not found
After update Document Db SDK .NET to 1.10.0 or latest, exception by login.

```<code>[MissingMethodException: Method not found: 'System.Threading.Tasks.Task`1<Microsoft.Azure.Documents.Client.FeedResponse`1<!!0>> Microsoft.Azure.Documents.Linq.IDocumentQuery`1.ExecuteNextAsync()'.]
   DocumentDB.AspNet.Identity.<GetUsers>d__9.MoveNext() +0
   System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start(TStateMachine& stateMachine) +94
   DocumentDB.AspNet.Identity.UserStore`1.GetUsers(Expression`1 predicate) +146
   DocumentDB.AspNet.Identity.<FindByNameAsync>d__17.MoveNext() +366
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.AspNet.Identity.CultureAwaiter`1.GetResult() +59
   Microsoft.AspNet.Identity.<FindAsync>d__12.MoveNext() +267
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +28
   Rezzame.Providers.<GrantResourceOwnerCredentials>d__2.MoveNext() in D:\Project\rezzame\Rezzame\Providers\ApplicationOAuthProvider.cs:39
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Security.OAuth.<InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync>d__3f.MoveNext() +466
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) +25
   Microsoft.Owin.Security.OAuth.<InvokeTokenEndpointAsync>d__22.MoveNext() +1548
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) +25
   Microsoft.Owin.Security.OAuth.<InvokeAsync>d__0.MoveNext() +1103
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +435
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +638
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.AspNet.Identity.Owin.<Invoke>d__0.MoveNext() +404
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +182
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<DoFinalWork>d__2.MoveNext() +180
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +69
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +64
   System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +380
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</code>```

ApplicationOAuthProvider.cs here error occurs

```<code>Line 39:             ApplicationUser user = await userManager.FindAsync(context.UserName.ToLower(), context.Password);
</code>```

Init user manager

```<code> public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(new Uri(ConfigurationManager.AppSettings["Endpoint"]), ConfigurationManager.AppSettings["AuthKey"], ConfigurationManager.AppSettings["Database"], "Users"));
</code>```

DocumentDB ASP.Net Identity is v1.0.10-beta

NOTE: some methods do not work in the SDK to get data, after updating all SDK in the project they started to work but did not work login.

Someone has idea what it could be?

答:
I tested DocumentDB ASP.Net Identity[v1.0.10-beta] with demo code. It works correctly on my side. The following is my detail steps. Please refer to check it.

Download the demo code from the github

Change the IdentityConfig with my documentdb info

Run the demo code local and registry a user. Then I can find the user can login and get the registried user from the Azure portal

4.In the package manager console (View > Other Windows > Package Manager Console) type in :

```<code>Install-Package DocumentDB.AspNet.Identity -Pre
</code>```

Try to login with the registried user

According to error info,update the Newtonsoft.Json version  to 10.0.2

Registry another user using customized collection

Login with the registried user successfully.

Body:
After update Document Db SDK .NET to 1.10.0 or latest, exception by login.

[MissingMethodException: Method not found: 'System.Threading.Tasks.Task`1<Microsoft.Azure.Documents.Client.FeedResponse`1<!!0>> Microsoft.Azure.Documents.Linq.IDocumentQuery`1.ExecuteNextAsync()'.]
   DocumentDB.AspNet.Identity.<GetUsers>d__9.MoveNext() +0
   System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start(TStateMachine& stateMachine) +94
   DocumentDB.AspNet.Identity.UserStore`1.GetUsers(Expression`1 predicate) +146
   DocumentDB.AspNet.Identity.<FindByNameAsync>d__17.MoveNext() +366
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.AspNet.Identity.CultureAwaiter`1.GetResult() +59
   Microsoft.AspNet.Identity.<FindAsync>d__12.MoveNext() +267
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +28
   Rezzame.Providers.<GrantResourceOwnerCredentials>d__2.MoveNext() in D:\Project\rezzame\Rezzame\Providers\ApplicationOAuthProvider.cs:39
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Security.OAuth.<InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync>d__3f.MoveNext() +466
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) +25
   Microsoft.Owin.Security.OAuth.<InvokeTokenEndpointAsync>d__22.MoveNext() +1548
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) +25
   Microsoft.Owin.Security.OAuth.<InvokeAsync>d__0.MoveNext() +1103
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +435
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Security.Infrastructure.<Invoke>d__0.MoveNext() +638
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.AspNet.Identity.Owin.<Invoke>d__0.MoveNext() +404
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +182
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<DoFinalWork>d__2.MoveNext() +180
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +69
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +64
   System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +380
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

ApplicationOAuthProvider.cs here error occurs

Line 39:             ApplicationUser user = await userManager.FindAsync(context.UserName.ToLower(), context.Password);

Init user manager

 public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(new Uri(ConfigurationManager.AppSettings["Endpoint"]), ConfigurationManager.AppSettings["AuthKey"], ConfigurationManager.AppSettings["Database"], "Users"));

DocumentDB ASP.Net Identity is v1.0.10-beta

NOTE: some methods do not work in the SDK to get data, after updating all SDK in the project they started to work but did not work login.

Someone has idea what it could be?

Body:
I tested DocumentDB ASP.Net Identity[v1.0.10-beta] with demo code. It works correctly on my side. The following is my detail steps. Please refer to check it.

Download the demo code from the github

Change the IdentityConfig with my documentdb info

Run the demo code local and registry a user. Then I can find the user can login and get the registried user from the Azure portal

4.In the package manager console (View > Other Windows > Package Manager Console) type in :

Install-Package DocumentDB.AspNet.Identity -Pre

Try to login with the registried user

According to error info,update the Newtonsoft.Json version  to 10.0.2

Registry another user using customized collection

Login with the registried user successfully.


来源: stackexchange

问:
several scrolling in RecyclerView causes to error xamarin.android
I have a RecyclerView that contains cardViews as members and cardviews contains image views that there images come from urls with an async method.
It works but when i scroll it fast several times it causes to an unhandled error.
what shoud I do?</p>

```<code>    public override async void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
    {
        var item = items[position];

        var holder = viewHolder as MyViewHolder;

        holder.image.SetImageBitmap(null);

        holder.fname.Text = items[position].fname;
        holder.sname.Text = items[position].sname;
        holder.age.Text = items[position].age.ToString();
        holder.progressLayout.Visibility = ViewStates.Visible;

        using (var imageBitmap = await GetImageBitmapFromUrl(items[position].imageURL))
        {
            var width = imageBitmap.Width;
            var height = imageBitmap.Height;

            var max = Math.Max(width, height);

            var scale = (double)holder.image.Width / max;

            var scaled = Bitmap.CreateScaledBitmap(imageBitmap, (int)(width * scale), (int)(height * scale), false);
            holder.image.SetImageBitmap(scaled);
        }

        holder.progressLayout.Visibility = ViewStates.Gone;

    }

    private async Task<Bitmap> GetImageBitmapFromUrl(string url)
    {
        Bitmap imageBitmap = null;

        using (var webClient = new WebClient())
        {
            var imageBytes = await webClient.DownloadDataTaskAsync(url);
            if (imageBytes != null && imageBytes.Length > 0)
            {
                imageBitmap = await BitmapFactory.DecodeByteArrayAsync(imageBytes, 0, imageBytes.Length);
            }
        }

        return imageBitmap;
    }
</code>```

答:
Solved,
I disposed the "scaled" variable after setting it as imageview bitmap</p>

```<code>            var scaled = Bitmap.CreateScaledBitmap(imageBitmap, (int)(width * scale), (int)(height * scale), false);
            holder.image.SetImageBitmap(scaled);
            scaled.Dispose(); // here
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a RecyclerView that contains cardViews as members and cardviews contains image views that there images come from urls with an async method.
It works but when i scroll it fast several times it causes to an unhandled error.
what shoud I do?

    public override async void OnBindViewHolder(RecyclerView.ViewHolder viewHolder, int position)
    {
        var item = items[position];

        var holder = viewHolder as MyViewHolder;

        holder.image.SetImageBitmap(null);

        holder.fname.Text = items[position].fname;
        holder.sname.Text = items[position].sname;
        holder.age.Text = items[position].age.ToString();
        holder.progressLayout.Visibility = ViewStates.Visible;

        using (var imageBitmap = await GetImageBitmapFromUrl(items[position].imageURL))
        {
            var width = imageBitmap.Width;
            var height = imageBitmap.Height;

            var max = Math.Max(width, height);

            var scale = (double)holder.image.Width / max;

            var scaled = Bitmap.CreateScaledBitmap(imageBitmap, (int)(width * scale), (int)(height * scale), false);
            holder.image.SetImageBitmap(scaled);
        }

        holder.progressLayout.Visibility = ViewStates.Gone;

    }

    private async Task<Bitmap> GetImageBitmapFromUrl(string url)
    {
        Bitmap imageBitmap = null;

        using (var webClient = new WebClient())
        {
            var imageBytes = await webClient.DownloadDataTaskAsync(url);
            if (imageBytes != null && imageBytes.Length > 0)
            {
                imageBitmap = await BitmapFactory.DecodeByteArrayAsync(imageBytes, 0, imageBytes.Length);
            }
        }

        return imageBitmap;
    }

Body:
Solved,
I disposed the "scaled" variable after setting it as imageview bitmap

            var scaled = Bitmap.CreateScaledBitmap(imageBitmap, (int)(width * scale), (int)(height * scale), false);
            holder.image.SetImageBitmap(scaled);
            scaled.Dispose(); // here


问:
RegEx with OR not matching first expression
i'm trying to create a Regular Expression with an Or

i have this

```<code>(?<data1>a[^b]+b)|(?<data2>^[^b]+b)
</code>```

the goal is to capture everything behind a or, when a is not present, everything from the start.

```<code>data = "123412123b" result should be "123412123b"
data = "123412a123b" result should be "a123b"
</code>```

it always matches the second part of the or as it captures to group (data2)
can anyone tell me why this happens

答:
The string is parsed from left to right by default and when the first alternative fails the regex engine tries the second one. The second alternative matches the same text as the first one, so when the string contains b after 1 or more chars other than b, the second alternative will always win.

You may override the default regex engine behavior in .NET by passing the RegexOptions.RightToLeft option to make it look for a match in the opposite direction:

```<code>var pattern = "a[^b]+b|^[^b]+b";
var result = Regex.Match("123412a123b", pattern, RegexOptions.RightToLeft);
if (result.Success)
    Console.WriteLine(result.Value);
</code>```

See the C# demo

Body:
i'm trying to create a Regular Expression with an Or

i have this

(?<data1>a[^b]+b)|(?<data2>^[^b]+b)

the goal is to capture everything behind a or, when a is not present, everything from the start.

data = "123412123b" result should be "123412123b"
data = "123412a123b" result should be "a123b"

it always matches the second part of the or as it captures to group (data2)
can anyone tell me why this happens

Body:
The string is parsed from left to right by default and when the first alternative fails the regex engine tries the second one. The second alternative matches the same text as the first one, so when the string contains b after 1 or more chars other than b, the second alternative will always win.

You may override the default regex engine behavior in .NET by passing the RegexOptions.RightToLeft option to make it look for a match in the opposite direction:

var pattern = "a[^b]+b|^[^b]+b";
var result = Regex.Match("123412a123b", pattern, RegexOptions.RightToLeft);
if (result.Success)
    Console.WriteLine(result.Value);

See the C# demo


问:
Constraining movement of a SKSpriteNode to a fixed area within a scene
How can I constrain manual movement of an SKSpriteNode to a fixed rectangular area within a scene?  This fixed rectangular area a also a SKSpriteNode which is fixed within the scene.  In other words, I want to constrain manual movement of an object (SKSpriteNode) to be completely contained within another SKSpriteNode or at least in the same space that it occupies.  I have tried several different approaches (e.g. using an SKShapeNode that has an edged-based physics body), but nothing seems to work.  This seems like it should be a fairly simple task to accomplish.  Thanks for any help or hints you can offer.</p>

答:
```<code>    let rangeX = SKRange(lowerLimit: CGFloat, upperLimit: CGFloat)
    let contraintX = SKConstraint.positionX(rangeX)
    let rangeY = SKRange(lowerLimit: CGFloat, upperLimit: CGFloat)
    let contraintY = SKConstraint.positionY(rangeY)
    yourObject.constraints = [contraintX, contraintY]
</code>```


问:
What is the best way to query SharePoint data?
Should I just use ADO.NET to directly access the underlying data in the database or does .NET have a better way to do this?

I am currently using SharePoint 2007 but we are about to move to 2010.  I am using Visual Studio 2010.

答:
You should definitely not access the SharePoint content databases directly.

There is a search web service you can use to get items or the list web services allow you to pull data out easily enough. If you are hosting your code within SharePoint, use the SharePoint object model. It is simple enough to get what you need.

ContentLicense: CC BY-SA 2.5


问:
Linux delete egrepped lines
I pass file to my egrep expression (tcpdump log), then I want to delete all matched lines

Code example:

```<code>cat file | tr -d '\000' |egrep -i 'user: | usr: ' --color=auto --line-buffered -B20
</code>```

How can I delete all matched lines now?

答:
You can do all that using sed:

```<code>sed -iE '/use?r: /d; s/\x0//g' file
</code>```

Title: Linux delete egrepped lines

Body:
I pass file to my egrep expression (tcpdump log), then I want to delete all matched lines

Code example:

cat file | tr -d '\000' |egrep -i 'user: | usr: ' --color=auto --line-buffered -B20

How can I delete all matched lines now?

Body:
You can do all that using sed:

sed -iE '/use?r: /d; s/\x0//g' file


问:
How can I call particular array value of array in php?
I'm getting below output as an array.

```<code>$array =
        Array
    (
        [12] => Array
            (
                [1] => Array
                    (
                        [14] => Array
                            (
                                [0] => Array
                                    (
                                        [name] => Avaya Implementation  Services
                                        [service_id] => 14
                                        [ser_type_id] => 1
                                        [service_desc] =>Avaya Implementation Servic
                                    )

                            )

                    )

            )

    );
</code>```

I want to print only service_desc array value. and I don't want call like $array[12][1][14][0]['service_desc'];

How can I call particular service_desc array value of the array?

答:
You can use array_walk_rescursive to frame a single dimensional array of matching keys:

DEMO

```<code><?php
$array[12][1][14][0]['service_desc']  = 'Avaya Implementation Servic';
$array[12][1][14][0]['service']       = 'dsfasf';
$array[12][1][114][0]['service_desc'] = 'Avaya Implementation Servicasdfdsf';

$searchKey = 'service_desc';

$desiredValues = [];
array_walk_recursive($array, function ($v, $k) use ($searchKey, &$desiredValues) {
    if ($k === $searchKey) {
        $desiredValues[] = $v;
    }
});

print_r($desiredValues);
</code>```

So this will yield:

```<code>Array
(
    [0] => Avaya Implementation Servic
    [1] => Avaya Implementation Servicasdfdsf
)
</code>```

Body:
I'm getting below output as an array.

$array =
        Array
    (
        [12] => Array
            (
                [1] => Array
                    (
                        [14] => Array
                            (
                                [0] => Array
                                    (
                                        [name] => Avaya Implementation  Services
                                        [service_id] => 14
                                        [ser_type_id] => 1
                                        [service_desc] =>Avaya Implementation Servic
                                    )

                            )

                    )

            )

    );

I want to print only service_desc array value. and I don't want call like $array[12][1][14][0]['service_desc'];

How can I call particular service_desc array value of the array?

Body:
You can use array_walk_rescursive to frame a single dimensional array of matching keys:

DEMO

<?php
$array[12][1][14][0]['service_desc']  = 'Avaya Implementation Servic';
$array[12][1][14][0]['service']       = 'dsfasf';
$array[12][1][114][0]['service_desc'] = 'Avaya Implementation Servicasdfdsf';

$searchKey = 'service_desc';

$desiredValues = [];
array_walk_recursive($array, function ($v, $k) use ($searchKey, &$desiredValues) {
    if ($k === $searchKey) {
        $desiredValues[] = $v;
    }
});

print_r($desiredValues);

So this will yield:

Array
(
    [0] => Avaya Implementation Servic
    [1] => Avaya Implementation Servicasdfdsf
)


问:
Compiling error on have 2 next variables
Im trying to run code that will copy the text "ready" or "cancel" in column L, based on if there is a value in Column S or T respectively in the specif row.

I keep getting the error Compile error: Invalid Next control variable reference.

My code is as follows,

```<code>    Dim TimeToRun

Sub auto_open()
    Call ScheduleCopyPriceOver
End Sub

Sub ScheduleCopyPriceOver()
    TimeToRun = Now + TimeValue("00:00:10")
    Application.OnTime TimeToRun, "CopyPriceOver"
End Sub

Sub CopyPriceOver()
Dim lRow    As Long
Dim ws      As Worksheet

Set ws = ThisWorkbook.Sheets("Orders")

Application.ScreenUpdating = False

    For SRow = 1 To 5000
    For TRow = 1 To 5000
    If ws.Cells(SRow, 19) = SRow Then
        ws.Cells(SRow, 12).Select
        ActiveCell.FormulaR1C1 = "ready"

     ElseIf ws.Cells(TRow, 20) = TRow Then
            ws.Cells(TRow, 12).Select
            ActiveCell.FormulaR1C1 = "Cancel"

        Call ScheduleCopyPriceOver

    End If
    Next SRow
    Next TRow

End Sub

Sub auto_close()
    On Error Resume Next
    Application.OnTime TimeToRun, "CopyPriceOver", , False
End Sub
</code>```

答:
This is what Variatus meant...
Also it's not necessary to select a cell as per your code as selecting cells inside a loop will make your code slow.</p>

```<code>Sub CopyPriceOver()
    Dim lRow As Long
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Orders")
    Application.ScreenUpdating = False
    For SRow = 1 To 5000
        For TRow = 1 To 5000
            If ws.Cells(SRow, 19) = SRow Then
                ws.Cells(SRow, 12).Select
                ws.Cells(SRow, 12).Value = "ready"
            ElseIf ws.Cells(TRow, 20) = TRow Then
                ws.Cells(TRow, 12).Select
                ws.Cells(TRow, 12).Value = "Cancel"
                Call ScheduleCopyPriceOver
            End If
        Next TRow
    Next SRow
End Sub
</code>```

Body:
Im trying to run code that will copy the text "ready" or "cancel" in column L, based on if there is a value in Column S or T respectively in the specif row.

I keep getting the error Compile error: Invalid Next control variable reference.

My code is as follows,

    Dim TimeToRun

Sub auto_open()
    Call ScheduleCopyPriceOver
End Sub

Sub ScheduleCopyPriceOver()
    TimeToRun = Now + TimeValue("00:00:10")
    Application.OnTime TimeToRun, "CopyPriceOver"
End Sub

Sub CopyPriceOver()
Dim lRow    As Long
Dim ws      As Worksheet

Set ws = ThisWorkbook.Sheets("Orders")

Application.ScreenUpdating = False

    For SRow = 1 To 5000
    For TRow = 1 To 5000
    If ws.Cells(SRow, 19) = SRow Then
        ws.Cells(SRow, 12).Select
        ActiveCell.FormulaR1C1 = "ready"

     ElseIf ws.Cells(TRow, 20) = TRow Then
            ws.Cells(TRow, 12).Select
            ActiveCell.FormulaR1C1 = "Cancel"

        Call ScheduleCopyPriceOver

    End If
    Next SRow
    Next TRow

End Sub

Sub auto_close()
    On Error Resume Next
    Application.OnTime TimeToRun, "CopyPriceOver", , False
End Sub

Body:
This is what Variatus meant...
Also it's not necessary to select a cell as per your code as selecting cells inside a loop will make your code slow.

Sub CopyPriceOver()
    Dim lRow As Long
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Orders")
    Application.ScreenUpdating = False
    For SRow = 1 To 5000
        For TRow = 1 To 5000
            If ws.Cells(SRow, 19) = SRow Then
                ws.Cells(SRow, 12).Select
                ws.Cells(SRow, 12).Value = "ready"
            ElseIf ws.Cells(TRow, 20) = TRow Then
                ws.Cells(TRow, 12).Select
                ws.Cells(TRow, 12).Value = "Cancel"
                Call ScheduleCopyPriceOver
            End If
        Next TRow
    Next SRow
End Sub


问:
What's the simplest way of returning the larger of two numbers?
Let's say I have an entity that looks like this:

```<code>public class Album()
{
    public DateTime LastUpdated { get; set; }
    public List<Picture> Pictures { get; set; }
}
</code>```

What I want to do is create a LastActivity property that will return the latest date of the activity. This is easy enough for the Pictures collection:

```<code>public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated); }
}
</code>```

However, I also want to consider the LastUpdated property on the Album entity as well. I could use this code:

```<code>public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated) > this.LastUpdated
              ? Pictures.Max(x => x.LastUpdated)
              : this.LastUpdated) };
}
</code>```

But this is bad because it will do the Max() transformation twice. Is there a better way of writing this code?

Answer

This is the solution I came up with, based on the accepted answer:

```<code>public virtual DateTime LastActivity
{
    get
    {
        var max = Pictures.Any() ? Pictures.Max(x => x.LastUpdated) : DateTime.MinValue;
        return max > this.LastUpdated ? max : this.LastUpdated;
    }
}
</code>```

The thing to watch out for is that if you do a Max() on an empty collection, you'll get an exception, so you have to check to see if there's anything in the collection first.

答: Just assign the picture dates maximum to a local variable and then do the comparison you've already written.</p>

Body:
Let's say I have an entity that looks like this:

public class Album()
{
    public DateTime LastUpdated { get; set; }
    public List<Picture> Pictures { get; set; }
}

What I want to do is create a LastActivity property that will return the latest date of the activity. This is easy enough for the Pictures collection:

public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated); }
}

However, I also want to consider the LastUpdated property on the Album entity as well. I could use this code:

public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated) > this.LastUpdated
              ? Pictures.Max(x => x.LastUpdated)
              : this.LastUpdated) };
}

But this is bad because it will do the Max() transformation twice. Is there a better way of writing this code?

Answer

This is the solution I came up with, based on the accepted answer:

public virtual DateTime LastActivity
{
    get
    {
        var max = Pictures.Any() ? Pictures.Max(x => x.LastUpdated) : DateTime.MinValue;
        return max > this.LastUpdated ? max : this.LastUpdated;
    }
}

The thing to watch out for is that if you do a Max() on an empty collection, you'll get an exception, so you have to check to see if there's anything in the collection first.


问:
Select microphone source from headset instead of handy mic
is it possible to record audio from my Bluetooth headset instead of using the integrated android smartphone microphone?
When i am connecting my headset to my phone I can use the mic while I am phoning but in any other case it does not record anything, for example when I am trying to record audio with a recording app it uses the mic from the phone. SO is there any solution for selecting the headset mic instead or can  I write an application for it?</p>

答:
You have to handle the following intent.
https://developer.android.com/reference/android/speech/RecognizerIntent.html#ACTION_VOICE_SEARCH_HANDS_FREE

You can use the following code to use bluetooth headset mic.

```<code>AudioManager audiomanager= (AudioManager)mContext.getSystemService(Context
            .AUDIO_SERVICE);
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
    mContext.registerReceiver(mBluetoothScoReceiver, intentFilter);
audiomanager.startBluetoothSco();
</code>```

and listen for the broadcast receiver.

```<code>private BroadcastReceiver mBluetoothScoReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);

        if (state == AudioManager.SCO_AUDIO_STATE_CONNECTED) {
            // Start recording audio
            log("audio connected");
            startRecording();
        } else if(state == AudioManager.SCO_AUDIO_STATE_DISCONNECTED){
            log("audio disconnected");
        }
    }
};
</code>```

and for switching(to disconnect bluetooth headset mic) you can use this code.

```<code>mAudioManager.stopBluetoothSco();
</code>```

Body:
You have to handle the following intent.
https://developer.android.com/reference/android/speech/RecognizerIntent.html#ACTION_VOICE_SEARCH_HANDS_FREE

You can use the following code to use bluetooth headset mic.

AudioManager audiomanager= (AudioManager)mContext.getSystemService(Context
            .AUDIO_SERVICE);
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
    mContext.registerReceiver(mBluetoothScoReceiver, intentFilter);
audiomanager.startBluetoothSco();

and listen for the broadcast receiver.

private BroadcastReceiver mBluetoothScoReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);

        if (state == AudioManager.SCO_AUDIO_STATE_CONNECTED) {
            // Start recording audio
            log("audio connected");
            startRecording();
        } else if(state == AudioManager.SCO_AUDIO_STATE_DISCONNECTED){
            log("audio disconnected");
        }
    }
};

and for switching(to disconnect bluetooth headset mic) you can use this code.

mAudioManager.stopBluetoothSco();


问:
How to inject custom font to UIWebView when loadRequest?
I use UIWebView to display search test in Myanmar font like this

```<code>    NSString *googleText = @"မြန်မာဘာသာ";
    NSString *googleLink = [NSString stringWithFormat:@"http://www.google.com/search?hl=my&lr=lang_my&q=%@",
                            [[googleText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"
                             ]
                            ];

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:googleLink]]];
</code>```

This is the result

Is there any way that we can inject custom font into UIWebView when load content from a server?

I'm not load html files in my bundle, so I can't use custom font in CSS like this question or this one

Please help! Thanks!

答:
You can refer following Working code .

```<code>NSString *cssString = [[[[@"body { font-family:" stringByAppendingString:centuryGothicRegular] stringByAppendingString:@"; font-size:"] stringByAppendingString:[NSString stringWithFormat:@"%ld",normalFont]] stringByAppendingString:@"}\""] ; //1

NSString *javascriptString = @"var style = document.createElement('style'); style.innerHTML = '%@'; document.head.appendChild(style)"; // 2
NSString *javascriptWithCSSString = [NSString stringWithFormat:javascriptString, cssString]; // 3
NSLog(@"javascriptWithCSSString: \n %@", javascriptWithCSSString);
NSString *loadedContent = [webView stringByEvaluatingJavaScriptFromString:javascriptWithCSSString];
NSLog(@"loaded ocntent: %@", loadedContent);
</code>```

Font name and size are declare as constant you can change according to your required font

Body:
I use UIWebView to display search test in Myanmar font like this

    NSString *googleText = @"မြန်မာဘာသာ";
    NSString *googleLink = [NSString stringWithFormat:@"http://www.google.com/search?hl=my&lr=lang_my&q=%@",
                            [[googleText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"
                             ]
                            ];

    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:googleLink]]];

This is the result

Is there any way that we can inject custom font into UIWebView when load content from a server?

I'm not load html files in my bundle, so I can't use custom font in CSS like this question or this one

Please help! Thanks!

Body:
You can refer following Working code .

NSString *cssString = [[[[@"body { font-family:" stringByAppendingString:centuryGothicRegular] stringByAppendingString:@"; font-size:"] stringByAppendingString:[NSString stringWithFormat:@"%ld",normalFont]] stringByAppendingString:@"}\""] ; //1

NSString *javascriptString = @"var style = document.createElement('style'); style.innerHTML = '%@'; document.head.appendChild(style)"; // 2
NSString *javascriptWithCSSString = [NSString stringWithFormat:javascriptString, cssString]; // 3
NSLog(@"javascriptWithCSSString: \n %@", javascriptWithCSSString);
NSString *loadedContent = [webView stringByEvaluatingJavaScriptFromString:javascriptWithCSSString];
NSLog(@"loaded ocntent: %@", loadedContent);

Font name and size are declare as constant you can change according to your required font


问:
Nth max salary in Oracle
To find out the Nth max sal in oracle i'm using below query

```<code>SELECT DISTINCE sal
FROM emp a
WHERE (
       SELECT COUNT(DISTINCE sal)
       FROM emp b
       WHERE a.sal<=b.sal)=&n;
</code>```

But According to me by using the above query it will take more time to execute if table size is big.

i'm trying to use the below query

```<code>SELECT sal
FROM (
      SELECT DISTINCE sal
      FROM emp
           ORDER BY sal DESC )
WHERE rownum=3;
</code>```

but not getting output.. any suggetions please .. Please share any link on how to optimise queries and decrease the time for a query to execute.

答:
This will show the 3rd max salary from table employee.
If you want to find out the 5th or 6th (whatever you want) value then just change the where condition like this where rownum<=5" or "where rownum<=6 and so on...

```<code>select min(sal) from(select distinct(sal) from emp  where rownum<=3 order by sal desc);
</code>```

Title: Nth max salary in Oracle

Body:
To find out the Nth max sal in oracle i'm using below query

SELECT DISTINCE sal
FROM emp a
WHERE (
       SELECT COUNT(DISTINCE sal)
       FROM emp b
       WHERE a.sal<=b.sal)=&n;

But According to me by using the above query it will take more time to execute if table size is big.

i'm trying to use the below query

SELECT sal
FROM (
      SELECT DISTINCE sal
      FROM emp
           ORDER BY sal DESC )
WHERE rownum=3;

but not getting output.. any suggetions please .. Please share any link on how to optimise queries and decrease the time for a query to execute.

Body:
This will show the 3rd max salary from table employee.
If you want to find out the 5th or 6th (whatever you want) value then just change the where condition like this where rownum<=5" or "where rownum<=6 and so on...

select min(sal) from(select distinct(sal) from emp  where rownum<=3 order by sal desc);


问:
Android -urlConnection.getInputStream() fails - InputStream stays null
I'm trying to retrieve JSON data from the Google Directions Server in Android. But getting the inputstream fails and an exception is thrown. I get the error message ,,null" and that the inputstream is null.

What am I doing wrong with the HTTP connection? The URL is working on my browser.

```<code>     private String doRequest() {
    String response = null;
    HttpURLConnection urlConnection = null;
    InputStream in = null;
    URL url = null;
    String queryString ="https://maps.googleapis.com/maps/api/directions/json?origin=40.71926430971954,-74.26603317260742&destination=40.74309523218185," +
            "-74.24732208251953&sensor=false&mode=walking&alternatives=true&key=AIzaSyASF2b0E0HHilJL5I936vqRbiBjM5XuPRA";

    try {
        url = new URL(queryString);
        urlConnection = (HttpURLConnection) url.openConnection();
        in = urlConnection.getInputStream();
    }

    catch (Exception e) {
        {
            StringBuilder builder = new StringBuilder();
            if (response == null)
                builder.append("Response is null.");
            if (url == null)
                builder.append("url is null.");
            if (urlConnection == null)
                builder.append("UrlConnection is null.");
            if (in == null)
                builder.append("Inputstream is null.");

            return builder.toString() +e.getMessage();
        }

    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
    }
    if (response == null)
    {
        return "sorry, response is null. At least it passed the exceptions.";
    }
    return response;
}
</code>```

EDIT:

Here is the error message

EDIT 2:

Okay, I've tried a mix of every ones suggestions. Now when I execute the code nothing happens. I can't open a dialog, so I don't know what problem it is this time.

```<code>public void getJSON(View v)
{
   AsyncTask<String, Void, String>hello = new GetData(this).execute(queryString);
}
</code>```

import android.app.Dialog;

import android.app.ProgressDialog;

import android.content.Context;

import android.content.DialogInterface;

import android.net.http.HttpsConnection;

import android.os.AsyncTask;

import android.support.v7.app.AlertDialog;

import android.view.View;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

(public class GetData extends AsyncTask)

{

```<code>private Exception exception;
public String response;
private Context context;
private ProgressDialog dialog = null;
public GetData(Context context)
{
    this.context = context;
}

protected String doInBackground(String... urls)
{
    this.response = doRequest(urls[0]);

    return response;
}

protected void onPostExecute() {
    // TODO: check this.exception
    // TODO: do something with the feed

    if (this.exception != null && response != null)
    {
        getDialog(getResponse(), context).show();
    }
    else
    {
        getDialog("sorry" + exception.getMessage(), context).show();
    }

}

private String doRequest(String queryString) {
    String response1 = null;
    HttpsURLConnection urlConnection = null;
    InputStream in = null;
    URL url = null;

    try {
        url = new URL(queryString);
        urlConnection =(HttpsURLConnection) url.openConnection();

        urlConnection.setRequestMethod("GET"); // or POST
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
        urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        int responseCode = urlConnection.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK)
        {
            in = urlConnection.getInputStream();
            response1 = convertStreamToString(in);
        }

    } catch (Exception e) {
        {
            StringBuilder builder = new StringBuilder();
            if (response1 == null)
                builder.append("Response is null.");
            if (url == null)
                builder.append("url is null.");
            if (urlConnection == null)
                builder.append("UrlConnection is null.");
            if (in == null)
                builder.append("Inputstream is null.");

            return builder.toString() + e.getMessage();
        }

    }

    finally
    {
        if (urlConnection != null)
            urlConnection.disconnect();
    }

    if (response1 == null)
    {
        return "sorry, response is null. At least it passed the exceptions.";
    }
    return response1;
}

private String convertStreamToString(java.io.InputStream is)
{
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

public String getResponse()
{
    return this.response;
}

public Dialog getDialog(String string, Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(string);
    builder.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    return builder.create();

}
</code>```

答:
First, add Internet permission to your manifest file:

```<code><uses-permission android:name="android.permission.INTERNET" />
</code>```

Then add this to your existing code:

```<code>urlConnection.setRequestMethod("GET"); // or POST
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
</code>```

Then check the response code :

```<code>if (responseCode == HttpURLConnection.HTTP_OK) {
}
</code>```

You should also change the way you read the InputStream to something like this:

```<code>try {
    BufferedReader input = new BufferedReader(
            new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
    StringBuilder strB = new StringBuilder();
    String str;
    while (null != (str = input.readLine())) {
        strB.append(str).append("\r\n");
    }
    input.close();
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

Body:
I'm trying to retrieve JSON data from the Google Directions Server in Android. But getting the inputstream fails and an exception is thrown. I get the error message ,,null" and that the inputstream is null.

What am I doing wrong with the HTTP connection? The URL is working on my browser.

     private String doRequest() {
    String response = null;
    HttpURLConnection urlConnection = null;
    InputStream in = null;
    URL url = null;
    String queryString ="https://maps.googleapis.com/maps/api/directions/json?origin=40.71926430971954,-74.26603317260742&destination=40.74309523218185," +
            "-74.24732208251953&sensor=false&mode=walking&alternatives=true&key=AIzaSyASF2b0E0HHilJL5I936vqRbiBjM5XuPRA";

    try {
        url = new URL(queryString);
        urlConnection = (HttpURLConnection) url.openConnection();
        in = urlConnection.getInputStream();
    }

    catch (Exception e) {
        {
            StringBuilder builder = new StringBuilder();
            if (response == null)
                builder.append("Response is null.");
            if (url == null)
                builder.append("url is null.");
            if (urlConnection == null)
                builder.append("UrlConnection is null.");
            if (in == null)
                builder.append("Inputstream is null.");

            return builder.toString() +e.getMessage();
        }

    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
    }
    if (response == null)
    {
        return "sorry, response is null. At least it passed the exceptions.";
    }
    return response;
}

EDIT:

Here is the error message

EDIT 2:

Okay, I've tried a mix of every ones suggestions. Now when I execute the code nothing happens. I can't open a dialog, so I don't know what problem it is this time.

public void getJSON(View v)
{
   AsyncTask<String, Void, String>hello = new GetData(this).execute(queryString);
}

import android.app.Dialog;

import android.app.ProgressDialog;

import android.content.Context;

import android.content.DialogInterface;

import android.net.http.HttpsConnection;

import android.os.AsyncTask;

import android.support.v7.app.AlertDialog;

import android.view.View;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

(public class GetData extends AsyncTask)

{

private Exception exception;
public String response;
private Context context;
private ProgressDialog dialog = null;
public GetData(Context context)
{
    this.context = context;
}

protected String doInBackground(String... urls)
{
    this.response = doRequest(urls[0]);

    return response;
}

protected void onPostExecute() {
    // TODO: check this.exception
    // TODO: do something with the feed

    if (this.exception != null && response != null)
    {
        getDialog(getResponse(), context).show();
    }
    else
    {
        getDialog("sorry" + exception.getMessage(), context).show();
    }

}

private String doRequest(String queryString) {
    String response1 = null;
    HttpsURLConnection urlConnection = null;
    InputStream in = null;
    URL url = null;

    try {
        url = new URL(queryString);
        urlConnection =(HttpsURLConnection) url.openConnection();

        urlConnection.setRequestMethod("GET"); // or POST
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
        urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);

        int responseCode = urlConnection.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK)
        {
            in = urlConnection.getInputStream();
            response1 = convertStreamToString(in);
        }

    } catch (Exception e) {
        {
            StringBuilder builder = new StringBuilder();
            if (response1 == null)
                builder.append("Response is null.");
            if (url == null)
                builder.append("url is null.");
            if (urlConnection == null)
                builder.append("UrlConnection is null.");
            if (in == null)
                builder.append("Inputstream is null.");

            return builder.toString() + e.getMessage();
        }

    }

    finally
    {
        if (urlConnection != null)
            urlConnection.disconnect();
    }

    if (response1 == null)
    {
        return "sorry, response is null. At least it passed the exceptions.";
    }
    return response1;
}

private String convertStreamToString(java.io.InputStream is)
{
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

public String getResponse()
{
    return this.response;
}

public Dialog getDialog(String string, Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setMessage(string);
    builder.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    return builder.create();

}

Body:
First, add Internet permission to your manifest file:

<uses-permission android:name="android.permission.INTERNET" />

Then add this to your existing code:

urlConnection.setRequestMethod("GET"); // or POST
urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");
urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);

Then check the response code :

if (responseCode == HttpURLConnection.HTTP_OK) {
}

You should also change the way you read the InputStream to something like this:

try {
    BufferedReader input = new BufferedReader(
            new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
    StringBuilder strB = new StringBuilder();
    String str;
    while (null != (str = input.readLine())) {
        strB.append(str).append("\r\n");
    }
    input.close();
} catch (IOException e) {
    e.printStackTrace();
}


答:
How about this? </p>

```<code>(?<data>a?[^ab]+b)
</code>```

Title: RegEx with OR not matching first expression

Body:
How about this?

(?<data>a?[^ab]+b)


问:
Unknown column keeps on appearing
I have already read the docs of CI however I am still encountering error with regards to my query. I posted my answer hoping you could help me with this.

```<code>    $code = $_SESSION['affiliate_code'];
    $email  = $this->db->query('select email from affiliates where referral_code = '.$code);
</code>```

What happening is that the query being created looks like this

```<code>    select email from affiliates where referral_code = dTE7TkDcOa86;
</code>```

but in order to work it should be like

```<code>    select email from affiliates where referral_code = 'dTE7TkDcOa86';
</code>```

How can I make my code work correctly?
I appreciate your help with this. Thank you.

答:
Please try This </p>

```<code>$email  = $this->db->query("select email from affiliates where referral_code = '".$code."' ");
</code>```

<p>Use Fallowing :- </p>

```<code>$this->db->select('email')->from('affiliates')->where('referral_code',$code);
$query = $this->db->get();
</code>```

Title: Unknown column keeps on appearing

Body:
I have already read the docs of CI however I am still encountering error with regards to my query. I posted my answer hoping you could help me with this.

    $code = $_SESSION['affiliate_code'];
    $email  = $this->db->query('select email from affiliates where referral_code = '.$code);

What happening is that the query being created looks like this

    select email from affiliates where referral_code = dTE7TkDcOa86;

but in order to work it should be like

    select email from affiliates where referral_code = 'dTE7TkDcOa86';

How can I make my code work correctly?
I appreciate your help with this. Thank you.

Body:
Please try This

$email  = $this->db->query("select email from affiliates where referral_code = '".$code."' ");

Use Fallowing :-

$this->db->select('email')->from('affiliates')->where('referral_code',$code);
$query = $this->db->get();


问:
Build Docker image in Jenkins (in Docker image) - Cloud docker agent
I try to learn how to configure Jenkins (in the Docker container) to build Docker Images based on a Dockerfile.

At first I installed DockerToolbox. (OS  Windows 7 Home)

Then I pulled latest Jenkins image from Dockerhub, ran container and logged in as admin.

Based on this tutorial: https://www.katacoda.com/courses/jenkins/build-docker-images I try to  configure the plugin to communicate with a Docker host/daemon. (step 3)

In (Jenkins/configure/Cloud section) I have to fill the Name and Docker-Url then Test Connection.

In the Docker terminal I typed docker-machine config to get Url.

Unfortunately after Testing connection I get exception below:

```<code>shaded.org.apache.http.client.ClientProtocolException
javax.ws.rs.ProcessingException: shaded.org.apache.http.client.ClientProtocolException
    at org.glassfish.jersey.apache.connector.ApacheConnector.apply(ApacheConnector.java:481)
    at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:252)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:701)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:697)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:420)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:316)
    at com.github.dockerjava.jaxrs.VersionCmdExec.execute(VersionCmdExec.java:26)
    at com.github.dockerjava.jaxrs.VersionCmdExec.execute(VersionCmdExec.java:13)
    at com.github.dockerjava.jaxrs.AbstrSyncDockerCmdExec.exec(AbstrSyncDockerCmdExec.java:23)
    at com.github.dockerjava.core.command.AbstrDockerCmd.exec(AbstrDockerCmd.java:35)
    at com.nirima.jenkins.plugins.docker.DockerCloud$DescriptorImpl.doTestConnection(DockerCloud.java:698)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:335)
    at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:175)
    at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:108)
    at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:124)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
    at org.kohsuke.stapler.MetaClass$5.doDispatch(MetaClass.java:236)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:649)
    at org.kohsuke.stapler.Stapler.service(Stapler.java:238)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
    at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:135)
    at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:126)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:80)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)
    at hudson.security.UnwrapSecurityExceptionFilter.doFilter(UnwrapSecurityExceptionFilter.java:51)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at jenkins.security.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:117)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.ui.rememberme.RememberMeProcessingFilter.doFilter(RememberMeProcessingFilter.java:142)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at jenkins.security.BasicHeaderProcessor.doFilter(BasicHeaderProcessor.java:93)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
    at hudson.security.HttpSessionContextIntegrationFilter2.doFilter(HttpSessionContextIntegrationFilter2.java:67)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:76)
    at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:82)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:553)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:499)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544)
    at winstone.BoundedExecutorService$1.run(BoundedExecutorService.java:77)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: shaded.org.apache.http.client.ClientProtocolException
    at shaded.org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
    at shaded.org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:71)
    at org.glassfish.jersey.apache.connector.ApacheConnector.apply(ApacheConnector.java:435)
    ... 82 more
Caused by: shaded.org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response
    at shaded.org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:151)
    at shaded.org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:57)
    at shaded.org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
    at shaded.org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
    at shaded.org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:167)
    at shaded.org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
    at shaded.org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at shaded.org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:271)
    at shaded.org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
    at shaded.org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
    at shaded.org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at shaded.org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
</code>```

I'm not sure whether I'm missing something or perhaps there is more efficient approach.

Thank you in advance for a hint.

Cloud settings:

cloud settings screenshot

答:
Thank you for following the Katacoda scenario. It sounds like the Docker Daemon is not listening on a HTTPS port. The docker-machine command will return the IP address of the Docker VM, but by default, the daemon does not listen on a HTTPS port and only via Unix Sockets.

As you're on the same machine, you could try using something like unix:///var/run/docker.sock or /var/run/docker.sock instead of a IP/Port.

If you want to use IP/Port, you need to modify the Docker Daemon settings, with boot2docker this is done via https://github.com/docker/machine/issues/3859

Body:
I try to learn how to configure Jenkins (in the Docker container) to build Docker Images based on a Dockerfile.

At first I installed DockerToolbox. (OS  Windows 7 Home)

Then I pulled latest Jenkins image from Dockerhub, ran container and logged in as admin.

Based on this tutorial: https://www.katacoda.com/courses/jenkins/build-docker-images I try to  configure the plugin to communicate with a Docker host/daemon. (step 3)

In (Jenkins/configure/Cloud section) I have to fill the Name and Docker-Url then Test Connection.

In the Docker terminal I typed docker-machine config to get Url.

Unfortunately after Testing connection I get exception below:

shaded.org.apache.http.client.ClientProtocolException
javax.ws.rs.ProcessingException: shaded.org.apache.http.client.ClientProtocolException
    at org.glassfish.jersey.apache.connector.ApacheConnector.apply(ApacheConnector.java:481)
    at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:252)
    at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:701)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:444)
    at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:697)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:420)
    at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:316)
    at com.github.dockerjava.jaxrs.VersionCmdExec.execute(VersionCmdExec.java:26)
    at com.github.dockerjava.jaxrs.VersionCmdExec.execute(VersionCmdExec.java:13)
    at com.github.dockerjava.jaxrs.AbstrSyncDockerCmdExec.exec(AbstrSyncDockerCmdExec.java:23)
    at com.github.dockerjava.core.command.AbstrDockerCmd.exec(AbstrDockerCmd.java:35)
    at com.nirima.jenkins.plugins.docker.DockerCloud$DescriptorImpl.doTestConnection(DockerCloud.java:698)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:335)
    at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:175)
    at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:108)
    at org.kohsuke.stapler.MetaClass$1.doDispatch(MetaClass.java:124)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
    at org.kohsuke.stapler.MetaClass$5.doDispatch(MetaClass.java:236)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
    at org.kohsuke.stapler.Stapler.tryInvoke(Stapler.java:746)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:876)
    at org.kohsuke.stapler.Stapler.invoke(Stapler.java:649)
    at org.kohsuke.stapler.Stapler.service(Stapler.java:238)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
    at hudson.util.PluginServletFilter$1.doFilter(PluginServletFilter.java:135)
    at hudson.util.PluginServletFilter.doFilter(PluginServletFilter.java:126)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at hudson.security.csrf.CrumbFilter.doFilter(CrumbFilter.java:80)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:84)
    at hudson.security.UnwrapSecurityExceptionFilter.doFilter(UnwrapSecurityExceptionFilter.java:51)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at jenkins.security.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:117)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.providers.anonymous.AnonymousProcessingFilter.doFilter(AnonymousProcessingFilter.java:125)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.ui.rememberme.RememberMeProcessingFilter.doFilter(RememberMeProcessingFilter.java:142)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at jenkins.security.BasicHeaderProcessor.doFilter(BasicHeaderProcessor.java:93)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
    at hudson.security.HttpSessionContextIntegrationFilter2.doFilter(HttpSessionContextIntegrationFilter2.java:67)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:76)
    at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:82)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:553)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
    at org.eclipse.jetty.server.Server.handle(Server.java:499)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:257)
    at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544)
    at winstone.BoundedExecutorService$1.run(BoundedExecutorService.java:77)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: shaded.org.apache.http.client.ClientProtocolException
    at shaded.org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
    at shaded.org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:71)
    at org.glassfish.jersey.apache.connector.ApacheConnector.apply(ApacheConnector.java:435)
    ... 82 more
Caused by: shaded.org.apache.http.ProtocolException: The server failed to respond with a valid HTTP response
    at shaded.org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:151)
    at shaded.org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:57)
    at shaded.org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:259)
    at shaded.org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:163)
    at shaded.org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:167)
    at shaded.org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:273)
    at shaded.org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:125)
    at shaded.org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:271)
    at shaded.org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
    at shaded.org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
    at shaded.org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at shaded.org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)

I'm not sure whether I'm missing something or perhaps there is more efficient approach.

Thank you in advance for a hint.

Cloud settings:

cloud settings screenshot


答:
Use -v flag

```<code> -v, --invert-match
         Selected lines are those not matching any of the specified patterns.
</code>```

```<code>cat file | tr -d '\000' |egrep -iv 'user: | usr: ' --color=auto --line-buffered -B20 > newfile
</code>```

Title: Linux delete egrepped lines

Body:
I pass file to my egrep expression (tcpdump log), then I want to delete all matched lines

Code example:

cat file | tr -d '\000' |egrep -i 'user: | usr: ' --color=auto --line-buffered -B20

How can I delete all matched lines now?

Body:
Use -v flag

 -v, --invert-match
         Selected lines are those not matching any of the specified patterns.

cat file | tr -d '\000' |egrep -iv 'user: | usr: ' --color=auto --line-buffered -B20 > newfile


问:
Enum.HasFlag, why no Enum.SetFlag?
I have to build an extension method for each flag type I declare, like so:

```<code>public static EventMessageScope SetFlag(this EventMessageScope flags,
    EventMessageScope flag, bool value)
{
    if (value)
        flags |= flag;
    else
        flags &= ~flag;

    return flags;
}
</code>```

Why isn't there an Enum.SetFlag like there is an Enum.HasFlag?

Also, why does this not work always?

```<code>public static bool Get(this EventMessageScope flags, EventMessageScope flag)
{
    return ((flags & flag) != 0);
}
</code>```

For example, if I have:

```<code>var flag = EventMessageScope.Private;
</code>```

And check it like:

```<code>if(flag.Get(EventMessageScope.Public))
</code>```

Where EventMessageScope.Public really is EventMessageScope.Private | EventMessageScope.PublicOnly, it returns true.

When it's not, because Private is not public, it's just half public.

The same goes for:

if(flag.Get(EventMessageScope.None))

Which returns false, except the scope is actually None (0x0), when it should always return true?

答:
Here is another quick and dirty way to SetFlag for any Enum:</p>

```<code>public static T SetFlag<T>(this T flags, T flag, bool value) where T : struct, IComparable, IFormattable, IConvertible
    {
        int flagsInt = flags.ToInt32(NumberFormatInfo.CurrentInfo);
        int flagInt = flag.ToInt32(NumberFormatInfo.CurrentInfo);
        if (value)
        {
            flagsInt |= flagInt;
        }
        else
        {
            flagsInt &= ~flagInt;
        }
        return (T)(Object)flagsInt;
    }
</code>```

Title: Enum.HasFlag, why no Enum.SetFlag?

Body:
I have to build an extension method for each flag type I declare, like so:

public static EventMessageScope SetFlag(this EventMessageScope flags,
    EventMessageScope flag, bool value)
{
    if (value)
        flags |= flag;
    else
        flags &= ~flag;

    return flags;
}

Why isn't there an Enum.SetFlag like there is an Enum.HasFlag?

Also, why does this not work always?

public static bool Get(this EventMessageScope flags, EventMessageScope flag)
{
    return ((flags & flag) != 0);
}

For example, if I have:

var flag = EventMessageScope.Private;

And check it like:

if(flag.Get(EventMessageScope.Public))

Where EventMessageScope.Public really is EventMessageScope.Private | EventMessageScope.PublicOnly, it returns true.

When it's not, because Private is not public, it's just half public.

The same goes for:

if(flag.Get(EventMessageScope.None))

Which returns false, except the scope is actually None (0x0), when it should always return true?

Body:
Here is another quick and dirty way to SetFlag for any Enum:

public static T SetFlag<T>(this T flags, T flag, bool value) where T : struct, IComparable, IFormattable, IConvertible
    {
        int flagsInt = flags.ToInt32(NumberFormatInfo.CurrentInfo);
        int flagInt = flag.ToInt32(NumberFormatInfo.CurrentInfo);
        if (value)
        {
            flagsInt |= flagInt;
        }
        else
        {
            flagsInt &= ~flagInt;
        }
        return (T)(Object)flagsInt;
    }

ContentLicense: CC BY-SA 4.0


问:
DialogResult in WPF Application
I am currently developing an application in C# using WPF, I have always only used WinForms. Normally if I want to ask the user a question instead of making my own dialogue I use

DialogResult result = MessageBox.Show(
    "My Message Question", "My Title", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
```

This is the first time that I have used a WPF form and DialogResult does not seem to be available. What do I use to get the same effect?

答:
Use MessageBoxResult instead. And use the MessageBox class. But this message box will look pretty ugly "classic" style.

Another option would be to use Extended WPF toolkit

Yet another option would be to go here and download CrossTechnologySamples.exe then look into the VistaBridge project. I recommend you give a good look here because you will find other samples for other dialogs (like FileOpen, FileSave etc.) that do not exist by default in WPF.

Title: DialogResult in WPF Application

Body:
I am currently developing an application in C# using WPF, I have always only used WinForms. Normally if I want to ask the user a question instead of making my own dialogue I use

DialogResult result = MessageBox.Show(
    "My Message Question", "My Title", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

This is the first time that I have used a WPF form and DialogResult does not seem to be available. What do I use to get the same effect?


问:
Testing CShtml files in MVC project using jasmine
I would like to test my javascript code (that includes jQuery library) that is in my CShtml file at a MVC project that runs on visual studio 2015.
I know that testing on js files can be done using jasmine.

Can I test a cshtml file using jasmine?

Where can i find a good tutorial on the subject?

答:
You could use Chutzpah. It is a JavaScript test runner which works fine with Jasmine. It is available as a plug-in for Visual Studio and is easy to setup. It also integrates with the Test Explorer of Visual Studio. The wiki explains the features and how it works.

The following thread can help you:

Setup Jasmine Test Framework on MVC 5

This is a good read too


问:
Python: superimposing and smoothing graphics
I have 100 different graphics, they looks like

I need to superimpose all of them and next smooth result.
I try this

```<code>import Image

first = Image.open("test1.png")
second = Image.open("test2.png")

first.paste(second, (0, 0), second)
first.show()
</code>```

But how can I do it to 100 graphics? And how can I smooth result?
First 10 steps in dataframe looks like

```<code>       active nodes
graph
0              1024
1               598
2               349
3               706
4               541
5               623
6               576
7               614
8               578
9               613
10              595
</code>```

答:
You have it just as an image, or you also have the data that makes the graph?
If you have the data, the easiest way to smooth it is to use convolution.

```<code>n=100
smoothed_data=np.convolve(data,[1/n]*n,'same')
</code>```

Body:
I have 100 different graphics, they looks like

I need to superimpose all of them and next smooth result.
I try this

import Image

first = Image.open("test1.png")
second = Image.open("test2.png")

first.paste(second, (0, 0), second)
first.show()

But how can I do it to 100 graphics? And how can I smooth result?
First 10 steps in dataframe looks like

       active nodes
graph
0              1024
1               598
2               349
3               706
4               541
5               623
6               576
7               614
8               578
9               613
10              595

Body:
You have it just as an image, or you also have the data that makes the graph?
If you have the data, the easiest way to smooth it is to use convolution.

n=100
smoothed_data=np.convolve(data,[1/n]*n,'same')


问:
Change modal form depending on the button clicked
I have a table showing the information of the users, with an edit button for each one.

I want to show a modal form with the details for the user I want to edit, but I don't know how to get the details from the list, and passing them to the modal as a model.

Here is my View:

```<code>@model MyApp.Models.User
@{
    ViewBag.Title = "Users";
    var roles = new List<string> { "Manager", "Admin" };
    var userRoles = (List<string>)ViewData["userRoles"];
}

<h2>@ViewBag.Title</h2>

@if (userRoles.Any(u => roles.Contains(u)))
{
    using (Html.BeginForm("Update", "Admin", FormMethod.Post, new { id = "update-form", value = "" }))
    {
    <div class="modal fade" id="user-editor" >
        <div class="modal-header">
            <a class="close" data-dismiss="modal"><h3>×</h3></a>
            <h3 id="modal-title">Edit User</h3>
        </div>
        <div class="modal-body">
            <div class="form-group">
                @Html.Label("Name", new { @class = "col-md-2 control-label" })
                <div class="col-md-10">
                    @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
                </div>
            </div>
            <div class="form-group">
                @Html.Label("Age", new { @class = "col-md-2 control-label" })
                <div class="col-md-10">
                    @Html.TextBoxFor(m => m.Age, new { @class = "form-control" })
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <a class="btn" data-dismiss="modal">Close</a>
            <input type="submit" class="btn btn-primary" value="Save Changes" />
        </div>
    </div>
    }
}

<table class="table-bordered table-hover" id="tbusers">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            @if (userRoles.Any(u => roles.Contains(u)))
            {
                <th>Edit</th>
            }
        </tr>
    </thead>
    <tbody>
        @foreach (var u in users)
        {
            <tr id="@u.Id">
                <td>@u.Name</td>
                <td>@u.Age</td>
                @if (userRoles.Any(u => roles.Contains(u)))
                {
                    <td><a type="button" class="btn edit-btn" href="#user-editor" data-toggle="modal">Edit</a></td>
                }
            </tr>
        }
    </tbody>
</table>
</code>```

答:
I've created a testing sample which will help you understand how can you achieve this.
Index.cshtml which will show a list of employees

```<code>@model IEnumerable<MvcApplication1.Models.Employee>
@using MvcApplication1.Models;
<h2>Index</h2>
<table>
@foreach (Employee item in Model)
{
    <tr>
        <td>@Html.ActionLink(@item.EmployeeName, "Name", new { id = item.ID })</td>
        <td>
            <button type="button" data-id='@item.ID' class="anchorDetail btn btn-info btn-sm" data-toggle="modal"
         data-target="#myModal">
                Open Large Modal</button></td>
    </tr>
 }
</table>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">×</button>
            <h4 class="modal-title">Details</h4>
        </div>
        <div class="modal-body">
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>
   </div>
  </div>
</code>```

At the same page, reference the following scripts

```<code><script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</code>```

JQuery AJAX call for getting/setting the data of individual employee from ActionMethod at the same page

```<code><script>
$(document).ready(function () {
    var TeamDetailPostBackURL = '/Employee/Details';
    $(document).on('click', '.anchorDetail', function () {
        var $buttonClicked = $(this);
        var id = $buttonClicked.attr('data-id');
        var options = { "backdrop": "static", keyboard: true };
        $.ajax({
            type: "GET",
            url: TeamDetailPostBackURL,
            contentType: "application/json; charset=utf-8",
            data: { "Id": id },
            datatype: "json",
            success: function (data) {
                debugger;
                $('.modal-body').html(data);
                $('#myModal').modal(options);
                $('#myModal').modal('show');

            },
            error: function () {
                alert("Dynamic content load failed.");
            }
        });
    });
    $("#closbtn").click(function () {
        $('#myModal').modal('hide');
    });
});
</code>```

Now Create a class of Employee(because i'm not using EF)

```<code>public class Employee
{
    public int ID { get; set; }
    public string EmployeeName { get; set; }
}
</code>```

Create controller named Employee and 2 ActionMethods like these:

```<code>public ActionResult Index()
{
  return View(emp);//sends a List of employees to Index View
}
public ActionResult Details(int Id)
{
  return PartialView("Details",
  emp.Where(x=>x.ID==Convert.ToInt32(Id)).FirstOrDefault());
}
</code>```

I'm returning PartialView because I need to load a page within a page.
Details.cshtml

```<code>@model MvcApplication1.Models.Employee
<fieldset>
<legend>Employee</legend>
<div class="display-label">
     @Html.DisplayNameFor(model => model.ID)
</div>
<div class="display-field">
    @Html.DisplayFor(model => model.ID)
</div>
<div class="display-label">
     @Html.DisplayNameFor(model => model.EmployeeName)
</div>
<div class="display-field">
    @Html.DisplayFor(model => model.EmployeeName)
</div>
</fieldset>
<p>@Html.ActionLink("Back to List", "Index")</p>
</code>```

When you execute and visit the Index page of Employee, you'll see screen like this:

And the Modal Dialog with results will be shown like this:

Note: You need to add reference of jquery and Bootstrap and you can further design/customize it according to your needs

Hope it helps!

Body:
I have a table showing the information of the users, with an edit button for each one.

I want to show a modal form with the details for the user I want to edit, but I don't know how to get the details from the list, and passing them to the modal as a model.

Here is my View:

@model MyApp.Models.User
@{
    ViewBag.Title = "Users";
    var roles = new List<string> { "Manager", "Admin" };
    var userRoles = (List<string>)ViewData["userRoles"];
}

@ViewBag.Title

@if (userRoles.Any(u => roles.Contains(u)))
{
    using (Html.BeginForm("Update", "Admin", FormMethod.Post, new { id = "update-form", value = "" }))
    {

×

Edit User

                @Html.Label("Name", new { @class = "col-md-2 control-label" })

                    @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })

                @Html.Label("Age", new { @class = "col-md-2 control-label" })

                    @Html.TextBoxFor(m => m.Age, new { @class = "form-control" })

            Close
            <input type="submit" class="btn btn-primary" value="Save Changes" />

    }
}

            Name
            Age
            @if (userRoles.Any(u => roles.Contains(u)))
            {
                Edit
            }

        @foreach (var u in users)
        {

                @u.Name
                @u.Age
                @if (userRoles.Any(u => roles.Contains(u)))
                {
                    Edit
                }

        }

Body:
I've created a testing sample which will help you understand how can you achieve this.
Index.cshtml which will show a list of employees

@model IEnumerable<MvcApplication1.Models.Employee>
@using MvcApplication1.Models;
<h2>Index</h2>
<table>
@foreach (Employee item in Model)
{
    <tr>
        <td>@Html.ActionLink(@item.EmployeeName, "Name", new { id = item.ID })</td>
        <td>
            <button type="button" data-id='@item.ID' class="anchorDetail btn btn-info btn-sm" data-toggle="modal"
         data-target="#myModal">
                Open Large Modal</button></td>
    </tr>
 }
</table>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            <h4 class="modal-title">Details</h4>
        </div>
        <div class="modal-body">
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>
   </div>
  </div>

At the same page, reference the following scripts

<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />

JQuery AJAX call for getting/setting the data of individual employee from ActionMethod at the same page

<script>
$(document).ready(function () {
    var TeamDetailPostBackURL = '/Employee/Details';
    $(document).on('click', '.anchorDetail', function () {
        var $buttonClicked = $(this);
        var id = $buttonClicked.attr('data-id');
        var options = { "backdrop": "static", keyboard: true };
        $.ajax({
            type: "GET",
            url: TeamDetailPostBackURL,
            contentType: "application/json; charset=utf-8",
            data: { "Id": id },
            datatype: "json",
            success: function (data) {
                debugger;
                $('.modal-body').html(data);
                $('#myModal').modal(options);
                $('#myModal').modal('show');

            },
            error: function () {
                alert("Dynamic content load failed.");
            }
        });
    });
    $("#closbtn").click(function () {
        $('#myModal').modal('hide');
    });
});

Now Create a class of Employee(because i'm not using EF)

public class Employee
{
    public int ID { get; set; }
    public string EmployeeName { get; set; }
}

Create controller named Employee and 2 ActionMethods like these:

public ActionResult Index()
{
  return View(emp);//sends a List of employees to Index View
}
public ActionResult Details(int Id)
{
  return PartialView("Details",
  emp.Where(x=>x.ID==Convert.ToInt32(Id)).FirstOrDefault());
}

I'm returning PartialView because I need to load a page within a page.
Details.cshtml

@model MvcApplication1.Models.Employee
<fieldset>
<legend>Employee</legend>
<div class="display-label">
     @Html.DisplayNameFor(model => model.ID)
</div>
<div class="display-field">
    @Html.DisplayFor(model => model.ID)
</div>
<div class="display-label">
     @Html.DisplayNameFor(model => model.EmployeeName)
</div>
<div class="display-field">
    @Html.DisplayFor(model => model.EmployeeName)
</div>
</fieldset>
<p>@Html.ActionLink("Back to List", "Index")</p>

When you execute and visit the Index page of Employee, you'll see screen like this:

And the Modal Dialog with results will be shown like this:

Note: You need to add reference of jquery and Bootstrap and you can further design/customize it according to your needs

Hope it helps!


问:
How can I write the query as raw in Laravel?
Here is my query:

```<code>SELECT rid
FROM relations
WHERE rootid IN (736, 781)
GROUP BY rid HAVING COUNT(rid) = 2");
</code>```

I'm trying to implement that in Laravel. How can I do that? (both "query builder and eloquent approaches are fine to me")

This doesn't work: (it throws "something went wrong")

```<code>DB::table('relations')
->select('')
->whereRaw('rootid IN (736, 781)')
->groupBy('rid')
->havingRaw('COUNT(rid) = 2')
->get();
</code>```

答:
```<code>$sql = 'SELECT rid FROM relations WHERE rootid IN (736, 781)
         GROUP BY rid HAVING COUNT(rid) = 2)';

$result = DB::SELECT($sql);
</code>```

Body:
Here is my query:

SELECT rid
FROM relations
WHERE rootid IN (736, 781)
GROUP BY rid HAVING COUNT(rid) = 2");

I'm trying to implement that in Laravel. How can I do that? (both "query builder and eloquent approaches are fine to me")

This doesn't work: (it throws "something went wrong")

DB::table('relations')
->select('')
->whereRaw('rootid IN (736, 781)')
->groupBy('rid')
->havingRaw('COUNT(rid) = 2')
->get();


问:
magit merge conflict `checkout --theirs/--ours`
Sometimes when resolving a git conflict, I'll know that one side is better for a file and I'll resolve it with git checkout --theirs path/to/file.

However it is not obvious how to do this in magit, so I always drop to the CLI to do it. Is it possible to do this easily?

答:
If you right-click on the arrows at the head of the conflict

```<code><<<<<<<< HEAD
</code>```

a menu will appear and will let you select the appropriate action.

Body:
If you right-click on the arrows at the head of the conflict

<<<<<<<< HEAD

a menu will appear and will let you select the appropriate action.


答:
I use the following in a framework library...

```<code>public static T Maximum<T>(params T[] values)
    where T : struct, IComparable<T>
{
    var rV = values[0];
    foreach (var v in values.Where
        (v => v.CompareTo(rV) > 0))
        rV = v;
    return rV;
}
</code>```

In client code I can simply write

var maxVal = lib.Maximum(Value1, Value2,  .... , ValueN);

Title: What's the simplest way of returning the larger of two numbers?

Body:
Let's say I have an entity that looks like this:

public class Album()
{
    public DateTime LastUpdated { get; set; }
    public List<Picture> Pictures { get; set; }
}

What I want to do is create a LastActivity property that will return the latest date of the activity. This is easy enough for the Pictures collection:

public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated); }
}

However, I also want to consider the LastUpdated property on the Album entity as well. I could use this code:

public DateTime LastActivity
{
    get { return Pictures.Max(x => x.LastUpdated) > this.LastUpdated
              ? Pictures.Max(x => x.LastUpdated)
              : this.LastUpdated) };
}

But this is bad because it will do the Max() transformation twice. Is there a better way of writing this code?

Answer

This is the solution I came up with, based on the accepted answer:

public virtual DateTime LastActivity
{
    get
    {
        var max = Pictures.Any() ? Pictures.Max(x => x.LastUpdated) : DateTime.MinValue;
        return max > this.LastUpdated ? max : this.LastUpdated;
    }
}

The thing to watch out for is that if you do a Max() on an empty collection, you'll get an exception, so you have to check to see if there's anything in the collection first.

Body:
I use the following in a framework library...

public static T Maximum<T>(params T[] values)
    where T : struct, IComparable<T>
{
    var rV = values[0];
    foreach (var v in values.Where
        (v => v.CompareTo(rV) > 0))
        rV = v;
    return rV;
}

In client code I can simply write

var maxVal = lib.Maximum(Value1, Value2,  .... , ValueN);


问:
Parse CSS using JSoup in Java
I am trying to parse https://www.avito.ru/voronezh. On page there are 50 elements:

```<code><a class="item-description-title-link" href="/voronezh/mebel_i_interer/kuhni_1132166621" title="Кухни в Воронеже">
 Кухни
 </a>
</code>```

But some of these elements has following CSS properties:

```<code>element.style {
}
7cad82b….css?b0b9a4e:1
.item_table.item-highlight .item-description-title-link {
    background-color: #fbfe23;
    line-height: 19px;
    color: #0091d9;
    margin-top: -1px;
    padding: 2px 3px 0;
    display: inline-block;
}
</code>```

How I can get only elements with background-color: #fbfe23;?

答:
it seems you are trying to use Jsoup. Here is a solution using this lib. I  fetched all elements with class item-description-title-link in the page.</p>

```<code>import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.text.ParseException;

public class SouSoup {
    private static String url = "https://www.avito.ru/voronezh";

    /* Get Data */
    public static void getData() throws IOException, ParseException {
        System.out.println("Fetching file");
        Document doc = Jsoup.connect(url).get();
        Elements res=doc.getElementsByClass("item-description-title-link");
       for (Element elt : res) {
            System.out.println(res.text());
            }
    }

    public static void main(String[] args) throws IOException, ParseException{
        SouSoup.getData();
    }
}
</code>```

Title: Parse CSS using JSoup in Java

Body:
I am trying to parse https://www.avito.ru/voronezh. On page there are 50 elements:

 Кухни

But some of these elements has following CSS properties:

element.style {
}
7cad82b….css?b0b9a4e:1
.item_table.item-highlight .item-description-title-link {
    background-color: #fbfe23;
    line-height: 19px;
    color: #0091d9;
    margin-top: -1px;
    padding: 2px 3px 0;
    display: inline-block;
}

How I can get only elements with background-color: #fbfe23;?

Body:
it seems you are trying to use Jsoup. Here is a solution using this lib. I  fetched all elements with class item-description-title-link in the page.

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.text.ParseException;

public class SouSoup {
    private static String url = "https://www.avito.ru/voronezh";

    /* Get Data */
    public static void getData() throws IOException, ParseException {
        System.out.println("Fetching file");
        Document doc = Jsoup.connect(url).get();
        Elements res=doc.getElementsByClass("item-description-title-link");
       for (Element elt : res) {
            System.out.println(res.text());
            }
    }

    public static void main(String[] args) throws IOException, ParseException{
        SouSoup.getData();
    }
}


问:
MQTT Load Testing via Jenkins using JMETER
I'm trying to run MQTT test using JMeter on Jenkins. I've integrated maven and used Github repository to run the script. The problem is when i try to run a simple API test, jenkins automatically creates a .jtl file(provided that i've added post build action) In case of MQTT test script, Jenkins Build is successful but the test fails showing this error " no JMeter files matching '*.jtl' have been found.". Why is it so???</p>

答:
Do you use Jenkins performance plugin? If not you should do it.

Do you run JMeter in the Non GUI mode? If not you have to.
In this article how to run JMeter with jenkins you'll find step by step guide for Jenkins configuration for launching JMeter tests.