问:
Under what circumstance C# ASP.NET HttpContext.Current.Session throws, IndexOutOfRangeException?
I am getting an error that doesn't happen very often, but the client has seen it and wants it fixed.

Basically, it's an IndexOutOfRangeException exception, but what's odd is that the trace points to System.Web.HttpContext.Current. How is that possible?

The line that it fails on is like this:

     at
  System.Collections.ArrayList.Add(Object value)   at
  System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String
  name, Object value)    at
  System.Web.SessionState.SessionStateItemCollection.set_Item(String
  name, Object value)    at
  WebStateManager.set_Item(String key, Object value)
  in
  \WebStateManager.cs:line
  53    at UIStateManager.get_BookingParameters() in
  WS\App_Code\Managers\UIStateManager.cs:line
  2746

  Index was outside the bounds of
  the array.

```<code>System.Web.HttpContext context = System.Web.HttpContext.Current;
</code>```

If it was an array, I could do counts and other checks, but what kind of check would I do here other than a try-catch?
enter link description here

```<code>public class Example
{
   public static void Main()
   {
      int[] values1 = { 3, 6, 9, 12, 15, 18, 21 };
      int[] values2 = new int[6];

      // Assign last element of the array to the new array.
      values2[values1.Length - 1] = values1[values1.Length - 1];
   }
}
// The example displays the following output:
//       Unhandled Exception:
//       System.IndexOutOfRangeException:
//       Index was outside the bounds of the array.
//       at Example.Main()
</code>```

My Project Code

```<code>public override object this[string key]
        {
            get
            {
                if (Helpers.CommonFunctions.IsHttpSessionNull)
                { return null; }

                return HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()];
            }
            set
            {
                if (Helpers.CommonFunctions.IsHttpSessionNull)
                { return; }

                if (value == null)
                {
                    try
                    {
                        if (HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()] != null)
                        {
                            HttpContext.Current.Session.Remove(key + Helpers.CommonFunctions.GetAppDomainMultiplexer());
                        }
                    }
                    catch
                    {
                    }
                }
                else
                {
                        HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()] = value;

                }
            }
        }
</code>```

The fault stack trace is as follows;

```<code>0:072> !clrstack
    OS Thread Id: 0x31ec (72)
            Child SP               IP Call Site
    000000aea766d968 000007f9736a4650 [HelperMethodFrame: 000000aea766d968]
    000000aea766da50 000007f9674e0e5a System.Collections.ArrayList.Add(System.Object)
    000000aea766da90 000007f966655292 System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(System.String, System.Object)
    000000aea766dae0 000007f9650ac4c9 System.Web.SessionState.SessionStateItemCollection.set_Item(System.String, System.Object)
    000000aea766db20 000007f90ed89ce9 UTL.WebStateManager.set_Item(System.String, System.Object)
    000000aea766dbf0 000007f90f29370c WebStateManagerHelper.get_OriginalPNR()
    000000aea766dc80 000007f90f29242d QueryDynamicLoggingComponent.LogTransaction(System.String, System.String)
    000000aea766e110 000007f90f2917e3 WSHelper.Log(System.String, System.String, Boolean, System.String)
    000000aea766e160 000007f90f28fd17 WSHelper.GetResponse(System.String, SecurityInfo, System.String, System.String, System.String ByRef, System.String, System.String)
    000000aea766e5d0 000007f90f29eae6 WSHelper.SendQuery(System.String, SecurityInfo, System.String)
    000000aea766e7f0 000007f90f29e7f8 WSHelper.SendQuery(SecurityInfo, System.String)
    000000aea766e840 000007f90f29e4af APIWSPool.SendAndReceiveQueryToString(Agency, System.String, Token, Boolean)
    000000aea766e940 000007f90f29e374 APIWSPool.SendAndReceiveQuery(Agency, Token, Boolean)
    000000aea766e9b0 000007f90f6168f4 FlightBookingManager.SearchFlightForMPSearchedFlightRecommendations1(Agency, FlightFareDrivenSearchInfo, Boolean)
    000000aea766eb80 000007f90f615ec1 ApiFlightBookingProvider.SearchFlightForMPSearchedFlightRecommendations1(Agency, FlightFareDrivenSearchInfo, Boolean)
    000000aea766ebe0 000007f90f6158f2 APICOM.Threading.OWCOutboundSearchThread.Work()
    000000aea766edb0 000007f9674e2d45 System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
    000000aea766ef10 000007f9674e2ab9 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
    000000aea766ef40 000007f9674e2a97 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
    000000aea766ef90 000007f9674fa161 System.Threading.ThreadHelper.ThreadStart()
    000000aea766f2a8 000007f96e0eab53 [GCFrame: 000000aea766f2a8]
    000000aea766f5f8 000007f96e0eab53 [DebuggerU2MCatchHandlerFrame: 000000aea766f5f8]
    000000aea766f788 000007f96e0eab53 [ContextTransitionFrame: 000000aea766f788]
    000000aea766f9a8 000007f96e0eab53 [DebuggerU2MCatchHandlerFrame: 000000aea766f9a8]
</code>```

答:
SessionStateItemCollection is not thread-safe (see https://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionstateitemcollection(v=vs.110).aspx), and you likely have multiple threads writing / reading from the session state at the same time.

You need to find your code that accesses HttpContext.Session or Page.Session and make sure that code is not running in a background thread.

See https://msdn.microsoft.com/en-us/library/system.indexoutofrangeexception(v=vs.110).aspx - (search for "Violating thread safety")

Below is some example code using locking to try and avoid the issue. This code is very quick and dirty. I do not recommend it. But short of re-architecting your system, it may be worthwhile. If you use this technique, you must put it around every use of Session.

```<code>    public override object this[string key]
    {
        get
        {
            if (Helpers.CommonFunctions.IsHttpSessionNull)
            { return null; }

            lock (HttpContext.Current.Session)
            {
                return HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()];
            }
        }
        set
        {
            if (Helpers.CommonFunctions.IsHttpSessionNull)
            { return; }

            lock (HttpContext.Current.Session)
            {
                if (value == null)
                {
                    try
                    {
                        if (HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()] != null)
                        {
                            HttpContext.Current.Session.Remove(key + Helpers.CommonFunctions.GetAppDomainMultiplexer());
                        }
                    }
                    catch
                    {
                    }
                }
                else
                {
                    HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()] = value;

                }
            }
        }
</code>```

Body:
I am getting an error that doesn't happen very often, but the client has seen it and wants it fixed.

Basically, it's an IndexOutOfRangeException exception, but what's odd is that the trace points to System.Web.HttpContext.Current. How is that possible?

The line that it fails on is like this:

     at
  System.Collections.ArrayList.Add(Object value)   at
  System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(String
  name, Object value)    at
  System.Web.SessionState.SessionStateItemCollection.set_Item(String
  name, Object value)    at
  WebStateManager.set_Item(String key, Object value)
  in
  \WebStateManager.cs:line
  53    at UIStateManager.get_BookingParameters() in
  WS\App_Code\Managers\UIStateManager.cs:line
  2746

  Index was outside the bounds of
  the array.

System.Web.HttpContext context = System.Web.HttpContext.Current;

If it was an array, I could do counts and other checks, but what kind of check would I do here other than a try-catch?
enter link description here

public class Example
{
   public static void Main()
   {
      int[] values1 = { 3, 6, 9, 12, 15, 18, 21 };
      int[] values2 = new int[6];

      // Assign last element of the array to the new array.
      values2[values1.Length - 1] = values1[values1.Length - 1];
   }
}
// The example displays the following output:
//       Unhandled Exception:
//       System.IndexOutOfRangeException:
//       Index was outside the bounds of the array.
//       at Example.Main()

My Project Code

public override object this[string key]
        {
            get
            {
                if (Helpers.CommonFunctions.IsHttpSessionNull)
                { return null; }

                return HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()];
            }
            set
            {
                if (Helpers.CommonFunctions.IsHttpSessionNull)
                { return; }

                if (value == null)
                {
                    try
                    {
                        if (HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()] != null)
                        {
                            HttpContext.Current.Session.Remove(key + Helpers.CommonFunctions.GetAppDomainMultiplexer());
                        }
                    }
                    catch
                    {
                    }
                }
                else
                {
                        HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()] = value;

                }
            }
        }

The fault stack trace is as follows;

0:072> !clrstack
    OS Thread Id: 0x31ec (72)
            Child SP               IP Call Site
    000000aea766d968 000007f9736a4650 [HelperMethodFrame: 000000aea766d968]
    000000aea766da50 000007f9674e0e5a System.Collections.ArrayList.Add(System.Object)
    000000aea766da90 000007f966655292 System.Collections.Specialized.NameObjectCollectionBase.BaseAdd(System.String, System.Object)
    000000aea766dae0 000007f9650ac4c9 System.Web.SessionState.SessionStateItemCollection.set_Item(System.String, System.Object)
    000000aea766db20 000007f90ed89ce9 UTL.WebStateManager.set_Item(System.String, System.Object)
    000000aea766dbf0 000007f90f29370c WebStateManagerHelper.get_OriginalPNR()
    000000aea766dc80 000007f90f29242d QueryDynamicLoggingComponent.LogTransaction(System.String, System.String)
    000000aea766e110 000007f90f2917e3 WSHelper.Log(System.String, System.String, Boolean, System.String)
    000000aea766e160 000007f90f28fd17 WSHelper.GetResponse(System.String, SecurityInfo, System.String, System.String, System.String ByRef, System.String, System.String)
    000000aea766e5d0 000007f90f29eae6 WSHelper.SendQuery(System.String, SecurityInfo, System.String)
    000000aea766e7f0 000007f90f29e7f8 WSHelper.SendQuery(SecurityInfo, System.String)
    000000aea766e840 000007f90f29e4af APIWSPool.SendAndReceiveQueryToString(Agency, System.String, Token, Boolean)
    000000aea766e940 000007f90f29e374 APIWSPool.SendAndReceiveQuery(Agency, Token, Boolean)
    000000aea766e9b0 000007f90f6168f4 FlightBookingManager.SearchFlightForMPSearchedFlightRecommendations1(Agency, FlightFareDrivenSearchInfo, Boolean)
    000000aea766eb80 000007f90f615ec1 ApiFlightBookingProvider.SearchFlightForMPSearchedFlightRecommendations1(Agency, FlightFareDrivenSearchInfo, Boolean)
    000000aea766ebe0 000007f90f6158f2 APICOM.Threading.OWCOutboundSearchThread.Work()
    000000aea766edb0 000007f9674e2d45 System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
    000000aea766ef10 000007f9674e2ab9 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
    000000aea766ef40 000007f9674e2a97 System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object)
    000000aea766ef90 000007f9674fa161 System.Threading.ThreadHelper.ThreadStart()
    000000aea766f2a8 000007f96e0eab53 [GCFrame: 000000aea766f2a8]
    000000aea766f5f8 000007f96e0eab53 [DebuggerU2MCatchHandlerFrame: 000000aea766f5f8]
    000000aea766f788 000007f96e0eab53 [ContextTransitionFrame: 000000aea766f788]
    000000aea766f9a8 000007f96e0eab53 [DebuggerU2MCatchHandlerFrame: 000000aea766f9a8]

Body:
SessionStateItemCollection is not thread-safe (see https://msdn.microsoft.com/en-us/library/system.web.sessionstate.sessionstateitemcollection(v=vs.110).aspx), and you likely have multiple threads writing / reading from the session state at the same time.

You need to find your code that accesses HttpContext.Session or Page.Session and make sure that code is not running in a background thread.

See https://msdn.microsoft.com/en-us/library/system.indexoutofrangeexception(v=vs.110).aspx - (search for "Violating thread safety")

Below is some example code using locking to try and avoid the issue. This code is very quick and dirty. I do not recommend it. But short of re-architecting your system, it may be worthwhile. If you use this technique, you must put it around every use of Session.

    public override object this[string key]
    {
        get
        {
            if (Helpers.CommonFunctions.IsHttpSessionNull)
            { return null; }

            lock (HttpContext.Current.Session)
            {
                return HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()];
            }
        }
        set
        {
            if (Helpers.CommonFunctions.IsHttpSessionNull)
            { return; }

            lock (HttpContext.Current.Session)
            {
                if (value == null)
                {
                    try
                    {
                        if (HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()] != null)
                        {
                            HttpContext.Current.Session.Remove(key + Helpers.CommonFunctions.GetAppDomainMultiplexer());
                        }
                    }
                    catch
                    {
                    }
                }
                else
                {
                    HttpContext.Current.Session[key + Helpers.CommonFunctions.GetAppDomainMultiplexer()] = value;

                }
            }
        }


来源: stackexchange

问:
drupal 6.19 password reset redirect
I trying in drupal 6.19  to redirect the 'user/password' page after submit to 'alter location'   then user page.

I am using in theme hook to get the preprocess function and in it I edit the $variables as:

```<code>$variables['form']['#action'] = 'alter location';
</code>```

and after that I use drupal_render() .

in the drupal debug I see that the #action is set to the 'alter location' but in the
html tag I still see action='user/password' and it not redirect me to the desired location.

Thanks in advance

答:
In Drupal forms work like this: User requests a page containing the form. A function creates a structured array that makes up that form. This array gets rendered in the theme layer. If the user submits the form, Drupal calls the same routine to again build the structured array. But now it's used to validate and process user input. If the processing routine returns a path or ?destination or #redirect is set, Drupal does an internal redirect. If not, the same form is displayed again. Then and only then is your code in the theming layer executed. However it's to late to inject #redirect. Drupal won't look at it anymore.

Changing the #action is rather senseless as thereby the user input is sent to a URL that Drupal's menu system translates and calls routines that do not expect nor process the input.

Try the path redirect module. If it does not work follow these instructions to create a custom module.

ContentLicense: CC BY-SA 2.5

Title: drupal 6.19 password reset redirect

Body:
I trying in drupal 6.19  to redirect the 'user/password' page after submit to 'alter location'   then user page.

I am using in theme hook to get the preprocess function and in it I edit the $variables as:

$variables['form']['#action'] = 'alter location';

and after that I use drupal_render() .

in the drupal debug I see that the #action is set to the 'alter location' but in the
html tag I still see action='user/password' and it not redirect me to the desired location.

Thanks in advance


问:
Increasing Variables
So I am writing a program that will need to increase some variables by the amount that the user types. I thought a code like this would work:

```<code>var = 0
increase = input("Increase by: ")
var + increase
print(var)
</code>```

But it just says that var is 0. I even tried making the input type int, int(input(""))

Still didn't work. Why won't it increase the variable?

Keep in mind, I am using Python 2.7

EDIT It was solved! I just made it var += increase

答:
you're missing the setting of var. When you add var + increase it needs to be

```<code>var=var+increase.
return var or print(var)
</code>```

basically, you're adding var to increase without doing anything with the resulting sum.

ContentLicense: CC BY-SA 3.0

Title: Increasing Variables

Body:
So I am writing a program that will need to increase some variables by the amount that the user types. I thought a code like this would work:

var = 0
increase = input("Increase by: ")
var + increase
print(var)

But it just says that var is 0. I even tried making the input type int, int(input(""))

Still didn't work. Why won't it increase the variable?

Keep in mind, I am using Python 2.7

EDIT It was solved! I just made it var += increase

Body:
you're missing the setting of var. When you add var + increase it needs to be

var=var+increase.
return var or print(var)

basically, you're adding var to increase without doing anything with the resulting sum.


问:
Crop black artifacts from stabilized video
I have a video that I need to stabilize with matlab.
I managed to get a stabilized video, but it has some black artifacts on the frame edges (an example can be seen here - it's not my video but has the same problem).

Is there an efficient way to get a final video without those artifacts?
I  thought about cropping every frame to the same size, but to know that size one must process the whole video in order to know the maximal "penetration" of those artifacts.

I examined some frames individually and I noticed that the artifacts are pure black (i.e the intensity level is 0), if that makes it a little bit easier.

thanks.

答:
Just in case someone might find it useful sometime - I came up with this implementation (solution is mainly based on this answer (the last part), which was answered to a similar question regarding a single image...):

```<code>function [] = stabilizeVideo(fileName)

    % open video reader and writer
    InputVid = vision.VideoFileReader(fileName);
    StabilizedVid = vision.VideoFileWriter('StabilizedVidWithArtifacts.avi');

    leftPent = 0;
    upPent = 0;
    [downPent, rightPent] = size(imgB);

    % any initialization you might need...

    while ~isDone(InputVid)
        % Stabilize frame... the warped frame is called 'imgBp'
        % write the warped frame to the video
        step(StabilizedVid,imgBp);

        % now the magic happens:
        [up, down, left, right] = FindMaxArtifactPenetration(imgBp);
        leftPent = max(left, leftPent);
        rightPent = min(right, rightPent);
        upPent = max(up, upPent);
        downPent = min(down, downPent);

    end
    release(InputVid);
    release(StabilizedVid);
    cropArtifacts(upPent, downPent, leftPent, rightPent);
    display(num2str(toc));
end
</code>```

I wrote those helper functions:

```<code>function [up, down, left, right] = FindMaxArtifactPenetration(I)
    % allow RGB or grayscale image
    if size(I,3)==3
        I1 = rgb2gray(I);
    else
        I1 = I;
    end

    nonZeroCols = find(any(I1)); % find non-zero cols
    left = min(nonZeroCols);
    right = max(nonZeroCols);
    I2 = I1(:, left : right, :);
    nonZeroRows = find(any(I2, 2)); % find non-zero rows
    up = min(nonZeroRows);
    down = max(nonZeroRows);
end

function [] = cropArtifacts(minRow, maxRow, minCol, maxCol)

    % reload video with artifacts, crop every frame and save it in the
    % new video
    InputVid = vision.VideoFileReader('StabilizedVidWithArtifacts.avi');
    StabilizedVid = vision.VideoFileWriter('StabilizedVid.avi');
    while ~isDone(InputVid)
        frame = step(InputVid);
        step(StabilizedVid, frame(minRow:maxRow, minCol:maxCol, :));
    end
    release(InputVid);
    release(StabilizedVid);

end
</code>```

Body:
Just in case someone might find it useful sometime - I came up with this implementation (solution is mainly based on this answer (the last part), which was answered to a similar question regarding a single image...):

function [] = stabilizeVideo(fileName)

    % open video reader and writer
    InputVid = vision.VideoFileReader(fileName);
    StabilizedVid = vision.VideoFileWriter('StabilizedVidWithArtifacts.avi');

    leftPent = 0;
    upPent = 0;
    [downPent, rightPent] = size(imgB);

    % any initialization you might need...

    while ~isDone(InputVid)
        % Stabilize frame... the warped frame is called 'imgBp'
        % write the warped frame to the video
        step(StabilizedVid,imgBp);

        % now the magic happens:
        [up, down, left, right] = FindMaxArtifactPenetration(imgBp);
        leftPent = max(left, leftPent);
        rightPent = min(right, rightPent);
        upPent = max(up, upPent);
        downPent = min(down, downPent);

    end
    release(InputVid);
    release(StabilizedVid);
    cropArtifacts(upPent, downPent, leftPent, rightPent);
    display(num2str(toc));
end

I wrote those helper functions:

function [up, down, left, right] = FindMaxArtifactPenetration(I)
    % allow RGB or grayscale image
    if size(I,3)==3
        I1 = rgb2gray(I);
    else
        I1 = I;
    end

    nonZeroCols = find(any(I1)); % find non-zero cols
    left = min(nonZeroCols);
    right = max(nonZeroCols);
    I2 = I1(:, left : right, :);
    nonZeroRows = find(any(I2, 2)); % find non-zero rows
    up = min(nonZeroRows);
    down = max(nonZeroRows);
end

function [] = cropArtifacts(minRow, maxRow, minCol, maxCol)

    % reload video with artifacts, crop every frame and save it in the
    % new video
    InputVid = vision.VideoFileReader('StabilizedVidWithArtifacts.avi');
    StabilizedVid = vision.VideoFileWriter('StabilizedVid.avi');
    while ~isDone(InputVid)
        frame = step(InputVid);
        step(StabilizedVid, frame(minRow:maxRow, minCol:maxCol, :));
    end
    release(InputVid);
    release(StabilizedVid);

end


问:
Firebase limits
I intend to develop an simple chat application inheriting the funtionalities of FCM. I would like to know the limits imposed over as it may restrict myself of implementing certain tasks. I would also like to know the number of connections at a given instant and the limit on number of messages could be send from a device?</p>

答:
You don't have any limitations regarding an app which uses a Firebase database. If we are speaking about pricing list, it's true there is a free plan, and if want to stay in this plan, you need to have less than 100 Simultaneous connections, less than 1GB stored and less than 10GB/month GB downloaded according to Firebase pricing list.

Hope it helps.

Title: Firebase limits


问:
Dynamic Currency Formating in HTML
How to align dynamic Currency accordingly to the Currency format?

Example:
if currency has dollar it should be left aligned ($ 100)
if currency has euro it should be right aligned (100 gbp)

Is there any best possible way we can bring this out.
Thanks in advance for your help.

答:
In ATG you could use

```<code><dsp:valueof param="amount" converter="currency" locale="en_US" />
</code>```

Or if you want to do it with Javascript, there is this library: http://numeraljs.com/ check the currency sector.

Title: Dynamic Currency Formating in HTML

Body:
In ATG you could use

<dsp:valueof param="amount" converter="currency" locale="en_US" />

Or if you want to do it with Javascript, there is this library: http://numeraljs.com/ check the currency sector.


问:
Unable to Connect to Bluetooth device
This is the piece of code from Standard from Google sample code BluetoothChat.
BluetoothChatService.java

```<code>public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[1024];
        int bytes;

        // Keep listening to the InputStream while connected
        while (mState == STATE_CONNECTED) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                break;
            }
        }
    }
</code>```

As soon as I try to connect the device using

```<code>mChatService.connect(device, false);
</code>```

I get following exception

```<code>java.io.IOException: bt socket closed, read return: -1
at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:872)
at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
at java.io.InputStream.read(InputStream.java:163)
</code>```

Any help would be appreciated.

答:
It looks like socket was closed before you passed it in your mConnectedThread's constructor.

There is one tricky thing in Google sample, in mConnectThread when socket was actually connected we make mConnectThread null, and next code won't be executed:

```<code>if (mConnectThread != null) {
    mConnectThread.cancel();
    mConnectThread = null;
}
</code>```

that means that cancel() method which closes the socket will be skipped.

Basically, make sure you don't call close() method in ConnectThread after your socket was connected.

Title: Unable to Connect to Bluetooth device

Body:
This is the piece of code from Standard from Google sample code BluetoothChat.
BluetoothChatService.java

public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[1024];
        int bytes;

        // Keep listening to the InputStream while connected
        while (mState == STATE_CONNECTED) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                break;
            }
        }
    }

As soon as I try to connect the device using

mChatService.connect(device, false);

I get following exception

java.io.IOException: bt socket closed, read return: -1
at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:872)
at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
at java.io.InputStream.read(InputStream.java:163)

Any help would be appreciated.

Body:
It looks like socket was closed before you passed it in your mConnectedThread's constructor.

There is one tricky thing in Google sample, in mConnectThread when socket was actually connected we make mConnectThread null, and next code won't be executed:

if (mConnectThread != null) {
    mConnectThread.cancel();
    mConnectThread = null;
}

that means that cancel() method which closes the socket will be skipped.

Basically, make sure you don't call close() method in ConnectThread after your socket was connected.


问:
Class method takes exactly 2 arguments (1 given)
please explain where is my error

```<code>class SomeClass1():
  def func1(self,text):
    .....
class SomeClass2():
   def func2(self):
     a=SomeClass1.func1("string")
</code>```

Gives an error:
in func2 a=SomeClass1.func1("string"), func1 takes exactly 2 arguments (1 given)

答:
For the sake of completeness, here's a solution that calls the function through the class, passing an instance as a parameter.</p>

```<code>class SomeClass2():
   def func2(self):
     obj = SomeClass1()
     a = SomeClass1.func1(obj, "string") # this will help you understand the meaning of `self` as parameters inside those functions.
</code>```

Body:
please explain where is my error

class SomeClass1():
  def func1(self,text):
    .....
class SomeClass2():
   def func2(self):
     a=SomeClass1.func1("string")

Gives an error:
in func2 a=SomeClass1.func1("string"), func1 takes exactly 2 arguments (1 given)

Body:
For the sake of completeness, here's a solution that calls the function through the class, passing an instance as a parameter.

class SomeClass2():
   def func2(self):
     obj = SomeClass1()
     a = SomeClass1.func1(obj, "string") # this will help you understand the meaning of `self` as parameters inside those functions.


问:
Define bean depending on Spring's bean
When using Spring Boot, a lot of beans are created implicitly by Spring Boot itself. For example, when I link the spring-boot-starter-data-redis dependency, the jedisConnectionFactory bean is created automatically under the hood.

What I'm looking for is the way to define my custom bean with a dependency on such an implicit bean, e.g. new MyService( jedisConnectionFactory ). The problem is that I don't have a variable or a method which would be resolved to that implicit bean.

For now I've come up with the following solution: create a separate BeanConfig class, autowire/inject ApplicationContext into it and then retrieve the required bean with ApplicationContext.getBean( Class<T> ) method call:

```<code>@Bean
public Transport eventTransport() {
    final JedisConnectionFactory jedisConnectionFactory = context.getBean( JedisConnectionFactory.class );
    return new RedisTransport( jedisConnectionFactory.getHostName(), jedisConnectionFactory.getPort() );
}
</code>```

Is there any integrated way to get a reference to the beans defined internally? So that I could move this bean definition to MyApplication class without injecting the ApplicationContext instance.

答:
First as a rule of thumb if you starting to resort to the ApplicationContext or BeanFactory to obtain beans you are, generally speaking, doing it wrong (at least when simply developing an application with Spring).

When using @Bean on a method, effectively making it a factory method for those beans, you can use 0 or more method arguments. (This is also explained in the reference guide). The arguments are resolved against the context and will have the beans injected (or fail starting if it cannot be found).

So in your case you can simply add JedisConnnectionFactory (or maybe the ConnectionFactory interface) as a method argument for your eventTransport method.

```<code>@Bean
public Transport eventTransport(final JedisConnectionFactory jedisConnectionFactory) {
    return new RedisTransport( jedisConnectionFactory.getHostName(), jedisConnectionFactory.getPort() );
}
</code>```

This also allows Spring to resolve dependencies between beans instead of hoping the bean is already constructed and fully ready for use.

Title: Define bean depending on Spring's bean

Body:
When using Spring Boot, a lot of beans are created implicitly by Spring Boot itself. For example, when I link the spring-boot-starter-data-redis dependency, the jedisConnectionFactory bean is created automatically under the hood.

What I'm looking for is the way to define my custom bean with a dependency on such an implicit bean, e.g. new MyService( jedisConnectionFactory ). The problem is that I don't have a variable or a method which would be resolved to that implicit bean.

For now I've come up with the following solution: create a separate BeanConfig class, autowire/inject ApplicationContext into it and then retrieve the required bean with ApplicationContext.getBean( Class<T> ) method call:

@Bean
public Transport eventTransport() {
    final JedisConnectionFactory jedisConnectionFactory = context.getBean( JedisConnectionFactory.class );
    return new RedisTransport( jedisConnectionFactory.getHostName(), jedisConnectionFactory.getPort() );
}

Is there any integrated way to get a reference to the beans defined internally? So that I could move this bean definition to MyApplication class without injecting the ApplicationContext instance.

Body:
First as a rule of thumb if you starting to resort to the ApplicationContext or BeanFactory to obtain beans you are, generally speaking, doing it wrong (at least when simply developing an application with Spring).

When using @Bean on a method, effectively making it a factory method for those beans, you can use 0 or more method arguments. (This is also explained in the reference guide). The arguments are resolved against the context and will have the beans injected (or fail starting if it cannot be found).

So in your case you can simply add JedisConnnectionFactory (or maybe the ConnectionFactory interface) as a method argument for your eventTransport method.

@Bean
public Transport eventTransport(final JedisConnectionFactory jedisConnectionFactory) {
    return new RedisTransport( jedisConnectionFactory.getHostName(), jedisConnectionFactory.getPort() );
}

This also allows Spring to resolve dependencies between beans instead of hoping the bean is already constructed and fully ready for use.


问:
Output file of PowerShell script not created after scheduling using Task Scheduler
I have made a PowerShell script which will watch some logs and saves output in error.txt (created within script), which is working fine while running it individually.
But when I scheduled it for automatic execution using Task Scheduler, the output file error.txt is not created. Rest all is working fine.

Following is my script:

$Modified = Get-Item "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\logs\error.log" |
            Foreach {$_.LastWriteTime.ToLongTimeString()}

$DateTime = Get-Date -format "ddd MMM dd HH:mm:ss yyyy"
$DateTime1 = Get-Date -format "ddd MMM dd"
$Time4 = Get-Date -format "HH"
echo $Time4

$test = ($Time4) - 1
echo $test

$test2 = $DateTime1 +" " + $test
echo $test2

$a = Get-Content "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\logs\error.log" |
     Where-Object {$_ -match $test2} |
     Where-Object {$_ -match "error"}

if ($a) {
  Get-Content "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\logs\error.log" |
    Where-Object {$_ -match $test2} |
    Where-Object {$_ -match "error"} |
    Out-File -Append  error.txt
} else {
  echo -$DateTime---no-errors-in-last-hour- |
    Out-File -Append error.txt
}
```

<p>When I scheduled it to run every 5 minutes, rather then creating <code>error.txt</code> and showing <code>echo</code> part, it only shows echo part.</p>

<p>Following are the parameters I pass to scheduler to run PowerShell:</p>

```%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe
```

<p>Following are the arguements to run PowerShell script:</p>

```-File "C:\Users\gurlove.chopra\Desktop\SAMPLE_WATCHER8.PS1"
```

Can anyone help me regarding why my file is not getting created?

Also I tried creating a .BAT file which calls this PowerShell script and scheduled it in same manner, but I faced the same results, that is individually it is working fine but using Task Scheduler I got the same result.

答:
Thanks both of you elzooilogico and Ansgar Wiechers for your concern, it is source of great help.

I made a slight change in my powershell script , which is rather then writing only the name of file , i gave the full path and bingo it is working.

My file looks like this now:

```<code>$Modified= Get-Item "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\logs\error.log"| Foreach {$_.LastWriteTime.ToLongTimeString()}

$DateTime= Get-Date -format "ddd MMM dd HH:mm:ss yyyy"

$DateTime1 = Get-Date -format "ddd MMM dd"

$DateTime2 = Get-Date -format "HH:mm:ss"

$Time4 = Get-Date -format "HH"
echo $Time4
$Time5 = Get-Date -format "mm"

$Time6 = Get-Date -format "ss"

$test= ($Time4)- 1
echo $test

$test2= $DateTime1 +" " + $test
echo $test2

$a= Get-Content "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\logs\error.log"|Where-Object {$_ -match $test2}|Where-Object {$_ -match "error"}

if ($a){
Get-Content "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\logs\error.log"|Where-Object {$_ -match $test2}|Where-Object {$_ -match "error"} | Out-File -Append C:\Users\gurlove.chopra\Desktop\error.txt
}
else{
echo -$DateTime---no-errors-in-last-hour-|Out-File -Append C:\Users\gurlove.chopra\Desktop\error.txt
}
</code>```

Body:
I have made a PowerShell script which will watch some logs and saves output in error.txt (created within script), which is working fine while running it individually.
But when I scheduled it for automatic execution using Task Scheduler, the output file error.txt is not created. Rest all is working fine.

Following is my script:

$Modified = Get-Item "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\logs\error.log" |
            Foreach {$_.LastWriteTime.ToLongTimeString()}

$DateTime = Get-Date -format "ddd MMM dd HH:mm:ss yyyy"
$DateTime1 = Get-Date -format "ddd MMM dd"
$Time4 = Get-Date -format "HH"
echo $Time4

$test = ($Time4) - 1
echo $test

$test2 = $DateTime1 +" " + $test
echo $test2

$a = Get-Content "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\logs\error.log" |
     Where-Object {$_ -match $test2} |
     Where-Object {$_ -match "error"}

if ($a) {
  Get-Content "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\logs\error.log" |
    Where-Object {$_ -match $test2} |
    Where-Object {$_ -match "error"} |
    Out-File -Append  error.txt
} else {
  echo -$DateTime---no-errors-in-last-hour- |
    Out-File -Append error.txt
}

When I scheduled it to run every 5 minutes, rather then creating error.txt and showing echo part, it only shows echo part.

Following are the parameters I pass to scheduler to run PowerShell:

%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe

Following are the arguements to run PowerShell script:

-File "C:\Users\gurlove.chopra\Desktop\SAMPLE_WATCHER8.PS1"

Can anyone help me regarding why my file is not getting created?

Also I tried creating a .BAT file which calls this PowerShell script and scheduled it in same manner, but I faced the same results, that is individually it is working fine but using Task Scheduler I got the same result.

Body:
Thanks both of you elzooilogico and Ansgar Wiechers for your concern, it is source of great help.

I made a slight change in my powershell script , which is rather then writing only the name of file , i gave the full path and bingo it is working.

My file looks like this now:

$Modified= Get-Item "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\logs\error.log"| Foreach {$_.LastWriteTime.ToLongTimeString()}

$DateTime= Get-Date -format "ddd MMM dd HH:mm:ss yyyy"

$DateTime1 = Get-Date -format "ddd MMM dd"

$DateTime2 = Get-Date -format "HH:mm:ss"

$Time4 = Get-Date -format "HH"
echo $Time4
$Time5 = Get-Date -format "mm"

$Time6 = Get-Date -format "ss"

$test= ($Time4)- 1
echo $test

$test2= $DateTime1 +" " + $test
echo $test2

$a= Get-Content "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\logs\error.log"|Where-Object {$_ -match $test2}|Where-Object {$_ -match "error"}

if ($a){
Get-Content "C:\Program Files (x86)\Apache Software Foundation\Apache2.2\logs\error.log"|Where-Object {$_ -match $test2}|Where-Object {$_ -match "error"} | Out-File -Append C:\Users\gurlove.chopra\Desktop\error.txt
}
else{
echo -$DateTime---no-errors-in-last-hour-|Out-File -Append C:\Users\gurlove.chopra\Desktop\error.txt
}


问:
Binding resize event handler to table row with jQuery
I wonder if it's possible to bind a resize event handler to a table's row.</p>

答:
Yes and no, yes, but not by default.  There is however a plugin to support this by Ben Alman - the jQuery resize event plugin, which allows resize on more than just window.

You can test out a demonstration of it with a
 here.

Body:
Yes and no, yes, but not by default.  There is however a plugin to support this by Ben Alman - the jQuery resize event plugin, which allows resize on more than just window.

You can test out a demonstration of it with a <tr> here.


问:
Merging mulit-valued dictionaries
Lets say I have two dictionaries with multiple values per key:

```<code>Dict1 = { key1 : [value1,value2] }
Dict2 = { key1 : [value3,value4], key2 : [value5,value6]}
</code>```

I want to merge them into one dictionary like this:

```<code>mergedDict = { key 1 : [value1,value2,value3,value4], key 2 : [0,0,value5,value6] }
</code>```

答:
Try with defaultdict:

```<code>from collections import defaultdict
dict1  = { 'key1' : ['value1','value2'] }
dict2 = { 'key1' : ['value3','value4'], 'key2' : ['value5','value6']}
dict3 = defaultdict(list)
for d1, d2 in dict1.items() + dict2.items():
    dict3[d1].extend(d2)
dict(dict3) #convert defaultdict to dict
</code>```

Output:

```<code>{'key1': ['value1', 'value2', 'value3', 'value4'],
 'key2': ['value5', 'value6']}
</code>```

Title: Merging mulit-valued dictionaries

Body:
Lets say I have two dictionaries with multiple values per key:

Dict1 = { key1 : [value1,value2] }
Dict2 = { key1 : [value3,value4], key2 : [value5,value6]}

I want to merge them into one dictionary like this:

mergedDict = { key 1 : [value1,value2,value3,value4], key 2 : [0,0,value5,value6] }

Body:
Try with defaultdict:

from collections import defaultdict
dict1  = { 'key1' : ['value1','value2'] }
dict2 = { 'key1' : ['value3','value4'], 'key2' : ['value5','value6']}
dict3 = defaultdict(list)
for d1, d2 in dict1.items() + dict2.items():
    dict3[d1].extend(d2)
dict(dict3) #convert defaultdict to dict

Output:

{'key1': ['value1', 'value2', 'value3', 'value4'],
 'key2': ['value5', 'value6']}


问:
Find unique value in group of groups
Guess i have two groups

```<code>using System.Collections.Generic;

namespace ConsoleApplication
{
    internal class Student
    {
        public string Name;
        public string Surname;
        public int Mark;
    }

    internal class Program
    {
        private static void Main()
        {
            var twoGroups = new List<List<Student>>
            {
                new List<Student>
                {
                    new Student { Name = "Anna",  Surname = "Mors",  Mark = 4 },
                    new Student { Name = "Jimmy", Surname = "Lemon", Mark = 4 }
                },
                new List<Student>
                {
                    new Student { Name = "Anna",  Surname = "Mors",   Mark = 4 },
                    new Student { Name = "Tommy", Surname = "Wojski", Mark = 4 },
                    new Student { Name = "Jimmy", Surname = "Lemon",  Mark = 4 }
                }
            };
        }
    }
}
</code>```

How can i get unique persons from both groups (by Name or any other property) with linq?

It's obvious there is Tommy, but i dont know how can i pick him with linq (or pick a list of unique persons.

UPD

Also, can i pick group contain only unique student.

```<code>using System.Collections.Generic;

namespace ConsoleApplication
{
    internal class GroupOfStudents
    {
        public string Code;
        public List<Student> Students;
    }

    internal class Student
    {
        public string Name;
        public string Surname;
        public int Mark;
    }

    internal class Program
    {
        private static void Main()
        {
            var twoGroups = new List<GroupOfStudents>
            {
                new GroupOfStudents
                {
                    Code = "A1",
                    Students = new List<Student>
                    {
                        new Student { Name = "Anna",  Surname = "Mors",  Mark = 4 },
                        new Student { Name = "Jimmy", Surname = "Lemon", Mark = 4 }
                    }
                },
                new GroupOfStudents()
                {
                    Code = "B2",
                    Students = new List<Student>
                    {
                        new Student { Name = "Anna",  Surname = "Mors",   Mark = 4 },
                        new Student { Name = "Tommy", Surname = "Wojski", Mark = 4 },
                        new Student { Name = "Jimmy", Surname = "Lemon",  Mark = 4 }
                    }
                }
            };
        }
    }
}
</code>```

I think i need to pick student and push him to new Group with same name, right?

答:
flaten the nested lists into one SelectMany()

group by unique criterias GroupBy() (I choose all properties)

select unique records Where()

code:

```<code>List<Student> result = twoGroups.SelectMany(x => x)
                       .GroupBy(x => new { x.Name, x.Surname, x.Mark })
                       .Where(x => x.Count() == 1)
                       .Select(x => x.First())
                       .ToList();
</code>```

Title: Find unique value in group of groups

Body:
Guess i have two groups

using System.Collections.Generic;

namespace ConsoleApplication
{
    internal class Student
    {
        public string Name;
        public string Surname;
        public int Mark;
    }

    internal class Program
    {
        private static void Main()
        {
            var twoGroups = new List<List<Student>>
            {
                new List<Student>
                {
                    new Student { Name = "Anna",  Surname = "Mors",  Mark = 4 },
                    new Student { Name = "Jimmy", Surname = "Lemon", Mark = 4 }
                },
                new List<Student>
                {
                    new Student { Name = "Anna",  Surname = "Mors",   Mark = 4 },
                    new Student { Name = "Tommy", Surname = "Wojski", Mark = 4 },
                    new Student { Name = "Jimmy", Surname = "Lemon",  Mark = 4 }
                }
            };
        }
    }
}

How can i get unique persons from both groups (by Name or any other property) with linq?

It's obvious there is Tommy, but i dont know how can i pick him with linq (or pick a list of unique persons.

UPD

Also, can i pick group contain only unique student.

using System.Collections.Generic;

namespace ConsoleApplication
{
    internal class GroupOfStudents
    {
        public string Code;
        public List<Student> Students;
    }

    internal class Student
    {
        public string Name;
        public string Surname;
        public int Mark;
    }

    internal class Program
    {
        private static void Main()
        {
            var twoGroups = new List<GroupOfStudents>
            {
                new GroupOfStudents
                {
                    Code = "A1",
                    Students = new List<Student>
                    {
                        new Student { Name = "Anna",  Surname = "Mors",  Mark = 4 },
                        new Student { Name = "Jimmy", Surname = "Lemon", Mark = 4 }
                    }
                },
                new GroupOfStudents()
                {
                    Code = "B2",
                    Students = new List<Student>
                    {
                        new Student { Name = "Anna",  Surname = "Mors",   Mark = 4 },
                        new Student { Name = "Tommy", Surname = "Wojski", Mark = 4 },
                        new Student { Name = "Jimmy", Surname = "Lemon",  Mark = 4 }
                    }
                }
            };
        }
    }
}

I think i need to pick student and push him to new Group with same name, right?

Body:
flaten the nested lists into one SelectMany()

group by unique criterias GroupBy() (I choose all properties)

select unique records Where()

code:

List<Student> result = twoGroups.SelectMany(x => x)
                       .GroupBy(x => new { x.Name, x.Surname, x.Mark })
                       .Where(x => x.Count() == 1)
                       .Select(x => x.First())
                       .ToList();


问:
Firebase Database Permission denied with read/write permissions set to true
I'm having trouble writing to my Firebase database in my simple Android app. I've set my database rules to be public:

```<code>{
  "rules": {
    ".read": true,
    ".write": true
  }
}
</code>```

Created a simple class Message:

```<code>import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class Message {
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference dbRef = database.getReference();
    public String sender;
    public String message;

    public Message(){}

    public Message(String sender, String message) {
        this.sender = sender;
        this.message = message;
    }
}
</code>```

And set a button to perform the onClick method writeNewMessage with these being the significant lines of code:

```<code>int counter = 0;

public void writeNewMessage(View view) {

        counter += 1;
        Message messageToWrite = new Message("John", "Simple message: " + counter);
        String messageId = String.valueOf(counter);

        dbRef.child("users").child(messageId).setValue(messageToWrite);
    }
</code>```

When running, I receive the error:

```<code>W/RepoOperation: setValue at /users/1 failed: DatabaseError: Permission denied
</code>```

I know this question seems simple and likely to have been repeated, but I have yet to find any that asks this problem without having their error be involved in authentication or some other component. The simplicity of the problem is what confuses me the most.

EDIT: I've also found this error as well:

```<code>Failed to load module descriptor class: Didn't find class "com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.ModuleDescriptor"
</code>```

答:
Complete Solution:

1). Firstly go to Authentication Tab and select SIGN-IN-METHOD turn Anonymous On

2). Secondly go to Database Tab and write Rule

```<code>{
"rules": {
".read": true,
".write": true
}}
</code>```

3). Thirdly go to Storage Tab and write following rule

```<code>service firebase.storage {
 match /b/myapplicationname-f2266.appspot.com/o {
 match /{allPaths=**} {
 allow read, write;
}}}
</code>```

Note This solution is only for testing purpose with following steps you are giving public permission for Read and Write your database.

Body:
I'm having trouble writing to my Firebase database in my simple Android app. I've set my database rules to be public:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Created a simple class Message:

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class Message {
    FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference dbRef = database.getReference();
    public String sender;
    public String message;

    public Message(){}

    public Message(String sender, String message) {
        this.sender = sender;
        this.message = message;
    }
}

And set a button to perform the onClick method writeNewMessage with these being the significant lines of code:

int counter = 0;

public void writeNewMessage(View view) {

        counter += 1;
        Message messageToWrite = new Message("John", "Simple message: " + counter);
        String messageId = String.valueOf(counter);

        dbRef.child("users").child(messageId).setValue(messageToWrite);
    }

When running, I receive the error:

W/RepoOperation: setValue at /users/1 failed: DatabaseError: Permission denied

I know this question seems simple and likely to have been repeated, but I have yet to find any that asks this problem without having their error be involved in authentication or some other component. The simplicity of the problem is what confuses me the most.

EDIT: I've also found this error as well:

Failed to load module descriptor class: Didn't find class "com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.ModuleDescriptor"

Body:
Complete Solution:

1). Firstly go to Authentication Tab and select SIGN-IN-METHOD turn Anonymous On

2). Secondly go to Database Tab and write Rule

{
"rules": {
".read": true,
".write": true
}}

3). Thirdly go to Storage Tab and write following rule

service firebase.storage {
 match /b/myapplicationname-f2266.appspot.com/o {
 match /{allPaths=**} {
 allow read, write;
}}}

Note This solution is only for testing purpose with following steps you are giving public permission for Read and Write your database.

ContentLicense: CC BY-SA 4.0


问:
plot_ly doesn´t show graph in Shiny app
I have a problem with shiny app. My shinyapp doesn´t show graph. I have this code. I dont see my graph in shiny enviroment, i see in rstudio viewer.

```<code>## app.R ##

    library("shiny")

setwd('C:/work')

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(

    fluidRow(
      plotOutput("plot", height = 250)),
      box(
        title = "Controls",
        selectInput("select",label="Select",
                    choices=setNames(as.list(data$prov), data$prov))
      )
    )
  )

server <- function(input, output){

  output$plot<- renderPlot({
    plot_ly(bbdd,x=~prov, y=~number, type='bar')

  })
}

shinyApp(ui, server)
</code>```

Its my first app in shiny, dont kill me!

thanks

答: Change plotOutput and renderPlot to plotlyOutput and renderPlotly respectively. you also need to load the plotly package and your data for the plot.

Title: plot_ly doesn´t show graph in Shiny app

Body:
I have a problem with shiny app. My shinyapp doesn´t show graph. I have this code. I dont see my graph in shiny enviroment, i see in rstudio viewer.

## app.R ##

    library("shiny")

setwd('C:/work')

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(

    fluidRow(
      plotOutput("plot", height = 250)),
      box(
        title = "Controls",
        selectInput("select",label="Select",
                    choices=setNames(as.list(data$prov), data$prov))
      )
    )
  )

server <- function(input, output){

  output$plot<- renderPlot({
    plot_ly(bbdd,x=~prov, y=~number, type='bar')

  })
}

shinyApp(ui, server)

Its my first app in shiny, dont kill me!

thanks


答:
You need to update var. All you are doing in line 3 is assigning var + increase to ans. Try doing this:</p>

```<code>var = 0
increase = input("Increase by: ")
var = var + increase
print var
</code>```

Title: Increasing Variables

Body:
So I am writing a program that will need to increase some variables by the amount that the user types. I thought a code like this would work:

var = 0
increase = input("Increase by: ")
var + increase
print(var)

But it just says that var is 0. I even tried making the input type int, int(input(""))

Still didn't work. Why won't it increase the variable?

Keep in mind, I am using Python 2.7

EDIT It was solved! I just made it var += increase

Body:
You need to update var. All you are doing in line 3 is assigning var + increase to ans. Try doing this:

var = 0
increase = input("Increase by: ")
var = var + increase
print var


问:
What is the use of #region and #endregion in c#?
give me an example what can I achieved if I use this block or not and
what is the use behind the name after start region </p>

```<code>#region MyClass definition
//Some code
#endregion
</code>```

答:
There is no (technical) reason to use #Region.

The only thing it does is provide an easy way to collapse code.

As an example, for a relatively bulky class; I tend to separate some things in different regions:

Constructors and properties

Private or protected methods

Public methods.

That's just one example. You can separate code however you want, it has no effect on how the application works.

Body:
give me an example what can I achieved if I use this block or not and
what is the use behind the name after start region

#region MyClass definition
//Some code
#endregion


答:
You can use SelectMany, GroupBy and Count

```<code>IEnumerable<Student> uniqueStudents = twoGroups
    .SelectMany(list => list)
    .GroupBy(student => student.Name)
    .Where(g => g.Count() == 1)
    .Select(g => g.First());
</code>```

This selects only students which aren't contained multiple times in one of both(or both) lists.

If you want to group-by multiple properties use an anonymous type

```<code>    .GroupBy(student => new { student.Name, student.Surname })
</code>```

If you want to allow duplicates in the same list but not across multiple lists:

```<code>IEnumerable<Student> uniqueStudents = twoGroups
    .SelectMany((list, index) => list.Select(student => new { student, index }))
    .GroupBy(x => x.student.Name)
    .Where(g =>
    {
        int index = g.First().index;
        return g.Skip(1).All(x => x.index == index);
    })
    .Select(g => g.First().student);
</code>```

Acc. your Edit

If you want to remove all students from the lists which appear also in other groups:

```<code>var studentNameLookup = twoGroups.SelectMany(g => g.Students).ToLookup(s => s.Name);
twoGroups.ForEach(g => g.Students.RemoveAll(s => studentNameLookup[s.Name].Count() > 1));
</code>```

Title: Find unique value in group of groups

Body:
You can use SelectMany, GroupBy and Count

IEnumerable<Student> uniqueStudents = twoGroups
    .SelectMany(list => list)
    .GroupBy(student => student.Name)
    .Where(g => g.Count() == 1)
    .Select(g => g.First());

This selects only students which aren't contained multiple times in one of both(or both) lists.

If you want to group-by multiple properties use an anonymous type

    .GroupBy(student => new { student.Name, student.Surname })

If you want to allow duplicates in the same list but not across multiple lists:

IEnumerable<Student> uniqueStudents = twoGroups
    .SelectMany((list, index) => list.Select(student => new { student, index }))
    .GroupBy(x => x.student.Name)
    .Where(g =>
    {
        int index = g.First().index;
        return g.Skip(1).All(x => x.index == index);
    })
    .Select(g => g.First().student);

Acc. your Edit

If you want to remove all students from the lists which appear also in other groups:

var studentNameLookup = twoGroups.SelectMany(g => g.Students).ToLookup(s => s.Name);
twoGroups.ForEach(g => g.Students.RemoveAll(s => studentNameLookup[s.Name].Count() > 1));


问:
asp.net MVC And I need to setup 301 redirects
I have a site moving from php to asp.net MVC And I need to setup 301 redirects for it so like www.mystoresitem.com/products/widget1name  needs to redirect to www.mystoresitem.com/widget1name for 700+ different widgets how do I redirect this with out doing it for each product/widget.  </p>

答:
First of all you need to be sure that you installed URL Rewrite module in your IIS

Then in your web.config just add this rules inside system.webServer section:

```<code><rewrite>
    <rules>
        <rule name="Redirects to products">
            <match url="^products/(.*)" />
            <action type="Redirect" url="/{R:1}" />
        </rule>
    </rules>
</rewrite>
</code>```

It will automatically redirect all your urls

www.mystoresitem.com/products/{productname} to www.mystoresitem.com/{productname}

Body:
First of all you need to be sure that you installed URL Rewrite module in your IIS

Then in your web.config just add this rules inside system.webServer section:

<rewrite>
    <rules>
        <rule name="Redirects to products">
            <match url="^products/(.*)" />
            <action type="Redirect" url="/{R:1}" />
        </rule>
    </rules>
</rewrite>

It will automatically redirect all your urls

www.mystoresitem.com/products/{productname} to www.mystoresitem.com/{productname}


问:
How to record when Make a call between two numbers not registered in twilio
I did when Make a call between two numbers not registered in Twilio using following link "Make a call between two numbers not registered in twilio" in C#. But I need to record while pressing 1 during the call at any time.Thanks in advance.</p>

答:
Twilio developer evangelist here.

You cannot nest a <Gather> within a <Dial>, so you can't interrupt a call between two people by pressing 1.

You could place your callers in a <Conference> (in fact, according to that SO question you linked to, it looks like you might have already). Then you can use <Dial>'s hangupOnStar attribute to end the conference for the moderator and allow them to record the call.

You'd then need to direct the moderator into a new <Conference> with the record attribute set to record-from-start. And then you'd need to redirect the original caller from their original conference to the conference that is being recorded.

Let me know if that helps at all.


答:
If you are wanting to call it the same way, you can change func1 like this

```<code>class SomeClass1():
    @staticmethod
    def func1(text):
        print(text)
</code>```

In this case, 'func1' becomes a static method. This means you don't need to create an instance to call it.

Title: Class method takes exactly 2 arguments (1 given)

Body:
please explain where is my error

class SomeClass1():
  def func1(self,text):
    .....
class SomeClass2():
   def func2(self):
     a=SomeClass1.func1("string")

Gives an error:
in func2 a=SomeClass1.func1("string"), func1 takes exactly 2 arguments (1 given)

Body:
If you are wanting to call it the same way, you can change func1 like this

class SomeClass1():
    @staticmethod
    def func1(text):
        print(text)

In this case, 'func1' becomes a static method. This means you don't need to create an instance to call it.


问:
ggplot strange ordering of stacked bar
I am attempting to create a diverging stacked bar like here, and am experiencing a similar issue to this SO question. My approach is slightly different though as I am managing it all via a single dataset, rather than two and my colours are independent of my data.

Reprex as follows:

```<code>library(tidyverse)
library(RColorBrewer)
x <- tribble(
  ~response, ~count,
  0,         -27,
  1,          -9,
  2,         -41,
  3,         -43,
  4,         -58,
  5,        -120,
  5,         120,
  6,         233,
  7,         379,
  8,         388,
  9,         145,
  10,         61
) %>%
  mutate(response = factor(response))

ggplot(x, aes(x = 1, y = count, fill = response)) +
  geom_col() +
  scale_fill_brewer(palette = "RdBu") +
  coord_flip()
</code>```

This gives me an image like this:

The issue is to do with the ordering of the stacked data on the right hand side of the zero where they stacking appears to be in descending order. Any thoughts on how to fix this would be greatly appreciated (expected ordering would be 0-10, not 0-5,10-5)

答:
Although not intuitive (for me), use:

```<code>ggplot(x, aes(x = 1, y = order(count), fill = response)) +
  geom_col() +
  scale_fill_brewer(palette = "RdBu",direction=1) +
  coord_flip()
</code>```

It takes into account the ordering based on response (rather than order(response))

Title: ggplot strange ordering of stacked bar

Body:
I am attempting to create a diverging stacked bar like here, and am experiencing a similar issue to this SO question. My approach is slightly different though as I am managing it all via a single dataset, rather than two and my colours are independent of my data.

Reprex as follows:

library(tidyverse)
library(RColorBrewer)
x <- tribble(
  ~response, ~count,
  0,         -27,
  1,          -9,
  2,         -41,
  3,         -43,
  4,         -58,
  5,        -120,
  5,         120,
  6,         233,
  7,         379,
  8,         388,
  9,         145,
  10,         61
) %>%
  mutate(response = factor(response))

ggplot(x, aes(x = 1, y = count, fill = response)) +
  geom_col() +
  scale_fill_brewer(palette = "RdBu") +
  coord_flip()

This gives me an image like this:

The issue is to do with the ordering of the stacked data on the right hand side of the zero where they stacking appears to be in descending order. Any thoughts on how to fix this would be greatly appreciated (expected ordering would be 0-10, not 0-5,10-5)

Body:
Although not intuitive (for me), use:

ggplot(x, aes(x = 1, y = order(count), fill = response)) +
  geom_col() +
  scale_fill_brewer(palette = "RdBu",direction=1) +
  coord_flip()

It takes into account the ordering based on response (rather than order(response))


问:
How to convert a XML with multiple inner loops using XSL
I have an XML with multiple inner loops, I need to loop through 1 node after another and to display it in HTML view. The XML is given below

```<code> <?xml version ="1.0" encoding ="utf-8" ?>
    <TestUser>
      <Users>
        <UserData name="test123" address="USA"/>
        <UserCommunication>
          <Communication mode="Te" value="123456879"/>
          <Qualification>
            <PG value="No"></PG>
          </Qualification>
            <Qualification>
            <UG value="YES"></UG>
          </Qualification>
        </UserCommunication>
      </Users>
      <Users>
        <UserData name="test124" address="UK"/>
        <UserCommunication>
          <Communication mode="Te" value="1567894525"/>
          <Qualification>
            <PG value="No"></PG>
          </Qualification>
           <Qualification>
            <UG value="YES"></UG>
          </Qualification>
        </UserCommunication>
      </Users>
      <Users>
        <UserData name="test125" address="INDIA"/>
        <UserCommunication>
          <Communication mode="Te" value="5465897845"/>
          <Qualification>
            <PG value="YES"></PG>
          </Qualification>
           <Qualification>
            <UG value="YES"></UG>
          </Qualification>
        </UserCommunication>
      </Users>
    </TestUser>
</code>```

I need to display the Users details one by one in an HTML view using XSLT as in the image below.

Can anyone help me to achieve this?

答:
```<code>Check following Code:-
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="TestUser">
<html>
<head>
</head>
<body>
<table border="5" style="border-collapse: collapse;">
<thead>
<th bgcolor="greeen">User Name</th>
<th bgcolor="greeen">User_Addrss</th>
<th bgcolor="greeen">User_Telephone</th>
<th bgcolor="greeen">PG</th>
<th bgcolor="greeen">UG</th>
</thead>
<xsl:for-each select="//Users/UserData">
<tr>
<td><xsl:value-of select="@name"/></td>
<td><xsl:value-of select="@address"/></td>
<td><xsl:value-of select="../UserCommunication/Communication/@value"/></td>
<td><xsl:value-of select="../UserCommunication/Qualification/PG/@value"/> </td>
<td><xsl:value-of select="../UserCommunication/Qualification/UG/@value"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
</code>```

Body:
I have an XML with multiple inner loops, I need to loop through 1 node after another and to display it in HTML view. The XML is given below

 <?xml version ="1.0" encoding ="utf-8" ?>
    <TestUser>
      <Users>
        <UserData name="test123" address="USA"/>
        <UserCommunication>
          <Communication mode="Te" value="123456879"/>
          <Qualification>
            <PG value="No"></PG>
          </Qualification>
            <Qualification>
            <UG value="YES"></UG>
          </Qualification>
        </UserCommunication>
      </Users>
      <Users>
        <UserData name="test124" address="UK"/>
        <UserCommunication>
          <Communication mode="Te" value="1567894525"/>
          <Qualification>
            <PG value="No"></PG>
          </Qualification>
           <Qualification>
            <UG value="YES"></UG>
          </Qualification>
        </UserCommunication>
      </Users>
      <Users>
        <UserData name="test125" address="INDIA"/>
        <UserCommunication>
          <Communication mode="Te" value="5465897845"/>
          <Qualification>
            <PG value="YES"></PG>
          </Qualification>
           <Qualification>
            <UG value="YES"></UG>
          </Qualification>
        </UserCommunication>
      </Users>
    </TestUser>

I need to display the Users details one by one in an HTML view using XSLT as in the image below.

Can anyone help me to achieve this?


问:
How can i generate child model in mongoose
I'm trying to model the following.

I have a parent model that is called Brick that has some attributes.
There will be 5+ type of bricks that will all have their own specific attributes wich are needed also.

I want to be able to select all Bricks of a certain custumer id later, whatever the type (TwitterBrick, facebookBrick et cetera)  is.

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model
module.exports = mongoose.model('Brick', new Schema({
    type: String,
    userid: { type: String, required: true},
    animationspeed: { type: Number, min: 1, max: 100 },
    socialsite: String,     // none, twitter, instagram
    socialsearchtags: String,
    tagline: { type: String, minlength:3,maxlength: 25 },

}));
</code>```

An example for a child is TwitterBrick.
for now it is:

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('TwitterBrick', new Schema({
    bgColor1: String,
    bgColor2: String,
    bannerBgColor1: String,
    bannerBgColor2: String,
}));
</code>```

TwitterBrick should inherit the attributes of Brick , but i don't know how..
Can you help me in the right direction?

Thanks!
Steven

答:
That's because you didn't "require" the previous file, so technically it's out of scope and the TwitterWallBrickSchema doesn't have a clue what's a "BrickSchema".
Either you put the two models in the same file , or require the first file in the second file.

Body:
I'm trying to model the following.

I have a parent model that is called Brick that has some attributes.
There will be 5+ type of bricks that will all have their own specific attributes wich are needed also.

I want to be able to select all Bricks of a certain custumer id later, whatever the type (TwitterBrick, facebookBrick et cetera)  is.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model
module.exports = mongoose.model('Brick', new Schema({
    type: String,
    userid: { type: String, required: true},
    animationspeed: { type: Number, min: 1, max: 100 },
    socialsite: String,     // none, twitter, instagram
    socialsearchtags: String,
    tagline: { type: String, minlength:3,maxlength: 25 },

}));

An example for a child is TwitterBrick.
for now it is:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('TwitterBrick', new Schema({
    bgColor1: String,
    bgColor2: String,
    bannerBgColor1: String,
    bannerBgColor2: String,
}));

TwitterBrick should inherit the attributes of Brick , but i don't know how..
Can you help me in the right direction?

Thanks!
Steven


问:
Jenkins pipeline BuildDiscarderProperty
I am trying to utilize BuildDiscarderProperty option with our jenkins job template. But currently it is working only with properties function which is not favoring with usage of job template. Could someone help us to configure BuildDiscarderProperty option without using properties function?
Thanks</p>

答:
Per the comments, here's a full declarative pipeline that discards old builds:

```<code>pipeline {
  agent { label 'docker' }
  options {
    buildDiscarder(logRotator(numToKeepStr: '200'))
  }
  stages {
    stage ('build') {
      steps {
        sh 'ls'
      }
    }
  }
}
</code>```

I assert that templates are deprecated. Sound right? :)

Title: Jenkins pipeline BuildDiscarderProperty

Body:
Per the comments, here's a full declarative pipeline that discards old builds:

pipeline {
  agent { label 'docker' }
  options {
    buildDiscarder(logRotator(numToKeepStr: '200'))
  }
  stages {
    stage ('build') {
      steps {
        sh 'ls'
      }
    }
  }
}

I assert that templates are deprecated. Sound right? :)


问:
Build html parts from value of a js function
I really don't know how to put that in words correctly, sorry if the title misleads.

I have a function in a js file, which checks if an element is in a data array. If so the html page should show all the values of the element (so far so good). But if the element is not in the array, my html page should only display: Element not found.

js function:

```<code>function containsID(arr, number) {
    var i = arr.length;
    while (i--) {
       if (arr[i].id === number) {
           return true;
       }
    }
    return false;
}
</code>```

html:

```<code>{% if containsID(data, id) %} //I want something like that
    <p>{{data[id].text}}</p>
{% else %}
    <p> Not found </p>
{% endif %}
</code>```

答:
```<code>   var desiredLogic = function(id){
         var itemWithGivenId = arr.filter( x=> {  return x.id === id } );
           if ( itemWithGivenId.length ) {
               document.createElement("p").innerText = itemWithGivenId.text;
               //append this element wherever you want to see it on the page
              }
          else{
             document.createElement("p").innerText = "Not found";
             //append this element wherever you want to see it on the page
              }
        }
</code>```

Body:
I really don't know how to put that in words correctly, sorry if the title misleads.

I have a function in a js file, which checks if an element is in a data array. If so the html page should show all the values of the element (so far so good). But if the element is not in the array, my html page should only display: Element not found.

js function:

function containsID(arr, number) {
    var i = arr.length;
    while (i--) {
       if (arr[i].id === number) {
           return true;
       }
    }
    return false;
}

html:

{% if containsID(data, id) %} //I want something like that

{{data[id].text}}

{% else %}

 Not found

{% endif %}


问:
How to get a value from SQL Query?
```<code>conn.Open();
string query = "INSERT INTO Film (Film, Jaartal, Cijfer) VALUES ('" + filmnaam + "','" + jaartal + "','" + cijfer + "')";
string LastID = "SELECT TOP 1 Id FROM Film ORDER BY Id DESC";

SqlCommand cmd = new SqlCommand(query, conn);
SqlCommand cmd2 = new SqlCommand(LastID, conn);
cmd.ExecuteNonQuery();

using (SqlDataReader dr = cmd2.ExecuteReader())
{

     while (dr.Read())
     {
          string ID = dr["Id"].ToString();
          string add= "INSERT INTO GenreFilm (FilmId) VALUES ('" + ID + "')";
          SqlCommand cmd3 = new SqlCommand(add, conn);
          cmd3.ExecuteNonQuery();

     }
}
</code>```

I am trying to add the value (ID) of my (LastID) query to my database table. But i cant seem to do it right. Above is my existing code. Any help/tips will be greatly appreciated!

答:
this does not directly provide a solution but a flow to follow keeping in mind what @ADyson indicated about parameter (SQL-Injection) and what @Dimitry indicated about allowing the database to get the value for you. Hopefully this will assist.

The code has comments sprinkled within. The first class, DemoForOperations is showing how to call the method in the second class Operations. Of course you can call the insert method in operations from wherever you want.

```<code>using System;
using System.Data.SqlClient;

namespace StackOverFlowSample
{
    public class DemoForOperations
    {
        public void TheDemo()
        {
            var ops = new Operations();
            var firstName = "Karen";
            var lastName = "Payne";
            var returningNewId = 0;
            if (ops.SampleInsert(firstName,lastName,ref returningNewId))
            {
                // success, returningNewId has the new key value which can be
                // used for whatever you want e.g. as a value for another query.
            }
            else
            {
                // failed, you can use the following the
                // figure out the issue
                var exceptionMessage = ops.Exception.Message;
            }

        }
    }
    public class Operations
    {
        private Exception exception;
        public Exception Exception { get { return exception; } }
        /// <summary>
        /// Insert a record
        /// </summary>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <param name="NewIdentifier">
        /// pass in a valid int by ref
        /// </param>
        /// <returns>
        /// true if successful, false otherwise and will set the property
        /// Exception so that the caller can see what went wrong
        /// </returns>
        public bool SampleInsert(string FirstName, string LastName, ref int NewIdentifier)
        {
            // here we create the connection new but of course a connection can be created
            // outside of the method that is in-scope of this method
            using (SqlConnection cn = new SqlConnection() { ConnectionString = "TODO" })
            {
                // setup for insert using parameters
                // along with a secondary query to return the new primary key value
                var statement = "INSERT INTO Contacts (FirstName,LastName) " +
                                "VALUES (@FirstName,@LastName); " +
                                "SELECT CAST(scope_identity() AS int);";

                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = cn;
                    cmd.CommandText = statement;

                    try
                    {
                        // setup our parameters
                        cmd.Parameters.AddWithValue("@FirstName", FirstName);
                        cmd.Parameters.AddWithValue("@LastName", LastName);

                        cn.Open();

                        // get new primary key
                        NewIdentifier = Convert.ToInt32(cmd.ExecuteScalar());

                        return true;

                    }
                    catch (Exception ex)
                    {
                        exception = ex;
                        return false;
                    }
                }
            }
        }
    }
}
</code>```

Title: How to get a value from SQL Query?

Body:
conn.Open();
string query = "INSERT INTO Film (Film, Jaartal, Cijfer) VALUES ('" + filmnaam + "','" + jaartal + "','" + cijfer + "')";
string LastID = "SELECT TOP 1 Id FROM Film ORDER BY Id DESC";

SqlCommand cmd = new SqlCommand(query, conn);
SqlCommand cmd2 = new SqlCommand(LastID, conn);
cmd.ExecuteNonQuery();

using (SqlDataReader dr = cmd2.ExecuteReader())
{

     while (dr.Read())
     {
          string ID = dr["Id"].ToString();
          string add= "INSERT INTO GenreFilm (FilmId) VALUES ('" + ID + "')";
          SqlCommand cmd3 = new SqlCommand(add, conn);
          cmd3.ExecuteNonQuery();

     }
}

I am trying to add the value (ID) of my (LastID) query to my database table. But i cant seem to do it right. Above is my existing code. Any help/tips will be greatly appreciated!

Body:
this does not directly provide a solution but a flow to follow keeping in mind what @ADyson indicated about parameter (SQL-Injection) and what @Dimitry indicated about allowing the database to get the value for you. Hopefully this will assist.

The code has comments sprinkled within. The first class, DemoForOperations is showing how to call the method in the second class Operations. Of course you can call the insert method in operations from wherever you want.

using System;
using System.Data.SqlClient;

namespace StackOverFlowSample
{
    public class DemoForOperations
    {
        public void TheDemo()
        {
            var ops = new Operations();
            var firstName = "Karen";
            var lastName = "Payne";
            var returningNewId = 0;
            if (ops.SampleInsert(firstName,lastName,ref returningNewId))
            {
                // success, returningNewId has the new key value which can be
                // used for whatever you want e.g. as a value for another query.
            }
            else
            {
                // failed, you can use the following the
                // figure out the issue
                var exceptionMessage = ops.Exception.Message;
            }

        }
    }
    public class Operations
    {
        private Exception exception;
        public Exception Exception { get { return exception; } }
        /// <summary>
        /// Insert a record
        /// </summary>
        /// <param name="FirstName"></param>
        /// <param name="LastName"></param>
        /// <param name="NewIdentifier">
        /// pass in a valid int by ref
        /// </param>
        /// <returns>
        /// true if successful, false otherwise and will set the property
        /// Exception so that the caller can see what went wrong
        /// </returns>
        public bool SampleInsert(string FirstName, string LastName, ref int NewIdentifier)
        {
            // here we create the connection new but of course a connection can be created
            // outside of the method that is in-scope of this method
            using (SqlConnection cn = new SqlConnection() { ConnectionString = "TODO" })
            {
                // setup for insert using parameters
                // along with a secondary query to return the new primary key value
                var statement = "INSERT INTO Contacts (FirstName,LastName) " +
                                "VALUES (@FirstName,@LastName); " +
                                "SELECT CAST(scope_identity() AS int);";

                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = cn;
                    cmd.CommandText = statement;

                    try
                    {
                        // setup our parameters
                        cmd.Parameters.AddWithValue("@FirstName", FirstName);
                        cmd.Parameters.AddWithValue("@LastName", LastName);

                        cn.Open();

                        // get new primary key
                        NewIdentifier = Convert.ToInt32(cmd.ExecuteScalar());

                        return true;

                    }
                    catch (Exception ex)
                    {
                        exception = ex;
                        return false;
                    }
                }
            }
        }
    }
}


问:
Dynamiclly append different class with increment numereic value by click event
I have a span tag and a button tag

```<code><span class="myspan">1</span>
<button id="add">Add +1</button>
var arr=["myspan1","myspan2","myspan3","myspan4"}
</code>```

I want to append more span tag with new class from  this array with increment value by clicking button.
Like this output:

```<code><span class="myspan1">1</span>
<span class="myspan2">2</span>
<span class="myspan3">3</span>
<span class="myspan4">4</span>
</code>```

i  try `
this JsFiddle

But i can not add class name to new append tag from array.

Another useful link for appending tag with new class from array
http://jsbin.com/nojipowo/2/edit?html,css,js,output
...
But i can not bring my desire output at any case...enter code here

value increaseesenter code here this snippet

    <button onclick="buttonClick();">Click Me</button>    <input type="text" id="inc" value="0"></input>```
</div>
</div>
</p>

<p>another attempt...anyone can help.. to get desire output</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var elements = document.getElementsByClassName("myspan");var len = backgrounds.length;

$("#add").click( function() {
(i < elements.length){

  $(".new-field").append('<span class="myspan">1</span><script');
    var value = parseInt($(".myspan").text(), 10) + 1;
    elements[i].className += ' ' + backgrounds[i%len];
    i++;
    $(".background").text(i);
    }
});</code>```

*/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="myspan">1</span>

<button id="add">Add +1</button>
<div class="new-field">

</div></code>```

答:
Try this check the span length via parseInt($(".myspan").length) .And use with Array#forEach for iterate the array instead of increment i.parseInt  used convert ths string to number

var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];

var len = backgrounds.length;

$("#add").click( function() {
var len = parseInt($(".myspan").length)
backgrounds.forEach(function(a){
  $(".new-field").append(''+(len++)+'');
    })
    console.log($(".new-field").html())
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="myspan">1</span>

<button id="add">Add +1</button>
<div class="new-field">

</div></code>```

Body:
I have a span tag and a button tag

1
<button id="add">Add +1</button>
var arr=["myspan1","myspan2","myspan3","myspan4"}

I want to append more span tag with new class from  this array with increment value by clicking button.
Like this output:

1
2
3
4

i  try `
this JsFiddle

But i can not add class name to new append tag from array.

Another useful link for appending tag with new class from array
http://jsbin.com/nojipowo/2/edit?html,css,js,output
...
But i can not bring my desire output at any case...enter code here

value increaseesenter code here this snippet

    <button onclick="buttonClick();">Click Me</button>    <input type="text" id="inc" value="0"></input>

another attempt...anyone can help.. to get desire output

var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];
var elements = document.getElementsByClassName("myspan");var len = backgrounds.length;

$("#add").click( function() {
(i < elements.length){

  $(".new-field").append('1

Body:
Try this check the span length via parseInt($(".myspan").length) .And use with Array#forEach for iterate the array instead of increment i.parseInt  used convert ths string to number

var i=6;
var backgrounds = ["myspan1", "myspan2", "myspan4"];

var len = backgrounds.length;

$("#add").click( function() {
var len = parseInt($(".myspan").length)
backgrounds.forEach(function(a){
  $(".new-field").append('<span class="'+a+'">'+(len++)+'</span>');
    })
    console.log($(".new-field").html())
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="myspan">1</span>

<button id="add">Add +1</button>
<div class="new-field">

</div>


问:
Very slow reaction RSSI_CHANGED_ACTION
I already red some Questions about this topic
like this one for example:
Application never receives RSSI_CHANGED_ACTION

But they solved the problem using SCAN_RESULTS_AVAILABLE_ACTION.
I also did this but now I have to use RSSI_CHANGED_ACTION because of customer requirements.

It seems like it reacts slow to rssi changes. For example it only change when I make bigger location changes.
When I use SCAN_RESULTS_AVAILABLE_ACTION it changes very often. Even when I am just in one room.

So why is RSSI_CHANGED_ACTION slow reacting?

答:
I found the answer why it´s "slow reacting".
In WifiStateMachine.java I found this snippet here:

```<code>        /*
         * Rather then sending the raw RSSI out every time it
         * changes, we precalculate the signal level that would
         * be displayed in the status bar, and only send the
         * broadcast if that much more coarse-grained number
         * changes. This cuts down greatly on the number of
         * broadcasts, at the cost of not informing others
         * interested in RSSI of all the changes in signal
         * level.
         */
</code>```

and in WifiWatchdogStateMachine.java I found this here:

```<code>  /* RSSI Levels as used by notification icon
   Level 4  -55 <= RSSI
   Level 3  -66 <= RSSI < -55
   Level 2  -77 <= RSSI < -67
   Level 1  -88 <= RSSI < -78
   Level 0         RSSI < -88 */
</code>```

I think it is self explaining.
I tested this out and you get only a Broadcast recieve If you pass one level.
For example you have better or equal -55 dbm and after next polling you have betwenn -66 and -55 you get a Broadcastrecieve. But if your dBm Value just changes between -55 and -66 you will never receive a broadcast.

Title: Very slow reaction RSSI_CHANGED_ACTION

Body:
I found the answer why it´s "slow reacting".
In WifiStateMachine.java I found this snippet here:

        /*
         * Rather then sending the raw RSSI out every time it
         * changes, we precalculate the signal level that would
         * be displayed in the status bar, and only send the
         * broadcast if that much more coarse-grained number
         * changes. This cuts down greatly on the number of
         * broadcasts, at the cost of not informing others
         * interested in RSSI of all the changes in signal
         * level.
         */

and in WifiWatchdogStateMachine.java I found this here:

  /* RSSI Levels as used by notification icon
   Level 4  -55 <= RSSI
   Level 3  -66 <= RSSI < -55
   Level 2  -77 <= RSSI < -67
   Level 1  -88 <= RSSI < -78
   Level 0         RSSI < -88 */

I think it is self explaining.
I tested this out and you get only a Broadcast recieve If you pass one level.
For example you have better or equal -55 dbm and after next polling you have betwenn -66 and -55 you get a Broadcastrecieve. But if your dBm Value just changes between -55 and -66 you will never receive a broadcast.


问:
How to get the difference between 2 int arrays as a percentage
Mathematically we can solve it like Given Amount / Total Amount * 100 to get the percentage difference. But what I need is to compare 2 Integer Arrays (in C# Win App) and get the percentage of the difference.
Like :

```<code>1 -----> -2
2 ----->  3
3 ----->  7
4 ----->  456
5 ----->  13
</code>```

These two columns are 2 Integer Arrays and I should get the difference between them.

How can I get this? A mathematical answer or an algorithm, whatever can be used to solve the problem.

答:
What do you mean by difference? you can get the array of differences by:</p>

```<code>int[] array = new int[arr1.Length];
for (i = 0; i < array.Length; i++)
{
  array[i] = array1[i] - array2[i];
}
</code>```

Body:
Mathematically we can solve it like Given Amount / Total Amount * 100 to get the percentage difference. But what I need is to compare 2 Integer Arrays (in C# Win App) and get the percentage of the difference.
Like :

1 -----> -2
2 ----->  3
3 ----->  7
4 ----->  456
5 ----->  13

These two columns are 2 Integer Arrays and I should get the difference between them.

How can I get this? A mathematical answer or an algorithm, whatever can be used to solve the problem.

Body:
What do you mean by difference? you can get the array of differences by:

int[] array = new int[arr1.Length];
for (i = 0; i < array.Length; i++)
{
  array[i] = array1[i] - array2[i];
}


问:
Need to copy text file from one folder to another in windows using jmeter
My requirement is to copy text file from one folder to another in  windows OS using jmeter. So how can we achieve this using jmeter?

Please help!

Thanks,
Abhishek

答:
Use OS Process Sampler and write your command in Command field

see Manual


问:
MySQL JOIN and GROUP BY
I should get 1 as a result, because object 3 has one attribute (a3) which is over zero. Because of the groupref join (which is needed) i get 3.
I tried to group but didn't get it working.

Reduced statement

```<code>SELECT COUNT(IF(a3 > 0, TRUE, NULL)) AS a3
FROM objects AS o
LEFT JOIN attribs AS a ON o.id=a.oid
LEFT JOIN group_ref AS gx ON gx.oid = o.id
</code>```

Reduced tables

```<code>attribs
------------
oid |   attrib  |   value
------------------------
1   |   a1  |   3
2   |   a2  |   0
3   |   a3  |   1

objects
------------
id  |   title
------------
1   |   obj1
2   |   obj2
3   |   obj3

groups
------------
id  |   title
------------
1   |   g1
2   |   g2
3   |   g3

group_ref
------------
gid |   oid
------------
1   |   1
1   |   2
2   |   1
3   |   3
3   |   2
3   |   1
</code>```

答:
Isn't this what you want ?</p>

```<code>SELECT COUNT(*) AS a3 FROM attribs WHERE attrib = a3 HAVING value > 0
</code>```

Title: MySQL JOIN and GROUP BY

Body:
I should get 1 as a result, because object 3 has one attribute (a3) which is over zero. Because of the groupref join (which is needed) i get 3.
I tried to group but didn't get it working.

Reduced statement

SELECT COUNT(IF(a3 > 0, TRUE, NULL)) AS a3
FROM objects AS o
LEFT JOIN attribs AS a ON o.id=a.oid
LEFT JOIN group_ref AS gx ON gx.oid = o.id

Reduced tables

attribs
------------
oid |   attrib  |   value
------------------------
1   |   a1  |   3
2   |   a2  |   0
3   |   a3  |   1

objects
------------
id  |   title
------------
1   |   obj1
2   |   obj2
3   |   obj3

groups
------------
id  |   title
------------
1   |   g1
2   |   g2
3   |   g3

group_ref
------------
gid |   oid
------------
1   |   1
1   |   2
2   |   1
3   |   3
3   |   2
3   |   1

Body:
Isn't this what you want ?

SELECT COUNT(*) AS a3 FROM attribs WHERE attrib = a3 HAVING value > 0


问:
Update values incrementally in mysql
One field of my table's field is set to 0 for all rows. But I want to update the incremental value by step 1 in an update query.

How can I do that in mysql?

答:
One way is to create a new table with an AUTO_INCREMENT column instead of the original column, inserting all data from the old into the new table, and then renaming the new and deleting the old.

Another way is to run your update query with a MySQL variable that generates an increasing number for each row (to emulate the ROW_NUMBER() function found in other DBMS systems).

Title: Update values incrementally in mysql