问:
Bluetooth creates socket but blocks at connect() ANDROID
I am using code from the Google Bluetooth Chat Example to set up a bluetooth listening server.  I want the app to listen always for an incoming connection.  When the app sees a connection request it will accept the connection, read in the string that the remote device will send, and then respond by sending a file.

The problem is that the app never accepts the connection.  It blocks at socket = mmServerSocket.accept(); and never moves on.  See the code below after the line if(D) System.out.println("Waiting to connect************"); To test it I start the activity that starts the thread and then attempt to connect with my laptop and send a file.  When I do this the overall Android bluetooth manager sees the file and downloads it effectively bypassing my Android device.  Is this the only way to test it?  I cant figure out if its a testing or coding problem.

```<code>private class AcceptThread extends Thread {
    // The local server socket
    private final BluetoothServerSocket mmServerSocket;

    public AcceptThread() {
        BluetoothServerSocket tmp = null;

        // Create a new listening server socket
        try {
            tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
        } catch (IOException e) {
            Log.e(TAG, "listen() failed", e);
        }
        mmServerSocket = tmp;
    }

    public void run() {
        if (D) Log.d(TAG, "BEGIN mAcceptThread" + this);
        setName("AcceptThread");
        BluetoothSocket socket = null;

        // Listen to the server socket if we're not connected
        while (mState != STATE_CONNECTED) {
            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception
                if(D) System.out.println("Waiting to connect************");
                socket = mmServerSocket.accept();
                if(D) System.out.println("We have accepted connection and are connected***************");
            } catch (IOException e) {
                Log.e(TAG, "accept() failed", e);
                break;
            }

            // If a connection was accepted
            if (socket != null) {
                synchronized (BluetoothServer.this) {
                    switch (mState) {
                    case STATE_LISTEN:
                    case STATE_CONNECTING:
                        // Situation normal. Start the connected thread.
                        connected(socket, socket.getRemoteDevice());
                        break;
                    case STATE_NONE:
                    case STATE_CONNECTED:
                        // Either not ready or already connected. Terminate new socket.
                        try {
                            socket.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Could not close unwanted socket", e);
                        }
                        break;
                    }
                }
            }
        }
        if (D) Log.i(TAG, "END mAcceptThread");
    }
</code>```

答:
The solution to this problem lies in your androidmanifest.xml file;

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

The phone isn't giving your program permissions

I have actually added some code but I guess it got edited out

Body:
I am using code from the Google Bluetooth Chat Example to set up a bluetooth listening server.  I want the app to listen always for an incoming connection.  When the app sees a connection request it will accept the connection, read in the string that the remote device will send, and then respond by sending a file.

The problem is that the app never accepts the connection.  It blocks at socket = mmServerSocket.accept(); and never moves on.  See the code below after the line if(D) System.out.println("Waiting to connect************"); To test it I start the activity that starts the thread and then attempt to connect with my laptop and send a file.  When I do this the overall Android bluetooth manager sees the file and downloads it effectively bypassing my Android device.  Is this the only way to test it?  I cant figure out if its a testing or coding problem.

private class AcceptThread extends Thread {
    // The local server socket
    private final BluetoothServerSocket mmServerSocket;

    public AcceptThread() {
        BluetoothServerSocket tmp = null;

        // Create a new listening server socket
        try {
            tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
        } catch (IOException e) {
            Log.e(TAG, "listen() failed", e);
        }
        mmServerSocket = tmp;
    }

    public void run() {
        if (D) Log.d(TAG, "BEGIN mAcceptThread" + this);
        setName("AcceptThread");
        BluetoothSocket socket = null;

        // Listen to the server socket if we're not connected
        while (mState != STATE_CONNECTED) {
            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception
                if(D) System.out.println("Waiting to connect************");
                socket = mmServerSocket.accept();
                if(D) System.out.println("We have accepted connection and are connected***************");
            } catch (IOException e) {
                Log.e(TAG, "accept() failed", e);
                break;
            }

            // If a connection was accepted
            if (socket != null) {
                synchronized (BluetoothServer.this) {
                    switch (mState) {
                    case STATE_LISTEN:
                    case STATE_CONNECTING:
                        // Situation normal. Start the connected thread.
                        connected(socket, socket.getRemoteDevice());
                        break;
                    case STATE_NONE:
                    case STATE_CONNECTED:
                        // Either not ready or already connected. Terminate new socket.
                        try {
                            socket.close();
                        } catch (IOException e) {
                            Log.e(TAG, "Could not close unwanted socket", e);
                        }
                        break;
                    }
                }
            }
        }
        if (D) Log.i(TAG, "END mAcceptThread");
    }

Body:
The solution to this problem lies in your androidmanifest.xml file;

uses-permission android:name="android.permission.BLUETOOTH_ADMIN"
uses-permission android:name="android.permission.BLUETOOTH"

The phone isn't giving your program permissions

I have actually added some code but I guess it got edited out


来源: stackexchange

问:
How to tell protostuff to pack property to fixed32 and not int32
I'm trying to serialize the following Java object to protobuf using protostuff:

```<code>public class HeaderTest
{

  private int version;
  private UUID messageId;

  public HeaderTest() {} // required by jackson

  public HeaderTest(UUID messageId, int version)
  {

    this.messageId = messageId;
    this.version = version;

  }

  public int getVersion() {
    return version;
  }

  public void setVersion(int version) {
    this.version = version;
  }

  public UUID getMessageId() {
    return messageId;
  }

  public void setMessageId(UUID messageId) {
    this.messageId = messageId;
  }
}
</code>```

With the following code:

```<code>Schema<HeaderTest> headerTestSchema = RuntimeSchema.getSchema(HeaderTest.class);
byte[] headerTestBuff = ProtostuffIOUtil.toByteArray(headerTestInstance, headerTestSchema, LinkedBuffer.allocate());
</code>```

I would like to get fixed size buffer but protostuff serialize the version integer as varint type ( the amount of bytes use to represent the integer changes according to the integer size )

How can I tell protostuff to serialize specific property as fixed32 with fix amount of bytes

Thanks

答:
RuntimeSchema does not allow you to select fixed32 as a type for integer field. It can use only int32/int64.

The only thing that you can do - you can estimate maximum size of the buffer. Each int32 takes at most 5 bytes.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to serialize the following Java object to protobuf using protostuff:

public class HeaderTest
{

  private int version;
  private UUID messageId;

  public HeaderTest() {} // required by jackson

  public HeaderTest(UUID messageId, int version)
  {

    this.messageId = messageId;
    this.version = version;

  }

  public int getVersion() {
    return version;
  }

  public void setVersion(int version) {
    this.version = version;
  }

  public UUID getMessageId() {
    return messageId;
  }

  public void setMessageId(UUID messageId) {
    this.messageId = messageId;
  }
}

With the following code:

Schema<HeaderTest> headerTestSchema = RuntimeSchema.getSchema(HeaderTest.class);
byte[] headerTestBuff = ProtostuffIOUtil.toByteArray(headerTestInstance, headerTestSchema, LinkedBuffer.allocate());

I would like to get fixed size buffer but protostuff serialize the version integer as varint type ( the amount of bytes use to represent the integer changes according to the integer size )

How can I tell protostuff to serialize specific property as fixed32 with fix amount of bytes

Thanks


问:
RadioButton.IsChecked Not Going False
I have a UWP app in C#. I have a Radio Button that the user can turn check or uncheck. It is checked by default and the user can uncheck it when they wish. However when they uncheck it the bool value for RadioButton.IsChecked never returns false making impossible for the user to then recheck the Radio Button if required. My code is below.

```<code>    private void usingmltBtn_Click(object sender, RoutedEventArgs e)
    {

        if (RadioButton.IsChecked == true)
        {
            RadioButton.IsChecked = false;
            i2cerrRec.Visibility = Visibility.Collapsed;
            i2cerrTxt.Visibility = Visibility.Collapsed;
            mltI2Cnck = 0;

        }
        else if (RadioButton.IsChecked == false)
        {
            RadioButton.IsChecked = true;
            mlttempLbl.Text = "N/C";
        }

    }
</code>```

Thanks for your help.

答:
I can see 2 problems in here:

1- I might be wrong but the method you posted is triggered by a control whose name is usingltBtn (Not descriptive by the way) if this is the case you might be running this code with the trigger of another control.

2- Either the name of the RadioButton is usingltBtn or not you are not referencing the code to your control RadioButton is the name of a class not a specific control.

How to fix this? If the name of your control is usingltBtn use usingltBtn.IsChecked instead of RadioButton.IsChecked if not find the name of your control and use it

Title: RadioButton.IsChecked Not Going False

Body:
I have a UWP app in C#. I have a Radio Button that the user can turn check or uncheck. It is checked by default and the user can uncheck it when they wish. However when they uncheck it the bool value for RadioButton.IsChecked never returns false making impossible for the user to then recheck the Radio Button if required. My code is below.

    private void usingmltBtn_Click(object sender, RoutedEventArgs e)
    {

        if (RadioButton.IsChecked == true)
        {
            RadioButton.IsChecked = false;
            i2cerrRec.Visibility = Visibility.Collapsed;
            i2cerrTxt.Visibility = Visibility.Collapsed;
            mltI2Cnck = 0;

        }
        else if (RadioButton.IsChecked == false)
        {
            RadioButton.IsChecked = true;
            mlttempLbl.Text = "N/C";
        }

    }

Thanks for your help.


问:
Split a text into two lines
Is there a way to force a part of a text to display on a new line with CSS?

So when the HTML looks like this:

```<code><p>Hello, my name is John.</p>
</code>```

The result will be:

Hello,

my name is John.

The HTML is generated dynamically, so I cannot change it.

答:
p::before {
  float: right;
  width: calc(100% - 3.6em);
  height: 1em;
  content: '';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Hello, my name is John.</p></code>```

Please note that this is rather fidgety: the 3.6em is somewhere in between the width of "Hello," and the width of "Hello, my". So this depends on the font as well as the word(s) you need it to break after. I had to experiment a bit with different fonts to find a good average size.

Title: Split a text into two lines

Body:
Is there a way to force a part of a text to display on a new line with CSS?

So when the HTML looks like this:

Hello, my name is John.

The result will be:

Hello,

my name is John.

The HTML is generated dynamically, so I cannot change it.

Body:
p::before {
  float: right;
  width: calc(100% - 3.6em);
  height: 1em;
  content: '';
}

<p>Hello, my name is John.</p>

Please note that this is rather fidgety: the 3.6em is somewhere in between the width of "Hello," and the width of "Hello, my". So this depends on the font as well as the word(s) you need it to break after. I had to experiment a bit with different fonts to find a good average size.

ContentLicense: CC BY-SA 4.0


问:
ReactiveX: Make Observable.Create() be called only once
I'm trying to build a data access layer with ReactiveX (more precisely, Rx.Net) and SQLite.Net.

Part of the job is making an observable that returns the database connection, so that it can be open lazily, only when needed. This is what I came up with so far:

```<code>var connection = Observable.Create<SQLiteConnection>(observer =>
{
    Debug.WriteLine("CheckInStore: Opening database connection");
    var database = new SQLiteConnection(configuration.ConnectionString.DatabasePath);

    observer.OnNext(database);
    observer.OnCompleted();

    return Disposable.Create(() =>
    {
        Debug.WriteLine("CheckInStore: Closing database connection");
        database.Close();
    });
});

// Further down the line, a query would look like this:
var objects = connection.SelectMany(db => db.Query<>("select * from MyTable"));
</code>```

Unfortunately, every time somebody subscribes to this observable, a new connection is created. And it is also closed once the subscription is disposed.

I tried using .Replay(1).RefCount(), but it didn't change anything. I'm not sure to understand that whole RefCount thing anyway.

How can I make this database connection a singleton?

答:
Have a look at this code, which is equivalent, but doesn't open a DB connection:

```<code>var conn = Observable.Create<int>(o =>
    {
        Debug.WriteLine("Opening");
        o.OnNext(1);
        o.OnCompleted(); //This forces closing code to be called. Comment me out.
        return Disposable.Create(() =>
        {
            Debug.WriteLine("Closing");
        });
    })
    //.Replay(1)
    //.RefCount() //.Replay(1).RefCount is necessary if you want to cache the result
    ;

var sub1 = conn.SelectMany(i => Observable.Return(i)).Subscribe(i => Debug.WriteLine($"1: {i}"));
var sub2 = conn.SelectMany(i => Observable.Return(i)).Subscribe(i => Debug.WriteLine($"2: {i}"));
sub1.Dispose();
sub2.Dispose();
var sub3 = conn.SelectMany(i => Observable.Return(i)).Subscribe(i => Debug.WriteLine($"3: {i}"));
sub3.Dispose();
</code>```

There's a number of problems here:

Your dispose/unsubscription code will get called everytime you either unsubscribe or complete the observable. Since you're calling OnCompleted, it's going to be open/closed every time.

If you want to re-use the same connection, you need to use .Replay(1).RefCount(). Observable.Create runs the whole function every time a subscriber connects, there's nothing (except .Replay(1).Refcount()) that caches it for you.

Even if you add .Replay(1).Refcount() and remove OnCompleted, you will still get disposal (meaning DB-Closed) behavior if there's no outstanding subscriptions (like after the sub2.Dispose() call).

If you don't dispose the subscriptions, either through using(var sub = connection.SelectMany(...)) or explicitly via sub.Dispose(), you'll never unsubscribe, since this Observable has no way of terminating. In other words, opposite problem of 3, your Close code will never happen.

I hope you get the picture: This is a pretty error-prone way of doing things. I would recommend a simple iterative call, since that tends to work better for DB calls anyway. If you insist on RX, I would look at Observable.Using for your DB connection initialization.

Body:
I'm trying to build a data access layer with ReactiveX (more precisely, Rx.Net) and SQLite.Net.

Part of the job is making an observable that returns the database connection, so that it can be open lazily, only when needed. This is what I came up with so far:

var connection = Observable.Create<SQLiteConnection>(observer =>
{
    Debug.WriteLine("CheckInStore: Opening database connection");
    var database = new SQLiteConnection(configuration.ConnectionString.DatabasePath);

    observer.OnNext(database);
    observer.OnCompleted();

    return Disposable.Create(() =>
    {
        Debug.WriteLine("CheckInStore: Closing database connection");
        database.Close();
    });
});

// Further down the line, a query would look like this:
var objects = connection.SelectMany(db => db.Query<>("select * from MyTable"));

Unfortunately, every time somebody subscribes to this observable, a new connection is created. And it is also closed once the subscription is disposed.

I tried using .Replay(1).RefCount(), but it didn't change anything. I'm not sure to understand that whole RefCount thing anyway.

How can I make this database connection a singleton?

Body:
Have a look at this code, which is equivalent, but doesn't open a DB connection:

var conn = Observable.Create<int>(o =>
    {
        Debug.WriteLine("Opening");
        o.OnNext(1);
        o.OnCompleted(); //This forces closing code to be called. Comment me out.
        return Disposable.Create(() =>
        {
            Debug.WriteLine("Closing");
        });
    })
    //.Replay(1)
    //.RefCount() //.Replay(1).RefCount is necessary if you want to cache the result
    ;

var sub1 = conn.SelectMany(i => Observable.Return(i)).Subscribe(i => Debug.WriteLine($"1: {i}"));
var sub2 = conn.SelectMany(i => Observable.Return(i)).Subscribe(i => Debug.WriteLine($"2: {i}"));
sub1.Dispose();
sub2.Dispose();
var sub3 = conn.SelectMany(i => Observable.Return(i)).Subscribe(i => Debug.WriteLine($"3: {i}"));
sub3.Dispose();

There's a number of problems here:

Your dispose/unsubscription code will get called everytime you either unsubscribe or complete the observable. Since you're calling OnCompleted, it's going to be open/closed every time.

If you want to re-use the same connection, you need to use .Replay(1).RefCount(). Observable.Create runs the whole function every time a subscriber connects, there's nothing (except .Replay(1).Refcount()) that caches it for you.

Even if you add .Replay(1).Refcount() and remove OnCompleted, you will still get disposal (meaning DB-Closed) behavior if there's no outstanding subscriptions (like after the sub2.Dispose() call).

If you don't dispose the subscriptions, either through using(var sub = connection.SelectMany(...)) or explicitly via sub.Dispose(), you'll never unsubscribe, since this Observable has no way of terminating. In other words, opposite problem of 3, your Close code will never happen.

I hope you get the picture: This is a pretty error-prone way of doing things. I would recommend a simple iterative call, since that tends to work better for DB calls anyway. If you insist on RX, I would look at Observable.Using for your DB connection initialization.


问:
C Not able to include a format specifier when assign a string
I'd like to be able to use the %d format specifier when assign a value to a string called answer. I tried to do this but I can't get the format specifier replaced by an integer when running the program...
Here's my code:

```<code>#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    const char *answer;
    int year;
    printf("Enter a year: \n");
    scanf("%d", &year);
    if ( (year % 400 == 0) || ( (year % 4 == 0) && !(year % 100 == 0) ) ){
        answer =  "%d does have a bissextus day", year;
    }
    else {
        answer = "%d doesn't have a bissextus day", year;
    }

    printf("%s\n", answer);

    return 0;
}
</code>```

I'd also like to know if in this case it's a good choice to use const char *answer and if it's not, I'd like to know what I should use instead.

答:
answer =  "%d does have a bissextus day", year;

Here your storing string data in which %d formate specififer doesnt has any effect with int type year, your expecting it should print year. Something which in double quotes in C is treated as string with null termination in the end.

Try this code, its just simple and straight forward:

```<code>#include <stdio.h>
#include <stdlib.h>

int main(){
    int year;
    printf("Enter a year:");
    scanf("%d", &year);

    if ( (year % 400 == 0) || ( (year % 4 == 0) && !(year % 100 == 0) ) ){
        printf("%d does have a bissextus day", year);
    } else {
        printf("%d doesn't have a bissextus day", year);
    }
    return 0;
}
</code>```

Output :

```<code>./a.exe
Enter a year:2017
2017 doesn't have a bissextus day
$  ./a.exe
Enter a year:2000
2000 does have a bissextus day
</code>```

Body:
I'd like to be able to use the %d format specifier when assign a value to a string called answer. I tried to do this but I can't get the format specifier replaced by an integer when running the program...
Here's my code:

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    const char *answer;
    int year;
    printf("Enter a year: \n");
    scanf("%d", &year);
    if ( (year % 400 == 0) || ( (year % 4 == 0) && !(year % 100 == 0) ) ){
        answer =  "%d does have a bissextus day", year;
    }
    else {
        answer = "%d doesn't have a bissextus day", year;
    }

    printf("%s\n", answer);

    return 0;
}

I'd also like to know if in this case it's a good choice to use const char *answer and if it's not, I'd like to know what I should use instead.

Body:
answer =  "%d does have a bissextus day", year;

Here your storing string data in which %d formate specififer doesnt has any effect with int type year, your expecting it should print year. Something which in double quotes in C is treated as string with null termination in the end.

Try this code, its just simple and straight forward:

#include <stdio.h>
#include <stdlib.h>

int main(){
    int year;
    printf("Enter a year:");
    scanf("%d", &year);

    if ( (year % 400 == 0) || ( (year % 4 == 0) && !(year % 100 == 0) ) ){
        printf("%d does have a bissextus day", year);
    } else {
        printf("%d doesn't have a bissextus day", year);
    }
    return 0;
}

Output :

./a.exe
Enter a year:2017
2017 doesn't have a bissextus day
$  ./a.exe
Enter a year:2000
2000 does have a bissextus day


问:
SSIS Parameters With Functions
I've done quite a bit of searching on this but haven't been able to come up with a solid solution.  I have a use case where for example I want to include the date in the file name, let's say I use the following formula:

```<code>"EmployeeCount_"+(DT_STR,4,1252)DATEPART( "yyyy" , getdate() )+ RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2)  + RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".csv"
</code>```

This works out great as a variable, but what if I want to pass this function as a parameter from SSMS?  Is there a way for Parameters to be evaluated as a expression?  I attempted passing the parameter into a variable to achieve the desired effect to no available.

Am I missing something here, or should I just be hard coding this into a variable / calculating this elsewhere and pulling it into SSIS from a table?

答:
If you want to retrieve the value from a database function and store in a variable you can use the Execute SQL Task.

You can combine variables with expressions in other variables along with scripts. Where you perform the calculation is your choice.

Title: SSIS Parameters With Functions

Body:
I've done quite a bit of searching on this but haven't been able to come up with a solid solution.  I have a use case where for example I want to include the date in the file name, let's say I use the following formula:

"EmployeeCount_"+(DT_STR,4,1252)DATEPART( "yyyy" , getdate() )+ RIGHT("0" + (DT_STR,4,1252)DATEPART( "mm" , getdate() ), 2)  + RIGHT("0" + (DT_STR,4,1252)DATEPART( "dd" , getdate() ), 2) +".csv"

This works out great as a variable, but what if I want to pass this function as a parameter from SSMS?  Is there a way for Parameters to be evaluated as a expression?  I attempted passing the parameter into a variable to achieve the desired effect to no available.

Am I missing something here, or should I just be hard coding this into a variable / calculating this elsewhere and pulling it into SSIS from a table?


问:
ClassNotFoundException & app crashing
I'm working with Android Studio on a learning app, but when i run it, it crashes and give me this error code:

```<code>03-29 22:36:03.546 13455-13455/com.training.criminalintent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.training.criminalintent, PID: 13455
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.training.criminalintent/com.training.criminalintent.CrimeListActivity}: java.lang.ClassNotFoundException: Didn't find class "com.training.criminalintent.CrimeListActivity" on path: DexPathList[[zip file "/data/app/com.training.criminalintent-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2290)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
    at android.app.ActivityThread.access$800(ActivityThread.java:156)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:211)
    at android.app.ActivityThread.main(ActivityThread.java:5371)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:945)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.training.criminalintent.CrimeListActivity" on path: DexPathList[[zip file "/data/app/com.training.criminalintent-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2280)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
    at android.app.ActivityThread.access$800(ActivityThread.java:156)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:211)
    at android.app.ActivityThread.main(ActivityThread.java:5371)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:945)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740)
Suppressed: java.lang.ClassNotFoundException: com.training.criminalintent.CrimeListActivity
    at java.lang.Class.classForName(Native Method)
    at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
    at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
        ... 13 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
</code>```

I looked for a solution but didn't find something adequate for android studio, but most importantly i didn't find the source of the problem, why android studio is behaving like that.

EDIT: The activity exists in the manifest File :

```<code><application
>     android:allowBackup="true"
>     android:icon="@mipmap/ic_launcher"
>     android:label="@string/app_name"
>     android:supportsRtl="true"
>     android:theme="@style/AppTheme">
>     <activity android:name=".CrimeListActivity">
>         <intent-filter>
>             <action android:name="android.intent.action.MAIN" />
>             <category android:name="android.intent.category.LAUNCHER" />
>         </intent-filter>
>     </activity>
>     <activity android:name=".CrimePagerActivity">
>     </activity> </application>
</code>```

I must also precise that before i downgraded the tools folder in the sdk (compatibility problem with another software)[I named the folder tools ==> toolsXXXX and download the version 24.2 and put the tools folder in the sdk folder], it was working..

答: Try performing an uninstall of your application, perform a clean build, gradle sync, and then run your application again.</p>

Title: ClassNotFoundException & app crashing

Body:
I'm working with Android Studio on a learning app, but when i run it, it crashes and give me this error code:

03-29 22:36:03.546 13455-13455/com.training.criminalintent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.training.criminalintent, PID: 13455
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.training.criminalintent/com.training.criminalintent.CrimeListActivity}: java.lang.ClassNotFoundException: Didn't find class "com.training.criminalintent.CrimeListActivity" on path: DexPathList[[zip file "/data/app/com.training.criminalintent-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2290)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
    at android.app.ActivityThread.access$800(ActivityThread.java:156)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:211)
    at android.app.ActivityThread.main(ActivityThread.java:5371)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:945)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.training.criminalintent.CrimeListActivity" on path: DexPathList[[zip file "/data/app/com.training.criminalintent-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1066)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2280)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442)
    at android.app.ActivityThread.access$800(ActivityThread.java:156)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1351)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:211)
    at android.app.ActivityThread.main(ActivityThread.java:5371)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:945)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740)
Suppressed: java.lang.ClassNotFoundException: com.training.criminalintent.CrimeListActivity
    at java.lang.Class.classForName(Native Method)
    at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
    at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
        ... 13 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

I looked for a solution but didn't find something adequate for android studio, but most importantly i didn't find the source of the problem, why android studio is behaving like that.

EDIT: The activity exists in the manifest File :

<application
>     android:allowBackup="true"
>     android:icon="@mipmap/ic_launcher"
>     android:label="@string/app_name"
>     android:supportsRtl="true"
>     android:theme="@style/AppTheme">
>     <activity android:name=".CrimeListActivity">
>         <intent-filter>
>             <action android:name="android.intent.action.MAIN" />
>             <category android:name="android.intent.category.LAUNCHER" />
>         </intent-filter>
>     </activity>
>     <activity android:name=".CrimePagerActivity">
>     </activity> </application>

I must also precise that before i downgraded the tools folder in the sdk (compatibility problem with another software)[I named the folder tools ==> toolsXXXX and download the version 24.2 and put the tools folder in the sdk folder], it was working..


问:
Why does this HashSet code snippet behave this way?
Given the following code:

```<code>public class NewClass {

    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("Orange", "Pineapple", "Banana", "Banana");
        Set<String> fruitsSet = new HashSet<>();

        for (String fruit : fruits) {
            fruitsSet.add(fruit);
        }

        for (String fruit : fruitsSet) {
            System.out.println(fruit);
        }
    }
}
</code>```

Every time I run the code, the order of the elements is the same, eliminating the duplicate item Banana, as is typical of HashSet implementation:

```<code>Banana
Pineapple
Orange
</code>```

My question is, why is the order the same every time, since the specification says "It makes no guarantees as to the iteration order of the set" (https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html)

答: "No guarantees" means just that: no guarantees.  It could be exactly the order you inserted the elements into the set, every time.  It could be random order.  It could be exactly the same order at all times except Tuesdays when it's a full moon.  "No guarantees" does not mean "random" or "unpredictable," it just means you can't depend on any particular order because it could change for any reason.

Body:
Given the following code:

public class NewClass {

    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("Orange", "Pineapple", "Banana", "Banana");
        Set<String> fruitsSet = new HashSet<>();

        for (String fruit : fruits) {
            fruitsSet.add(fruit);
        }

        for (String fruit : fruitsSet) {
            System.out.println(fruit);
        }
    }
}

Every time I run the code, the order of the elements is the same, eliminating the duplicate item Banana, as is typical of HashSet implementation:

Banana
Pineapple
Orange

My question is, why is the order the same every time, since the specification says "It makes no guarantees as to the iteration order of the set" (https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html)


问:
How to implement login in angular js:binding and input value to the REST API URL?
I'm trying to input a username and password into the input fields and send them to the API URL to authenticate the user and return data. I can provide hardcoded credentials to the URL and successfully login. But what I need is to able to input values in the Web interface dynamically and perform the login.

I have no idea how to bind input values into the URL and how the format should be written. Please help with this.

My controller with hard-coded username and password:

```<code>var login = angular.module('login', []);
    login.controller('loginController',       ['$scope','$http','$location',function($scope, $http) {
     $scope.loginauth = function(username,password)
     {
           $http({
           method  : 'POST',
           url     : 'http://televisionarybackendservices.azurewebsites.net/auth/login?username=Evangeli&password=1234',
           headers : {'Content-Type': 'application/x-www-form-urlencoded'}
          })
          .success(function(data) {
               console.log(data)
              $scope.userData = data;

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

enter code here}]);

My html modal to log in;

```<code><div id="loginModal" class="modal fade" role="dialog" ng-controller="loginController">
    <div class="modal-dialog">
            <div class="modal-content">
               <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal">×</button>
                     <h4 class="modal-title">Login</h4>
               </div>
               <div class="modal-body">
                  <form class="form" action="" method="POST" enctype="multipart/form-data" role="form">
                  <div class="form-group">
                    <label for="ue">Username</label>
                    <input type="text" class="form-control" id="ue" placeholder="" ng-model="username">
                  </div>
                  <div class="form-group">
                    <label for="pwd">Password</label>
                    <input type="password" class="form-control" id="pwd" placeholder="" ng-model="password">
                  </div>
                  </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-success" ng-click="loginauth(username,password)">Login</button>
                    <button type="button" class="btn btn-success" data-dismiss="modal">Close</button>
                    <div ng-repeat="data in userData">
                        {{data.username}}<br />
                        {{data.created_at}}
                    </div>

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

I need to enter username and password dynamically and not supply hard-coded values. Thanks in advance.

答:
Well i got the answer.This is for anyone who need help.

```<code>  var login = angular.module('login', []);
    login.controller('loginController', ['$scope','$http','$location',function($scope, $http) {
     $scope.loginauth = function(username,password)
     {
           $http({
           method  : 'POST',
           url     : 'http://televisionarybackendservices.azurewebsites.net/auth/login',
            data: jQuery.param({
        username: $scope.username,
        password: $scope.password
                 }),
           headers : {'Content-Type': 'application/x-www-form-urlencoded'}
          })
          .success(function(data) {
               console.log(data)
              $scope.userData = data;

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

}]);

Body:
I'm trying to input a username and password into the input fields and send them to the API URL to authenticate the user and return data. I can provide hardcoded credentials to the URL and successfully login. But what I need is to able to input values in the Web interface dynamically and perform the login.

I have no idea how to bind input values into the URL and how the format should be written. Please help with this.

My controller with hard-coded username and password:

var login = angular.module('login', []);
    login.controller('loginController',       ['$scope','$http','$location',function($scope, $http) {
     $scope.loginauth = function(username,password)
     {
           $http({
           method  : 'POST',
           url     : 'http://televisionarybackendservices.azurewebsites.net/auth/login?username=Evangeli&password=1234',
           headers : {'Content-Type': 'application/x-www-form-urlencoded'}
          })
          .success(function(data) {
               console.log(data)
              $scope.userData = data;

        });
     };

enter code here}]);

My html modal to log in;

                  <button type="button" class="close" data-dismiss="modal">×</button>

Login

                  <form class="form" action="" method="POST" enctype="multipart/form-data" role="form">

                    Username
                    <input type="text" class="form-control" id="ue" placeholder="" ng-model="username">

                    Password
                    <input type="password" class="form-control" id="pwd" placeholder="" ng-model="password">

                  </form>

                    <button type="button" class="btn btn-success" ng-click="loginauth(username,password)">Login</button>
                    <button type="button" class="btn btn-success" data-dismiss="modal">Close</button>

                        {{data.username}}

                        {{data.created_at}}

I need to enter username and password dynamically and not supply hard-coded values. Thanks in advance.

Body:
Well i got the answer.This is for anyone who need help.

  var login = angular.module('login', []);
    login.controller('loginController', ['$scope','$http','$location',function($scope, $http) {
     $scope.loginauth = function(username,password)
     {
           $http({
           method  : 'POST',
           url     : 'http://televisionarybackendservices.azurewebsites.net/auth/login',
            data: jQuery.param({
        username: $scope.username,
        password: $scope.password
                 }),
           headers : {'Content-Type': 'application/x-www-form-urlencoded'}
          })
          .success(function(data) {
               console.log(data)
              $scope.userData = data;

        });
     };

}]);


问:
Angular2 get google Analytics Id from service and add it to index.html
I have added the following code in my index.html

```<code>    <script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXX-X', 'auto');

</script>
</code>```

I would like to get the UA number from a service and not hardcode it here, since it changes based on the environment we are on. I would like to know how to make the service call and inject this value.

Thanks,

答:
Found a way to do it, not sure if its the best way.

```

Body:
I have added the following code in my index.html

I would like to get the UA number from a service and not hardcode it here, since it changes based on the environment we are on. I would like to know how to make the service call and inject this value.

Thanks,

Body:
Found a way to do it, not sure if its the best way.

<script>
  var id ='';
  var propertiesUrl = '../someurl';
  function httpGet()
  {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", propertiesUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    var jsonResponse = JSON.parse(xmlHttp.responseText);
    id = jsonResponse.analyticsId;

    if (xmlHttp.readyState === XMLHttpRequest.DONE && xmlHttp.status === 200) {
      (function (i, s, o, g, r, a, m) {
        i['GoogleAnalyticsObject'] = r;
        i[r] = i[r] || function () {
            (i[r].q = i[r].q || []).push(arguments)
          }, i[r].l = 1 * new Date();
        a = s.createElement(o),
          m = s.getElementsByTagName(o)[0];
        a.async = 1;
        a.src = g;
        m.parentNode.insertBefore(a, m)
      })(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
      ga('create', id, 'auto');
    }

  }
  httpGet();

</script>


问:
running optimizer in parallel
I would like to run the fmin_powell optimizer for different arguments from the f list at the same time.

```<code>f = ['1','2','3','4','5','6']
optg_res = opt.fmin_powell(runner, coeff, args=(f,f), disp=0)
</code>```

Is there any easy method of doing it? Maybe I would use any bash command to run it?

答:
You can use the multiprocessing module for it and have each call to fmin_powell run in a separate process in parallel. Pool.map() submits the calls to a process pool and returns a list of result values for each value in the parameter list.

See this example code for 4 processes in parallel based on the code given in your question:

```<code>from multiprocessing.pool import Pool

def optimize(f):
    return opt.fmin_powell(runner, coeff, args=(f,f), disp=0)

f = [1,2,3,4,5,6]

p = Pool(processes=4)
results = p.map(optimize,f)
</code>```

Title: running optimizer in parallel

Body:
I would like to run the fmin_powell optimizer for different arguments from the f list at the same time.

f = ['1','2','3','4','5','6']
optg_res = opt.fmin_powell(runner, coeff, args=(f,f), disp=0)

Is there any easy method of doing it? Maybe I would use any bash command to run it?

Body:
You can use the multiprocessing module for it and have each call to fmin_powell run in a separate process in parallel. Pool.map() submits the calls to a process pool and returns a list of result values for each value in the parameter list.

See this example code for 4 processes in parallel based on the code given in your question:

from multiprocessing.pool import Pool

def optimize(f):
    return opt.fmin_powell(runner, coeff, args=(f,f), disp=0)

f = [1,2,3,4,5,6]

p = Pool(processes=4)
results = p.map(optimize,f)


问:
What's jQuery’s Data Method? How & Why is it used?
What's jQuery’s Data Method? How & Why is it used?</p>

答:
Basically it stores some arbitrary data in any DOM element in a safe way.

from the docs:

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

ContentLicense: CC BY-SA 2.5


问:
Disappearing Objects
so for my first project with MonoGame I decided to make a tetris clone but I have an issue which I don't know how to solve.

Currently my code is generating a block and moves it downwards until it reach a specific y position. The block need to stay at this position and a new block spawns. I'm doing this with a List which contains object of the block class and then just draw all the blocks in this list.

I took out parts which I believe are not involved in the problem:

```<code> public class PlayField : DrawableGameComponent
    {
        private Game1 gameRef;
        private Texture2D fieldTexture;
        private BlockGenerator blockGenerator;
        private Texture2D[] allBlocks;

        private Block currentBlock;

        public bool[,] fieldFilled;
        private int down_Blocks = 22;
        private int side_Blocks = 10;

        public List<Block> placedBlocks;

        public PlayField(Game game) : base(game)
        {
            placedBlocks = new List<Block>();
            allBlocks = new Texture2D[4];
            blockGenerator = new BlockGenerator(allBlocks,gameRef);

        }
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            try
            {
                if (currentBlock.isMoving == false)
                {
                    placedBlocks.Add(currentBlock);
                    currentBlock = null;
                    currentBlock = blockGenerator.GenerateBlock();
                }
                else
                {
                    currentBlock.UpdatePosition(gameTime);
                    if (InputManager.CheckForKeyBoardRelease(Keys.A))
                    {
                        currentBlock.MoveLeft();
                    }

                    if (InputManager.CheckForKeyBoardRelease(Keys.D))
                    {
                        currentBlock.MoveRight();
                    }
                }
            }
            catch(NullReferenceException e)
            {
                currentBlock = blockGenerator.GenerateBlock();
            }

        }

        public override void Draw(GameTime gameTime)
        {
            gameRef.SpriteBatch.Begin();

            if(currentBlock != null)
            {
                currentBlock.DrawBlocks();
            }

            foreach(Block b in placedBlocks)
            {
                b.DrawBlocks();
            }

            gameRef.SpriteBatch.End();
            base.Draw(gameTime);
        }
</code>```

The method "GenerateBlock" returns a object of type "Block"

```<code>public class Block : DrawableGameComponent
    {
        Game1 gameRef;
        public Texture2D blockTexture;
        public Vector2[] blockPositions;
        TimeSpan lastMove;
        TimeSpan blockMove = TimeSpan.FromMilliseconds(500);

        public bool isMoving;

        public Block(Game game, Texture2D _blockTexture, Vector2[] _blockPositions) : base(game)
        {
            gameRef = (Game1)game;
            blockTexture = _blockTexture;
            blockPositions = _blockPositions;
            isMoving = true;
        }

        public void UpdatePosition(GameTime gameTime)
        {
            Vector2 bottomBlockPositon = FindBottomBlock();
            if(bottomBlockPositon.Y < 550)
            {
                if (WaitTillMove(gameTime))
                {
                    for (int i = 0; i < blockPositions.Length; i++)
                    {
                        blockPositions[i] = new Vector2(blockPositions[i].X, blockPositions[i].Y + 25);
                    }
                }
            }
            else
            {
                isMoving = false;
                Console.WriteLine("X: " +blockPositions[0].X + " Y:" + blockPositions[0].Y);
            }

        }

        public Vector2 FindBottomBlock()
        {
            Vector2 result = new Vector2(0, 0);
            for(int i = 0; i < blockPositions.Length; i++)
            {
                if(blockPositions[i].Y > result.Y)
                {
                    result = blockPositions[i];
                }
            }

            return result;
        }

        public bool WaitTillMove(GameTime gameTime)
        {
            if (lastMove + blockMove < gameTime.TotalGameTime)
            {
                lastMove = gameTime.TotalGameTime;
                return true;
            }
            return false;
        }

        public void DrawBlocks()
        {
            gameRef.SpriteBatch.Draw(blockTexture, blockPositions[0], Color.White);
            gameRef.SpriteBatch.Draw(blockTexture, blockPositions[1], Color.White);
            gameRef.SpriteBatch.Draw(blockTexture, blockPositions[2], Color.White);
            gameRef.SpriteBatch.Draw(blockTexture, blockPositions[3], Color.White);
        }
    }
</code>```

Debugging says that my List contains an Element even though it has the wrong positions. But this shouldn't matter because I still only "see" one Block at the same time.

Hopefully someone can toss me into the right direction.

Edit:

```<code>public class BlockGenerator
    {
        Random random;
        Texture2D[] allBlocks;
        Vector2[] blockPositions;
        Texture2D currentBlock;
        BlockEnums currentBlockEnum;

        Game1 gameRef;

        public BlockGenerator(Texture2D[] blocks, Game1 game)
        {
            gameRef = (Game1)game;
            allBlocks = blocks;
            currentBlock = allBlocks[1];
            blockPositions = new Vector2[4];
            random = new Random();
        }

        public Block GenerateBlock()
        {
            int colorValue = random.Next(0, 4);     //0 = blue, 1 = green, 2 = red, 3 = yellow

            currentBlock = allBlocks[colorValue];
            currentBlockEnum = BlockEnums.Line;

            blockPositions[0] = new Vector2(100, 0);
            blockPositions[1] = new Vector2(125, 0);
            blockPositions[2] = new Vector2(150, 0);
            blockPositions[3] = new Vector2(175, 0);

            Block generatedBlock = new Block(gameRef,currentBlock, blockPositions);

            return generatedBlock;
        }
</code>```

答:
```<code>public class BlockGenerator
    {
        Random random;
        Texture2D[] allBlocks;
        Vector2[] blockPositions; // delete this
</code>```

Then move the initialization code from the constructor into GenerateBlock (add var).

```<code>var blockPositions = new Vector2[4];
</code>```

Then it should work. You were creating new vectors each time you created a block but re-using the same instance of blockPositions each time, so both blocks do exist but will always have the exact same positions.

I haven't had time to test but I think it's right...let me know :)

edit: I'd also suggest moving blockPositions entirely into the Block class. I see no value (in the code you have posted, maybe you have plans for later) in having that logic outside of the class that really owns it...and if it was contained within the class to begin with you would have avoided this problem. Just a suggestion :)

Title: Disappearing Objects

Body:
so for my first project with MonoGame I decided to make a tetris clone but I have an issue which I don't know how to solve.

Currently my code is generating a block and moves it downwards until it reach a specific y position. The block need to stay at this position and a new block spawns. I'm doing this with a List which contains object of the block class and then just draw all the blocks in this list.

I took out parts which I believe are not involved in the problem:

 public class PlayField : DrawableGameComponent
    {
        private Game1 gameRef;
        private Texture2D fieldTexture;
        private BlockGenerator blockGenerator;
        private Texture2D[] allBlocks;

        private Block currentBlock;

        public bool[,] fieldFilled;
        private int down_Blocks = 22;
        private int side_Blocks = 10;

        public List<Block> placedBlocks;

        public PlayField(Game game) : base(game)
        {
            placedBlocks = new List<Block>();
            allBlocks = new Texture2D[4];
            blockGenerator = new BlockGenerator(allBlocks,gameRef);

        }
        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            try
            {
                if (currentBlock.isMoving == false)
                {
                    placedBlocks.Add(currentBlock);
                    currentBlock = null;
                    currentBlock = blockGenerator.GenerateBlock();
                }
                else
                {
                    currentBlock.UpdatePosition(gameTime);
                    if (InputManager.CheckForKeyBoardRelease(Keys.A))
                    {
                        currentBlock.MoveLeft();
                    }

                    if (InputManager.CheckForKeyBoardRelease(Keys.D))
                    {
                        currentBlock.MoveRight();
                    }
                }
            }
            catch(NullReferenceException e)
            {
                currentBlock = blockGenerator.GenerateBlock();
            }

        }

        public override void Draw(GameTime gameTime)
        {
            gameRef.SpriteBatch.Begin();

            if(currentBlock != null)
            {
                currentBlock.DrawBlocks();
            }

            foreach(Block b in placedBlocks)
            {
                b.DrawBlocks();
            }

            gameRef.SpriteBatch.End();
            base.Draw(gameTime);
        }

The method "GenerateBlock" returns a object of type "Block"

public class Block : DrawableGameComponent
    {
        Game1 gameRef;
        public Texture2D blockTexture;
        public Vector2[] blockPositions;
        TimeSpan lastMove;
        TimeSpan blockMove = TimeSpan.FromMilliseconds(500);

        public bool isMoving;

        public Block(Game game, Texture2D _blockTexture, Vector2[] _blockPositions) : base(game)
        {
            gameRef = (Game1)game;
            blockTexture = _blockTexture;
            blockPositions = _blockPositions;
            isMoving = true;
        }

        public void UpdatePosition(GameTime gameTime)
        {
            Vector2 bottomBlockPositon = FindBottomBlock();
            if(bottomBlockPositon.Y < 550)
            {
                if (WaitTillMove(gameTime))
                {
                    for (int i = 0; i < blockPositions.Length; i++)
                    {
                        blockPositions[i] = new Vector2(blockPositions[i].X, blockPositions[i].Y + 25);
                    }
                }
            }
            else
            {
                isMoving = false;
                Console.WriteLine("X: " +blockPositions[0].X + " Y:" + blockPositions[0].Y);
            }

        }

        public Vector2 FindBottomBlock()
        {
            Vector2 result = new Vector2(0, 0);
            for(int i = 0; i < blockPositions.Length; i++)
            {
                if(blockPositions[i].Y > result.Y)
                {
                    result = blockPositions[i];
                }
            }

            return result;
        }

        public bool WaitTillMove(GameTime gameTime)
        {
            if (lastMove + blockMove < gameTime.TotalGameTime)
            {
                lastMove = gameTime.TotalGameTime;
                return true;
            }
            return false;
        }

        public void DrawBlocks()
        {
            gameRef.SpriteBatch.Draw(blockTexture, blockPositions[0], Color.White);
            gameRef.SpriteBatch.Draw(blockTexture, blockPositions[1], Color.White);
            gameRef.SpriteBatch.Draw(blockTexture, blockPositions[2], Color.White);
            gameRef.SpriteBatch.Draw(blockTexture, blockPositions[3], Color.White);
        }
    }

Debugging says that my List contains an Element even though it has the wrong positions. But this shouldn't matter because I still only "see" one Block at the same time.

Hopefully someone can toss me into the right direction.

Edit:

public class BlockGenerator
    {
        Random random;
        Texture2D[] allBlocks;
        Vector2[] blockPositions;
        Texture2D currentBlock;
        BlockEnums currentBlockEnum;

        Game1 gameRef;

        public BlockGenerator(Texture2D[] blocks, Game1 game)
        {
            gameRef = (Game1)game;
            allBlocks = blocks;
            currentBlock = allBlocks[1];
            blockPositions = new Vector2[4];
            random = new Random();
        }

        public Block GenerateBlock()
        {
            int colorValue = random.Next(0, 4);     //0 = blue, 1 = green, 2 = red, 3 = yellow

            currentBlock = allBlocks[colorValue];
            currentBlockEnum = BlockEnums.Line;

            blockPositions[0] = new Vector2(100, 0);
            blockPositions[1] = new Vector2(125, 0);
            blockPositions[2] = new Vector2(150, 0);
            blockPositions[3] = new Vector2(175, 0);

            Block generatedBlock = new Block(gameRef,currentBlock, blockPositions);

            return generatedBlock;
        }

Body:
public class BlockGenerator
    {
        Random random;
        Texture2D[] allBlocks;
        Vector2[] blockPositions; // delete this

Then move the initialization code from the constructor into GenerateBlock (add var).

var blockPositions = new Vector2[4];

Then it should work. You were creating new vectors each time you created a block but re-using the same instance of blockPositions each time, so both blocks do exist but will always have the exact same positions.

I haven't had time to test but I think it's right...let me know :)

edit: I'd also suggest moving blockPositions entirely into the Block class. I see no value (in the code you have posted, maybe you have plans for later) in having that logic outside of the class that really owns it...and if it was contained within the class to begin with you would have avoided this problem. Just a suggestion :)


问:
Adding filter on the right side table on Left outer joins
On outer joins(lets take a left outer join in this case) how does adding a filter on the right side table work?

```<code>SELECT s.id, i.name FROM Student s
LEFT OUTER JOIN Student_Instructor i
ON s.student_id=i.student_id
AND i.name='John'
</code>```

I understand that if the filter was on the Student table it would be more like "Get all rows with name= John first and join the tables".

But I am not sure if that is the case if the filter is on the right side table(Student_Instructor). How does the filter i.name='John' gets interpreted?

Thank you

答:
This can be done using Oracle (+) notation as well-

```<code>SELECT s.id FROM Student s, Student_Instructor i
WHERE s.student_id = i.student_id (+)
AND i.name(+)='John'
</code>```

Although, Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator.

Body:
On outer joins(lets take a left outer join in this case) how does adding a filter on the right side table work?

SELECT s.id, i.name FROM Student s
LEFT OUTER JOIN Student_Instructor i
ON s.student_id=i.student_id
AND i.name='John'

I understand that if the filter was on the Student table it would be more like "Get all rows with name= John first and join the tables".

But I am not sure if that is the case if the filter is on the right side table(Student_Instructor). How does the filter i.name='John' gets interpreted?

Thank you

Body:
This can be done using Oracle (+) notation as well-

SELECT s.id FROM Student s, Student_Instructor i
WHERE s.student_id = i.student_id (+)
AND i.name(+)='John'

Although, Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator.


问:
Is it a bug that generators don't work when passed to "numpy.array"?
If a generator is passed to numpy.array, numpy does not iterate over the object, nor does it complain, even if copy=True. Any attempt to index into the array fails, frequently much later and in far away code.

I understand that numpy wants to know the size of the array from the beginning, but this behavior is not good. It should either copy to an intermediate list or raise an exception.

答:
This is not a bug, but normal behaviour. If you want to create a array from an iterator, use fromiter:

```<code>>>> import numpy
>>> a = (i*i for i in range(7))
>>> numpy.array(a)
array(<generator object <genexpr> at 0x10dbc1b40>, dtype=object)
>>> numpy.fromiter(a, dtype=float)
array([  0.,   1.,   4.,   9.,  16.,  25.,  36.])
</code>```

Body:
This is not a bug, but normal behaviour. If you want to create a array from an iterator, use fromiter:

>>> import numpy
>>> a = (i*i for i in range(7))
>>> numpy.array(a)
array(<generator object <genexpr> at 0x10dbc1b40>, dtype=object)
>>> numpy.fromiter(a, dtype=float)
array([  0.,   1.,   4.,   9.,  16.,  25.,  36.])


问:
NodeJS NPM Proxy error when installing grunt
When I'm trying to install grunt via npm, I'm getting a following error:

```<code>C:\Program Files\nodejs\node_modules\npm>npm install -g grunt
npm ERR! network connect ETIMEDOUT
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "grunt"
npm ERR! cwd C:\Program Files\nodejs\node_modules\npm
npm ERR! node -v v0.10.33
npm ERR! npm -v 1.4.28
npm ERR! syscall connect
npm ERR! code ETIMEDOUT
npm ERR! errno ETIMEDOUT
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     C:\Program Files\nodejs\node_modules\npm\npm-debug.log
npm ERR! not ok code 0
</code>```

I´m using enterprise proxy configurations, and I believe that I'm having this error because of its configurations. What do I need to change in order to install grunt successfully?

答:
If you're frustrated and none of this monkey-business is working for you, just go Download and run the latest MSI.
https://nodejs.org/en/download/</p>

Body:
When I'm trying to install grunt via npm, I'm getting a following error:

C:\Program Files\nodejs\node_modules\npm>npm install -g grunt
npm ERR! network connect ETIMEDOUT
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "grunt"
npm ERR! cwd C:\Program Files\nodejs\node_modules\npm
npm ERR! node -v v0.10.33
npm ERR! npm -v 1.4.28
npm ERR! syscall connect
npm ERR! code ETIMEDOUT
npm ERR! errno ETIMEDOUT
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     C:\Program Files\nodejs\node_modules\npm\npm-debug.log
npm ERR! not ok code 0

I´m using enterprise proxy configurations, and I believe that I'm having this error because of its configurations. What do I need to change in order to install grunt successfully?


问:
Swift IF statement to perform action only once
I have an IF statement and I need it to trigger when the score >= 200 but only happen once and not repeatedly.

Here's my code:

```<code>if score >= 200 {

        meteRedTimer.invalidate()
        meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)

    } else {

    }
</code>```

However this constantly starts the timer all the time when the score is => 200 and not just one timer which I understand.

If I do score = 200 this would work however there is a chance the score could jump from 190 to 210 for example depending on the game play.

How could I basically stop this IF statement once it has been triggered once?

答:
create var didPermored = false and inside if statement

```<code>if score >= 200 && !didPermormed {
    didPermormed = true
    meteRedTimer.invalidate()
    meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)
} else {

//do stuff
}
</code>```

Body:
I have an IF statement and I need it to trigger when the score >= 200 but only happen once and not repeatedly.

Here's my code:

if score >= 200 {

        meteRedTimer.invalidate()
        meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)

    } else {

    }

However this constantly starts the timer all the time when the score is => 200 and not just one timer which I understand.

If I do score = 200 this would work however there is a chance the score could jump from 190 to 210 for example depending on the game play.

How could I basically stop this IF statement once it has been triggered once?

Body:
create var didPermored = false and inside if statement

if score >= 200 && !didPermormed {
    didPermormed = true
    meteRedTimer.invalidate()
    meteBlueTimer = Timer.scheduledTimer(timeInterval: 0.7, target: self, selector: #selector(self.makeBlueMete), userInfo: nil, repeats: true)
} else {

//do stuff
}


问:
Does a writable computed observable really need an extra internal observable?
I am trying to use a writable computed observable, but do not really get it why I cannot get some data in the observable by just typing in it. I found that I need an extra observable to copy content from the write: to the read:, which seems weird.

```<code>        self.fullName = ko.pureComputed({
            read: function () {
                return ...data from other observables to show in the observable;
            },
            write: function (value) {
                  // value is the content in the input
                  // can be sent to other observables
            },
            owner: self
        });
</code>```

I found that in the above model, what you type in the observable is not really inside.

In the complete example below (including test output and comments) I use an extra observable to copy data from write: to read:. Crucial in my project is the checkbox to decide if you get two observables filled identically by typing in one of them, or differently by typing in both of them.

```<code>    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Writable computed observables</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <script src='https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js'></script>
    </head>
    <body>
        <h1>Writable computed observables</h1>
        <p>See: <a href="http://knockoutjs.com/documentation/computed-writable.html">Knockout Doc</a></p>
        <h2>Original example</h2>
        <div>
            First name: <input data-bind="textInput: firstName" />
            <span data-bind="text: firstName"></span>
        </div>
        <div>
            Last name: <input data-bind="textInput: lastName" />
            <span data-bind="text: lastName"></span>
        </div>
        <div class="heading">
            Hello, <input data-bind="textInput: fullName" />
            <span data-bind="text: fullName"></span>
        </div>
        <h2>My example</h2>
        <div>
            Name: <input data-bind="textInput: Name" />
            <span data-bind="text: Name"></span>
        </div>
         <div>
            Mirror first name? <input type="checkbox" data-bind="checked: cbMirror" />
            <span data-bind="text: cbMirror"></span>
        </div>
        <script>
            function MyViewModel() {
                var self = this;
                // example from knockout site:
                self.firstName = ko.observable('Planet');
                self.lastName = ko.observable('Earth');

                self.fullName = ko.pureComputed({
                    read: function () {
                        //return;
                        return self.firstName() + " " + self.lastName();
                    },
                    write: function (value) {
                          // value is the content in the input field, visible on form,
                          // but apparently not yet in the observable.
                          // now copy this value to first/last-name observables,
                          // that in turn copy it to the read-function,
                          // that returns it to the observable.
                        var lastSpacePos = value.lastIndexOf(" ");
                        if (lastSpacePos > 0) { // Ignore values with no space character
                            self.firstName(value.substring(0, lastSpacePos)); // Update "firstName"
                            self.lastName(value.substring(lastSpacePos + 1)); // Update "lastName"
                        }
                    },
                    owner: self
                });

                // checkbox whether or not to mirror between two fields
                self.cbMirror = ko.observable(false);
                // this observable is to help the writable computed observable to copy input from write() to read()
                self.tmpName = ko.observable();
                // the writable computed observable that may mirror another field, depending on the checkbox
                self.Name = ko.pureComputed({
                        read: function () {
                            return self.cbMirror() ? self.firstName() : self.tmpName();
                        },
                        write: function (value) {
                            //if (self.cbMirror()){
                            //  self.firstName(value);
                            //}else{
                                self.tmpName(value);
                            //}
                        },
                        owner: self
                });
            }

            ko.applyBindings(new MyViewModel());
        </script>
    </body>
    </html>
</code>```

The question, hence: is there really no better way, to directly get some content from write: to read: without the extra observable self.tmpName?

Update:

With the understanding gained from the Answer below, I could simplify the write: part of my example code, see the unneeded code that I commented-out.

答:
Yes you need an observable if you want to store the user input. A computed doesn't store information it only modifies it. It's like the difference between a variable and a function. Functions don't store their values for later viewing it's only modifying an input and giving an output.

the writable computed observable doesn't store data. It passes the data to the backing observable. That's the entire point of the write portion is to take the value and store it somewhere. If you add another span to look at the value of tmpName you'll see that it's storing whatever you type unless cbMirror is checked.

Body:
I am trying to use a writable computed observable, but do not really get it why I cannot get some data in the observable by just typing in it. I found that I need an extra observable to copy content from the write: to the read:, which seems weird.

        self.fullName = ko.pureComputed({
            read: function () {
                return ...data from other observables to show in the observable;
            },
            write: function (value) {
                  // value is the content in the input
                  // can be sent to other observables
            },
            owner: self
        });

I found that in the above model, what you type in the observable is not really inside.

In the complete example below (including test output and comments) I use an extra observable to copy data from write: to read:. Crucial in my project is the checkbox to decide if you get two observables filled identically by typing in one of them, or differently by typing in both of them.

    <!DOCTYPE html>

        <title>Writable computed observables</title>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />

Writable computed observables

See: Knockout Doc

Original example

            First name: <input data-bind="textInput: firstName" />

            Last name: <input data-bind="textInput: lastName" />

            Hello, <input data-bind="textInput: fullName" />

My example

            Name: <input data-bind="textInput: Name" />

            Mirror first name? <input type="checkbox" data-bind="checked: cbMirror" />

The question, hence: is there really no better way, to directly get some content from write: to read: without the extra observable self.tmpName?

Update:

With the understanding gained from the Answer below, I could simplify the write: part of my example code, see the unneeded code that I commented-out.


问:
Detect Exact Windows 10 Version to Echo Colored Text in Batch File
Based on this post for changing the output color of command prompt text in Windows 10, I'm looking for the best way to detect the OS version in a batch file IF statement.

How to echo with different colors in the Windows command line

From my understanding, colorized text was added in Windows 10 Threshold 2 November 18, 2015 (10.0.10586.11)

In Windows 10 version history, up until the Version 1607 (Anniversary Update), there was a major.minor.build.revision numbering scheme so I want the detection to be very granular.

https://en.wikipedia.org/wiki/Windows_10_version_history

I found this post which compares major.minor.build to a user input, but can't wrap my head around what it's doing for my needs.

https://github.com/LogicDaemon/PersonalUseScripts/blob/c3346df9c7c0f57b584b5c0238b8e8b76096c42c/cmd/superuser%20q%20891742/CheckWinVer.cmd

So based on that information, I'm trying to compare the detected version of windows to 10.0.10586.11 in a batch file.

If its greater than or equal to that version, colorize the text, if not use standard formatting.

This was my first attempt to colorize text in an IF statement.  Although this appeared to work in Windows 10, it didn't work in Windows 8.1 because string "10." is less than "6.3"

```<code>FOR /F "tokens=4-5 delims=. " %%i in ('ver') DO SET Version=%%i.%%j
IF "%Version%" GEQ "10.0" (echo [92mHere is my text in green.[0m) ELSE (echo Here is my text)
</code>```

Note the required escape characters are missing in the above sample

答:
Compare numeric values instead of strings (e.g. Windows 8.1 returns 603):

```<code>FOR /F "tokens=4-5 delims=. " %%i in ('ver') DO SET /A _Version=%%i*100+%%j
IF %_Version% GEQ 1000 (echo [92mHere is my text in green.[0m) ELSE (echo Here is my text)
</code>```

Edit. Instead of wikipedia, I'd use a primary source Windows 10 release information on Microsoft’s TechNet site.

```<code>FOR /F "tokens=4-7 delims=[]. " %%i in ('ver') DO (
  SET /A _MajorMinor = %%i * 100 + %%j
  set /A _Build      = %%k0 /10
  set /A _Revision   = %%l0 /10
)
set "_AE="        AE like Ansi Escape
IF %_MajorMinor% GEQ 1000 if %_Build% GTR 10586 ( set "_AE=Yes" ) else (
      if %_Build% EQU 10586 if %_Revision% GEQ 11 set "_AE=Yes" )
rem use the _AE flag
if defined _AE (echo [92mHere is my text in green.[0m) ELSE (echo Here is my text)
</code>```

Used nested IFs (effective as of logical AND).

The set /A _Revision = %%l0 /10 construct used to avoid Missing operator on Windows 8 where the 7th token %%l results to an empty string.

Body:
Based on this post for changing the output color of command prompt text in Windows 10, I'm looking for the best way to detect the OS version in a batch file IF statement.

How to echo with different colors in the Windows command line

From my understanding, colorized text was added in Windows 10 Threshold 2 November 18, 2015 (10.0.10586.11)

In Windows 10 version history, up until the Version 1607 (Anniversary Update), there was a major.minor.build.revision numbering scheme so I want the detection to be very granular.

https://en.wikipedia.org/wiki/Windows_10_version_history

I found this post which compares major.minor.build to a user input, but can't wrap my head around what it's doing for my needs.

https://github.com/LogicDaemon/PersonalUseScripts/blob/c3346df9c7c0f57b584b5c0238b8e8b76096c42c/cmd/superuser%20q%20891742/CheckWinVer.cmd

So based on that information, I'm trying to compare the detected version of windows to 10.0.10586.11 in a batch file.

If its greater than or equal to that version, colorize the text, if not use standard formatting.

This was my first attempt to colorize text in an IF statement.  Although this appeared to work in Windows 10, it didn't work in Windows 8.1 because string "10." is less than "6.3"

FOR /F "tokens=4-5 delims=. " %%i in ('ver') DO SET Version=%%i.%%j
IF "%Version%" GEQ "10.0" (echo [92mHere is my text in green.[0m) ELSE (echo Here is my text)

Note the required escape characters are missing in the above sample

Body:
Compare numeric values instead of strings (e.g. Windows 8.1 returns 603):

FOR /F "tokens=4-5 delims=. " %%i in ('ver') DO SET /A _Version=%%i*100+%%j
IF %_Version% GEQ 1000 (echo [92mHere is my text in green.[0m) ELSE (echo Here is my text)

Edit. Instead of wikipedia, I'd use a primary source Windows 10 release information on Microsoft’s TechNet site.

FOR /F "tokens=4-7 delims=[]. " %%i in ('ver') DO (
  SET /A _MajorMinor = %%i * 100 + %%j
  set /A _Build      = %%k0 /10
  set /A _Revision   = %%l0 /10
)
set "_AE="        AE like Ansi Escape
IF %_MajorMinor% GEQ 1000 if %_Build% GTR 10586 ( set "_AE=Yes" ) else (
      if %_Build% EQU 10586 if %_Revision% GEQ 11 set "_AE=Yes" )
rem use the _AE flag
if defined _AE (echo [92mHere is my text in green.[0m) ELSE (echo Here is my text)

Used nested IFs (effective as of logical AND).

The set /A _Revision = %%l0 /10 construct used to avoid Missing operator on Windows 8 where the 7th token %%l results to an empty string.


问:
Move/Copy Firebase Object to Another Child Node
I have a user object in firebase that I need to move to another child node on the same tree.

The structure is like so:

```<code>users -> male   -> uid -> ......KVPs..objects...etc
      -> female -> uid -> ......KVPs..objects...etc
</code>```

I need to keep users separated by gender due to the nature of the app.
If a user changes their gender I want to move all their details to that selected gender.

I tried using AngularFire (firebaseObject) but it throws errors when I tried to set it in firebase due to the keys present in the object. I tried striping out the keys, using JSON.stringify, angular.toJSON but am not having any luck!!

I'm wondering is there a cleaner or recommended way to do this?
Appreciate If anyone has any pointers or can assist in anyway.

Many Thanks,
Noel

答:
Thanks for responding. I had it like this originally and I still capture the gender under the UID but I wanted to separate males and females. My app is for dating so I'm thinking it will be more efficient for doing searches based on the preferred sex attribute. I would think ~50% less nodes to search through initially. If you have some advice on this, would love to hear as I'm not too up on performance best practices for firebase/JSON.

I'm going to post the code I used for copying and cleaning up as might be helpful to someone. I had problems with 'on' listener, it was deleting both nodes. Changing this to 'once' resolved it.

```<code>// firebase refs
    desc.ref1 = new Firebase(desc.userRef+'/'+desc.oldGender+'/'+uid);
    desc.ref2 = new Firebase(desc.userRef+'/'+desc.gender+'/'+uid);

// copy user object
    desc.ref1.once("value", function(snapshot) {

        // copy user data to new gender tree
        desc.ref2.set(snapshot.val(), function(error) {
            if (error) {
                $log.info("could not copy user object." + error);
            } else {
                $log.info("user object copied successfully.");

                // remove user object under old gender
                desc.ref1.remove(desc.onComplete);
            }
        });
    }, function (errorObject) {
        $log.info("The read failed: " + errorObject.code);
    });
</code>```

Body:
I have a user object in firebase that I need to move to another child node on the same tree.

The structure is like so:

users -> male   -> uid -> ......KVPs..objects...etc
      -> female -> uid -> ......KVPs..objects...etc

I need to keep users separated by gender due to the nature of the app.
If a user changes their gender I want to move all their details to that selected gender.

I tried using AngularFire (firebaseObject) but it throws errors when I tried to set it in firebase due to the keys present in the object. I tried striping out the keys, using JSON.stringify, angular.toJSON but am not having any luck!!

I'm wondering is there a cleaner or recommended way to do this?
Appreciate If anyone has any pointers or can assist in anyway.

Many Thanks,
Noel

Body:
Thanks for responding. I had it like this originally and I still capture the gender under the UID but I wanted to separate males and females. My app is for dating so I'm thinking it will be more efficient for doing searches based on the preferred sex attribute. I would think ~50% less nodes to search through initially. If you have some advice on this, would love to hear as I'm not too up on performance best practices for firebase/JSON.

I'm going to post the code I used for copying and cleaning up as might be helpful to someone. I had problems with 'on' listener, it was deleting both nodes. Changing this to 'once' resolved it.

// firebase refs
    desc.ref1 = new Firebase(desc.userRef+'/'+desc.oldGender+'/'+uid);
    desc.ref2 = new Firebase(desc.userRef+'/'+desc.gender+'/'+uid);

// copy user object
    desc.ref1.once("value", function(snapshot) {

        // copy user data to new gender tree
        desc.ref2.set(snapshot.val(), function(error) {
            if (error) {
                $log.info("could not copy user object." + error);
            } else {
                $log.info("user object copied successfully.");

                // remove user object under old gender
                desc.ref1.remove(desc.onComplete);
            }
        });
    }, function (errorObject) {
        $log.info("The read failed: " + errorObject.code);
    });


答:
No it's a design decision. If you want to pass in a generator you need to use np.fromiter:

```<code>>>> np.fromiter((i for i in range(10)), float)
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])
</code>```

or convert it to a list before calling np.array:

```<code>>>> np.array(list(your_iterator))
</code>```

One reason for this is that numpy needs to iterate over the object several times: once to determine the length/dytpe of the resulting array and once to insert the items. That doesn't play well with generators and iterators which can be iterated only once. Also Generators can be infinite in length (i.e. itertools.count) and/or use "too much memory".

The rationale probably was: If someone wants to use generators to create an array it's going to use a lot of memory and will be slow - so it should be done intentionally: either by casting it to a list or using np.fromiter.

Title: Is it a bug that generators don't work when passed to "numpy.array"?

Body:
If a generator is passed to numpy.array, numpy does not iterate over the object, nor does it complain, even if copy=True. Any attempt to index into the array fails, frequently much later and in far away code.

I understand that numpy wants to know the size of the array from the beginning, but this behavior is not good. It should either copy to an intermediate list or raise an exception.

Body:
No it's a design decision. If you want to pass in a generator you need to use np.fromiter:

>>> np.fromiter((i for i in range(10)), float)
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])

or convert it to a list before calling np.array:

>>> np.array(list(your_iterator))

One reason for this is that numpy needs to iterate over the object several times: once to determine the length/dytpe of the resulting array and once to insert the items. That doesn't play well with generators and iterators which can be iterated only once. Also Generators can be infinite in length (i.e. itertools.count) and/or use "too much memory".

The rationale probably was: If someone wants to use generators to create an array it's going to use a lot of memory and will be slow - so it should be done intentionally: either by casting it to a list or using np.fromiter.


问:
Why do Magento configurable products have a SKU
I am about to create about 300 products (not many but enough).  Most of them are configurable so I will be entering a bunch of info then putting it together.  Each simple product that makes up a config product has its own sku, so why would a configurable product need a sku?</p>

答: To be pithy, because every "product" needs a human-usable identifier, and that pretty much defines a SKU. You could use the entity_id (PK column) instead, but then you'll just be pushing the question back a layer.</p>


问:
Printing the second half of a linked list in reverse order
I want to print the elements of a linked list, first in their order and then, once I reach the middle, in reverse order (from the last one backwards). For example:

If the elements are: 1 2 3 4 5 6

It should print: 1 2 3 6 5 4

But it's printing: 1 2 3 5 4

Why isn't it printing the last element? How can this be solved?

```<code>void reverse()
{
    int c=1;
    node *current,*prev,*temp;
    current=head;
    prev=NULL;
    std::stack<int>s;
    while(current->next!=NULL)
    {
        c++;
        s.push(current->data);
        current=current->next;
    }

    int mid=0;
    if((c%2)==0)
    {
        mid=c/2;
    }
    else
    {
        mid=(c+1)/2;
    }
    current=head;
    for(int i=0;i<mid;i++)
    {
        cout<<current->data<<"\t";
        current=current->next;
    }

    for(int i=mid;i>1;i--)
    {
       std::cout<<s.top()<<"\t";
       s.pop();
    }
    std::cout << '\n';
}
</code>```

答:
Let's assume that the list contains only one element. In this case this loop

```<code>while(current->next!=NULL)
{
    c++;
    s.push(current->data);
    current=current->next;
}
</code>```

will be executed never and as result the stack will be empty. Moreover the function initially has undefined behavior when the list in turn is empty and hence head is equal to NULL and you may not access current->next data member.

Well now let's assume that the list contains exactly two elements. The loop will be executed only once and the variable c gets value 2.  The calculated value of the variable mid will be equal to 1.

So this loop

```<code>for(int i=0;i<mid;i++)
{
    cout<<current->data<<"\t";
    current=current->next;
}
</code>```

executes only one iteration and the first element is outputted.

However the next loop

```<code>  for(int i=mid;i>1;i--)
  {
     std::cout<<s.top()<<"\t";
     s.pop();

  }
</code>```

will; be executed never because its condition i > 1 yields false because mid is equal to 1.

So the program has two wrong loops that should be rewritten.

Below is a demonstrative program that shows how the function can be implemented.

```<code>#include <iostream>
#include <stack>

struct node
{
    int data;
    node *next;
} *head = nullptr;

void append( int data )
{
    node **current = &head;

    while ( *current ) current = &( *current )->next;

    *current = new node { data, nullptr };
}

void clear()
{
    while ( head )
    {
        node *tmp = head;
        head = head->next;
        delete tmp;
    }
}

void reverse()
{
    std::stack<int> s;

    for ( node *current = head; current; current = current->next )
    {
        s.push( current->data );
    }

    std::stack<int>::size_type middle = ( s.size() + 1 ) / 2;
    std::stack<int>::size_type i = 0;

    for ( node *current = head; i < middle; i++ )
    {
        std::cout << current->data << '\t';
        current = current->next;
    }

    for ( i = s.size() - i; i != 0; i-- )
    {
        std::cout << s.top() << '\t';
        s.pop();
    }

    std::cout << std::endl;
}

int main()
{
    const int N = 10;

    for ( int i = 0; i < N; i++ )
    {
        for ( int j = 0; j <= i; j++ ) append( j );
        reverse();
        clear();
        std::cout << std::endl;
    }

    return 0;
}
</code>```

The program output is

```<code>0

0   1

0   1   2

0   1   3   2

0   1   2   4   3

0   1   2   5   4   3

0   1   2   3   6   5   4

0   1   2   3   7   6   5   4

0   1   2   3   4   8   7   6   5

0   1   2   3   4   9   8   7   6   5
</code>```

Body:
I want to print the elements of a linked list, first in their order and then, once I reach the middle, in reverse order (from the last one backwards). For example:

If the elements are: 1 2 3 4 5 6

It should print: 1 2 3 6 5 4

But it's printing: 1 2 3 5 4

Why isn't it printing the last element? How can this be solved?

void reverse()
{
    int c=1;
    node *current,*prev,*temp;
    current=head;
    prev=NULL;
    std::stack<int>s;
    while(current->next!=NULL)
    {
        c++;
        s.push(current->data);
        current=current->next;
    }

    int mid=0;
    if((c%2)==0)
    {
        mid=c/2;
    }
    else
    {
        mid=(c+1)/2;
    }
    current=head;
    for(int i=0;i<mid;i++)
    {
        cout<<current->data<<"\t";
        current=current->next;
    }

    for(int i=mid;i>1;i--)
    {
       std::cout<<s.top()<<"\t";
       s.pop();
    }
    std::cout << '\n';
}

Body:
Let's assume that the list contains only one element. In this case this loop

while(current->next!=NULL)
{
    c++;
    s.push(current->data);
    current=current->next;
}

will be executed never and as result the stack will be empty. Moreover the function initially has undefined behavior when the list in turn is empty and hence head is equal to NULL and you may not access current->next data member.

Well now let's assume that the list contains exactly two elements. The loop will be executed only once and the variable c gets value 2.  The calculated value of the variable mid will be equal to 1.

So this loop

for(int i=0;i<mid;i++)
{
    cout<<current->data<<"\t";
    current=current->next;
}

executes only one iteration and the first element is outputted.

However the next loop

  for(int i=mid;i>1;i--)
  {
     std::cout<<s.top()<<"\t";
     s.pop();

  }

will; be executed never because its condition i > 1 yields false because mid is equal to 1.

So the program has two wrong loops that should be rewritten.

Below is a demonstrative program that shows how the function can be implemented.

#include <iostream>
#include <stack>

struct node
{
    int data;
    node *next;
} *head = nullptr;

void append( int data )
{
    node **current = &head;

    while ( *current ) current = &( *current )->next;

    *current = new node { data, nullptr };
}

void clear()
{
    while ( head )
    {
        node *tmp = head;
        head = head->next;
        delete tmp;
    }
}

void reverse()
{
    std::stack<int> s;

    for ( node *current = head; current; current = current->next )
    {
        s.push( current->data );
    }

    std::stack<int>::size_type middle = ( s.size() + 1 ) / 2;
    std::stack<int>::size_type i = 0;

    for ( node *current = head; i < middle; i++ )
    {
        std::cout << current->data << '\t';
        current = current->next;
    }

    for ( i = s.size() - i; i != 0; i-- )
    {
        std::cout << s.top() << '\t';
        s.pop();
    }

    std::cout << std::endl;
}

int main()
{
    const int N = 10;

    for ( int i = 0; i < N; i++ )
    {
        for ( int j = 0; j <= i; j++ ) append( j );
        reverse();
        clear();
        std::cout << std::endl;
    }

    return 0;
}

The program output is

0

0   1

0   1   2

0   1   3   2

0   1   2   4   3

0   1   2   5   4   3

0   1   2   3   6   5   4

0   1   2   3   7   6   5   4

0   1   2   3   4   8   7   6   5

0   1   2   3   4   9   8   7   6   5


问:
Why is numpys covariance totally different then mine?
I calculate my covariance with following formula:

```<code>np.dot(X_zero_mean, X_zero_mean.T) / (X_zero_mean.shape[0] -1)
</code>```

and compare it to

```<code>np.cov(X_zero_mean.T)
</code>```

I both print the resulting matrices to console and create a figure out of them, but they are not the same. Why? Could it be that cov avoids some numerical error, that is happening with my above formula?
First one is my covariance, second one is the numpy cov:

答: Without your exact matrices it's difficult to tell, but I would guess that it's because you're taking the transpose of the matrix before passing it to np.cov. That would also explain why numpy's result looks like it's of much higher dimension than yours. np.cov(X.T) is equivalent to np.dot(X.T, X), not np.dot(X, X.T).

Body:
I calculate my covariance with following formula:

np.dot(X_zero_mean, X_zero_mean.T) / (X_zero_mean.shape[0] -1)

and compare it to

np.cov(X_zero_mean.T)

I both print the resulting matrices to console and create a figure out of them, but they are not the same. Why? Could it be that cov avoids some numerical error, that is happening with my above formula?
First one is my covariance, second one is the numpy cov:


问:
Error "Assignment cannot be null" trying to create assignment in workfront to a team
I am trying to assign a team to a task in Workfront and keep getting the error "assignment cannot be null".  I am providing a valid TeamID and setting the field isTeamAssignment set to true.  If I make the same call by trying to assign an individual, it works fine, but I am of course trying to assign a team to a task.

Here is an example of my POST request (I have replaced some of the actual values with VALUE):

Method: POST
URL: https://ent.attask-ondemand.com/attask/api/assgn

Data: sessionID=VALUE&teamID=VALUE&projectID=VALUE&taskID=VALUE&isTeamAssignment=true&status=AA"

答:
Aside from your authentication (sessionID or API key) you should pass only two values to the assign method: objID and objCode. Ensure that you are calling the assign method within the object to which you want to assign a team.

For example: <baseurl>/task/<taskID>/assign?objID=<teamID>&objCode=TEAMOB&<authentication>

Ensure that you make the call as a PUT method.


问:
Java - HashMap Iteration - Exception
I want to iterate a HashMap like:

```<code>        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            map.replace(entry.getKey(), entry.getValue()-1);
            if (entry.getValue() == 0) {
                map.remove(entry.getKey(), 0);
            }
        }
</code>```

This ends in an Exception: java.util.ConcurrentModificationException

Any solutions?

Kind regards

答:
```<code> Iterator<Map.Entry<Integer, Integer>> entryItr = map.entrySet().iterator();
 while (entryItr.hasNext()) {
   Map.Entry<Integer, Integer> entry = entryItr.next();
   if (entry.getValue() > 1) {
     entry.setValue(entry.getValue() - 1);
   } else {
     entryItr.remove();
   }
 }
</code>```

Title: Java - HashMap Iteration - Exception

Body:
I want to iterate a HashMap like:

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            map.replace(entry.getKey(), entry.getValue()-1);
            if (entry.getValue() == 0) {
                map.remove(entry.getKey(), 0);
            }
        }

This ends in an Exception: java.util.ConcurrentModificationException

Any solutions?

Kind regards