问:
I'm not getting EditText Value in another class
MainActivity.java (First Class)

```<code>package com.example.we.reportcardjavaclass;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    public EditText one, two, three, four, five, six;
    public String bang1, bang2, bang3, bang4, bang5, bang6;
    public Button results;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Find the View that shows the numbers category

    }

    public void getResult(View view){
        results = (Button) findViewById(R.id.result);
        Intent numbersIntent = new Intent(MainActivity.this, result.class);
        startActivity(numbersIntent);
        one = (EditText) findViewById(R.id.name);
        bang1 = one.getText().toString();

        two = (EditText) findViewById(R.id.Class);
        bang2 = two.getText().toString();

        three = (EditText) findViewById(R.id.English);
        bang3 = three.getText().toString();

        four = (EditText) findViewById(R.id.Hindi);
        bang4 = four.getText().toString();

        five = (EditText) findViewById(R.id.Maths);
        bang5 = five.getText().toString();

        six = (EditText) findViewById(R.id.Science);
        bang6 = six.getText().toString();

    }

}
</code>```

activity_main.xml (First Layout File)

```<code><?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".MainActivity">

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.we.reportcardjavaclass.MainActivity"
    android:padding="16dp">

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Student's Name"
        android:id="@+id/name"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Class"
        android:id="@+id/Class"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="64dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in English"
        android:id="@+id/English"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="128dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in Hindi"
        android:id="@+id/Hindi"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="192dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in Maths"
        android:id="@+id/Maths"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="256dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in Science"
        android:id="@+id/Science"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="320dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <Button
        android:text="Get result"
        android:id="@+id/result"
        android:onClick="getResult"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="384dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"/>

</android.support.constraint.ConstraintLayout>
</ScrollView>

## result.xml (Second Layout File) ##

<?xml version="1.0" encoding="utf-8"?>

<ScrollView android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="32dp">

    <android.support.v7.widget.CardView
        android:id="@+id/resultCard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardElevation="2dp"
        android:layout_gravity="center_vertical"
        card_view:cardUseCompatPadding="true">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingBottom="20dp"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:paddingTop="20dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                >

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"
                    android:text="Student's Name"
                    android:textAllCaps="true"
                    android:textSize="20sp"
                    android:textStyle="bold"/>

                <TextView
                    android:id="@+id/one"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"

                    android:textAllCaps="false"
                    android:textSize="15sp"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"
                    android:text="Class"
                    android:textAllCaps="true"
                    android:textSize="20sp"
                    android:textStyle="bold"/>

                <TextView
                    android:id="@+id/two"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="40dp"
                    android:textAllCaps="false"
                    android:textSize="15sp"
                    android:textStyle="normal"/>

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="160dp"
                android:background="@color/cardview_dark_background"
                android:padding="20dp"
                >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:text="English"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />

                <TextView
                    android:id="@+id/three"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginTop="40dp"
                    android:text="Hindi"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />

                <TextView
                    android:id="@+id/four"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="40dp"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginTop="80dp"
                    android:text="Maths"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />

                <TextView
                    android:id="@+id/five"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="80dp"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginTop="120dp"
                    android:text="Science"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />
                <TextView
                    android:id="@+id/six"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="120dp"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

            </RelativeLayout>
            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="350dp"
                android:text="BACK TO HOME"
                />
        </FrameLayout>
    </android.support.v7.widget.CardView>
</LinearLayout></ScrollView>
</code>```

Second Class

```<code>package com.example.we.reportcardjavaclass;

import android.os.Bundle;
import android.widget.TextView;

/**
 * Created by we on 08-07-2017.
 */

public class result extends MainActivity{

    public TextView one, two, three, four, five, six;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
        setTitle(bang1+"s Result");
        one = (TextView) findViewById(R.id.one);
        one.setText(bang1);
        two = (TextView) findViewById(R.id.two);
        two.setText(bang2);
        three = (TextView) findViewById(R.id.three);
        three.setText(bang3);
        four = (TextView) findViewById(R.id.four);
        four.setText(bang4);
        five = (TextView) findViewById(R.id.five);
        five.setText(bang5);
        six = (TextView) findViewById(R.id.six);
        six.setText(bang6);
    }
}
</code>```

EditText values are getting stored MainActivity.java in variables bang - 123456. I added public modifier while declaring them so I can access these in second class too. In second class I want to use these variable values to set in into Textviews but while running it is not showing the value.

I have also attached the screenshots of both layouts after running in my emulator.

Screenshot 1

Screenshot 2

In second layout it is supposed to show name and other values.

答:
I would suggest that you take a few steps back and get a better understanding of Android's fundamentals, including Activities in general. Perhaps a good place to start, would be understanding the Activity Lifecycle.

An answer to your question isn't very simple, because the way in which Android works is likely very different from your understanding.

In short, your second activity is a completely different instance of a class than the first. Extending the second from the first does not mean that the assigned variables are available to the second, it merely means that the class inherits the structure of its parent in the form of methods and fields.

You should instead be designing your activities in such a way that they relay those strings. When launching your second activity, include those strings in the intent when starting it.

For instance:

public class MainActivity extends AppCompatActivity {

    // ...

    /** Your method where the second activity is launched */
    public void onButtonClicked() {
        Intent intent = new Intent(this, SecondActivity.class);
        intent.putString(SecondActivity.EXTRA_BANG1, bang1);
        // ...
        startActivity(intent);
    }

}

public class SecondActivity extends AppCompatActivity {

    public static final String EXTRA_BANG1 = "bang1";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
        // ...
        TextView tvOne = (TextView) findViewById(R.id.one);
        // ...

        String bang1 = getIntent().getString(EXTRA_BANG1);
        tvOne.setText(bang1);
    }

}
```

I thoroughly recommend reading up in the Android documentation (it's excellently written!) to better understand how (and why) it works through this mechanism. In particular, this article on Sending data between activities is very relevant to you.

Body:
MainActivity.java (First Class)

package com.example.we.reportcardjavaclass;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    public EditText one, two, three, four, five, six;
    public String bang1, bang2, bang3, bang4, bang5, bang6;
    public Button results;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Find the View that shows the numbers category

    }

    public void getResult(View view){
        results = (Button) findViewById(R.id.result);
        Intent numbersIntent = new Intent(MainActivity.this, result.class);
        startActivity(numbersIntent);
        one = (EditText) findViewById(R.id.name);
        bang1 = one.getText().toString();

        two = (EditText) findViewById(R.id.Class);
        bang2 = two.getText().toString();

        three = (EditText) findViewById(R.id.English);
        bang3 = three.getText().toString();

        four = (EditText) findViewById(R.id.Hindi);
        bang4 = four.getText().toString();

        five = (EditText) findViewById(R.id.Maths);
        bang5 = five.getText().toString();

        six = (EditText) findViewById(R.id.Science);
        bang6 = six.getText().toString();

    }

}

activity_main.xml (First Layout File)

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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=".MainActivity">

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.we.reportcardjavaclass.MainActivity"
    android:padding="16dp">

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Student's Name"
        android:id="@+id/name"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Class"
        android:id="@+id/Class"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="64dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in English"
        android:id="@+id/English"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="128dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in Hindi"
        android:id="@+id/Hindi"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="192dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in Maths"
        android:id="@+id/Maths"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="256dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <EditText
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:hint="Grade in Science"
        android:id="@+id/Science"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="320dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp" />

    <Button
        android:text="Get result"
        android:id="@+id/result"
        android:onClick="getResult"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="384dp"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"/>

</android.support.constraint.ConstraintLayout>
</ScrollView>

## result.xml (Second Layout File) ##

<?xml version="1.0" encoding="utf-8"?>

<ScrollView android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="32dp">

    <android.support.v7.widget.CardView
        android:id="@+id/resultCard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardElevation="2dp"
        android:layout_gravity="center_vertical"
        card_view:cardUseCompatPadding="true">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingBottom="20dp"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            android:paddingTop="20dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                >

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"
                    android:text="Student's Name"
                    android:textAllCaps="true"
                    android:textSize="20sp"
                    android:textStyle="bold"/>

                <TextView
                    android:id="@+id/one"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"

                    android:textAllCaps="false"
                    android:textSize="15sp"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="20dp"
                    android:text="Class"
                    android:textAllCaps="true"
                    android:textSize="20sp"
                    android:textStyle="bold"/>

                <TextView
                    android:id="@+id/two"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="40dp"
                    android:textAllCaps="false"
                    android:textSize="15sp"
                    android:textStyle="normal"/>

            </LinearLayout>

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="160dp"
                android:background="@color/cardview_dark_background"
                android:padding="20dp"
                >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:text="English"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />

                <TextView
                    android:id="@+id/three"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginTop="40dp"
                    android:text="Hindi"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />

                <TextView
                    android:id="@+id/four"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="40dp"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginTop="80dp"
                    android:text="Maths"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />

                <TextView
                    android:id="@+id/five"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="80dp"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentLeft="true"
                    android:layout_marginTop="120dp"
                    android:text="Science"
                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="bold"
                    />
                <TextView
                    android:id="@+id/six"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginTop="120dp"

                    android:textAllCaps="true"
                    android:textColor="@android:color/white"
                    android:textStyle="normal"/>

            </RelativeLayout>
            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="350dp"
                android:text="BACK TO HOME"
                />
        </FrameLayout>
    </android.support.v7.widget.CardView>
</LinearLayout></ScrollView>

Second Class

package com.example.we.reportcardjavaclass;

import android.os.Bundle;
import android.widget.TextView;

/**
 * Created by we on 08-07-2017.
 */

public class result extends MainActivity{

    public TextView one, two, three, four, five, six;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
        setTitle(bang1+"s Result");
        one = (TextView) findViewById(R.id.one);
        one.setText(bang1);
        two = (TextView) findViewById(R.id.two);
        two.setText(bang2);
        three = (TextView) findViewById(R.id.three);
        three.setText(bang3);
        four = (TextView) findViewById(R.id.four);
        four.setText(bang4);
        five = (TextView) findViewById(R.id.five);
        five.setText(bang5);
        six = (TextView) findViewById(R.id.six);
        six.setText(bang6);
    }
}

EditText values are getting stored MainActivity.java in variables bang - 123456. I added public modifier while declaring them so I can access these in second class too. In second class I want to use these variable values to set in into Textviews but while running it is not showing the value.

I have also attached the screenshots of both layouts after running in my emulator.

Screenshot 1

Screenshot 2

In second layout it is supposed to show name and other values.

Body:
I would suggest that you take a few steps back and get a better understanding of Android's fundamentals, including Activities in general. Perhaps a good place to start, would be understanding the Activity Lifecycle.

An answer to your question isn't very simple, because the way in which Android works is likely very different from your understanding.

In short, your second activity is a completely different instance of a class than the first. Extending the second from the first does not mean that the assigned variables are available to the second, it merely means that the class inherits the structure of its parent in the form of methods and fields.

You should instead be designing your activities in such a way that they relay those strings. When launching your second activity, include those strings in the intent when starting it.

For instance:

public class MainActivity extends AppCompatActivity {

    // ...

    /** Your method where the second activity is launched */
    public void onButtonClicked() {
        Intent intent = new Intent(this, SecondActivity.class);
        intent.putString(SecondActivity.EXTRA_BANG1, bang1);
        // ...
        startActivity(intent);
    }

}

public class SecondActivity extends AppCompatActivity {

    public static final String EXTRA_BANG1 = "bang1";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);
        // ...
        TextView tvOne = (TextView) findViewById(R.id.one);
        // ...

        String bang1 = getIntent().getString(EXTRA_BANG1);
        tvOne.setText(bang1);
    }

}

I thoroughly recommend reading up in the Android documentation (it's excellently written!) to better understand how (and why) it works through this mechanism. In particular, this article on Sending data between activities is very relevant to you.


来源: stackexchange

问:
CSS/javascript hover error in IE8 - fine in chrome etc
I have a strange error with a css/javascript hover script on all ie versions.

The culprit is here: http://www.gardensandhomesdirect.co.uk

Underneath the main banner and the featured products area there are 3 'buttons', christmas, garden and home that have on-hover effects.

in firefox/chrome etc they are working fine and the hover goes over the original area as it should do. however in IE the hover moves the item over to the right?

Ive looked at the css and im not sure what isnt working from IE's point of view.

Any help on this is appreciated :)

答:
Under the style for .hover-panel add:

```<code>left: 0;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Under the style for .hover-panel add:

left: 0;


问:
Custom pandoc writer with Hakyll
I'm trying to write a special Hakyll compiler to use a lua script to build my website. I found this function which seams to make what I want :

```<code>customWriterCompilerWith :: (WriterOptions -> Pandoc -> IO String)
                         -> ReaderOptions -> WriterOptions
                         -> Compiler (Item String)
customWriterCompilerWith customWriter ropt wopt = do
    body <- getResourceBody
    withItemBody (unsafeCompiler . customWriter wopt) $ readPandocWith ropt body
</code>```

However, when I try to compile this function, I get this error :

```<code>• Couldn't match expected type ‘Item Pandoc’
              with actual type ‘Compiler (Item Pandoc)’
• In the second argument of ‘($)’, namely
    ‘readPandocWith ropt body’
</code>```

After searching in the Hakyll documentation, there is a difference between the type of readPandocWith in versions 4.6.8.0 and 4.9.8.0 (my version) :

```<code>readPandocWith:: ReaderOptions-> Item String-> Item Pandoc -- 4.6.8.0

readPandocWith:: ReaderOptions-> Item String-> Compiler (Item Pandoc) -- 4.9.8.0
</code>```

I didn't find in the Hakyll documentation a function (whose type should be Compiler (Item Pandoc)-> Item Pandoc) which could help me.

Do you know how to solve this problem ?

Do you know another way to make a custom Hakyll compiler with a LUA script ?

答:
As mentioned by @user2407038, the following should work:

```<code>customWriterCompilerWith customWriter ropt wopt = do
    body <- getResourceBody
    doc  <- readPandocWith ropt body
    withItemBody (unsafeCompiler . customWriter wopt) doc
</code>```

To read more about <- (which is syntactic sugar for >>=), I can recommend http://learnyouahaskell.com (the monad chapter).

ContentLicense: CC BY-SA 3.0

Title: Custom pandoc writer with Hakyll

Body:
I'm trying to write a special Hakyll compiler to use a lua script to build my website. I found this function which seams to make what I want :

customWriterCompilerWith :: (WriterOptions -> Pandoc -> IO String)
                         -> ReaderOptions -> WriterOptions
                         -> Compiler (Item String)
customWriterCompilerWith customWriter ropt wopt = do
    body <- getResourceBody
    withItemBody (unsafeCompiler . customWriter wopt) $ readPandocWith ropt body

However, when I try to compile this function, I get this error :

• Couldn't match expected type ‘Item Pandoc’
              with actual type ‘Compiler (Item Pandoc)’
• In the second argument of ‘($)’, namely
    ‘readPandocWith ropt body’

After searching in the Hakyll documentation, there is a difference between the type of readPandocWith in versions 4.6.8.0 and 4.9.8.0 (my version) :

readPandocWith:: ReaderOptions-> Item String-> Item Pandoc -- 4.6.8.0

readPandocWith:: ReaderOptions-> Item String-> Compiler (Item Pandoc) -- 4.9.8.0

I didn't find in the Hakyll documentation a function (whose type should be Compiler (Item Pandoc)-> Item Pandoc) which could help me.

Do you know how to solve this problem ?

Do you know another way to make a custom Hakyll compiler with a LUA script ?

Body:
As mentioned by @user2407038, the following should work:

customWriterCompilerWith customWriter ropt wopt = do
    body <- getResourceBody
    doc  <- readPandocWith ropt body
    withItemBody (unsafeCompiler . customWriter wopt) doc

To read more about <- (which is syntactic sugar for >>=), I can recommend http://learnyouahaskell.com (the monad chapter).


问:
App:clean delete directory in android studio error
Sometimes the error occur as the title.

There are not error in syntax and others.

I use windows OS and Android Studio version 2.2.3.

Error:Execution failed for task ':app:clean'.

  Unable to delete directory: C:\Users\sang\Desktop\android_studio_mob_term\mobile_programming_17-master\app\build\intermediates\exploded-aar\com.android.support

Can I delete the directory?

答:
```<code>task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

add this in project level gradle at bottom

Body:
task clean(type: Delete) {
    delete rootProject.buildDir
}

add this in project level gradle at bottom


问:
Why won't the following async await tasks always be finished in the same order?
This is a question on an answer given in this question:

How and When to use `async` and `await`

The answer was this: https://stackoverflow.com/a/31479502/1164004

To have a complete question I will also copy paste the answer:

Here is a quick console program to make it clear to those who follow. The "TaskToDo" method is your long running method that you want to make async. Making it run Async is done by the TestAsync method. The test loops method just runs through the "TaskToDo" tasks and runs them Async. You can see that in the results because they don't complete in the same order from run to run - they are reporting to the console UI thread when they complete. Simplistic, but I think the simplistic examples bring out the core of the pattern better than more involved examples:

```<code>    class Program
    {
        static void Main(string[] args)
        {
            TestLoops();
            Console.Read();
        }

        private static async void TestLoops()
        {
            for (int i = 0; i < 100; i++)
            {
                await TestAsync(i);
            }
        }

        private static Task TestAsync(int i)
        {
            return Task.Run(() => TaskToDo(i));
        }

        private async static void TaskToDo(int i)
        {
            await Task.Delay(10);
            Console.WriteLine(i);
        }
    }
</code>```

Now for my part: As for my understanding, an await call means that if the task is over, the code will continue. if its not, it will return to the calling context until the task finishes. If that's the case then why isn't it correct to say that in the program above, the first iteration of the loop will return to the main method's context until the task is finished and only then will the next iteration of the for loop be carried out and continue in that manner for all iteration of the loop? If it waits for the first one to end and then the 2nd and then 3rd and so on, how can it be that the tasks will not finish in the natural order?

答:
For your code the execution will flow like this:

Enter the loop (iteration 0)

Call TestAsync(0)

Create a new task (()=>TaskToDo(0))

The task calls to Task.Delay.

Because the delay task is not completed, the control is returned to the caller (the lambda).

Lambda completes, and it fires the task you created in step 3.

This task is now completed and loop goes forward, creating new tasks.

Then the await Task.Delay code starts to work when delays complete, causing random ordered output to console.

Body:
This is a question on an answer given in this question:

How and When to use `async` and `await`

The answer was this: https://stackoverflow.com/a/31479502/1164004

To have a complete question I will also copy paste the answer:

Here is a quick console program to make it clear to those who follow. The "TaskToDo" method is your long running method that you want to make async. Making it run Async is done by the TestAsync method. The test loops method just runs through the "TaskToDo" tasks and runs them Async. You can see that in the results because they don't complete in the same order from run to run - they are reporting to the console UI thread when they complete. Simplistic, but I think the simplistic examples bring out the core of the pattern better than more involved examples:

    class Program
    {
        static void Main(string[] args)
        {
            TestLoops();
            Console.Read();
        }

        private static async void TestLoops()
        {
            for (int i = 0; i < 100; i++)
            {
                await TestAsync(i);
            }
        }

        private static Task TestAsync(int i)
        {
            return Task.Run(() => TaskToDo(i));
        }

        private async static void TaskToDo(int i)
        {
            await Task.Delay(10);
            Console.WriteLine(i);
        }
    }

Now for my part: As for my understanding, an await call means that if the task is over, the code will continue. if its not, it will return to the calling context until the task finishes. If that's the case then why isn't it correct to say that in the program above, the first iteration of the loop will return to the main method's context until the task is finished and only then will the next iteration of the for loop be carried out and continue in that manner for all iteration of the loop? If it waits for the first one to end and then the 2nd and then 3rd and so on, how can it be that the tasks will not finish in the natural order?


问:
WPF Binding - StringFormat - Not Formatting
I have a ToolTip with a value set as:

```<code>Value="{Binding Path=DataItem.EquitySold, StringFormat=Reserved (Equity Share: \{0\}%)}"
</code>```

The toolip is displaying as:

72

But I expect it to be:

Reserved (Equity Share: 72%)

What is wrong with my binding?

答: I assume it is what your datatype supports - as far as I know it is passed on as arguments to IFormattable.</p>

Body:
I have a ToolTip with a value set as:

Value="{Binding Path=DataItem.EquitySold, StringFormat=Reserved (Equity Share: \{0\}%)}"

The toolip is displaying as:

72

But I expect it to be:

Reserved (Equity Share: 72%)

What is wrong with my binding?


问:
Subscriber should not stop on error in observable
I am struggling with a subscriber, which automatically unsubscribe itself on error:

```<code>observable
  .subscribe(
    (data) => {
      // some logic encountering an error during execution
      // comparable to throw new Error()
    }
  )
</code>```

I can prevent it with using try / catch:

```<code>observable
  .subscribe(
    (data) => try {
        // some logic encountering an error during execution
        // comparable to throw new Error()
      } catch(e) {
      }
  )
</code>```

But it feels like a work around.

I have dived into the source of Subscriber and SafeSubscriber, which automatically call unsubscribe on error:

```<code>  private __tryOrUnsub(fn: Function, value?: any): void {
    try {
      fn.call(this._context, value);
    } catch (err) {
      this.unsubscribe();
      throw err;
    }
  }
</code>```

Is the only way to prevent this behavior to implement an own Subscriber or using try / catch?

答:
That's correct behavior. You can use the catch() operator to subscribe to the same source Observable again (or a different one on error).

```<code>source
  .catch(err => Observable.of(null))
  .subscribe(...);
</code>```

This will just return null in the next handler instead of the original error.

Also note that any exception is rethrown if the subscriber doesn't have any error handler.

For example to just avoid throwing an error you could make:

```<code>source
  ...
  .subscribe(..., error => {});
</code>```

However this will always unsubscribe the chain because this is one of the basic principles of Observables. They emit zero or more next notifications and one complete or error notification but never both.

It's hard to tell what problem are you trying to solve where you don't want to unsubscribe, sometimes you can use Subject and only pass it next notifications and ignore the rest...:

```<code>const subject = new Subject();
source.subscribe(val => subject.next(val));

subject.subscribe(...);
</code>```

Body:
I am struggling with a subscriber, which automatically unsubscribe itself on error:

observable
  .subscribe(
    (data) => {
      // some logic encountering an error during execution
      // comparable to throw new Error()
    }
  )

I can prevent it with using try / catch:

observable
  .subscribe(
    (data) => try {
        // some logic encountering an error during execution
        // comparable to throw new Error()
      } catch(e) {
      }
  )

But it feels like a work around.

I have dived into the source of Subscriber and SafeSubscriber, which automatically call unsubscribe on error:

  private __tryOrUnsub(fn: Function, value?: any): void {
    try {
      fn.call(this._context, value);
    } catch (err) {
      this.unsubscribe();
      throw err;
    }
  }

Is the only way to prevent this behavior to implement an own Subscriber or using try / catch?

Body:
That's correct behavior. You can use the catch() operator to subscribe to the same source Observable again (or a different one on error).

source
  .catch(err => Observable.of(null))
  .subscribe(...);

This will just return null in the next handler instead of the original error.

Also note that any exception is rethrown if the subscriber doesn't have any error handler.

For example to just avoid throwing an error you could make:

source
  ...
  .subscribe(..., error => {});

However this will always unsubscribe the chain because this is one of the basic principles of Observables. They emit zero or more next notifications and one complete or error notification but never both.

It's hard to tell what problem are you trying to solve where you don't want to unsubscribe, sometimes you can use Subject and only pass it next notifications and ignore the rest...:

const subject = new Subject();
source.subscribe(val => subject.next(val));

subject.subscribe(...);


问:
Invalid numeric literal with jq
I have a large amount of JSON from a 3rd party system which I would like to pre-process with jq, but I am having difficulty composing the query, test case follows:

```<code>$ cat test.json
{
  "a": "b",
  "c": "d",
  "e": {
         "1": {
            "f": "g",
            "h": "i"
          }
       }
}
$ cat test.json|jq .e.1.f
jq: error: Invalid numeric literal at EOF at line 1, column 3 (while parsing '.1.') at <top-level>, line 1:
.e.1.f
</code>```

How would I get "g" as my output here? Or how do I cast that 1 to a "1" so it is handled correctly?

答:
From jq manual :

You can also look up fields of an object using syntax like .["foo"]
  (.foo above is a shorthand version of this, but only for
  identifier-like strings).

You also need quotes and use -r if you want raw output :

```<code>jq -r '.e["1"].f' test.json
</code>```

Title: Invalid numeric literal with jq

Body:
I have a large amount of JSON from a 3rd party system which I would like to pre-process with jq, but I am having difficulty composing the query, test case follows:

$ cat test.json
{
  "a": "b",
  "c": "d",
  "e": {
         "1": {
            "f": "g",
            "h": "i"
          }
       }
}
$ cat test.json|jq .e.1.f
jq: error: Invalid numeric literal at EOF at line 1, column 3 (while parsing '.1.') at <top-level>, line 1:
.e.1.f

How would I get "g" as my output here? Or how do I cast that 1 to a "1" so it is handled correctly?

Body:
From jq manual :

You can also look up fields of an object using syntax like .["foo"]
  (.foo above is a shorthand version of this, but only for
  identifier-like strings).

You also need quotes and use -r if you want raw output :

jq -r '.e["1"].f' test.json


问:
Promise.map() progress indicator
I'm trying to concurrently send many GET requests to an JSON API. I'm using Bluebird promises in Node.js, and using request-promise for send HTTP requests, like so:

```<code>const rp = require('request-promise');
//urlsArray is a 5000+ array of urls
Promise.map(urlsArray, url => {
  return rp(url)
    .then(results => {
       return JSON.parse(results);
    }).catch(err => { log(error);});
}).then(resultsArray => {
  log(resultsArray); // print out results
}).catch(err => {
  log(error);
});
</code>```

The problem is that with 5000+ urls in the array, the requests, even concurrently, can take a VERY long time because map() waits till all are done. How can I print out some sort of progress indicator (like a percentage) to the console while map is going through the requests?

I have tried log(results); after each request, but that just prints 5000 things to the console, which is not very handy. I'd prefer a percentage, or a number showing approximately how many are done.

答:
Remember that promise chains are just that: Chains. So you can insert a then into the chain for each of those promises to do your console update, and have it just pass back the same value it receives.

Actually, looking at your code, you don't even have to do that, as you're already using a per-URL then handler to parse the JSON. Just add to that:

```<code>const rp = require('request-promise');
//urlsArray is a 5000+ array of urls
let completed = 0;                                 // ***
Promise.map(urlsArray, url => {
  return rp(url)
    .then(results => {
       const parsed = JSON.parse(results);
       ++completed;                                // ***
       console.log(`Completed: ${completed}`);     // ***
       return parsed;
    }).catch(err => { log(error);});
}).then(resultsArray => {
  log(resultsArray); // print out results
}).catch(err => {
  log(error);
});
</code>```

(Note I'm parsing the JSON prior to saying that that request completed, in case the JSON is invalid and throws.)

But if you weren't already doing a per-promise activity, you could easily insert a then handler. Here's an example of doing that (with native promises, but it would be the same with Bluebird):

const data = [1, 2, 3, 4, 5];

function withoutReportingProgress() {
    return Promise.all(
        data.map(value => new Promise(resolve => {
            setTimeout(_ => {
                resolve(value);
            }, Math.random() * 500);
        }))
    );
}

function withReportingProgress() {
    let completed = 0;                              // ***
    return Promise.all(
        data.map(value => new Promise(resolve => {
            setTimeout(_ => {
                resolve(value);
            }, Math.random() * 500);
        })
        .then(value => {                            // ***
            ++completed;                            // ***
            console.log(`Completed: ${completed}`); // ***
            return value;                           // ***
        }))                                         // ***
    );
}

console.log("Starting without...");
withoutReportingProgress()
    .then(_ => {
        console.log("Done without");
        console.log("Starting with");
        withReportingProgress()
            .then(_ => {
                console.log("Done with");
            });
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
  max-height: 100% !important;
}</code>```

Title: Promise.map() progress indicator

Body:
I'm trying to concurrently send many GET requests to an JSON API. I'm using Bluebird promises in Node.js, and using request-promise for send HTTP requests, like so:

const rp = require('request-promise');
//urlsArray is a 5000+ array of urls
Promise.map(urlsArray, url => {
  return rp(url)
    .then(results => {
       return JSON.parse(results);
    }).catch(err => { log(error);});
}).then(resultsArray => {
  log(resultsArray); // print out results
}).catch(err => {
  log(error);
});

The problem is that with 5000+ urls in the array, the requests, even concurrently, can take a VERY long time because map() waits till all are done. How can I print out some sort of progress indicator (like a percentage) to the console while map is going through the requests?

I have tried log(results); after each request, but that just prints 5000 things to the console, which is not very handy. I'd prefer a percentage, or a number showing approximately how many are done.

Body:
Remember that promise chains are just that: Chains. So you can insert a then into the chain for each of those promises to do your console update, and have it just pass back the same value it receives.

Actually, looking at your code, you don't even have to do that, as you're already using a per-URL then handler to parse the JSON. Just add to that:

const rp = require('request-promise');
//urlsArray is a 5000+ array of urls
let completed = 0;                                 // ***
Promise.map(urlsArray, url => {
  return rp(url)
    .then(results => {
       const parsed = JSON.parse(results);
       ++completed;                                // ***
       console.log(`Completed: ${completed}`);     // ***
       return parsed;
    }).catch(err => { log(error);});
}).then(resultsArray => {
  log(resultsArray); // print out results
}).catch(err => {
  log(error);
});

(Note I'm parsing the JSON prior to saying that that request completed, in case the JSON is invalid and throws.)

But if you weren't already doing a per-promise activity, you could easily insert a then handler. Here's an example of doing that (with native promises, but it would be the same with Bluebird):

const data = [1, 2, 3, 4, 5];

function withoutReportingProgress() {
    return Promise.all(
        data.map(value => new Promise(resolve => {
            setTimeout(_ => {
                resolve(value);
            }, Math.random() * 500);
        }))
    );
}

function withReportingProgress() {
    let completed = 0;                              // ***
    return Promise.all(
        data.map(value => new Promise(resolve => {
            setTimeout(_ => {
                resolve(value);
            }, Math.random() * 500);
        })
        .then(value => {                            // ***
            ++completed;                            // ***
            console.log(`Completed: ${completed}`); // ***
            return value;                           // ***
        }))                                         // ***
    );
}

console.log("Starting without...");
withoutReportingProgress()
    .then(_ => {
        console.log("Done without");
        console.log("Starting with");
        withReportingProgress()
            .then(_ => {
                console.log("Done with");
            });
    });

.as-console-wrapper {
  max-height: 100% !important;
}


问:
Avoid repetition when selecting two columns of same table
Each time I would like to work on two variables from the same table, I repeat the table's name for selecting them like in the following example:

```<code>boxplot(hospital.Weight, hospital.Sex)
</code>```

This is a problem if the table's name changes because it requires two further changes to get it right.

Is there a more elegant way to avoid the repetition in the function call?

I tried:

```<code>boxplot(hospital( : , {'Weight', 'Sex'}))
</code>```

But this returns the columns as tables and boxplot as far as I understand only takes vectors.

答:
What I would do is create a dummy variable before generating your box plot so that you'd only have to change one line:</p>

```<code>table_name = hospital; %this is the line you'd change if the table name changes
boxplot(table_name.Weight, table_name.Sex)
</code>```

Body:
Each time I would like to work on two variables from the same table, I repeat the table's name for selecting them like in the following example:

boxplot(hospital.Weight, hospital.Sex)

This is a problem if the table's name changes because it requires two further changes to get it right.

Is there a more elegant way to avoid the repetition in the function call?

I tried:

boxplot(hospital( : , {'Weight', 'Sex'}))

But this returns the columns as tables and boxplot as far as I understand only takes vectors.

Body:
What I would do is create a dummy variable before generating your box plot so that you'd only have to change one line:

table_name = hospital; %this is the line you'd change if the table name changes
boxplot(table_name.Weight, table_name.Sex)


问:
Create row as a column in stored procedure
I have the following three tables and I want to so as last table using a stored procedure. Can anyone tell me how I can join them?

Disc:

```<code>DiscId  DiscName
1         a
2         b
3         c
</code>```

DiscDetail:

```<code>DiscDetailId  DiscId  DiscDetailName  Percentage
1             1       p               5
2             1       q               10
3             2       r               12
4             2       s               11
5             2       t               13
6             3       u               19
7             3       v               20
</code>```

Pur:

```<code>PurId  DiscId
1      1
2      2
3      1
4      1
</code>```

I want to show data as follows:

```<code>PurId  p  q   r   s   t
1      5  10
2             12  11  13
3      5  10
4      5  10
</code>```

答:
Use dynamic pivoting:

First declare all the columns :

```<code>DECLARE @Columns AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);

    SET @Columns = STUFF((SELECT distinct ',' + QUOTENAME(c.DiscDetailName  )
                FROM DiscDetail c
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)')
            ,1,1,'')
</code>```

Create dynamic pivot:

```<code>set @query = 'SELECT PurId, ' + @Columns + ' from
                (
                    select Pur.PurId
                        , DiscDetail.Percentage
                        , DiscDetail.DiscDetailName
                    from Pur
                    inner join Disc on Pur.DiscID = Disc.DiscId
                    inner join DiscDetail  on DiscDetail.ID = Disc.DiscId
               ) x
                pivot
                (
                     max(Percentage)
                    for DiscDetailName in (' + @Columns + ')
                ) p '

    execute(@query)
</code>```

Body:
I have the following three tables and I want to so as last table using a stored procedure. Can anyone tell me how I can join them?

Disc:

DiscId  DiscName
1         a
2         b
3         c

DiscDetail:

DiscDetailId  DiscId  DiscDetailName  Percentage
1             1       p               5
2             1       q               10
3             2       r               12
4             2       s               11
5             2       t               13
6             3       u               19
7             3       v               20

Pur:

PurId  DiscId
1      1
2      2
3      1
4      1

I want to show data as follows:

PurId  p  q   r   s   t
1      5  10
2             12  11  13
3      5  10
4      5  10

Body:
Use dynamic pivoting:

First declare all the columns :

DECLARE @Columns AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX);

    SET @Columns = STUFF((SELECT distinct ',' + QUOTENAME(c.DiscDetailName  )
                FROM DiscDetail c
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)')
            ,1,1,'')

Create dynamic pivot:

set @query = 'SELECT PurId, ' + @Columns + ' from
                (
                    select Pur.PurId
                        , DiscDetail.Percentage
                        , DiscDetail.DiscDetailName
                    from Pur
                    inner join Disc on Pur.DiscID = Disc.DiscId
                    inner join DiscDetail  on DiscDetail.ID = Disc.DiscId
               ) x
                pivot
                (
                     max(Percentage)
                    for DiscDetailName in (' + @Columns + ')
                ) p '

    execute(@query)


问:
OpenOffice SDK: convert document to PDF
I'm trying to build an application to convert documents (word, powerpoint) to PDF using the OpenOffice SDK.

I'm using C++ and all I want the application to do is take an input document filename and and output PDF filename, and do the conversion.

Are there any samples or easy way to get started?  Most of the documentation I see is using Java.

答:
I do this with C#, I share with you hoping it helps:</p>

```<code>// Connect to a running office and get the service manager
unoidl.com.sun.star.uno.XComponentContext m_xContext = uno.util.Bootstrap.bootstrap();
var mxMSFactory = (XMultiServiceFactory)m_xContext.getServiceManager();
XComponentLoader desktop = (XComponentLoader)mxMSFactory.createInstance("com.sun.star.frame.Desktop");
XComponentLoader xComponentLoader = (unoidl.com.sun.star.frame.XComponentLoader)desktop;
PropertyValue[] properties = new PropertyValue[1];
properties[0] = new PropertyValue();
properties[0].Name = "Hidden";
properties[0].Value = new uno.Any(true);

XComponent xComponent = xComponentLoader.loadComponentFromURL("file:///YOUR .ODT PATH", "_blank", 0, properties);
XTextDocument xDocument = (XTextDocument)xComponent;

XStorable xStorable = (XStorable)xDocument;
PropertyValue[] storeProps = new PropertyValue[3];
storeProps[0] = new PropertyValue();
storeProps[0].Name = "FilterName";
storeProps[0].Value = new uno.Any("writer_pdf_Export");
storeProps[1] = new PropertyValue();
storeProps[1].Name = "Overwrite";
storeProps[1].Value = new uno.Any(true);
storeProps[2] = new PropertyValue();
storeProps[2].Name = "SelectPdfVersion";
storeProps[2].Value = new uno.Any(1);

xStorable.storeToURL("file:///YOUR PDF PATH", storeProps);
xDocument.dispose();
</code>```

Title: OpenOffice SDK: convert document to PDF

Body:
I do this with C#, I share with you hoping it helps:

// Connect to a running office and get the service manager
unoidl.com.sun.star.uno.XComponentContext m_xContext = uno.util.Bootstrap.bootstrap();
var mxMSFactory = (XMultiServiceFactory)m_xContext.getServiceManager();
XComponentLoader desktop = (XComponentLoader)mxMSFactory.createInstance("com.sun.star.frame.Desktop");
XComponentLoader xComponentLoader = (unoidl.com.sun.star.frame.XComponentLoader)desktop;
PropertyValue[] properties = new PropertyValue[1];
properties[0] = new PropertyValue();
properties[0].Name = "Hidden";
properties[0].Value = new uno.Any(true);

XComponent xComponent = xComponentLoader.loadComponentFromURL("file:///YOUR .ODT PATH", "_blank", 0, properties);
XTextDocument xDocument = (XTextDocument)xComponent;

XStorable xStorable = (XStorable)xDocument;
PropertyValue[] storeProps = new PropertyValue[3];
storeProps[0] = new PropertyValue();
storeProps[0].Name = "FilterName";
storeProps[0].Value = new uno.Any("writer_pdf_Export");
storeProps[1] = new PropertyValue();
storeProps[1].Name = "Overwrite";
storeProps[1].Value = new uno.Any(true);
storeProps[2] = new PropertyValue();
storeProps[2].Name = "SelectPdfVersion";
storeProps[2].Value = new uno.Any(1);

xStorable.storeToURL("file:///YOUR PDF PATH", storeProps);
xDocument.dispose();


问:
success message does not fire on successful submission
My validation errors displays but if I fill the field in and submit, nothing happens. I am guessing something is wrong in the jQuery but I can't seem to see it. I have also included the code for the add-news-ajax.php

```<code>$(document).ready(function(){
            $('form').submit(function(e){
                e.preventDefault();
                var form = $( "#form1" ).serialize();
                $.ajax({
                    url: 'functions/add-news-ajax.php',
                    type: 'POST',
                    dataType: 'json',
                    data: form,
                })

                .done(function (data) {

                    if (!data.success) {

                        if(data.errors.n_title) {
                            $( "#title-error" ).hide().html(data.errors.n_title).fadeIn();
                        }

                    } else {

                        alert(data.message);
                    }
                })

                .fail(function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus + ': ' + errorThrown);
        });
    });
});
</code>```

here is the php from the ajax call:

```<code>$errors = array();
$response = array();

if(empty($_POST['n_title'])) {

    $errors['n_title'] = "<div class='alert alert-danger'> Title required </div>";
}

$response['errors'] = $errors;

if($errors) {

    $message['success'] = false;
    $response['message'] = "fail";

} else {

    $message['success'] = true;
    $response['message'] = "Success, yay!";
}

echo json_encode($response);
</code>```

答:
The data.success would be undefined in case you do not have a success field in your data. Hence you would never hot the else case where you write alert("success");

Probably you would want the done method to be as follows

```<code>done(function (data) {

                    if (data.message != "Success!") {

                        if(data.errors.n_title) {
                            $( "#title-error" ).hide().html(data.errors.n_title).fadeIn();
                        }

                    } else {

                        alert(data.message);
                    }
                })
</code>```

Body:
My validation errors displays but if I fill the field in and submit, nothing happens. I am guessing something is wrong in the jQuery but I can't seem to see it. I have also included the code for the add-news-ajax.php

$(document).ready(function(){
            $('form').submit(function(e){
                e.preventDefault();
                var form = $( "#form1" ).serialize();
                $.ajax({
                    url: 'functions/add-news-ajax.php',
                    type: 'POST',
                    dataType: 'json',
                    data: form,
                })

                .done(function (data) {

                    if (!data.success) {

                        if(data.errors.n_title) {
                            $( "#title-error" ).hide().html(data.errors.n_title).fadeIn();
                        }

                    } else {

                        alert(data.message);
                    }
                })

                .fail(function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus + ': ' + errorThrown);
        });
    });
});

here is the php from the ajax call:

$errors = array();
$response = array();

if(empty($_POST['n_title'])) {

    $errors['n_title'] = "
 Title required
";
}

$response['errors'] = $errors;

if($errors) {

    $message['success'] = false;
    $response['message'] = "fail";

} else {

    $message['success'] = true;
    $response['message'] = "Success, yay!";
}

echo json_encode($response);

Body:
The data.success would be undefined in case you do not have a success field in your data. Hence you would never hot the else case where you write alert("success");

Probably you would want the done method to be as follows

done(function (data) {

                    if (data.message != "Success!") {

                        if(data.errors.n_title) {
                            $( "#title-error" ).hide().html(data.errors.n_title).fadeIn();
                        }

                    } else {

                        alert(data.message);
                    }
                })


问:
jquery accordion jump and open to a specific section
i use jquery + jquerui in modx and the accordion. I wan't to have a horizontal menu on the top where I can jump (scroll) to the section (which opens). How would I achieve this.
Right now my js looks like this:

```<code>/ Accordion
        $("#accordion").children("div").each( function() {
                var a = $(this).find("a");
                var ref = $(a).attr("href");
                $(a).attr("href", "#");
            $(this).find("div").load(ref);
        });

        $("#accordion").ajaxStop(function() {
            $(this).accordion({
                header: "h2",
                active: true,
                collapsible: true,
                clearStyle: true,
                navigation: true
            });
        });
</code>```

EDIT: my accordion gets build with wayfinder:

```<code>[[Wayfinder? &startId=`6` &outerTpl=`outerTpl` &rowTpl=`rowTpl`]]
</code>```

rowTpl:

```<code><div>
        <h2><a href="[[+wf.link]]">[[+wf.title]]</a></h2>
        <div>
           <!-- placeholder for content -->
    </div>
</div>
</code>```

outerTpl:

```<code><div id="accordion">[[+wf.wrapper]]</div>
</code>```

The topmenu (horizontal) gets called like this:

```<code>[[Wayfinder? &startId=`6` &outerTpl=`QouterTpl` &rowTpl=`QrowTpl`]]
</code>```

QrowTpl:

```<code><li[[+wf.id]][[+wf.classes]]><a href="[[+wf.link]]" title="[[+wf.title]]" [[+wf.attributes]]>[[+wf.linktext]]</a>[[+wf.wrapper]]</li>
</code>```

QouterTpl

```<code><ul class="arrowunderline">[[+wf.wrapper]]</ul>
</code>```

Thanks for help

答:
use this on .ready function

```<code>$("#accordion").accordion('option', 'active' , 3);
</code>```

3 = the number of specific section in menu you want it active

Body:
i use jquery + jquerui in modx and the accordion. I wan't to have a horizontal menu on the top where I can jump (scroll) to the section (which opens). How would I achieve this.
Right now my js looks like this:

/ Accordion
        $("#accordion").children("div").each( function() {
                var a = $(this).find("a");
                var ref = $(a).attr("href");
                $(a).attr("href", "#");
            $(this).find("div").load(ref);
        });

        $("#accordion").ajaxStop(function() {
            $(this).accordion({
                header: "h2",
                active: true,
                collapsible: true,
                clearStyle: true,
                navigation: true
            });
        });

EDIT: my accordion gets build with wayfinder:

[[Wayfinder? &startId=`6` &outerTpl=`outerTpl` &rowTpl=`rowTpl`]]

rowTpl:

[[+wf.title]]

outerTpl:

[[+wf.wrapper]]

The topmenu (horizontal) gets called like this:

[[Wayfinder? &startId=`6` &outerTpl=`QouterTpl` &rowTpl=`QrowTpl`]]

QrowTpl:

[[+wf.linktext]][[+wf.wrapper]]

QouterTpl

[[+wf.wrapper]]

Thanks for help

Body:
use this on .ready function

$("#accordion").accordion('option', 'active' , 3);

3 = the number of specific section in menu you want it active


问:
How do I bottom-align grid elements in bootstrap fluid layout
I have a fluid layout using Twitter's bootstrap, wherein I have a row with two columns.  The first column has a lot of content, which I want to fill the span normally.  The second column just has a button and some text, which I want to bottom align relative to the cell in the first column.

Here's what I have:

```<code>-row-fluid-------------------------------------
+-span6----------+ +-span6----------+
|                | |short content   |
| content        | +----------------+
| that           |
| is tall        |
|                |
+----------------+
-----------------------------------------------
</code>```

Here's what I want:

```<code>-row-fluid-------------------------------------
+-span6----------+
|                |
| content        |
| that           |
| is tall        | +-span6----------+
|                | |short content   |
+----------------+ +----------------+
-----------------------------------------------
</code>```

I've seen solutions that make the first span an absolute height, and position the second span relative to it, but a solution where I didn't have to specify the absolute height of my divs would be preferred.  I'm also open to a complete rethink of how to achieve the same effect.  I'm not married to this use of the scaffolding, it just seemed to make the most sense to me.

This layout as a fiddle:

http://jsfiddle.net/ryansturmer/A7buv/3/

答:
Just set the parent to display:flex; and the child to margin-top:auto.  This will place the child content at the bottom of the parent element, assuming the parent element has a height greater than the child element.

There is no need to try and calculate a value for margin-top when you have a height on your parent element or another element greater than your child element of interest within your parent element.

Body:
I have a fluid layout using Twitter's bootstrap, wherein I have a row with two columns.  The first column has a lot of content, which I want to fill the span normally.  The second column just has a button and some text, which I want to bottom align relative to the cell in the first column.

Here's what I have:

-row-fluid-------------------------------------
+-span6----------+ +-span6----------+
|                | |short content   |
| content        | +----------------+
| that           |
| is tall        |
|                |
+----------------+
-----------------------------------------------

Here's what I want:

-row-fluid-------------------------------------
+-span6----------+
|                |
| content        |
| that           |
| is tall        | +-span6----------+
|                | |short content   |
+----------------+ +----------------+
-----------------------------------------------

I've seen solutions that make the first span an absolute height, and position the second span relative to it, but a solution where I didn't have to specify the absolute height of my divs would be preferred.  I'm also open to a complete rethink of how to achieve the same effect.  I'm not married to this use of the scaffolding, it just seemed to make the most sense to me.

This layout as a fiddle:

http://jsfiddle.net/ryansturmer/A7buv/3/


问:
Custom JSON serializers for a Symfony 3 entity
I have a Symfony 3.2 entity using Doctrine's Translatable extension.

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * Media
 *
 * @ORM\Table(name="medias")
 * @Gedmo\TranslationEntity(class="AppBundle\Entity\Translation\MediaTranslation")
 */
class Media implements Translatable
{
    /* [...] */

    /**
     * @var string|null
     *
     * @ORM\Column(type="text", nullable=true)
     * @Gedmo\Translatable
     * @Groups({"single_media"})
     */
    private $description;

    /* [...] */
}
```
<p>I know how to use the <em>basic</em> way to serialize this entity in JSON (I use <code>friendsofsymfony/rest-bundle</code> for the serialization of my REST API), but I would like to serialize it in a <em>custom</em> way like this...</p>
<pre class="lang-json prettyprint-override"><code>{
    "description": {
        "fr": "description en français",
        "en": "english description",
    }
}
</code>```

答:
try this :</p>

```<code>namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * Media
 *
 * @ORM\Table(name="medias")
 * @Gedmo\TranslationEntity(class="AppBundle\Entity\Translation\MediaTranslation")
 */
class Media implements Translatable, \Serializable
{
    /* [...] */

    /**
     * @var string|null
     *
     * @ORM\Column(type="text", nullable=true)
     * @Gedmo\Translatable
     * @Groups({"single_media"})
     */
    private $description;

    /* [...] */
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Symfony 3.2 entity using Doctrine's Translatable extension.

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * Media
 *
 * @ORM\Table(name="medias")
 * @Gedmo\TranslationEntity(class="AppBundle\Entity\Translation\MediaTranslation")
 */
class Media implements Translatable
{
    /* [...] */

    /**
     * @var string|null
     *
     * @ORM\Column(type="text", nullable=true)
     * @Gedmo\Translatable
     * @Groups({"single_media"})
     */
    private $description;

    /* [...] */
}

I know how to use the basic way to serialize this entity in JSON (I use friendsofsymfony/rest-bundle for the serialization of my REST API), but I would like to serialize it in a custom way like this...

{
    "description": {
        "fr": "description en français",
        "en": "english description",
    }
}

Body:
try this :

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * Media
 *
 * @ORM\Table(name="medias")
 * @Gedmo\TranslationEntity(class="AppBundle\Entity\Translation\MediaTranslation")
 */
class Media implements Translatable, \Serializable
{
    /* [...] */

    /**
     * @var string|null
     *
     * @ORM\Column(type="text", nullable=true)
     * @Gedmo\Translatable
     * @Groups({"single_media"})
     */
    private $description;

    /* [...] */
}


问:
How to format file in Visual Studio Code (hotkeys)?
How to format file | project folder | all project files (using hot keys AND using menu) in Visual Studio Code?</p>

答:
Try with this hotkeys</p>

```<code>Ctrl + Shift + i
</code>```

Body:
Try with this hotkeys

Ctrl + Shift + i


问:
Why do we need to use `int main` and not `void main` in C++?
Why do we need to use int main and not void main in C++?

答: Perhaps because it makes sense to cleanly exit with a status code from the main() method. In Java, we have to emulate this using System.exit() which is not all that graceful.

OwnerDisplayName: kasperasky

OwnerDisplayName: Rahul


问:
Possible values for R resources
I am using the R.drawable.x values as keys in a hashmap, but I need a value that means the absence of a drawable. For this I need to know what the possible values for R resources are. Does anybody know this or is it defined somewhere?</p>

答: Regex for drawable names:[a-z]{1}[a-z0-9_]*

Title: Possible values for R resources


问:
How to migrate from Neo4j Community to Enterprise edition (on Ubuntu)?
I'm currently running Neo4j Community edition, and would like to upgrade to the Enterprise edition.

What is the best way to do this?

I have installed the Enterprise edition with:

```<code>sudo apt-get install neo4j-enterprise
</code>```

But when I run...

```<code>sudo neo4j start
</code>```

...I believe I am still running the community edition.

I couldn't find any instructions on how to migrate on the Neo4j website.

答:
Take a dump of your database (neo4j-admin dump)

Remove the neo4j installation (sudo apt-get remove neo4j)

Install neo4j-enterprise (sudo apt-get install neo4j-enterprise)

Load the database (neo4j-admin load)

Do not combine the two installations together (as you have been doing).

Hope this helps,
Tom

Body:
I'm currently running Neo4j Community edition, and would like to upgrade to the Enterprise edition.

What is the best way to do this?

I have installed the Enterprise edition with:

sudo apt-get install neo4j-enterprise

But when I run...

sudo neo4j start

...I believe I am still running the community edition.

I couldn't find any instructions on how to migrate on the Neo4j website.


问:
Appending a list to create a nested list in python
I'm trying to make a nested list in Python, by asking the user to input the text file.
The input file is as shown below:

1.3 2.6 3.2 4.1
1 -3 2
-4.1

And finally the output should be:
[[1.3, 2.6, 3.2, 4.1], [1.0, -3.0, 2.0], [-4.1]]

My code can display the individual list one below the other, but I'm having difficulty in appending the lists.
As I'm new to python, any help is much appreciated. Thanks in advance.
My code is as follows:

```<code>#Ask the user to input a file name
file_name=input("Enter the Filename: ")

#Opening the file to read the content
infile=open(file_name,'r')

#Iterating for line in the file
for line in infile:
    line_str=line.split()

    for element in range(len(line_str)):
        line_str[element]=float(line_str[element])

    nlist=[[] for line in range(3)]
    nlist=nlist.append([line_str])
    print(nlist)
</code>```

答:
```<code>file_name=input("Enter the Filename: ")

# use "with" block to open file
# to ensure the file is closed once your code is done with it
with open(file_name,'r') as infile:
  # create "nlist" here and append each element to it during iteration
  nlist=[]
  for line in infile:
    line_str=line.split()
    # no need to iterate with range(len()); use a list comprehension
    # to map "float" to each list element
    line_str = [float(element) for element in line_str]
    nlist.append(line_str)
  print(nlist)
</code>```

Body:
I'm trying to make a nested list in Python, by asking the user to input the text file.
The input file is as shown below:

1.3 2.6 3.2 4.1
1 -3 2
-4.1

And finally the output should be:
[[1.3, 2.6, 3.2, 4.1], [1.0, -3.0, 2.0], [-4.1]]

My code can display the individual list one below the other, but I'm having difficulty in appending the lists.
As I'm new to python, any help is much appreciated. Thanks in advance.
My code is as follows:

#Ask the user to input a file name
file_name=input("Enter the Filename: ")

#Opening the file to read the content
infile=open(file_name,'r')

#Iterating for line in the file
for line in infile:
    line_str=line.split()

    for element in range(len(line_str)):
        line_str[element]=float(line_str[element])

    nlist=[[] for line in range(3)]
    nlist=nlist.append([line_str])
    print(nlist)


问:
TSQL RIGHT String function not working
I am having trouble understanding why the RIGHT function is not working for me. I tried to fit as much output in here, my apologies if it is confusing to read.

```<code>DECLARE @Nbr VARCHAR(27)

SELECT @Nbr = xmz.nbr
FROM @xml_temp AS xmz

SELECT @Nbr AS 'Number',
       LEFT(@Nbr, 4) AS 'LEFT',
       LEN(@Nbr) AS 'Length',
       SUBSTRING(@Nbr, 10, 4) AS 'SUBSTRING',
       RIGHT(@Nbr, 4) AS 'RIGHT'
</code>```

Number: 154448887859999

LEFT: 1544

Length: 15

SUBSTRING: 9999

RIGHT: EMPTY

答:
I found this to be quite revealing.

```<code>DECLARE @from char(4) = '5am';
DECLARE @to varchar(4) = '6am';
DECLARE @not_to_be varchar = '7am';
SET @from = RIGHT('0' + @from,4)
SELECT LEN(@from)
SELECT '''' + @from + ''''
SET @to = RIGHT('0' + @to,4)
SELECT LEN(@to)
SELECT '''' + @to + ''''
SET @not_to_be = RIGHT('0' + @not_to_be,4)
SELECT LEN(@not_to_be)
SELECT '''' + @not_to_be + ''''
</code>```

yields the following output

```<code>(No column name)
</code>```

1   3

```<code>(No column name)
</code>```

1   '5am '

```<code>(No column name)
</code>```

1   4

```<code>(No column name)
</code>```

1   '06am'

```<code>(No column name)
</code>```

1   1

```<code>(No column name)
</code>```

1   '0'

See for yourself

Title: TSQL RIGHT String function not working

Body:
I am having trouble understanding why the RIGHT function is not working for me. I tried to fit as much output in here, my apologies if it is confusing to read.

DECLARE @Nbr VARCHAR(27)

SELECT @Nbr = xmz.nbr
FROM @xml_temp AS xmz

SELECT @Nbr AS 'Number',
       LEFT(@Nbr, 4) AS 'LEFT',
       LEN(@Nbr) AS 'Length',
       SUBSTRING(@Nbr, 10, 4) AS 'SUBSTRING',
       RIGHT(@Nbr, 4) AS 'RIGHT'

Number: 154448887859999

LEFT: 1544

Length: 15

SUBSTRING: 9999

RIGHT: EMPTY

Body:
I found this to be quite revealing.

DECLARE @from char(4) = '5am';
DECLARE @to varchar(4) = '6am';
DECLARE @not_to_be varchar = '7am';
SET @from = RIGHT('0' + @from,4)
SELECT LEN(@from)
SELECT '''' + @from + ''''
SET @to = RIGHT('0' + @to,4)
SELECT LEN(@to)
SELECT '''' + @to + ''''
SET @not_to_be = RIGHT('0' + @not_to_be,4)
SELECT LEN(@not_to_be)
SELECT '''' + @not_to_be + ''''

yields the following output

(No column name)

1   3

(No column name)

1   '5am '

(No column name)

1   4

(No column name)

1   '06am'

(No column name)

1   1

(No column name)

1   '0'

See for yourself


问:
Ruby on rails migration error
I installed a gem acts-as-taggable-on whenever i tried to run rails db:migrate it would output this:

```<code>C:\Sites\novosti>rails db:migrate
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

Directly inheriting from ActiveRecord::Migration is not supported. Please specify the Rails release the migration was written for:

  class ActsAsTaggableOnMigration < ActiveRecord::Migration[4.2]
C:/Sites/novosti/db/migrate/20170708123900_acts_as_taggable_on_migration.acts_as_taggable_on_engine.rb:2:in `<top (required)>'
bin/rails:4:in `require'
bin/rails:4:in `<main>'
StandardError: Directly inheriting from ActiveRecord::Migration is not supported. Please specify the Rails release the migration was written for:

  class ActsAsTaggableOnMigration < ActiveRecord::Migration[4.2]
C:/Sites/novosti/db/migrate/20170708123900_acts_as_taggable_on_migration.acts_as_taggable_on_engine.rb:2:in `<top (required)>'
bin/rails:4:in `require'
bin/rails:4:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
</code>```

So i just added [5.1] and it fixed the problem but another one appeared

```<code>C:\Sites\novosti>rails db:migrate
== 20170708123900 ActsAsTaggableOnMigration: migrating ========================
-- create_table(:tags)
   -> 0.0028s
-- create_table(:taggings)
   -> 0.0033s
-- add_index(:taggings, :tag_id)
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

Index name 'index_taggings_on_tag_id' on table 'taggings' already exists
C:/Sites/novosti/db/migrate/20170708123900_acts_as_taggable_on_migration.acts_as_taggable_on_engine.rb:23:in `up'
bin/rails:4:in `require'
bin/rails:4:in `<main>'
ArgumentError: Index name 'index_taggings_on_tag_id' on table 'taggings' already exists
C:/Sites/novosti/db/migrate/20170708123900_acts_as_taggable_on_migration.acts_as_taggable_on_engine.rb:23:in `up'
bin/rails:4:in `require'
bin/rails:4:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
</code>```

答: Index name on a table should be unique. So this is an error from db as the the index already exists. Please drop the index on the table of the db before migration or you can remove the add_index in migration if the index is already ok in the table</p>

Title: Ruby on rails migration error

Body:
I installed a gem acts-as-taggable-on whenever i tried to run rails db:migrate it would output this:

C:\Sites\novosti>rails db:migrate
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

Directly inheriting from ActiveRecord::Migration is not supported. Please specify the Rails release the migration was written for:

  class ActsAsTaggableOnMigration < ActiveRecord::Migration[4.2]
C:/Sites/novosti/db/migrate/20170708123900_acts_as_taggable_on_migration.acts_as_taggable_on_engine.rb:2:in `<top (required)>'
bin/rails:4:in `require'
bin/rails:4:in `'
StandardError: Directly inheriting from ActiveRecord::Migration is not supported. Please specify the Rails release the migration was written for:

  class ActsAsTaggableOnMigration < ActiveRecord::Migration[4.2]
C:/Sites/novosti/db/migrate/20170708123900_acts_as_taggable_on_migration.acts_as_taggable_on_engine.rb:2:in `<top (required)>'
bin/rails:4:in `require'
bin/rails:4:in `'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

So i just added [5.1] and it fixed the problem but another one appeared

C:\Sites\novosti>rails db:migrate
== 20170708123900 ActsAsTaggableOnMigration: migrating ========================
-- create_table(:tags)
   -> 0.0028s
-- create_table(:taggings)
   -> 0.0033s
-- add_index(:taggings, :tag_id)
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

Index name 'index_taggings_on_tag_id' on table 'taggings' already exists
C:/Sites/novosti/db/migrate/20170708123900_acts_as_taggable_on_migration.acts_as_taggable_on_engine.rb:23:in `up'
bin/rails:4:in `require'
bin/rails:4:in `'
ArgumentError: Index name 'index_taggings_on_tag_id' on table 'taggings' already exists
C:/Sites/novosti/db/migrate/20170708123900_acts_as_taggable_on_migration.acts_as_taggable_on_engine.rb:23:in `up'
bin/rails:4:in `require'
bin/rails:4:in `'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)


问:
Accessing a dictionary inside a list
I am reading the Python crash course book, and I am stuck on something. I would like to iterate over a dictionary that's in a list to print out the values in the dictionary. I have 3 dictonaries that I put into a list, and Id like to iterate and print out the information from the dictonaries. Is this even possible?</p>

答:
Something like this should do the job, where dic = dictionary:

```<code>for your_dic in your_list:
    for key in your_dic:
        print(your_dic[key])
</code>```

If you want to access just one specific dictionary you could do:

```<code>temp_dict = your_list[0] # assign 0th element of the list to temp_dict
# Iterate over all keys in your dictionary and print them
for key in temp_dict:
    print(temp_dict[key])
</code>```

Keep in mind that dictionaries are not ordered, so iterating over all keys will not always lead to the same order of print statements

Title: Accessing a dictionary inside a list

Body:
Something like this should do the job, where dic = dictionary:

for your_dic in your_list:
    for key in your_dic:
        print(your_dic[key])

If you want to access just one specific dictionary you could do:

temp_dict = your_list[0] # assign 0th element of the list to temp_dict
# Iterate over all keys in your dictionary and print them
for key in temp_dict:
    print(temp_dict[key])

Keep in mind that dictionaries are not ordered, so iterating over all keys will not always lead to the same order of print statements


问:
Toggle animate division height on image click (hide by default?)
I have been searching on the internet but no good solution found so far. On my HTML page there is a #menu-button inside my fixed #header division and a #menu-panel division below this header. The menu panel toggle-collapses by clicking on the button image. The code below works great, except that the animated #menu-panel is visible by default.

Does anyone know how to make the division height 0 by default, but still toggle animate height when clicking the button? Code below:

```<code><body>

<div id="header">
  <img src="image" id="menu-button">
</div>

<div id="menu-panel">
  <ul>
    <li>some buttons listed here</li>
    <li>some buttons listed here</li>
    <li>some buttons listed here</li>
  </ul>
</div>

<script src="js/jquery-1.11.3.min.js"></script>
<script>
// header menu
  $(document).ready(function(){
  $("#menu-button").click(function(){
  $("#menu-panel").animate({
  height: 'toggle'
  });
  });
  });
</script>

</body>
</code>```

Thank you in advance!

Elmigo

答:
" The code below works great, except that the animated #menu-panel is visible by default."

Change this:

on

Body:
I have been searching on the internet but no good solution found so far. On my HTML page there is a #menu-button inside my fixed #header division and a #menu-panel division below this header. The menu panel toggle-collapses by clicking on the button image. The code below works great, except that the animated #menu-panel is visible by default.

Does anyone know how to make the division height 0 by default, but still toggle animate height when clicking the button? Code below:

some buttons listed here

some buttons listed here

some buttons listed here

Thank you in advance!

Elmigo

Body:
" The code below works great, except that the animated #menu-panel is visible by default."

Change this: <div id="menu-panel">
on <div id="menu-panel" style="display:none">


问:
Can't resolve symbol 'thisActivity'
I'm a new android developer.  I'm trying to get my app to check permissions and I found this bit of code here

```<code>int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
            Manifest.permission.ACCESS_NOTIFICATION_POLICY);
</code>```

The problem I'm having is that thisActivityis showing up with the error "Can't resolve symbol 'thisActivity'.

答:
thisActivity means you have to provide the reference of your activity.

Actually, if you are in MainActivity then you have to give MainActivity.this

So, your code for activity will be:

```<code>ContextCompat.checkSelfPermission(YourActivity.this,
            Manifest.permission.ACCESS_NOTIFICATION_POLICY);
</code>```

and your code for fragment will be:

```<code>ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.ACCESS_NOTIFICATION_POLICY);
</code>```

Title: Can't resolve symbol 'thisActivity'

Body:
I'm a new android developer.  I'm trying to get my app to check permissions and I found this bit of code here

int permissionCheck = ContextCompat.checkSelfPermission(thisActivity,
            Manifest.permission.ACCESS_NOTIFICATION_POLICY);

The problem I'm having is that thisActivityis showing up with the error "Can't resolve symbol 'thisActivity'.

Body:
thisActivity means you have to provide the reference of your activity.

Actually, if you are in MainActivity then you have to give MainActivity.this

So, your code for activity will be:

ContextCompat.checkSelfPermission(YourActivity.this,
            Manifest.permission.ACCESS_NOTIFICATION_POLICY);

and your code for fragment will be:

ContextCompat.checkSelfPermission(getActivity(),
            Manifest.permission.ACCESS_NOTIFICATION_POLICY);


问:
Are there any drawbacks to using head.js?
Things I am aware of:

Screen flicker if scripts alter styles / content (not an issue for me as I currently load scripts at the end of the page and so have workarounds already)

Inability to detect script load failure (not too concerned about this either as everything I develop is required to work with or without javascript. Might affect my workarounds for item 1 but happy with this risk)

It looks to be a very good option to me but I am hoping for some references (feel free to say only positive things!) before I invest time in incorporating it into my next project.

Currently we develop mid-to-large sized sites with, generally, a moderate amount of Javascript (although this is growing rapidly). We also use the jQuery library for the bulk of our Javascript.

Anyone have any experience? Good or bad! :)

P.S. for those interested this is head.js

答:
There would be no problem on using jquery or javascript library heavily. Try to main each library as unique.

I am using prototype, scriptaculous, jquery and many more jquery additional plugins. I faced an error while loading entire scripts. Then i found out its due to $ sign which is an important parameter of jquery and prototype.

i had used

```<code>    $.noConflict();
jQuery(document).ready(function($){
//jquery codes here
})
</code>```

So keep your script library unique

Body:
There would be no problem on using jquery or javascript library heavily. Try to main each library as unique.

I am using prototype, scriptaculous, jquery and many more jquery additional plugins. I faced an error while loading entire scripts. Then i found out its due to $ sign which is an important parameter of jquery and prototype.

i had used

    $.noConflict();
jQuery(document).ready(function($){
//jquery codes here
})

So keep your script library unique


问:
error when parsing value into Model (flask)
Objective is to accept UI multiple parameters and give it to the model (127.0.0.1:5002)using flask API and then the scoring from the model post back to UI (127.0.0.1:5001)

I am getting error (which is posted below at the end) when a model accept the value from the UI.
So i am posting values to 127.0.0.1:5002 where model takes that as 1 json object but i am getting error.

So i post 1 json object from this code (let me know if there is an issue in the code- i am a newbie)

```<code> <script>
 $(function() {$('#analysis').bind('click', function() {
   $.post('http://127.0.0.1:5002/',{
     'CK': $('CK').val(),
     'OCE': $('OCE').val(),
     'range_04': $('range_04').val(),
   },
   function(data) {
                 var parsed = JSON.parse(data);
                 $("#xyz").text(parsed['abc']);
             });
            return false;
     });
   });
</script>
</code>```

Now this code generates the json (and that json object feeds the model)

```<code>app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('args.xyz')

class getPredProb(Resource):
    def post(self):
        args = parser.parse_args()
        clf = joblib.load('AO.pkl')
        frameToScore = pandas.read_json('args.xyz')
        prediction = clf.predict(frameToScore)
        probability = clf.predict_proba(frameToScore)
        return json.dumps({'Prediction': prediction},{'Probability':probability}), 201, {'Access-Control-Allow-Origin': 'http://127.0.0.1:5001'}

api.add_resource(getPredProb, '/')

if __name__ == '__main__':
    #http_server = WSGIServer(('', 5002), app)
    #http_server.serve_forever()
    app.run(debug=True,port=5002)
</code>```

Image of ERROR

答: You're only passing a string, 'args.xyz', to read_json, you should use args['xyz'] (assuming this is the json data, as I don't see anything with an xyz key being passed to the backend).

Body:
Objective is to accept UI multiple parameters and give it to the model (127.0.0.1:5002)using flask API and then the scoring from the model post back to UI (127.0.0.1:5001)

I am getting error (which is posted below at the end) when a model accept the value from the UI.
So i am posting values to 127.0.0.1:5002 where model takes that as 1 json object but i am getting error.

So i post 1 json object from this code (let me know if there is an issue in the code- i am a newbie)

Now this code generates the json (and that json object feeds the model)

app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
parser.add_argument('args.xyz')

class getPredProb(Resource):
    def post(self):
        args = parser.parse_args()
        clf = joblib.load('AO.pkl')
        frameToScore = pandas.read_json('args.xyz')
        prediction = clf.predict(frameToScore)
        probability = clf.predict_proba(frameToScore)
        return json.dumps({'Prediction': prediction},{'Probability':probability}), 201, {'Access-Control-Allow-Origin': 'http://127.0.0.1:5001'}

api.add_resource(getPredProb, '/')

if __name__ == '__main__':
    #http_server = WSGIServer(('', 5002), app)
    #http_server.serve_forever()
    app.run(debug=True,port=5002)

Image of ERROR