问:
ImageView diplaying in one activity but not in aonther
I have an android app with 2 activities: activity_main and activity_login.

On top of my activities I have a logo. It is showing up fine in activity_main but not in the activity_login.

The strange this is they both use similar layout and similar code.

Here is my activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".app.MainActivity"
    android:background="@drawable/background_1">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/logo"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="36dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Sign a File"
        android:layout_marginTop="53dp"
        app:layout_constraintTop_toBottomOf="@+id/imageView"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.502" />

    <Button
        android:id="@+id/button2"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Button"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="30dp"
        app:layout_constraintTop_toBottomOf="@+id/button4"
        app:layout_constraintHorizontal_bias="0.502" />

    <Button
        android:id="@+id/button3"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Button"
        android:layout_marginTop="34dp"
        app:layout_constraintTop_toBottomOf="@+id/button1"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.502" />

    <Button
        android:id="@+id/button4"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Button"
        android:layout_marginTop="31dp"
        app:layout_constraintTop_toBottomOf="@+id/button3"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintVertical_bias="0.043"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent" />

</android.support.constraint.ConstraintLayout>
</code>```

And, here is my activity_login.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".login.LoginActivity"
    android:background="@drawable/background_1">

     <ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/logo"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="36dp" />

     <EditText
        android:id="@+id/usernameTextField"
        android:layout_width="291dp"
        android:layout_height="63dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="53dp"
        android:background="@color/editTextBackground"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Username"
        android:textColor="#000000"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <EditText
        android:id="@+id/passwordTextField"
        android:layout_width="291dp"
        android:layout_height="63dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="0dp"
        android:background="@color/editTextBackground"
        android:ems="10"
        android:inputType="textPassword"
        android:text="Password"
        android:textColor="#000000"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/usernameTextField" />

    <Button
        android:id="@+id/button"
        android:onClick="loginButtonClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="66dp"
        android:background="@color/editTextBackground"
        android:text="Log In"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/passwordTextField"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp" />

</android.support.constraint.ConstraintLayout>
</code>```

In the design view of the activity_login it's displaying the image fine. But, when I run a test on emulator/phone it just doesn't show.

I tried removing all the other views from login_activity and still got the same problem. I also tried making a new activity xml with the same ConstarintLayout where I just add logo as imageView, and when I run the app the logo is not showing up.

And, that same logo using the same imageView in constraintLayout works fine in my activity_main

UPDATE: Why the downvote?

UPDATE2: As adviced by rafsanahmad007 this works:

instead of:

app:srcCompat="@drawable/logo" use:

android:src="@drawable/logo"

But, it still doesn't explain why it was working using app:srcCompat in one activity and not the other one.

答: Try to use android:src="image_location" rather then app:srcCompat="image_location".

Body:
I have an android app with 2 activities: activity_main and activity_login.

On top of my activities I have a logo. It is showing up fine in activity_main but not in the activity_login.

The strange this is they both use similar layout and similar code.

Here is my activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".app.MainActivity"
    android:background="@drawable/background_1">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/logo"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="36dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Sign a File"
        android:layout_marginTop="53dp"
        app:layout_constraintTop_toBottomOf="@+id/imageView"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.502" />

    <Button
        android:id="@+id/button2"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Button"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="30dp"
        app:layout_constraintTop_toBottomOf="@+id/button4"
        app:layout_constraintHorizontal_bias="0.502" />

    <Button
        android:id="@+id/button3"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Button"
        android:layout_marginTop="34dp"
        app:layout_constraintTop_toBottomOf="@+id/button1"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintHorizontal_bias="0.502" />

    <Button
        android:id="@+id/button4"
        android:layout_width="195dp"
        android:layout_height="45dp"
        android:text="Button"
        android:layout_marginTop="31dp"
        app:layout_constraintTop_toBottomOf="@+id/button3"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        app:layout_constraintVertical_bias="0.043"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent" />

</android.support.constraint.ConstraintLayout>

And, here is my activity_login.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".login.LoginActivity"
    android:background="@drawable/background_1">

     <ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:srcCompat="@drawable/logo"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="36dp" />

     <EditText
        android:id="@+id/usernameTextField"
        android:layout_width="291dp"
        android:layout_height="63dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="53dp"
        android:background="@color/editTextBackground"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Username"
        android:textColor="#000000"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <EditText
        android:id="@+id/passwordTextField"
        android:layout_width="291dp"
        android:layout_height="63dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="0dp"
        android:background="@color/editTextBackground"
        android:ems="10"
        android:inputType="textPassword"
        android:text="Password"
        android:textColor="#000000"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/usernameTextField" />

    <Button
        android:id="@+id/button"
        android:onClick="loginButtonClick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="66dp"
        android:background="@color/editTextBackground"
        android:text="Log In"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/passwordTextField"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp" />

</android.support.constraint.ConstraintLayout>

In the design view of the activity_login it's displaying the image fine. But, when I run a test on emulator/phone it just doesn't show.

I tried removing all the other views from login_activity and still got the same problem. I also tried making a new activity xml with the same ConstarintLayout where I just add logo as imageView, and when I run the app the logo is not showing up.

And, that same logo using the same imageView in constraintLayout works fine in my activity_main

UPDATE: Why the downvote?

UPDATE2: As adviced by rafsanahmad007 this works:

instead of:

app:srcCompat="@drawable/logo" use:

android:src="@drawable/logo"

But, it still doesn't explain why it was working using app:srcCompat in one activity and not the other one.


来源: stackexchange

问:
How to generalize this C# code?
I have this code which initializes winforms textboxes.

```<code>txt0.Text = steps[0];
txt1.Text = steps[1];
txt2.Text = steps[2];
txt3.Text = steps[3];
</code>```

I'd like to generalize it like this:

```<code>for (int i = 0; i < steps.Length; i++)
{
    txti.Text = steps[i];
}
</code>```

Obviously this doesn't work because the name txti does not exist in current context.
How to make it work?

EDIT:
I want to avoid creating all the textboxes and picture boxes in code and adding them to tablelayoutpanel in code.

答:
You can do the type cast to reference the textboxes dynamically.</p>

```<code>for (int i = 0; i < steps.Length; i++)
{
    TextBox txt = this.FindControl("txt" + i.ToString()) as TextBox;
    txt.Text = steps[i];
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to generalize this C# code?

Body:
I have this code which initializes winforms textboxes.

txt0.Text = steps[0];
txt1.Text = steps[1];
txt2.Text = steps[2];
txt3.Text = steps[3];

I'd like to generalize it like this:

for (int i = 0; i < steps.Length; i++)
{
    txti.Text = steps[i];
}

Obviously this doesn't work because the name txti does not exist in current context.
How to make it work?

EDIT:
I want to avoid creating all the textboxes and picture boxes in code and adding them to tablelayoutpanel in code.

Body:
You can do the type cast to reference the textboxes dynamically.

for (int i = 0; i < steps.Length; i++)
{
    TextBox txt = this.FindControl("txt" + i.ToString()) as TextBox;
    txt.Text = steps[i];
}


问:
Validating POST data class
This is an extension of a question I asked earlier that was deemed to be unsafe practise, due to the use of eval(). So I went for another approach but I have run into a problem. I do not know how to convert it to a class. My attempt ends with an error when I try to use call_user_func_array. it can't find the function in the class. Can you give me some hint so I get going? Thanks!

The error message I get when I try to run my code is Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'testlength' not found or invalid function name but on all validation methods. This is what I don't understand. This is what I want help to understand why it does not work.

```<code>class ruleValidator
{

    protected $postData = array();
    protected $ruleSet  = array();
    var $exceptions = 'Å,Ä,Þ,å,ä,þ,Ø,Ö,Ð,ø,ö,ð,Æ,Ü,æ,ü,á,é,í,ñ,ó,ú,ü,Á,É,Í,Ñ,Ó,Ê,Ú,Ü,ß';

    function __construct(){
        $this->exceptions = explode(',',$exceptions);
    }

    function testlength($string,$threshold)
    {
        return strlen($string)<$threshold?
            'Your %s is too short.': // TRUE
            '';                      // FALSE
    }

    function testnumeric($string,$offset,$length,$switch=true)
    {
        if(is_numeric(substr($string,$offset,$length))===$switch)
        {
            return $switch?
                'Your %s has to begin with a character.': // Truely TRUE
                'Your %s is containing non numeric characters. Please enter only digits.'; // Falsely TRUE
        }
    }

    function testemail($string)
    {
        return filter_var($string, FILTER_VALIDATE_EMAIL)?
            '':                                   // TRUE
            'Your email is not in a valid form.'; // FALSE
    }

    function testpattern($string,$pattern='/^[0-9]{8,10}$/')
    {
        return preg_match($pattern, $string)?
            '': // TRUE
            'Your %s is entered incorrect. Please use the correct format when entering data.'; // FALSE
    }

    function testequalto($string1,$string2)
    {
        return $string1==$string2?
            '':                                       // TRUE
            'Your %s fields do not match eachother.'; // FALSE
    }

    function testchecked($bool)
    {
        return $bool===true?
            '':                                               // TRUE
            'You are required to check this %s to continue.'; // FALSE
    }

    function testspecchar($string,$excludes=array())
    {
        if(is_array($excludes)&&!empty($excludes))
        {
            foreach($excludes as $exclude)
            {
                $string=str_replace($exclude,'',$string);
            }
        }

        if(preg_match('/[^a-z0-9 ]+/i',$string))
        {
            return 'Your %s contains illegal characters.'; // TRUE
        }

        return;                                            // FALSE

    }

}
</code>```

This is an array with how the POST data is recieved in the validator and the rules I use for the different fields in the form.

```<code>    $exceptions = explode(',','Å,Ä,Þ,å,ä,þ,Ø,Ö,Ð,ø,ö,ð,Æ,Ü,æ,ü,á,é,í,ñ,ó,ú,ü,Á,É,Í,Ñ,Ó,Ê,Ú,Ü,ß');
    $postData = array
    (
        'name'             => 'Mikael',
        'familyname'       => 'Eriksson`',
        'username'         => 'Mik',
        'password'         => 'testtest',
        'password-confirm' => 'testtesty',
        'email'            => 'try.to@guess.it,se',
        'phone'            => '0000000000a',
        'policy'           => 0
    );
    $ruleSet = array
    (
        'name'=>array
        (
            'testlength'=>2,
            'testnumeric'=>array(0,1),
            'testspecchar'=>array($exceptions)
        ),
        'familyname'=>array
        (
            'testlength'=>2,
            'testnumeric'=>array(0,1),
            'testspecchar'=>array($exceptions)
        ),
        'username'=>array
        (
            'testlength'=>4,
            'testnumeric'=>array(0,1),
            'testspecchar'=>array()
        ),
        'email'=>array
        (
            'testemail'=>array()
        ),
        'phone'=>array
        (
            'testnumeric'=>array(0,strlen($postData['phone']),false),
            'testpattern'=>'/^[0-9]{8,10}$/'
        ),
        'password'=>array
        (
            'testlength'=>8
        ),
        'password-confirm'=>array
        (
            'testequalto'=>$postData['password-confirm']
        ),
        'policy'=>array
        (
            'testchecked'=>array()
        )
    );
</code>```

Here is how I validated the data up until now. It works, but I want to make this to a class to streamline the code in my project.

```<code>    foreach($postData as $key => $value)
    {
        if(!array_key_exists($key,$ruleSet))
        {
            $errors[] = "The field `$key` is not part of the form. Only send actual form data.";
            break;
        }

        $slice = array($key=>$ruleSet[$key]);
        foreach($slice as $rules => $rule)
        {
            foreach($rule as $rls => $r)
            {
                $r = array_merge((array)$value,(array)$r);
                $errors[] = sprintf(call_user_func_array($rls,$r),$key);
            }
        }
    }
    if(count($errors)>0) return implode(';;',array_filter($errors,'strlen'));
</code>```

答:
When you want to call a method of a class, you have to make an instance (using new) or call them statically when the methods are declared static.

In both ways, you have to tell call_user_func_array() that you are not calling a function in the global scope, but from within a class.

```<code>call_user_func_array(array('ruleValidator', $rls), $r)
</code>```

Then declare the functions static:

```<code>public static function testlength($string,$threshold) {

}
</code>```

Or with new:

```<code>$slice = array($key=>$ruleSet[$key]);
$callbackClass = new ruleValidator();
foreach($slice as $rules => $rule)

/** ... */

call_user_func_array(array($callbackClass, $rls), $r)
</code>```

Title: Validating POST data class

Body:
This is an extension of a question I asked earlier that was deemed to be unsafe practise, due to the use of eval(). So I went for another approach but I have run into a problem. I do not know how to convert it to a class. My attempt ends with an error when I try to use call_user_func_array. it can't find the function in the class. Can you give me some hint so I get going? Thanks!

The error message I get when I try to run my code is Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'testlength' not found or invalid function name but on all validation methods. This is what I don't understand. This is what I want help to understand why it does not work.

class ruleValidator
{

    protected $postData = array();
    protected $ruleSet  = array();
    var $exceptions = 'Å,Ä,Þ,å,ä,þ,Ø,Ö,Ð,ø,ö,ð,Æ,Ü,æ,ü,á,é,í,ñ,ó,ú,ü,Á,É,Í,Ñ,Ó,Ê,Ú,Ü,ß';

    function __construct(){
        $this->exceptions = explode(',',$exceptions);
    }

    function testlength($string,$threshold)
    {
        return strlen($string)<$threshold?
            'Your %s is too short.': // TRUE
            '';                      // FALSE
    }

    function testnumeric($string,$offset,$length,$switch=true)
    {
        if(is_numeric(substr($string,$offset,$length))===$switch)
        {
            return $switch?
                'Your %s has to begin with a character.': // Truely TRUE
                'Your %s is containing non numeric characters. Please enter only digits.'; // Falsely TRUE
        }
    }

    function testemail($string)
    {
        return filter_var($string, FILTER_VALIDATE_EMAIL)?
            '':                                   // TRUE
            'Your email is not in a valid form.'; // FALSE
    }

    function testpattern($string,$pattern='/^[0-9]{8,10}$/')
    {
        return preg_match($pattern, $string)?
            '': // TRUE
            'Your %s is entered incorrect. Please use the correct format when entering data.'; // FALSE
    }

    function testequalto($string1,$string2)
    {
        return $string1==$string2?
            '':                                       // TRUE
            'Your %s fields do not match eachother.'; // FALSE
    }

    function testchecked($bool)
    {
        return $bool===true?
            '':                                               // TRUE
            'You are required to check this %s to continue.'; // FALSE
    }

    function testspecchar($string,$excludes=array())
    {
        if(is_array($excludes)&&!empty($excludes))
        {
            foreach($excludes as $exclude)
            {
                $string=str_replace($exclude,'',$string);
            }
        }

        if(preg_match('/[^a-z0-9 ]+/i',$string))
        {
            return 'Your %s contains illegal characters.'; // TRUE
        }

        return;                                            // FALSE

    }

}

This is an array with how the POST data is recieved in the validator and the rules I use for the different fields in the form.

    $exceptions = explode(',','Å,Ä,Þ,å,ä,þ,Ø,Ö,Ð,ø,ö,ð,Æ,Ü,æ,ü,á,é,í,ñ,ó,ú,ü,Á,É,Í,Ñ,Ó,Ê,Ú,Ü,ß');
    $postData = array
    (
        'name'             => 'Mikael',
        'familyname'       => 'Eriksson`',
        'username'         => 'Mik',
        'password'         => 'testtest',
        'password-confirm' => 'testtesty',
        'email'            => 'try.to@guess.it,se',
        'phone'            => '0000000000a',
        'policy'           => 0
    );
    $ruleSet = array
    (
        'name'=>array
        (
            'testlength'=>2,
            'testnumeric'=>array(0,1),
            'testspecchar'=>array($exceptions)
        ),
        'familyname'=>array
        (
            'testlength'=>2,
            'testnumeric'=>array(0,1),
            'testspecchar'=>array($exceptions)
        ),
        'username'=>array
        (
            'testlength'=>4,
            'testnumeric'=>array(0,1),
            'testspecchar'=>array()
        ),
        'email'=>array
        (
            'testemail'=>array()
        ),
        'phone'=>array
        (
            'testnumeric'=>array(0,strlen($postData['phone']),false),
            'testpattern'=>'/^[0-9]{8,10}$/'
        ),
        'password'=>array
        (
            'testlength'=>8
        ),
        'password-confirm'=>array
        (
            'testequalto'=>$postData['password-confirm']
        ),
        'policy'=>array
        (
            'testchecked'=>array()
        )
    );

Here is how I validated the data up until now. It works, but I want to make this to a class to streamline the code in my project.

    foreach($postData as $key => $value)
    {
        if(!array_key_exists($key,$ruleSet))
        {
            $errors[] = "The field `$key` is not part of the form. Only send actual form data.";
            break;
        }

        $slice = array($key=>$ruleSet[$key]);
        foreach($slice as $rules => $rule)
        {
            foreach($rule as $rls => $r)
            {
                $r = array_merge((array)$value,(array)$r);
                $errors[] = sprintf(call_user_func_array($rls,$r),$key);
            }
        }
    }
    if(count($errors)>0) return implode(';;',array_filter($errors,'strlen'));

Body:
When you want to call a method of a class, you have to make an instance (using new) or call them statically when the methods are declared static.

In both ways, you have to tell call_user_func_array() that you are not calling a function in the global scope, but from within a class.

call_user_func_array(array('ruleValidator', $rls), $r)

Then declare the functions static:

public static function testlength($string,$threshold) {

}

Or with new:

$slice = array($key=>$ruleSet[$key]);
$callbackClass = new ruleValidator();
foreach($slice as $rules => $rule)

/** ... */

call_user_func_array(array($callbackClass, $rls), $r)


问:
Why does greater than behave like this in Javascript?
I'm looking at Comparison operators in Javascript and came across these examples:

```<code>console.log(1 < 2 < 3);
</code>```

This equals true, which feels like it makes sense as 1 is less than, 2 and 2 is less than 3...

```<code>console.log(3 > 2 > 1);
</code>```

However this equals false, which I don't understand...

Here's a jsFiddle to also show the behavior if you open up the web developer tools and look at the console.

Someone suggested, it had to do with precedence but reading about precedence at MDN, I can't find a explanation to this.

Can anyone explain in a resonable simple way, what is going on there?

答:
You are misunderstanding the way how does it works. If you write 3 > 2 > 1, the first operation is actually 3 > 2 which obviously returns true. But then it's true > 1 which returns false, because true is being changed by the math operator to 1.

In the 1 < 2 < 3 example, it returns true, because 1 < 2 returns true and true < 3 operation returns true aswell, because true is again being changed into 1 and 1 is obviously smaller than 3.

Body:
I'm looking at Comparison operators in Javascript and came across these examples:

console.log(1 < 2 < 3);

This equals true, which feels like it makes sense as 1 is less than, 2 and 2 is less than 3...

console.log(3 > 2 > 1);

However this equals false, which I don't understand...

Here's a jsFiddle to also show the behavior if you open up the web developer tools and look at the console.

Someone suggested, it had to do with precedence but reading about precedence at MDN, I can't find a explanation to this.

Can anyone explain in a resonable simple way, what is going on there?


问:
Bitcode signature failure in Xcode
I updated Xcode to the last version, and now when I'm trying to compile the project I'm getting an error "Invalid bitcode signature", hovewer, the bitcode for my project is disabled. How can I fix it? What should I change to sign my bitcode correctly?

My Podfile:

```<code>source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

target 'MyProjectName' do

pod 'Realm'
pod 'CorePlot'
pod 'GoogleMaps'

end
</code>```

I checked already, everything is fine with it.

答: If you using pod then please check the version of all libraries, some library may be not supporting in new version , you have to update pod files for that library.</p>

Title: Bitcode signature failure in Xcode

Body:
I updated Xcode to the last version, and now when I'm trying to compile the project I'm getting an error "Invalid bitcode signature", hovewer, the bitcode for my project is disabled. How can I fix it? What should I change to sign my bitcode correctly?

My Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

target 'MyProjectName' do

pod 'Realm'
pod 'CorePlot'
pod 'GoogleMaps'

end

I checked already, everything is fine with it.


问:
android studio 2.3 gradle project sync failed. basic functionality will not work
I have recently downloaded the Android studio (2.3) and it gives the below error. can anyone help me?

```<code>Gradle sync failed: Cause: startup failed:
                build file '/Users/shervinkoulena/AndroidStudioProjects/HelloWorld3/app/build.gradle': 1: expecting EOF, found ':' @ line 1, column 14.
                5apply plugin: 'com.android.application'
</code>```

Sorry, I am very new to programming. I am also using a mac if it helps. This is the build.grade content I see:

```<code>    5apply plugin:

    'com.android.application' android {
     compileSdkVersion 25
     buildToolsVersion "19.1.0"
    defaultConfig {
    applicationId "com.example.shervinkoulena.helloworld"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),              'proguard-rules.pro'
         }
        }
       }

    dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
     androidTestCompile('com.android.support.test.espresso:espresso-  core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
     testCompile 'junit:junit:4.12'
       }
</code>```

答: write this line in build.gradle apply plugin: 'com.android.application'

Body:
I have recently downloaded the Android studio (2.3) and it gives the below error. can anyone help me?

Gradle sync failed: Cause: startup failed:
                build file '/Users/shervinkoulena/AndroidStudioProjects/HelloWorld3/app/build.gradle': 1: expecting EOF, found ':' @ line 1, column 14.
                5apply plugin: 'com.android.application'

Sorry, I am very new to programming. I am also using a mac if it helps. This is the build.grade content I see:

    5apply plugin:

    'com.android.application' android {
     compileSdkVersion 25
     buildToolsVersion "19.1.0"
    defaultConfig {
    applicationId "com.example.shervinkoulena.helloworld"
    minSdkVersion 15
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),              'proguard-rules.pro'
         }
        }
       }

    dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
     androidTestCompile('com.android.support.test.espresso:espresso-  core:2.2.2', {
    exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
     testCompile 'junit:junit:4.12'
       }


问:
Delete temp files on startup
My program requires a temp folder to put data in while running. This data is not needed after exit of the program and should be deleted. Each running instance of the program needs one folder on its own.

If I use file.deleteOnExit(), this does not make sure the file gets deleted on crash of whatever kind. My idea thus is to check for old temp files on startup that didn't got deleted and remove them. But when starting another instance of the program it shouldn't delete the temp files of still running programs. How can I achieve this?

To be more specific: The temp files should be in the System's temp directory and should be deleted if the program exits normally. This question is only for the few times the program crashed. The program has to be OS-independent. A solution using the Path instead of the File classes is preferred.

答:
Usually it is a bad idea to let your application to have multiple instances if you need to rely on other common resources, like temp file. For example, if you already have two instances of apps, the third one just opened will be hard to tell whether it is the third one and whether other instance is still alive.

As you have said, deleteOnExit() will not clean temp file if JVM crash and Java doesn't provide a reliable way to clean temp file automatically.

So I have following suggestions:

If you can choose to make only one instance of application with multiple windows:

You can have a fixed location and clean it when startup. But, in this way, you may give up some portability of Java.

If your application is GUI application, you can create temp file through Java API and register some clean action on closing the main frame, etc. -- still fail to handle some crash situations

you may add shutdownHook -- still fail to handle some crash situations

If you insist on having multiple instances and your application is GUI application: have to use Java API to create temp file and may add listener or shutdownHook.

Title: Delete temp files on startup


问:
Number of ways to reach a node with minimum cost from a fixed node
There are n nodes(1,2.. n) in a weighted graph with m (m>n) bi-directional edges.

All weights are positive and there are no multiple edges.

There is one fixed origin(Node 1). We will always start traveling from the origin.

Now we have to find the number of ways (path) to reach each of the nodes(starting from the origin) with minimum cost.

(All paths counted should have the minimum cost to reach that node from the origin).

Input — First line contains n,m.

Next m lines contain u,v,w. => There is an edge between u and v of weight w(w>0).

Output — Print n-1 lines one for each node other than origin, containing the number of ways to reach each of the nodes(starting from the origin) with minimum cost.

Sample Test -

4 5

1 2 5

1 3 3

3 2 2

3 4 7

2 4 5

Output —

2

1

3

Here is my solution, Please check if this will work for all cases, I did Dijkstra + DP. I am not sure about the correctness of the code.

```<code>#define pp pair<int,int>
vector< pp > adj[N]; //List to store graph
int dis[N],dp[N];

int main()
{
  ios::sync_with_stdio(0);
  int i,j,k,m,n,t;
  cin>>n>>m;
  for(i=0;i<m;i++)
  {
   int u,v,w;
   cin>>u>>v>>w;

   adj[u].push_back({w,v});
   adj[v].push_back({w,v});
  }
priority_queue< pp , vector<pp > , greater<pp> > pq;   //Min Priority Queue
for(int i=0;i<=n;i++) dis[i] = INT_MAX;
dis[1] = 0;
dp[1] = 1;
pq.push({0,1});

while(!pq.empty())
{
  pp tp = pq.top();
  int u = tp.second;
  int d = tp.first;
  pq.pop();
  if(dis[u]<d) continue;       // We have better ans, so continue.

  for(i=0;i<adj[u].size();i++)  // Traversing all the egdes from node u
    {
      int v = adj[u][i].second;  //Adjacent vertex v .
      int w = adj[u][i].first;
      if(d + w <= dis[v] )
       {
        if(d+w==dis[v])
        dp[v] += dp[u];     //Add the possible ways to the v from u

        if(d + w < dis[v])
          {
           dis[v] = d + w;
           dp[v] = dp[u];   // Better ans so set it directly.
           pq.push({dis[v],v});  //Better ans found so push it into queue.
          }
       }
    }
 }

 cout<<endl;

 for(int i = 1;i<=n;i++)
 {
   cout<<i<<" dis = "<<dis[i]<<" ways = "<<dp[i]<<endl;
 }
 }
</code>```

答:
I think you are overcomplicating the problem by calculating both minimum distance and no. of pathways together.

I think you first just run dijsktra normally and calculate minimum
distances from source node to all the other nodes in one run

Then, modify the current graph with existing bidirectional edges into uni-directional edges from node u -> node
v, where distance[v] >= distance[u]  from source node S. This will result in a hierarchal graph with source S.

After this u can just run either BFS or DFS from source node and
count no. of ways of reaching that node by adding the no. of ways of reaching each parent node.

Body:
There are n nodes(1,2.. n) in a weighted graph with m (m>n) bi-directional edges.

All weights are positive and there are no multiple edges.

There is one fixed origin(Node 1). We will always start traveling from the origin.

Now we have to find the number of ways (path) to reach each of the nodes(starting from the origin) with minimum cost.

(All paths counted should have the minimum cost to reach that node from the origin).

Input — First line contains n,m.

Next m lines contain u,v,w. => There is an edge between u and v of weight w(w>0).

Output — Print n-1 lines one for each node other than origin, containing the number of ways to reach each of the nodes(starting from the origin) with minimum cost.

Sample Test -

4 5

1 2 5

1 3 3

3 2 2

3 4 7

2 4 5

Output —

2

1

3

Here is my solution, Please check if this will work for all cases, I did Dijkstra + DP. I am not sure about the correctness of the code.

#define pp pair<int,int>
vector< pp > adj[N]; //List to store graph
int dis[N],dp[N];

int main()
{
  ios::sync_with_stdio(0);
  int i,j,k,m,n,t;
  cin>>n>>m;
  for(i=0;i<m;i++)
  {
   int u,v,w;
   cin>>u>>v>>w;

   adj[u].push_back({w,v});
   adj[v].push_back({w,v});
  }
priority_queue< pp , vector<pp > , greater<pp> > pq;   //Min Priority Queue
for(int i=0;i<=n;i++) dis[i] = INT_MAX;
dis[1] = 0;
dp[1] = 1;
pq.push({0,1});

while(!pq.empty())
{
  pp tp = pq.top();
  int u = tp.second;
  int d = tp.first;
  pq.pop();
  if(dis[u]<d) continue;       // We have better ans, so continue.

  for(i=0;i<adj[u].size();i++)  // Traversing all the egdes from node u
    {
      int v = adj[u][i].second;  //Adjacent vertex v .
      int w = adj[u][i].first;
      if(d + w <= dis[v] )
       {
        if(d+w==dis[v])
        dp[v] += dp[u];     //Add the possible ways to the v from u

        if(d + w < dis[v])
          {
           dis[v] = d + w;
           dp[v] = dp[u];   // Better ans so set it directly.
           pq.push({dis[v],v});  //Better ans found so push it into queue.
          }
       }
    }
 }

 cout<<endl;

 for(int i = 1;i<=n;i++)
 {
   cout<<i<<" dis = "<<dis[i]<<" ways = "<<dp[i]<<endl;
 }
 }


问:
Requests to Websockets behind ELB [with proxy protocol] and Ngnix proxy server
I am trying to get Client IP which are connecting to the Nodejs websocket server.
This blog is what i am follwoing to do so
http://blog.seafuj.com/using-elb-with-websockets
.This is working and am getting the client IP.

Now my question is this:
Once the initial handshake and connection is made from client to server via ELB and ngnix; will the subsequent requests[sendText()] from client go via ELB
Or will they go directly to the websoket server bypassing the ELB.

Sample Client code:

```<code>var connection = ws.connect('ws://<ELB>:80');
    connection.on("connect", function () {
                console.log("Connection established");
                connection.sendText("Hi");
                connection.sendText("Hello");
        })
</code>```

Over here in comments i read that

2) From this moment on and for the lifetime of this TCP connection,
  the ELB maintains a quasi-direct connection between client and backend
  server. 3) "quasi-direct" means that the connection is proxied through
  the ELB. So while the TCP connection is alive, the ELB is fully aware
  of the two end points taking part (client and backend server). –
  Jan-Philip Gehrcke

How ever it is not clear to me whether the tcp requests [not the handshake and connection establishment ] go directly to the server OR via ELB->ngnix -> websoket server.

答:
Enabling proxy protocol in ELB will add information such as source ips, destination ips etc in headers apart from that it will not do anything else. All the request to server will go through elb only.
if you want to verify it boot the server in private subnet with private ip with elb on top of it ,still it will work. </p>

Body:
I am trying to get Client IP which are connecting to the Nodejs websocket server.
This blog is what i am follwoing to do so
http://blog.seafuj.com/using-elb-with-websockets
.This is working and am getting the client IP.

Now my question is this:
Once the initial handshake and connection is made from client to server via ELB and ngnix; will the subsequent requests[sendText()] from client go via ELB
Or will they go directly to the websoket server bypassing the ELB.

Sample Client code:

var connection = ws.connect('ws://<ELB>:80');
    connection.on("connect", function () {
                console.log("Connection established");
                connection.sendText("Hi");
                connection.sendText("Hello");
        })

Over here in comments i read that

2) From this moment on and for the lifetime of this TCP connection,
  the ELB maintains a quasi-direct connection between client and backend
  server. 3) "quasi-direct" means that the connection is proxied through
  the ELB. So while the TCP connection is alive, the ELB is fully aware
  of the two end points taking part (client and backend server). –
  Jan-Philip Gehrcke

How ever it is not clear to me whether the tcp requests [not the handshake and connection establishment ] go directly to the server OR via ELB->ngnix -> websoket server.


问:
Failed to import "android" module. Could not remove android presplash
I am new in kivy. I made one app, and it working fine in pc. But when I run it in mobile it getting crush. I checked in using adb logcat I am getting this type of error. Can you help on this

I/python  (25833): [WARNING] Call to deprecated function init in
  /home/rup/workspace/TeachersApp/.buildozer/android/platform/build/dists/artoflivingteachersupport/private/lib/python2.7/site-packages/kivy/uix/listview.py
  line 846.Called from
  /home/rup/workspace/TeachersApp/.buildozer/android/platform/build/dists/artoflivingteachersupport/private/lib/python2.7/site-packages/kivy/lang/builder.py
  line 564 by _apply_rule(). I/python  (25833): [WARNING] Call to
  deprecated function init in
  /home/rup/workspace/TeachersApp/.buildozer/android/platform/build/dists/artoflivingteachersupport/private/lib/python2.7/site-packages/kivy/adapters/adapter.py
  line 112.Called from
  /home/rup/workspace/TeachersApp/.buildozer/android/platform/build/dists/artoflivingteachersupport/private/lib/python2.7/site-packages/kivy/adapters/simplelistadapter.py
  line 54 by init(). I/python  (25833): [WARNING] Call to deprecated
  function init in
  /home/rup/workspace/TeachersApp/.buildozer/android/platform/build/dists/artoflivingteachersupport/private/lib/python2.7/site-packages/kivy/uix/abstractview.py
  line 43.Called from
  /home/rup/workspace/TeachersApp/.buildozer/android/platform/build/dists/artoflivingteachersupport/private/lib/python2.7/site-packages/kivy/uix/listview.py
  line 866 by init(). I/python  (25833): [WARNING] Call to
  deprecated function init in
  /home/rup/workspace/TeachersApp/.buildozer/android/platform/build/dists/artoflivingteachersupport/private/lib/python2.7/site-packages/kivy/adapters/adapter.py
  line 112.Called from
  /home/rup/workspace/TeachersApp/.buildozer/android/platform/build/dists/artoflivingteachersupport/private/lib/python2.7/site-packages/kivy/adapters/listadapter.py
  line 185 by init(). I/python  (25833): [WARNING] [Base        ]
  Unknown  provider I/python  (25833): [INFO   ] [Base        ]
  Start application main loop I/python  (25833): [ERROR  ] [Base

  ] Failed to import "android" module. Could not remove android
  presplash. I/python  (25833): [WARNING] Call to deprecated function
  init in /home/rup/workspace/TeachersApp/.buildozer/android/platform/build/dists/artoflivingteachersupport/private/lib/python2.7/site-packages/kivy/uix/selectableview.py
  line 39.Called from
  /home/rup/workspace/TeachersApp/.buildozer/android/platform/build/dists/artoflivingteachersupport/private/lib/python2.7/site-packages/kivy/uix/listview.py
  line 594 by init(). I/python  (25833): [INFO   ] [Base        ]
  Leaving application in progress... I/python  (25833): Python for
  android ended. I/DEBUG   (26018):     #00 pc 000bf63a
  /data/app/org.aolsc.artoflivingteachersupport-2/lib/arm/libpython2.7.so
  (PyThreadState_New+93) I/DEBUG   (26018):     #01 pc 000c9975
  /data/app/org.aolsc.artoflivingteachersupport-2/lib/arm/libpython2.7.so
  (PyThread_acquire_lock+76)

答:
```<code>[Base] Failed to import "android" module. Could not remove android presplash.
I/python (25833): [WARNING] Call to deprecated function init in /home/rup/workspace/TeachersApp/.buildozer/android/platform/build/dists/artoflivingteachersupport/private/lib/python2.7/site-packages/kivy/uix/selectableview.py line 39.
 Called from /home/rup/workspace/TeachersApp/.buildozer/android/platform/build/dists/artoflivingteachersupport/private/lib/python2.7/site-packages/kivy/uix/listview.py line 594 by init().
I/python (25833): [INFO ] [Base ] Leaving application in progress...
I/python (25833): Python for android ended.
</code>```

I strongly believe the fault is somewhere else as the android module doesn't crash anything, only notifies a user that it couldn't remove presplash, because it wasn't available.

If the android module was responsible, there wouldn't be the next line about ListView and it'd just crash right there. Also, ListView is getting old and you should definitely replace it with RecycleView as it's more reliable and improved.

Body:
[Base] Failed to import "android" module. Could not remove android presplash.
I/python (25833): [WARNING] Call to deprecated function init in /home/rup/workspace/TeachersApp/.buildozer/android/platform/build/dists/artoflivingteachersupport/private/lib/python2.7/site-packages/kivy/uix/selectableview.py line 39.
 Called from /home/rup/workspace/TeachersApp/.buildozer/android/platform/build/dists/artoflivingteachersupport/private/lib/python2.7/site-packages/kivy/uix/listview.py line 594 by init().
I/python (25833): [INFO ] [Base ] Leaving application in progress...
I/python (25833): Python for android ended.

I strongly believe the fault is somewhere else as the android module doesn't crash anything, only notifies a user that it couldn't remove presplash, because it wasn't available.

If the android module was responsible, there wouldn't be the next line about ListView and it'd just crash right there. Also, ListView is getting old and you should definitely replace it with RecycleView as it's more reliable and improved.


Title: Why does greater than behave like this in Javascript?

Body:
An idea

1<2<3 = (1<2)<3 = (true)<3 = (1)<3 = true

3>2>1 = (3>2)>1 = (true)>1 = (1)>1 = false


问:
How does reference work in Java?
I know objects are passed by value, but the value of the reference.

So say I have a class:

```<code>  //Definition for singly-linked list.
  public class ListNode {
      int val;
      ListNode next;
      ListNode(int x) { val = x; }
  }
</code>```

I do something like:

```<code>ListNode n = new ListNode(3);
ListNode n1 = new ListNode(4);
n.next = n1;
</code>```

So now I have a linked list:

```<code>n -> n1 -> null
</code>```

Suppose now I do something like:

```<code>/* Previous code from above
ListNode n = new ListNode(3);
ListNode n1 = new ListNode(4);
n.next = n1; */

ListNode ref = n;
n = n.next;
</code>```

What does ref point to now?

答:
Your Linked List initially is as below

n -> n1 -> null , if represented by values its like
 3 -> 4 -> null.

When you do ListNode ref = n;  then  ref refers to node with value 3.

Now when you do n = n.next; reference variable n refers to node with value 4. Reference variable ref is unaffected by this assignement. ref still refers to the node with value 3.

If n = n.next was not done and instead after doing ListNode ref = n;  the value was modified like n.val = 100 then as ref and n both would have been refering to same object ref.val == 100 would have been true.

P.S.

There is difference between reference and Objects. Reference variables refers to the Objects.  When two references refers same objects, then if modifications* (usually using . dot operator) in the state of object is done by one reference, same will be reflected ifthe object state is read by other reference referring to same object. But if one of the the reference is made to refer to another object (using assignment operator =), it does not affect other reference, it still refers to the object it was referring to.

*Note not always state is modified by operations Like .trim() on String object as String class is immutable. Just remember debugging and java docs are your greatest helping tools. When ever in doubt try it yourself,debug the code you write, refer the java docs and you will have a smooth learning. Happy Learning, cheers.

Title: How does reference work in Java?

Body:
I know objects are passed by value, but the value of the reference.

So say I have a class:

  //Definition for singly-linked list.
  public class ListNode {
      int val;
      ListNode next;
      ListNode(int x) { val = x; }
  }

I do something like:

ListNode n = new ListNode(3);
ListNode n1 = new ListNode(4);
n.next = n1;

So now I have a linked list:

n -> n1 -> null

Suppose now I do something like:

/* Previous code from above
ListNode n = new ListNode(3);
ListNode n1 = new ListNode(4);
n.next = n1; */

ListNode ref = n;
n = n.next;

What does ref point to now?


答:
1 < 2 < 3 in javascript corresponds to ((1 < 2) < 3), that corresponds to true < 3. You're actually comparing booleans with integers, it doesn't make any sense in my opinion.

If you want to make two comparisons at once you should rewrite the condition as 3 > 2 && 2 > 1


问:
Migrating from gcm to fcm on android
I want to migrate from gcm to fcm in android app.
Do I need to send push notification to old users of the android app from gcm or i can send it through the new fcm from server?

FCM is working fine I'm able to receive push notifications on my device through fcm but I'm not able to send push notifications to old GCM registration tokens from FCM console.

Below is the code I've added to my manifest file for fcm to work-

```<code><uses-permission android:name="com.google.android.z.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application>
    <service
        android:name=".view.activity.MyFcmListenerService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <service
        android:name=".view.activity.MyInstanceIDListenerService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
</application>
</code>```

答:
Actually it does work FCM and GCM are the under same hood. A token for GCM works for FCM as well.

GCM tokens retrieved via GoogleCloudMessaging.register() or
  InstanceID.getToken() will continue to work in FCM without any
  modification or renewal.

All you need to do is change your client side implementation as mentioned here. and update your server endpoint to fcm.googleapis.com/fcm/

Title: Migrating from gcm to fcm on android

Body:
I want to migrate from gcm to fcm in android app.
Do I need to send push notification to old users of the android app from gcm or i can send it through the new fcm from server?

FCM is working fine I'm able to receive push notifications on my device through fcm but I'm not able to send push notifications to old GCM registration tokens from FCM console.

Below is the code I've added to my manifest file for fcm to work-

<uses-permission android:name="com.google.android.z.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application>
    <service
        android:name=".view.activity.MyFcmListenerService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <service
        android:name=".view.activity.MyInstanceIDListenerService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
</application>

ContentLicense: CC BY-SA 4.0


问:
Alternative to Akka for handling tasks sequentially
I have a system which may generate certain events in the lifecycle of a transaction. On every even I need to update a row in a DB and also send out a UI event over websocket.

One option I have is to implement the event processing (DB and UI) in actors thus avoiding any locking issues - also I can afford minor delays so handling this sequentially will greatly simplify matters.

What are alternative ways of handling this in Scala as I feel maybe Actors might be overkill in this case?
There are those blogs stating that actors should be used for "concurrency with state" - though I would like to see a more appropriate mechanism in order to eliminate this option.

答: Actors avoid locking issues because they use queues to interact. You can use threads with (blocking) queues and get the same level of safety. The only advantage of Actors over Threads is that an Actor does not spend memory for call stack, thus we can have many more actors than threads in the same amount of core memory. The downside of actor model is that a complex algorithm which could be implemented in single thread require several actors and so actor implementation may look obscured.</p>


答:
```<code>console.log(1 < 2 < 3);
</code>```

evaluates as in the following way:

console.log(true < 3); is console.log(1 < 3); prints true

Then console.log(3 > 2 > 1)

evaluates as in the following way:

console.log(true > 1) is console.log(1 > 1) prints false

Body:
console.log(1 < 2 < 3);

evaluates as in the following way:

console.log(true < 3); is console.log(1 < 3); prints true

Then console.log(3 > 2 > 1)

evaluates as in the following way:

console.log(true > 1) is console.log(1 > 1) prints false


问:
How to configure Unity Container for resolving multiple dependency?
I am trying to implement DI on my .Net application. I have 3 API classes in my Data Access layer. I have to use any one of them at a time. I am trying to put conditional unity resolution but not sure how to accomplish it. Please some body help me with sample code how to manage my 3 injected classes conditionally.

Currently I have just registered my classes in following way-

```<code>            IUnityContainer _container = new UnityContainer();
            _container.RegisterType(typeof(IPolicyAdminApi), typeof(SomeApiclass1));
            _container.RegisterType(typeof(IPolicyAdminApi), typeof(SomeApiclass2));
            _container.RegisterType(typeof(IPolicyAdminApi), typeof(SomeApiclass3));
            IPolicyAdminApi policyAdmin = _container.Resolve<IPolicyAdminApi>();
            return policyAdmin;
</code>```

答:
Unity supports named registrations to allow for this disambiguation, so you can write your registration code like this:

```<code>IUnityContainer _container = new UnityContainer();
_container.RegisterType("A", typeof(IPolicyAdminApi), typeof(SomeApiclass1));
_container.RegisterType("B", typeof(IPolicyAdminApi), typeof(SomeApiclass2));
_container.RegisterType("C", typeof(IPolicyAdminApi), typeof(SomeApiclass3));
IPolicyAdminApi policyAdmin = _container.Resolve<IPolicyAdminApi>("A");
return policyAdmin;
</code>```

You can specify which registration you require using the Unity Dependency attribute:

```<code>public SomeConstructor([Dependency("A")] IPolicyAdminApi api)
{
}
</code>```

Body:
I am trying to implement DI on my .Net application. I have 3 API classes in my Data Access layer. I have to use any one of them at a time. I am trying to put conditional unity resolution but not sure how to accomplish it. Please some body help me with sample code how to manage my 3 injected classes conditionally.

Currently I have just registered my classes in following way-

            IUnityContainer _container = new UnityContainer();
            _container.RegisterType(typeof(IPolicyAdminApi), typeof(SomeApiclass1));
            _container.RegisterType(typeof(IPolicyAdminApi), typeof(SomeApiclass2));
            _container.RegisterType(typeof(IPolicyAdminApi), typeof(SomeApiclass3));
            IPolicyAdminApi policyAdmin = _container.Resolve<IPolicyAdminApi>();
            return policyAdmin;

Body:
Unity supports named registrations to allow for this disambiguation, so you can write your registration code like this:

IUnityContainer _container = new UnityContainer();
_container.RegisterType("A", typeof(IPolicyAdminApi), typeof(SomeApiclass1));
_container.RegisterType("B", typeof(IPolicyAdminApi), typeof(SomeApiclass2));
_container.RegisterType("C", typeof(IPolicyAdminApi), typeof(SomeApiclass3));
IPolicyAdminApi policyAdmin = _container.Resolve<IPolicyAdminApi>("A");
return policyAdmin;

You can specify which registration you require using the Unity Dependency attribute:

public SomeConstructor([Dependency("A")] IPolicyAdminApi api)
{
}


问:
aligned_alloc memory block in a copy assignment constructor crashes while being freed
I am maintaining some legacy code which was missing a copy assignment constructor in a managed Aligned Pointer class. I added one as follows (simplified view):

```<code>#include <iostream>
#include <cstring>
#include <stdlib.h>

template <class T, unsigned AlignB>
class AlignedPtr {
private:
    T *mpBlock;
    unsigned mBlkSize;
public:
    // Size specific Ctor
    AlignedPtr(unsigned uNum) :
    mpBlock(static_cast<T*>  (aligned_alloc(uNum*sizeof(T),  AlignB))),
    mBlkSize(uNum) {}
    // Default, empty Ctor
    AlignedPtr(void) : mpBlock(nullptr), mBlkSize(0) {}
    // Copy Assignment Ctor
    AlignedPtr& operator=(const AlignedPtr& x)
    {
        T *mpNewBlock(static_cast<T*>(aligned_alloc(x.mBlkSize*sizeof(T), AlignB)));
        for (size_t index=0; index < x.mBlkSize; index++) {
            mpNewBlock[index] = x.mpBlock[index];
        }
        free(mpBlock);
        mpBlock  = mpNewBlock;
        mBlkSize = x.mBlkSize;
        return *this;
    }
    // Destroy managed pointer
    ~AlignedPtr() {
        free(mpBlock);
    }
};

int main(int argc, char *argv[])
{

    AlignedPtr<float, 16> first_ptr;
    std::cout << "Pointer Initialized" << std::endl;

    first_ptr = AlignedPtr<float, 16>(8);
    std::cout << "Pointer Re-initialized" << std::endl;

    return 0;
}
</code>```

My expectation was that the program will terminate normally, however I saw AlignedPtr Dtor fail when first_ptr goes out of scope (main termination).
I compile above without any optimizations as:

```<code>g++ -std=c++11 -g aligned_alloc_bug.cpp -o aab
</code>```

On a Ubuntu 14.04 with g++ 4.8.2 and get the following run-time error:

```<code>Pointer Initialized
Pointer Re-initialized
*** Error in `./aab': free(): invalid next size (fast): 0x0000000001cf9080 ***
Aborted (core dumped)
</code>```

Interestingly when I replace aligned_alloc with malloc or posix_memalign for that matter program terminates correctly. Is this a bug in aligned_alloc or am I missing something basic?

P.S: 1) I did a brief search for a gcc bug which returned false. 2) Advise to avoid managing raw pointers is acknowledged in advance but I would appreciate any help for the problem at hand.

答:
You are passing the arguments to aligned_alloc in the wrong order, "documentation".

void *aligned_alloc(size_t alignment, size_t size);

This then results in memory corruption, which is only detected when you call free.

Also, you should consider implementing a copy constructor. Here is a simple implementation:

```<code>AlignedPtr(const AlignedPtr& x) { *this = x; }
</code>```

Body:
I am maintaining some legacy code which was missing a copy assignment constructor in a managed Aligned Pointer class. I added one as follows (simplified view):

#include <iostream>
#include <cstring>
#include <stdlib.h>

template <class T, unsigned AlignB>
class AlignedPtr {
private:
    T *mpBlock;
    unsigned mBlkSize;
public:
    // Size specific Ctor
    AlignedPtr(unsigned uNum) :
    mpBlock(static_cast<T*>  (aligned_alloc(uNum*sizeof(T),  AlignB))),
    mBlkSize(uNum) {}
    // Default, empty Ctor
    AlignedPtr(void) : mpBlock(nullptr), mBlkSize(0) {}
    // Copy Assignment Ctor
    AlignedPtr& operator=(const AlignedPtr& x)
    {
        T *mpNewBlock(static_cast<T*>(aligned_alloc(x.mBlkSize*sizeof(T), AlignB)));
        for (size_t index=0; index < x.mBlkSize; index++) {
            mpNewBlock[index] = x.mpBlock[index];
        }
        free(mpBlock);
        mpBlock  = mpNewBlock;
        mBlkSize = x.mBlkSize;
        return *this;
    }
    // Destroy managed pointer
    ~AlignedPtr() {
        free(mpBlock);
    }
};

int main(int argc, char *argv[])
{

    AlignedPtr<float, 16> first_ptr;
    std::cout << "Pointer Initialized" << std::endl;

    first_ptr = AlignedPtr<float, 16>(8);
    std::cout << "Pointer Re-initialized" << std::endl;

    return 0;
}

My expectation was that the program will terminate normally, however I saw AlignedPtr Dtor fail when first_ptr goes out of scope (main termination).
I compile above without any optimizations as:

g++ -std=c++11 -g aligned_alloc_bug.cpp -o aab

On a Ubuntu 14.04 with g++ 4.8.2 and get the following run-time error:

Pointer Initialized
Pointer Re-initialized
*** Error in `./aab': free(): invalid next size (fast): 0x0000000001cf9080 ***
Aborted (core dumped)

Interestingly when I replace aligned_alloc with malloc or posix_memalign for that matter program terminates correctly. Is this a bug in aligned_alloc or am I missing something basic?

P.S: 1) I did a brief search for a gcc bug which returned false. 2) Advise to avoid managing raw pointers is acknowledged in advance but I would appreciate any help for the problem at hand.

Body:
You are passing the arguments to aligned_alloc in the wrong order, "documentation".

void *aligned_alloc(size_t alignment, size_t size);

This then results in memory corruption, which is only detected when you call free.

Also, you should consider implementing a copy constructor. Here is a simple implementation:

AlignedPtr(const AlignedPtr& x) { *this = x; }


问:
Sum Values of Rows for Duplicate DropDownList Selected Item inside a gridview
I have a GridView inside my inventory application... I am using that grid view for product out... its is working fine but the thing i want is to check that if same product of same vendor is selected multiple times in gridview like i did in the picture then Sum its Quantity to ensure it is less than its Stock.
For single product it will just compare it with its Stock but For Every duplicate products, value of quantity will be added and compare it with its stock..
Any help would be highly appreciated...

e.g Computer Zone's Keyboard is selected twice and its has a stock of 15  ... I want to sum the quantity 10+7= 17 and throw a message if it is greater than its Stock which is 15 else save it as a row...
and Computer Zone's Pen is selected twice (it can be thrice or more)and its has a stock of 50 ...  quantity 10+60= 70 and throw a message if it is greater than its Stock which is 50...

答:
You can do this on RowDataBound of gridview easily.

Just you need to get the quantity,stock,product and vendor. however you can also do this by below function, it will give you records if there is something duplicate in gridview.

```<code> public void HighlightDuplicate(GridView gridview)
{
    for(int currentRow = 0; currentRow < gridview.Rows.Count - 1; currentRow++)
    {
        GridViewRow rowToCompare = gridview.Rows[currentRow];
        for (int otherRow = currentRow + 1; otherRow < gridview.Rows.Count; otherRow++)
        {
            GridViewRow row = gridview.Rows[otherRow];
            bool duplicateRow = true;
            //example: check Duplicate on column vendor(cell#0) and product(cell#1)
            if ((rowToCompare.Cells[0].Text) != (row.Cells[0].Text) && (rowToCompare.Cells[1].Text) != (row.Cells[1].Text))
            {
                duplicateRow = false;
            }
            else if (duplicateRow)
            {
                rowToCompare.Cells[1].Text = Convert.ToInt32(row.Cells[1].Text) + Convert.ToInt32(rowToCompare.Cells[1].Text);
row.Visible=false;
            }
        }
    }
}
</code>```

In this function you can check we are comparing the rows and inside we have cell and checking the cell values.

```<code>  if ((rowToCompare.Cells[0].Text) != (row.Cells[0].Text) && (rowToCompare.Cells[1].Text) != (row.Cells[1].Text))
        {
            duplicateRow = false;
        }
        else if (duplicateRow)
        {
            rowToCompare.Cells[1].Text = Convert.ToInt32(row.Cells[1].Text) + Convert.ToInt32(rowToCompare.Cells[1].Text);
row.Visible=false;
        }
</code>```

In this part we compare the cell index 0 and 1, these should not be same if same means we have vendor and product same. if vendor and product are same then are combining their value and setting to one row only and second row i set visible false you can perform some other operation if you want and also here you can check after addition of both rows values if either quantity greater or less and you can do any operation accordingly.
you can call this function after DataBind(). for example if gridview id is Gridview1 then:

```<code>  HighlightDuplicate(this.GridView1);
</code>```

Body:
You can do this on RowDataBound of gridview easily.

Just you need to get the quantity,stock,product and vendor. however you can also do this by below function, it will give you records if there is something duplicate in gridview.

 public void HighlightDuplicate(GridView gridview)
{
    for(int currentRow = 0; currentRow < gridview.Rows.Count - 1; currentRow++)
    {
        GridViewRow rowToCompare = gridview.Rows[currentRow];
        for (int otherRow = currentRow + 1; otherRow < gridview.Rows.Count; otherRow++)
        {
            GridViewRow row = gridview.Rows[otherRow];
            bool duplicateRow = true;
            //example: check Duplicate on column vendor(cell#0) and product(cell#1)
            if ((rowToCompare.Cells[0].Text) != (row.Cells[0].Text) && (rowToCompare.Cells[1].Text) != (row.Cells[1].Text))
            {
                duplicateRow = false;
            }
            else if (duplicateRow)
            {
                rowToCompare.Cells[1].Text = Convert.ToInt32(row.Cells[1].Text) + Convert.ToInt32(rowToCompare.Cells[1].Text);
row.Visible=false;
            }
        }
    }
}

In this function you can check we are comparing the rows and inside we have cell and checking the cell values.

  if ((rowToCompare.Cells[0].Text) != (row.Cells[0].Text) && (rowToCompare.Cells[1].Text) != (row.Cells[1].Text))
        {
            duplicateRow = false;
        }
        else if (duplicateRow)
        {
            rowToCompare.Cells[1].Text = Convert.ToInt32(row.Cells[1].Text) + Convert.ToInt32(rowToCompare.Cells[1].Text);
row.Visible=false;
        }

In this part we compare the cell index 0 and 1, these should not be same if same means we have vendor and product same. if vendor and product are same then are combining their value and setting to one row only and second row i set visible false you can perform some other operation if you want and also here you can check after addition of both rows values if either quantity greater or less and you can do any operation accordingly.
you can call this function after DataBind(). for example if gridview id is Gridview1 then:

  HighlightDuplicate(this.GridView1);


问:
How to horizontally pivot a table in python
Currently I have table in this format :

```Geo-id Name                            stat Year   index
111500  Anniston-Oxford-Jacksonville     AL 1991    0
111500  Anniston-Oxford-Jacksonville     AL 1992    91.675
111500  Anniston-Oxford-Jacksonville     AL 1993    93.8025
111500  Anniston-Oxford-Jacksonville     AL 1994    96.63
111500  Anniston-Oxford-Jacksonville     AL 1995    99.455
111500  Anniston-Oxford-Jacksonville     AL 1996    102.4875
111500  Anniston-Oxford-Jacksonville     AL 1997    109.0225
111500  Anniston-Oxford-Jacksonville     AL 1998    114.7075
111500  Anniston-Oxford-Jacksonville     AL 1999    116.005
112220  Auburn-Opelika                  AL  1992    90.695
112220  Auburn-Opelika                  AL  1993    94.2075
112220  Auburn-Opelika                  AL  1994    98.6825
112220  Auburn-Opelika                  AL  1995    103.3675
112220  Auburn-Opelika                  AL  1996    107.2725
112220  Auburn-Opelika                  AL  1997    111.7125
```

This should be converted to :

```
Geo-id  Name                            1991    1992    1993    1994 ........... 2017
111500  Anniston-Oxford-Jacksonville    0       91.675  93.8025 96.63
112220  Auburn-Opelika                  0       90.695  94.2075 98.6825 and so on .....

```

Keeping geoid and name vertical ( but repeating only once since it is pivoted horizontally).

Code I have so far :

```<code>   pre_horizontal_df = pd.read_csv('database_raw.csv')
   pre_horizontal_df['period'] = pre_horizontal_df.year.astype(str)
   df1 = pre_horizontal_df.groupby(['geoid', 'name'])['hpi'].mean().unstack()
   print (df1)
</code>```

But this is not working. Can this horizontal pivot be done in python df / pandas?

Body:
Currently I have table in this format :

Geo-id Name                            stat Year   index
111500  Anniston-Oxford-Jacksonville     AL 1991    0
111500  Anniston-Oxford-Jacksonville     AL 1992    91.675
111500  Anniston-Oxford-Jacksonville     AL 1993    93.8025
111500  Anniston-Oxford-Jacksonville     AL 1994    96.63
111500  Anniston-Oxford-Jacksonville     AL 1995    99.455
111500  Anniston-Oxford-Jacksonville     AL 1996    102.4875
111500  Anniston-Oxford-Jacksonville     AL 1997    109.0225
111500  Anniston-Oxford-Jacksonville     AL 1998    114.7075
111500  Anniston-Oxford-Jacksonville     AL 1999    116.005
112220  Auburn-Opelika                  AL  1992    90.695
112220  Auburn-Opelika                  AL  1993    94.2075
112220  Auburn-Opelika                  AL  1994    98.6825
112220  Auburn-Opelika                  AL  1995    103.3675
112220  Auburn-Opelika                  AL  1996    107.2725
112220  Auburn-Opelika                  AL  1997    111.7125

This should be converted to :

Geo-id  Name                            1991    1992    1993    1994 ........... 2017
111500  Anniston-Oxford-Jacksonville    0       91.675  93.8025 96.63
112220  Auburn-Opelika                  0       90.695  94.2075 98.6825 and so on .....

Keeping geoid and name vertical ( but repeating only once since it is pivoted horizontally).

Code I have so far :

   pre_horizontal_df = pd.read_csv('database_raw.csv')
   pre_horizontal_df['period'] = pre_horizontal_df.year.astype(str)
   df1 = pre_horizontal_df.groupby(['geoid', 'name'])['hpi'].mean().unstack()
   print (df1)

But this is not working. Can this horizontal pivot be done in python df / pandas?

Body:
You need add column Year which create new columns by unstack:

df1=pre_horizontal_df.groupby(['Geo-id','Name','Year'])['index'].mean().unstack(fill_value=0)
print (df1)
Year                                 1991    1992     1993     1994      1995  \
Geo-id Name
111500 Anniston-Oxford-Jacksonville   0.0  91.675  93.8025  96.6300   99.4550
112220 Auburn-Opelika                 0.0  90.695  94.2075  98.6825  103.3675

Year                                     1996      1997      1998     1999
Geo-id Name
111500 Anniston-Oxford-Jacksonville  102.4875  109.0225  114.7075  116.005
112220 Auburn-Opelika                107.2725  111.7125    0.0000    0.000

Another solution with pivot_table:

df1 = pre_horizontal_df.pivot_table(index=['Geo-id', 'Name'],
                                    columns='Year',
                                    values='index',
                                    fill_value=0)
print (df1)
Year                                 1991    1992     1993     1994      1995  \
Geo-id Name
111500 Anniston-Oxford-Jacksonville     0  91.675  93.8025  96.6300   99.4550
112220 Auburn-Opelika                   0  90.695  94.2075  98.6825  103.3675

Year                                     1996      1997      1998     1999
Geo-id Name
111500 Anniston-Oxford-Jacksonville  102.4875  109.0225  114.7075  116.005
112220 Auburn-Opelika                107.2725  111.7125    0.0000    0.000

Last if need index convert to columns:

df1 = df1.rename_axis(None, axis=1).reset_index()
print (df1)
   Geo-id                          Name  1991    1992     1993     1994  \
0  111500  Anniston-Oxford-Jacksonville   0.0  91.675  93.8025  96.6300
1  112220                Auburn-Opelika   0.0  90.695  94.2075  98.6825

       1995      1996      1997      1998     1999
0   99.4550  102.4875  109.0225  114.7075  116.005
1  103.3675  107.2725  111.7125    0.0000    0.000

EDIT:

If not duplicates per columns created new index and new columns, is possible use set_index with unstack:

print (pre_horizontal_df[pre_horizontal_df.duplicated(['Geo-id','Name','Year'], keep=False)])
Empty DataFrame
Columns: [Geo-id, Name, stat, Year, index]
Index: []

df1 = pre_horizontal_df.set_index(['Geo-id', 'Name', 'Year'])['index'].unstack(fill_value=0)
print (df1)
Year                                 1991    1992     1993     1994      1995  \
Geo-id Name
111500 Anniston-Oxford-Jacksonville   0.0  91.675  93.8025  96.6300   99.4550
112220 Auburn-Opelika                 0.0  90.695  94.2075  98.6825  103.3675

Year                                     1996      1997      1998     1999
Geo-id Name
111500 Anniston-Oxford-Jacksonville  102.4875  109.0225  114.7075  116.005
112220 Auburn-Opelika                107.2725  111.7125    0.0000    0.000


问:
Grails, Inserting lots of data using withTransaction results in OutOfMemoryError
I'm using Grails 1.1 beta2. I need to import a large amount of data into my Grails application. If I repeatedly instantiate a grails domain class and then save it, the performance is unacceptably slow. Take for example importing people from a phone book:

```<code>for (each person in legacy phone book) {
    // Construct new Grails domain class from legacy phone book person
    Person person = new Person(...)
    person.save()
}
</code>```

This turns out be painfully slow. Someone on the Grails mailing list suggest batching up saves in a transaction. So now I have:

```<code>List batch = new ArrayList()
for (each person in legacy phone book) {
    // Construct new Grails domain class from legacy phone book person
    Person person = new Person(...)
    batch.add(person)
    if (batch.size() > 500) {
        Person.withTransaction {
            for (Person p: batch)
                p.save()
            batch.clear()
        }
    }
}
// Save any remaining
for (Person p: batch)
    p.save()
</code>```

This works must faster, at least initially. Each transaction saves 500 records. As time goes on, the transactions take longer and longer. The first few transactions takes about 5 seconds, then it just creeps from there. After about 100 transactions, each one takes over a minute, which is once again unacceptable. Worse is that eventually Grails will eventually run out of Java heap memory. I can increase the JVM heap size, but that just delays the OutOfMemoryError exception.

Any ideas why this is? It's like there some internal resource not being released. The performance gets worse, memory is being held on to, and then eventually the system runs out of memory.

According to the Grails documentation, withTransaction passes the closure to Spring's TransactionStatus object. I couldn't find anything in TransactionStatus to close/end the transaction.

Edit: I'm running this from Grails' Console (grails console)

Edit: Here's the out of memory exception:

```<code>Exception thrown: Java heap space

java.lang.OutOfMemoryError: Java heap space
    at org.hibernate.util.IdentityMap.entryArray(IdentityMap.java:194)
    at org.hibernate.util.IdentityMap.concurrentEntries(IdentityMap.java:59)
    at org.hibernate.event.def.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:113)
    at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:65)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
    at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:655)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:732)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:701)
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)
</code>```

答:
This is a common issue with all hibernate applications and it is caused by the growth of the hibernate session. I'm guessing that the grails console holds a hibernate session open for you in a similar way to the 'open session in view' pattern that I know it uses in for normal web requests.

The solution is to get hold of the current session and clear it after each batch. I'm not sure how you get hold of spring bean using the console, normally for controllers or services you just declare them as members. Then you can get the current session with sessionFactory.getCurrentSession(). In order to clear it just call session.clear(), or if you what to be selective use session.evict(Object) for each Person object.

for a controller/service:

```<code>class FooController {
    def sessionFactory

    def doStuff = {
        List batch = new ArrayList()
        for (each person in legacy phone book) {
            // Construct new Grails domain class from legacy phone book person
            Person person = new Person(...)
            batch.add(person)
            if (batch.size() > 500) {
                Person.withTransaction {
                    for (Person p: batch)
                        p.save()
                    batch.clear()
                }
                // clear session here.
                sessionFactory.getCurrentSession().clear();
            }
        }
        // Save any remaining
        for (Person p: batch)
            p.save()
        }
    }
}
</code>```

Hope this helps.

OwnerDisplayName: Steve Kuo

ContentLicense: CC BY-SA 2.5

Body:
I'm using Grails 1.1 beta2. I need to import a large amount of data into my Grails application. If I repeatedly instantiate a grails domain class and then save it, the performance is unacceptably slow. Take for example importing people from a phone book:

for (each person in legacy phone book) {
    // Construct new Grails domain class from legacy phone book person
    Person person = new Person(...)
    person.save()
}

This turns out be painfully slow. Someone on the Grails mailing list suggest batching up saves in a transaction. So now I have:

List batch = new ArrayList()
for (each person in legacy phone book) {
    // Construct new Grails domain class from legacy phone book person
    Person person = new Person(...)
    batch.add(person)
    if (batch.size() > 500) {
        Person.withTransaction {
            for (Person p: batch)
                p.save()
            batch.clear()
        }
    }
}
// Save any remaining
for (Person p: batch)
    p.save()

This works must faster, at least initially. Each transaction saves 500 records. As time goes on, the transactions take longer and longer. The first few transactions takes about 5 seconds, then it just creeps from there. After about 100 transactions, each one takes over a minute, which is once again unacceptable. Worse is that eventually Grails will eventually run out of Java heap memory. I can increase the JVM heap size, but that just delays the OutOfMemoryError exception.

Any ideas why this is? It's like there some internal resource not being released. The performance gets worse, memory is being held on to, and then eventually the system runs out of memory.

According to the Grails documentation, withTransaction passes the closure to Spring's TransactionStatus object. I couldn't find anything in TransactionStatus to close/end the transaction.

Edit: I'm running this from Grails' Console (grails console)

Edit: Here's the out of memory exception:

Exception thrown: Java heap space

java.lang.OutOfMemoryError: Java heap space
    at org.hibernate.util.IdentityMap.entryArray(IdentityMap.java:194)
    at org.hibernate.util.IdentityMap.concurrentEntries(IdentityMap.java:59)
    at org.hibernate.event.def.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:113)
    at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:65)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:26)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
    at org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:655)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:732)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:701)
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)

LastEditorDisplayName: Steve Kuo

Body:
This is a common issue with all hibernate applications and it is caused by the growth of the hibernate session. I'm guessing that the grails console holds a hibernate session open for you in a similar way to the 'open session in view' pattern that I know it uses in for normal web requests.

The solution is to get hold of the current session and clear it after each batch. I'm not sure how you get hold of spring bean using the console, normally for controllers or services you just declare them as members. Then you can get the current session with sessionFactory.getCurrentSession(). In order to clear it just call session.clear(), or if you what to be selective use session.evict(Object) for each Person object.

for a controller/service:

class FooController {
    def sessionFactory

    def doStuff = {
        List batch = new ArrayList()
        for (each person in legacy phone book) {
            // Construct new Grails domain class from legacy phone book person
            Person person = new Person(...)
            batch.add(person)
            if (batch.size() > 500) {
                Person.withTransaction {
                    for (Person p: batch)
                        p.save()
                    batch.clear()
                }
                // clear session here.
                sessionFactory.getCurrentSession().clear();
            }
        }
        // Save any remaining
        for (Person p: batch)
            p.save()
        }
    }
}

Hope this helps.

OwnerDisplayName: gid


问:
Spark split a file into multiple folders based on a field
I am trying to split a set of S3 files like below based on a column into individual column based folders. I am not sure of the problem with my code below.

```<code>column 1, column 2
20130401, value1
20130402, value2
20130403, value3

val newDataDF = sqlContext.read.parquet("s3://xxxxxxx-bucket/basefolder/")
    newDataDF.cache()
    val uniq_days = newDataDF.select(newDataDF("column1")).distinct.show()
    uniq_days.cache()
    uniq_days.foreach(x => {newDataDF.filter(newDataDF("column1") === x).write.save(s"s3://xxxxxx-bucket/partitionedfolder/$x/")})
</code>```

Can you please help? Even a pyspark version is ok.
I am looking for following structure.

```<code>s3://xxxxxx-bucket/partitionedfolder/20130401/part-***

    column 1, column 2
    20130401, value 1
s3://xxxxxx-bucket/partitionedfolder/20130402/part-***

    column 1, column 2
    20130402, value 1
s3://xxxxxx-bucket/partitionedfolder/20130403/part-***

    column 1, column 2
    20130403, value 1
</code>```

Here is the error

```<code>org.apache.spark.SparkException: Job aborted due to stage failure: Task 22 in stage 82.0 failed 4 times, most recent failure: Lost task 22.3 in stage 82.0 (TID 2753

Driver stacktrace:
  at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1454)
Caused by: java.lang.NullPointerException
</code>```

Update with current solution:

```<code>val newDataDF = sqlContext.read.parquet("s3://xxxxxx-bucket/basefolder/")
newDataDF.cache()
val uniq_days = newDataDF.select(newDataDF("column1")).distinct.rdd.map(_.getString(0)).collect().toList
uniq_days.foreach(x => {newDataDF.filter(newDataDF("column1") === x).write.save(s"s3://xxxxxx-bucket/partitionedfolder/$x/")})
</code>```

答:
I think you missed "s" in the save. :)

http://docs.scala-lang.org/overviews/core/string-interpolation.html#the-s-string-interpolator

Change:

```<code>write.save("s3://xxxxxx-bucket/partitionedfolder/$x/")})
</code>```

To:

```<code>write.save(s"s3://xxxxxx-bucket/partitionedfolder/$x/")})
</code>```

There are more issues, show never returns any value.

Change:

```<code>val uniq_days = newDataDF.select(newDataDF("mevent_day")).distinct.show()
uniq_days.cache()
</code>```

To:

```<code>val uniq_days = newDataDF.select(newDataDF("mevent_day")).distinct.rdd.map(_.getString(0)).collect().toList
</code>```

Body:
I am trying to split a set of S3 files like below based on a column into individual column based folders. I am not sure of the problem with my code below.

column 1, column 2
20130401, value1
20130402, value2
20130403, value3

val newDataDF = sqlContext.read.parquet("s3://xxxxxxx-bucket/basefolder/")
    newDataDF.cache()
    val uniq_days = newDataDF.select(newDataDF("column1")).distinct.show()
    uniq_days.cache()
    uniq_days.foreach(x => {newDataDF.filter(newDataDF("column1") === x).write.save(s"s3://xxxxxx-bucket/partitionedfolder/$x/")})

Can you please help? Even a pyspark version is ok.
I am looking for following structure.

s3://xxxxxx-bucket/partitionedfolder/20130401/part-***

    column 1, column 2
    20130401, value 1
s3://xxxxxx-bucket/partitionedfolder/20130402/part-***

    column 1, column 2
    20130402, value 1
s3://xxxxxx-bucket/partitionedfolder/20130403/part-***

    column 1, column 2
    20130403, value 1

Here is the error

org.apache.spark.SparkException: Job aborted due to stage failure: Task 22 in stage 82.0 failed 4 times, most recent failure: Lost task 22.3 in stage 82.0 (TID 2753

Driver stacktrace:
  at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1454)
Caused by: java.lang.NullPointerException

Update with current solution:

val newDataDF = sqlContext.read.parquet("s3://xxxxxx-bucket/basefolder/")
newDataDF.cache()
val uniq_days = newDataDF.select(newDataDF("column1")).distinct.rdd.map(_.getString(0)).collect().toList
uniq_days.foreach(x => {newDataDF.filter(newDataDF("column1") === x).write.save(s"s3://xxxxxx-bucket/partitionedfolder/$x/")})

Body:
I think you missed "s" in the save. :)

http://docs.scala-lang.org/overviews/core/string-interpolation.html#the-s-string-interpolator

Change:

write.save("s3://xxxxxx-bucket/partitionedfolder/$x/")})

To:

write.save(s"s3://xxxxxx-bucket/partitionedfolder/$x/")})

There are more issues, show never returns any value.

Change:

val uniq_days = newDataDF.select(newDataDF("mevent_day")).distinct.show()
uniq_days.cache()

To:

val uniq_days = newDataDF.select(newDataDF("mevent_day")).distinct.rdd.map(_.getString(0)).collect().toList


答:
In JavaScript, chaining of comparison operators won't work; it will first evaluate the first comparison to true/false, convert it into 1/0 and then do the second comparsion:

```<code>1 < 2 < 3   =>   (1 < 2) < 3
            =>      true < 3
            =>         1 < 3
            =>          true

3 > 2 > 1   =>   (3 > 2) > 1
            =>      true > 1
            =>         1 > 1
            =>         false
</code>```

You should instead split it into two separate comparsions: 1 < 2 && 2 < 3.

Body:
I'm looking at Comparison operators in Javascript and came across these examples:

console.log(1 < 2 < 3);

This equals true, which feels like it makes sense as 1 is less than, 2 and 2 is less than 3...

console.log(3 > 2 > 1);

However this equals false, which I don't understand...

Here's a jsFiddle to also show the behavior if you open up the web developer tools and look at the console.

Someone suggested, it had to do with precedence but reading about precedence at MDN, I can't find a explanation to this.

Can anyone explain in a resonable simple way, what is going on there?

Body:
In JavaScript, chaining of comparison operators won't work; it will first evaluate the first comparison to true/false, convert it into 1/0 and then do the second comparsion:

1 < 2 < 3   =>   (1 < 2) < 3
            =>      true < 3
            =>         1 < 3
            =>          true

3 > 2 > 1   =>   (3 > 2) > 1
            =>      true > 1
            =>         1 > 1
            =>         false

You should instead split it into two separate comparsions: 1 < 2 && 2 < 3.


问:
How to generalize this C# code?
I have this code which initializes winforms textboxes.

```<code>txt0.Text = steps[0];
txt1.Text = steps[1];
txt2.Text = steps[2];
txt3.Text = steps[3];
</code>```

I'd like to generalize it like this:

```<code>for (int i = 0; i < steps.Length; i++)
{
    txti.Text = steps[i];
}
</code>```

Obviously this doesn't work because the name txti does not exist in current context.
How to make it work?

EDIT:
I want to avoid creating all the textboxes and picture boxes in code and adding them to tablelayoutpanel in code.

答:
You can try finding controls by their names:</p>

```<code>for (int i = 0; i < steps.Length; i++)
  Controls.Find("txt" + i, true)[0].Text = steps[i];
</code>```

Title: How to generalize this C# code?

Body:
I have this code which initializes winforms textboxes.

txt0.Text = steps[0];
txt1.Text = steps[1];
txt2.Text = steps[2];
txt3.Text = steps[3];

I'd like to generalize it like this:

for (int i = 0; i < steps.Length; i++)
{
    txti.Text = steps[i];
}

Obviously this doesn't work because the name txti does not exist in current context.
How to make it work?

EDIT:
I want to avoid creating all the textboxes and picture boxes in code and adding them to tablelayoutpanel in code.

Body:
You can try finding controls by their names:

for (int i = 0; i < steps.Length; i++)
  Controls.Find("txt" + i, true)[0].Text = steps[i];