问:
Collapsible Toolbar - Make Fragment Footer Always Visible in Android
I am making an app that has a ProfilePage with three fragments - About | Posts | Gallery, and I am using a collapsible toolbar with user's image. My second and third fragment will have a footer that should always be visible, but this is what I get:

When my image is expanded the footer disappears. What I want is for my two fragments to have these footers always visible and not depending on toolbar being collapsed or not. My gallery footer should be similar to post footer.

profile_layout.xml:

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

<android.support.design.widget.CoordinatorLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:id="@+id/main_content"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="256dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        contentScrim="?attr/colorPrimary"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:id="@+id/profile_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            android:scaleType="centerCrop"
            android:contentDescription="@string/profile_photo"
            app:layout_collapseMode="none"/>

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin">

            <ImageView
                android:id="@+id/toolbarEdit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="end"
                android:contentDescription="@string/block"
                android:paddingEnd="20dp"
                android:paddingStart="5dp"
                app:srcCompat="@drawable/ic_icon_edit" />
        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <android.support.design.widget.TabLayout
        android:id="@+id/myProfileTabs"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_gravity="bottom"
        app:tabContentStart="72dp"
        app:tabGravity="fill"
        app:tabMode="scrollable" />

    <android.support.v4.view.ViewPager
        android:id="@+id/myProfileViewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</LinearLayout>
</code>```

posts_fragment.xml:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/tile_bg"
android:orientation="vertical" >

<ListView
    android:id="@+id/list_view_messages"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:background="@null"
    android:divider="@null"
    android:transcriptMode="alwaysScroll"
    android:stackFromBottom="true">
</ListView>

<LinearLayout
    android:id="@+id/llMsgCompose"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    android:orientation="horizontal"
    android:weightSum="4" >

    <EditText
        android:id="@+id/inputMsg"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="3"
        android:background="@color/bg_msg_input"
        android:textColor="@color/text_msg_input"
        android:paddingLeft="6dp"
        android:paddingRight="6dp"/>

    <Button
        android:id="@+id/btnSend"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@color/ppdColorOrange"
        android:textColor="@color/white"
        android:text="@string/send" />
</LinearLayout>
</code>```

My PostsFragment (not yet implemented):

public class MyProfilePostsFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.navdrawer_my_profile_fragment_posts, container, false);
        return view;
    }
}
```

答:
I had the same requirement for my one of apps. I just did workaround.

Add your required layout in tab layout:

```<code><android.support.design.widget.CoordinatorLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:id="@+id/main_content"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="256dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            contentScrim="?attr/colorPrimary"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/profile_image"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:contentDescription="@string/profile_photo"
                app:layout_collapseMode="none"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin">

                <ImageView
                    android:id="@+id/toolbarEdit"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="end"
                    android:contentDescription="@string/block"
                    android:paddingEnd="20dp"
                    android:paddingStart="5dp"
                    app:srcCompat="@drawable/ic_icon_edit" />
            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.design.widget.TabLayout
            android:id="@+id/myProfileTabs"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_gravity="bottom"
            app:tabContentStart="72dp"
            app:tabGravity="fill"
            app:tabMode="scrollable" />

        <android.support.v4.view.ViewPager
            android:id="@+id/myProfileViewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />
    </LinearLayout>

    <-- Your required layout -->
    <LinearLayout
        android:id="@+id/tab123"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:gravity="bottom"
        android:orientation="horizontal"
        android:visibility="gone"
        android:weightSum="4">

        <EditText
            android:id="@+id/inputMsg"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:paddingLeft="6dp"
            android:paddingRight="6dp" />

        <Button
            android:id="@+id/btnSend"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="send" />
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>
</code>```

Add following code in your Tab activity:

TabLayout tabLayout;
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);//add your viewpager to TabLayout

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
        LinearLayout l=(LinearLayout) findViewById(R.id.tab123);
        final EditText text=(EditText) findViewById(R.id.inputMsg);
        Button send=(Button) findViewById(R.id.btnSend);

        if (tab.getPosition() == 0) {
            l.setVisibility(View.GONE);
            System.out.println("About tab");
        } else if (tab.getPosition() == 1) {
            l.setVisibility(View.VISIBLE);
            System.out.println("Posts tab");

            send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String msg = null;
                    msg = text.getText().toString(); //get input
                    // Perform your desired task.
                }
            });
        } else if (tab.getPosition() == 2) {
            l.setVisibility(View.VISIBLE);
            System.out.println("Gallery tab");

            send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String msg = null;
                    msg = text.getText().toString(); //get input
                    //Perform your desired task.
                }
            });
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }
});
```

ContentLicense: CC BY-SA 4.0

Body:
I am making an app that has a ProfilePage with three fragments - About | Posts | Gallery, and I am using a collapsible toolbar with user's image. My second and third fragment will have a footer that should always be visible, but this is what I get:

When my image is expanded the footer disappears. What I want is for my two fragments to have these footers always visible and not depending on toolbar being collapsed or not. My gallery footer should be similar to post footer.

profile_layout.xml:

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

<android.support.design.widget.CoordinatorLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:id="@+id/main_content"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="256dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        contentScrim="?attr/colorPrimary"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
            android:id="@+id/profile_image"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            android:scaleType="centerCrop"
            android:contentDescription="@string/profile_photo"
            app:layout_collapseMode="none"/>

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin">

            <ImageView
                android:id="@+id/toolbarEdit"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="end"
                android:contentDescription="@string/block"
                android:paddingEnd="20dp"
                android:paddingStart="5dp"
                app:srcCompat="@drawable/ic_icon_edit" />
        </android.support.v7.widget.Toolbar>

    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <android.support.design.widget.TabLayout
        android:id="@+id/myProfileTabs"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_gravity="bottom"
        app:tabContentStart="72dp"
        app:tabGravity="fill"
        app:tabMode="scrollable" />

    <android.support.v4.view.ViewPager
        android:id="@+id/myProfileViewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</LinearLayout>

posts_fragment.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/tile_bg"
android:orientation="vertical" >

<ListView
    android:id="@+id/list_view_messages"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:background="@null"
    android:divider="@null"
    android:transcriptMode="alwaysScroll"
    android:stackFromBottom="true">
</ListView>

<LinearLayout
    android:id="@+id/llMsgCompose"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    android:orientation="horizontal"
    android:weightSum="4" >

    <EditText
        android:id="@+id/inputMsg"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="3"
        android:background="@color/bg_msg_input"
        android:textColor="@color/text_msg_input"
        android:paddingLeft="6dp"
        android:paddingRight="6dp"/>

    <Button
        android:id="@+id/btnSend"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="@color/ppdColorOrange"
        android:textColor="@color/white"
        android:text="@string/send" />
</LinearLayout>

My PostsFragment (not yet implemented):

public class MyProfilePostsFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.navdrawer_my_profile_fragment_posts, container, false);
        return view;
    }
}

Body:
I had the same requirement for my one of apps. I just did workaround.

Add your required layout in tab layout:

<android.support.design.widget.CoordinatorLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   android:id="@+id/main_content"
   android:layout_width="match_parent"
   android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="256dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            contentScrim="?attr/colorPrimary"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/profile_image"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:contentDescription="@string/profile_photo"
                app:layout_collapseMode="none"/>

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin">

                <ImageView
                    android:id="@+id/toolbarEdit"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="end"
                    android:contentDescription="@string/block"
                    android:paddingEnd="20dp"
                    android:paddingStart="5dp"
                    app:srcCompat="@drawable/ic_icon_edit" />
            </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <android.support.design.widget.TabLayout
            android:id="@+id/myProfileTabs"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:layout_gravity="bottom"
            app:tabContentStart="72dp"
            app:tabGravity="fill"
            app:tabMode="scrollable" />

        <android.support.v4.view.ViewPager
            android:id="@+id/myProfileViewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior" />
    </LinearLayout>

    <-- Your required layout -->
    <LinearLayout
        android:id="@+id/tab123"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:gravity="bottom"
        android:orientation="horizontal"
        android:visibility="gone"
        android:weightSum="4">

        <EditText
            android:id="@+id/inputMsg"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="3"
            android:paddingLeft="6dp"
            android:paddingRight="6dp" />

        <Button
            android:id="@+id/btnSend"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="send" />
    </LinearLayout>
</android.support.design.widget.CoordinatorLayout>

Add following code in your Tab activity:

TabLayout tabLayout;
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);//add your viewpager to TabLayout

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
        LinearLayout l=(LinearLayout) findViewById(R.id.tab123);
        final EditText text=(EditText) findViewById(R.id.inputMsg);
        Button send=(Button) findViewById(R.id.btnSend);

        if (tab.getPosition() == 0) {
            l.setVisibility(View.GONE);
            System.out.println("About tab");
        } else if (tab.getPosition() == 1) {
            l.setVisibility(View.VISIBLE);
            System.out.println("Posts tab");

            send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String msg = null;
                    msg = text.getText().toString(); //get input
                    // Perform your desired task.
                }
            });
        } else if (tab.getPosition() == 2) {
            l.setVisibility(View.VISIBLE);
            System.out.println("Gallery tab");

            send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String msg = null;
                    msg = text.getText().toString(); //get input
                    //Perform your desired task.
                }
            });
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }
});


来源: stackexchange

问:
Passing Custom Types to an Apollo Mutation
Is there a way to pass a custom GraphQL Type with Apollo ?

e.g. : like the below, a Mutation to create an User (Custom User Type is already defined in the GraphQL schema) :

```<code>createUser(user: User): String
</code>```

I think that we're only allowed to pass Primary Types, so no Object.
Another option (not clean), would be to serialize an Object as a String and pass it as a String parameter, and in the resolver to deserialize it.

答:
It is possible to pass an object in a mutation. See for example this cheat sheet. But you have to define an extra input user GraphQL type and cannot use the user type.

In your case it could look like this:

`
type User {
  id: ID!
  username: String!
  // other query properties
}

input UserInput {
  username: Strin!
}
````
</div>
</div>
</p>

<p>And the mutation and the resolver could look like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>`
mutation createUser(user: UserInput!): String
`

Mutation: {
  createUser(_, { user }) {
    // create in database
  }
}</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to pass a custom GraphQL Type with Apollo ?

e.g. : like the below, a Mutation to create an User (Custom User Type is already defined in the GraphQL schema) :

createUser(user: User): String

I think that we're only allowed to pass Primary Types, so no Object.
Another option (not clean), would be to serialize an Object as a String and pass it as a String parameter, and in the resolver to deserialize it.

Body:
It is possible to pass an object in a mutation. See for example this cheat sheet. But you have to define an extra input user GraphQL type and cannot use the user type.

In your case it could look like this:

`
type User {
  id: ID!
  username: String!
  // other query properties
}

input UserInput {
  username: Strin!
}
`

And the mutation and the resolver could look like this:

`
mutation createUser(user: UserInput!): String
`

Mutation: {
  createUser(_, { user }) {
    // create in database
  }
}


问:
TensorFlow - Tflearning error feed_dict
I am working on a classification problem in python. Fact is, I'm not good yet in TensorFlow. So I have the same problem since a long time now and I don't know how to fix it. I hope you could help me :)

This is my data :

X : 8000 pictures : 32*32px and 3 colors (rgb), so I load a matrix X.shape = (8000,32,32,3)

Y : 4 classes (1,2,3 and 4): Y. shape = (8000,1)

This is my code :

```<code>network = input_data(shape=[None, 32, 32, 3], name='iput')
# Step 1: Convolution
network = conv_2d(network, 32, 3, activation='relu')
# Step 2: Max pooling
network = max_pool_2d(network, 2)
# Step 3: Convolution again
network = conv_2d(network, 64, 3, activation='relu')
# Step 4: Convolution yet again
network = conv_2d(network, 64, 3, activation='relu')
# Step 5: Max pooling again
network = max_pool_2d(network, 2)
# Step 6: Fully-connected 512 node neural network
network = fully_connected(network, 512, activation='relu')
# Step 7: Dropout - throw away some data randomly during training to prevent over-fitting
network = dropout(network, 0.5)
# Step 8: Fully-connected neural network with 4 outputs
network = fully_connected(network, 4, activation='softmax')
# Tell tflearn how we want to train the network
network = regression(network, optimizer='adam',
                     loss='categorical_crossentropy',
                     learning_rate=0.001)
model = tflearn.DNN(network)
model.fit(X, Y)
</code>```

This is my erros

Traceback (most recent call last):

File "", line 3, in

model.fit(X, Y)

File "/home/side/anaconda3/lib/python3.5/site-packages/tflearn/models/dnn.py",

line 157, in fit

self.targets)

File "/home/side/anaconda3/lib/python3.5/site-packages/tflearn/utils.py",
  line 267, in feed_dict_builder
      feed_dict[net_inputs[i]] = x
  IndexError: list index out of range

I have also tried to pass X as (8000,3072) Matrix
And Y as (8000,4) Matrix, for exemple :

[0 0 1 0  <-- Y[0] = 3

0 1 0 0  <-- Y[1] = 2

...]

I reuse this code : https://github.com/tflearn/tflearn/blob/master/examples/images/convnet_cifar10.py , used to class cifar10 data.

Thank you for your help,

Celia

答:
Another option is to add:

```<code>tf.reset_default_graph()
</code>```

As the first line of your code

Title: TensorFlow - Tflearning error feed_dict

Body:
I am working on a classification problem in python. Fact is, I'm not good yet in TensorFlow. So I have the same problem since a long time now and I don't know how to fix it. I hope you could help me :)

This is my data :

X : 8000 pictures : 32*32px and 3 colors (rgb), so I load a matrix X.shape = (8000,32,32,3)

Y : 4 classes (1,2,3 and 4): Y. shape = (8000,1)

This is my code :

network = input_data(shape=[None, 32, 32, 3], name='iput')
# Step 1: Convolution
network = conv_2d(network, 32, 3, activation='relu')
# Step 2: Max pooling
network = max_pool_2d(network, 2)
# Step 3: Convolution again
network = conv_2d(network, 64, 3, activation='relu')
# Step 4: Convolution yet again
network = conv_2d(network, 64, 3, activation='relu')
# Step 5: Max pooling again
network = max_pool_2d(network, 2)
# Step 6: Fully-connected 512 node neural network
network = fully_connected(network, 512, activation='relu')
# Step 7: Dropout - throw away some data randomly during training to prevent over-fitting
network = dropout(network, 0.5)
# Step 8: Fully-connected neural network with 4 outputs
network = fully_connected(network, 4, activation='softmax')
# Tell tflearn how we want to train the network
network = regression(network, optimizer='adam',
                     loss='categorical_crossentropy',
                     learning_rate=0.001)
model = tflearn.DNN(network)
model.fit(X, Y)

This is my erros

Traceback (most recent call last):

File "", line 3, in

model.fit(X, Y)

File "/home/side/anaconda3/lib/python3.5/site-packages/tflearn/models/dnn.py",

line 157, in fit

self.targets)

File "/home/side/anaconda3/lib/python3.5/site-packages/tflearn/utils.py",
  line 267, in feed_dict_builder
      feed_dict[net_inputs[i]] = x
  IndexError: list index out of range

I have also tried to pass X as (8000,3072) Matrix
And Y as (8000,4) Matrix, for exemple :

[0 0 1 0  <-- Y[0] = 3

0 1 0 0  <-- Y[1] = 2

...]

I reuse this code : https://github.com/tflearn/tflearn/blob/master/examples/images/convnet_cifar10.py , used to class cifar10 data.

Thank you for your help,

Celia

Body:
Another option is to add:

tf.reset_default_graph()

As the first line of your code


问:
Error if excel file exists in the Temp folder
Following code works good.

```<code>Dim xlProcess As New Process
xlProcess.StartInfo.FileName = "EXCEL.EXE"
xlProcess.StartInfo.Arguments = "/x /safe /readonly ""C:\Book1.xlsx"""
xlProcess.Start()
</code>```

Following picture shows the error when I just change directory.

答:
You forgot to put a & before the System.IO.Path.GetTempPath. You also forgot to put the double quote after /readonly. It should be like this: </p>

```<code>Dim xlProcess As New Process
xlProcess.StartInfo.FileName = "EXCEL.EXE"
xlProcess.StartInfo.Arguments = "/x /safe /readonly """ & System.IO.Path.GetTempPath & "Book1.xlsx"""
xlProcess.Start()
</code>```

Body:
Following code works good.

Dim xlProcess As New Process
xlProcess.StartInfo.FileName = "EXCEL.EXE"
xlProcess.StartInfo.Arguments = "/x /safe /readonly ""C:\Book1.xlsx"""
xlProcess.Start()

Following picture shows the error when I just change directory.

Body:
You forgot to put a & before the System.IO.Path.GetTempPath. You also forgot to put the double quote after /readonly. It should be like this:

Dim xlProcess As New Process
xlProcess.StartInfo.FileName = "EXCEL.EXE"
xlProcess.StartInfo.Arguments = "/x /safe /readonly """ & System.IO.Path.GetTempPath & "Book1.xlsx"""
xlProcess.Start()


问:
RFC822 compliant SMTP address
I'm getting mixed answers on whether the following SMTP address is RFC822 compliant:

```<code>"Jane Doe" <jane.doe@acme.com>
</code>```

Is the above format compliant or should it only be:

```<code>jane.doe@acme.com
</code>```

?

Looked at the following address specification from RFC822:

```<code>   6.  ADDRESS SPECIFICATION

 6.1.  SYNTAX

 address     =  mailbox                      ; one addressee
             /  group                        ; named list

 group       =  phrase ":" [#mailbox] ";"

 mailbox     =  addr-spec                    ; simple address
             /  phrase route-addr            ; name & addr-spec

 route-addr  =  "<" [route] addr-spec ">"

 route       =  1#("@" domain) ":"           ; path-relative

 addr-spec   =  local-part "@" domain        ; global address

 local-part  =  word *("." word)             ; uninterpreted
                                             ; case-preserved

 domain      =  sub-domain *("." sub-domain)

 sub-domain  =  domain-ref / domain-literal

 domain-ref  =  atom                         ; symbolic reference
</code>```

答:
Both email addresses are valid, for further email address RFC822 compliance checks please use the below tool.

http://sphinx.mythic-beasts.com/~pdw/cgi-bin/emailvalidate

Update

The RFC822 was obsoleted by RFC2822 to check RFC2822 use

http://proxy2.de/email-validation.php

EDIT

Thanks @jstedfast, The above link validates RFC5322 as well.

Title: RFC822 compliant SMTP address

Body:
I'm getting mixed answers on whether the following SMTP address is RFC822 compliant:

"Jane Doe" <jane.doe@acme.com>

Is the above format compliant or should it only be:

jane.doe@acme.com

?

Looked at the following address specification from RFC822:

   6.  ADDRESS SPECIFICATION

 6.1.  SYNTAX

 address     =  mailbox                      ; one addressee
             /  group                        ; named list

 group       =  phrase ":" [#mailbox] ";"

 mailbox     =  addr-spec                    ; simple address
             /  phrase route-addr            ; name & addr-spec

 route-addr  =  "<" [route] addr-spec ">"

 route       =  1#("@" domain) ":"           ; path-relative

 addr-spec   =  local-part "@" domain        ; global address

 local-part  =  word *("." word)             ; uninterpreted
                                             ; case-preserved

 domain      =  sub-domain *("." sub-domain)

 sub-domain  =  domain-ref / domain-literal

 domain-ref  =  atom                         ; symbolic reference


问:
Watson: Valid Expression required in - Condition [Anything else] evaluated to FALSE
when the intent is found and not able to find any entity the below error is popped up.

How could I change the dialog system to avoid the false case.

SpelParseException when evaluating DialogNode Id
  [node_1_1480493211176]. Condition [Anything else] evaluated to FALSE.
  org.springframework.expression.spel.SpelParseException: EL1041E:(pos
  9): After parsing a valid expression, there is still more data in the
  expression: 'else' (and there is 1 more error in the log)

答: Just need to add one more dialog with FALSE condition.</p>


问:
DB2 rownum equivalent
I have the below query in Oracle which I want to replicate in DB2 which uses the random function and the rownum.

Oracle Query :

```<code>SELECT *
FROM  (
   SELECT *
   FROM db2admin.QUESTION_BANK
   WHERE type='PROCESS'
   ORDER BY dbms_random.value
) WHERE rownum <=?
</code>```

I got alternate for random function but nothing for rownum. Below is query in DB2,

```<code>SELECT *
FROM  (
  SELECT *
  FROM db2admin.QUESTION_BANK
  WHERE type='PROCESS' ORDER BY RAND
) WHERE rownum <= ?
</code>```

The value for rownum is passed via PreparedStatement.

答:
try it:</p>

```<code>SELECT *
FROM  (
       SELECT f1.*, rownumber() over(ORDER BY f1.randm ) as rownum
       from (
            select f0.*, rand() as randm FROM db2admin.QUESTION_BANK f0
             WHERE f0.type='PROCESS'
            ) f1
      ) f2
WHERE f2.rownum <= ?
</code>```

Title: DB2 rownum equivalent

Body:
I have the below query in Oracle which I want to replicate in DB2 which uses the random function and the rownum.

Oracle Query :

SELECT *
FROM  (
   SELECT *
   FROM db2admin.QUESTION_BANK
   WHERE type='PROCESS'
   ORDER BY dbms_random.value
) WHERE rownum <=?

I got alternate for random function but nothing for rownum. Below is query in DB2,

SELECT *
FROM  (
  SELECT *
  FROM db2admin.QUESTION_BANK
  WHERE type='PROCESS' ORDER BY RAND
) WHERE rownum <= ?

The value for rownum is passed via PreparedStatement.

Body:
try it:

SELECT *
FROM  (
       SELECT f1.*, rownumber() over(ORDER BY f1.randm ) as rownum
       from (
            select f0.*, rand() as randm FROM db2admin.QUESTION_BANK f0
             WHERE f0.type='PROCESS'
            ) f1
      ) f2
WHERE f2.rownum <= ?


问:
Understanding Elm's Type Signature return types
I am trying to understand elm's type signatures.  What does this function return exactly?  It appears to be a function that accepts no arguments and returns ...</p>

```<code>route : Parser (Page -> a) a
</code>```

答:
As a learning exercise for myself I'm going to try to answer this. Others will chip in if I get something wrong.

I'm sure you are used to something like

```<code>type Person = Adult String | Child String Age
</code>```

Child is a type that takes two parameters. Parser is the same. But it's definition is pretty formidable

```<code>type Parser a b =
  Parser (State a -> List (State b))

type alias State value =
  { visited : List String
  , unvisited : List String
  , params : Dict String String
  , value : value
  }
</code>```

That said, you see how Parser is ultimately a wrapper around a function from a State to a list of States. Ultimately it is going to be passed a List of 'unvisited' strings or params; it will progressively 'visit' each one and the result will be combined into the final 'value'.

Next, note that while Parser takes two type parameters - a, b - parseHash is defined

```<code>parseHash : Parser (a -> a) a -> Location -> Maybe a
</code>```

So, your original

```<code>route : Parser (Page -> a) a
</code>```

is going to have to be

```<code>route : Parser (Page -> Page) Page
</code>```

to type check.

To return to your original question, therefore, route is a Parser (which is a very general object) that encapsulates instructions on how to go from one Page to another, and can be used - via parseHash - to tell you what Page to go to next, and that is of course what you would expect from a router.

Hope this gets you started

Body:
I am trying to understand elm's type signatures.  What does this function return exactly?  It appears to be a function that accepts no arguments and returns ...

route : Parser (Page -> a) a

Body:
As a learning exercise for myself I'm going to try to answer this. Others will chip in if I get something wrong.

I'm sure you are used to something like

type Person = Adult String | Child String Age

Child is a type that takes two parameters. Parser is the same. But it's definition is pretty formidable

type Parser a b =
  Parser (State a -> List (State b))

type alias State value =
  { visited : List String
  , unvisited : List String
  , params : Dict String String
  , value : value
  }

That said, you see how Parser is ultimately a wrapper around a function from a State to a list of States. Ultimately it is going to be passed a List of 'unvisited' strings or params; it will progressively 'visit' each one and the result will be combined into the final 'value'.

Next, note that while Parser takes two type parameters - a, b - parseHash is defined

parseHash : Parser (a -> a) a -> Location -> Maybe a

So, your original

route : Parser (Page -> a) a

is going to have to be

route : Parser (Page -> Page) Page

to type check.

To return to your original question, therefore, route is a Parser (which is a very general object) that encapsulates instructions on how to go from one Page to another, and can be used - via parseHash - to tell you what Page to go to next, and that is of course what you would expect from a router.

Hope this gets you started


问:
android ProgressBar is changing height dimension of parent LinearLayout
I have a bunch of RelativeLayout inside LinearLayout. Inside this will be ProgressBar and other elements.

The problem at the moment is that the ProgressBar is extending the height dimension of the parent LinearLayout when placed inside the RelativeLayout.

Here's the basics of what I have.

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_weight="1"
    android:weightSum="2">

    <RelativeLayout
        android:id="@+id/timer1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/darker_gray">

        <ProgressBar
            android:layout_width="200dp"
            android:layout_height="20dp"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:layout_centerInParent="true"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/timer2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_light"/>

</LinearLayout>
</code>```

The ProgressBar looks like it is extending height of the parent LinearLayout by the height of the ProgressBar. Which of course is not wanted.

Bare in mind that the above LinearLayout is inside another vertical LinearLayout where weightSum="3". So this distortion of the height means all will not fit in the screen vertically.

The one flaw I may have in my thinking is that because I have not yet completed the code (not put ProgressBar in each of the three levels) that it's just a quirk. I'll do that and report back. But it still seems to me this can't be a good thing.

答:
```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:orientation="horizontal"
    android:layout_weight="1">

    <RelativeLayout
        android:id="@+id/timer1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/darker_gray">

        <ProgressBar
            android:layout_width="200dp"
            android:layout_height="20dp"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:layout_centerInParent="true"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/timer2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_light"/>

</LinearLayout>

when using weights use the width or the height to 0dp which ever orientation u need
</code>```

Body:
I have a bunch of RelativeLayout inside LinearLayout. Inside this will be ProgressBar and other elements.

The problem at the moment is that the ProgressBar is extending the height dimension of the parent LinearLayout when placed inside the RelativeLayout.

Here's the basics of what I have.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_weight="1"
    android:weightSum="2">

    <RelativeLayout
        android:id="@+id/timer1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/darker_gray">

        <ProgressBar
            android:layout_width="200dp"
            android:layout_height="20dp"
            style="@android:style/Widget.ProgressBar.Horizontal"
            android:paddingLeft="16dp"
            android:paddingRight="16dp"
            android:layout_centerInParent="true"/>
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/timer2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@android:color/holo_blue_light"/>

</LinearLayout>

The ProgressBar looks like it is extending height of the parent LinearLayout by the height of the ProgressBar. Which of course is not wanted.

Bare in mind that the above LinearLayout is inside another vertical LinearLayout where weightSum="3". So this distortion of the height means all will not fit in the screen vertically.

The one flaw I may have in my thinking is that because I have not yet completed the code (not put ProgressBar in each of the three levels) that it's just a quirk. I'll do that and report back. But it still seems to me this can't be a good thing.


问:
Creating a list of lists from round robin not using a recipe
I am new to python and trying to learn how to round robin of a list into a list of lists. I saw posts with answers pointing to a standard round robin recipe, but I don't understand some of the concepts in it and would prefer a simpler solution.

I want to achieve something like this using a function, but I haven't been able to come close:

```<code>MYLIST = ['apples', 'oranges', 'bananas', 'grapes', 'strawberries', 'pears']
>>>myfunc(MYLIST)
[['apples', 'grapes'], ['oranges', 'strawberries'], ['bananas', 'pears']]
</code>```

I'm very confused after attempting to solve this problem using a combination of for loops, while loops and if statements. Nothing I did worked.

I don't have any code that works or comes close to working. Any help would be appreciated. Thanks.

答:
Try below code I don't know much about round robin algorithm but,</p>

```<code>l = ['apples', 'oranges', 'bananas', 'grapes', 'strawberries', 'pears']

half = len(l) / 2

l1 = l[:half]
l2 = l[half:]

l3 = []

for i in range(half):
    l3 += [l1[i],l2[i]],

print l3
</code>```

Body:
I am new to python and trying to learn how to round robin of a list into a list of lists. I saw posts with answers pointing to a standard round robin recipe, but I don't understand some of the concepts in it and would prefer a simpler solution.

I want to achieve something like this using a function, but I haven't been able to come close:

MYLIST = ['apples', 'oranges', 'bananas', 'grapes', 'strawberries', 'pears']
>>>myfunc(MYLIST)
[['apples', 'grapes'], ['oranges', 'strawberries'], ['bananas', 'pears']]

I'm very confused after attempting to solve this problem using a combination of for loops, while loops and if statements. Nothing I did worked.

I don't have any code that works or comes close to working. Any help would be appreciated. Thanks.

Body:
Try below code I don't know much about round robin algorithm but,

l = ['apples', 'oranges', 'bananas', 'grapes', 'strawberries', 'pears']

half = len(l) / 2

l1 = l[:half]
l2 = l[half:]

l3 = []

for i in range(half):
    l3 += [l1[i],l2[i]],

print l3


问:
Single precision big endian float values to Python's float (double precision, big endian)
I need to receive hex encoded single precision big endian float values coming from an Arduino over a serial line (RS-232). How do convert them to Python's float which are big endians with double precision?

The Arduino send something like "8192323E" and in Python I would like to have 0.174387. I found "Convert hex to float" but it seems that all of them don't work for single precision floats.

From the linked page, this looks promising:

```<code>from ctypes import *

def convert(s):
    i = int(s, 16)                   # convert from hex to a Python int
    cp = pointer(c_int(i))           # make this into a c integer
    fp = cast(cp, POINTER(c_float))  # cast the int pointer to a float pointer
    return fp.contents.value         # dereference the pointer, get the float
</code>```

But it still doesn't work with my single precision floats.

In Java (Processing) I've been able to do that:

```<code>float decodeFloat(String inString) {
  byte [] inData = new byte[4];

  inString = inString.substring(2, 10); // discard the leading "f:"
  inData[0] = (byte) unhex(inString.substring(0, 2));
  inData[1] = (byte) unhex(inString.substring(2, 4));
  inData[2] = (byte) unhex(inString.substring(4, 6));
  inData[3] = (byte) unhex(inString.substring(6, 8));

  int intbits = (inData[3] << 24) | ((inData[2] & 0xff) << 16) | ((inData[1] & 0xff) << 8) | (inData[0] & 0xff);
  //unhex(inString.substring(0, 8));
  return Float.intBitsToFloat(intbits);
}
</code>```

For your reference, this is the C code running on the Arduino implementing the hex encoding.

```<code>void serialFloatPrint(float f) {
  byte * b = (byte *) &f;
  Serial.print("f:");
  for(int i=0; i<4; i++) {

    byte b1 = (b[i] >> 4) & 0x0f;
    byte b2 = (b[i] & 0x0f);

    char c1 = (b1 < 10) ? ('0' + b1) : 'A' + b1 - 10;
    char c2 = (b2 < 10) ? ('0' + b2) : 'A' + b2 - 10;

    Serial.print(c1);
    Serial.print(c2);
  }
}
</code>```

答:
Building on Ignacio Vazquez-Abrams's answer,</p>

```<code>import binascii
import struct

text='8192323E'
print(struct.unpack('<f',binascii.unhexlify(text))[0])
# 0.17438699305057526
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need to receive hex encoded single precision big endian float values coming from an Arduino over a serial line (RS-232). How do convert them to Python's float which are big endians with double precision?

The Arduino send something like "8192323E" and in Python I would like to have 0.174387. I found "Convert hex to float" but it seems that all of them don't work for single precision floats.

From the linked page, this looks promising:

from ctypes import *

def convert(s):
    i = int(s, 16)                   # convert from hex to a Python int
    cp = pointer(c_int(i))           # make this into a c integer
    fp = cast(cp, POINTER(c_float))  # cast the int pointer to a float pointer
    return fp.contents.value         # dereference the pointer, get the float

But it still doesn't work with my single precision floats.

In Java (Processing) I've been able to do that:

float decodeFloat(String inString) {
  byte [] inData = new byte[4];

  inString = inString.substring(2, 10); // discard the leading "f:"
  inData[0] = (byte) unhex(inString.substring(0, 2));
  inData[1] = (byte) unhex(inString.substring(2, 4));
  inData[2] = (byte) unhex(inString.substring(4, 6));
  inData[3] = (byte) unhex(inString.substring(6, 8));

  int intbits = (inData[3] << 24) | ((inData[2] & 0xff) << 16) | ((inData[1] & 0xff) << 8) | (inData[0] & 0xff);
  //unhex(inString.substring(0, 8));
  return Float.intBitsToFloat(intbits);
}

For your reference, this is the C code running on the Arduino implementing the hex encoding.

void serialFloatPrint(float f) {
  byte * b = (byte *) &f;
  Serial.print("f:");
  for(int i=0; i<4; i++) {

    byte b1 = (b[i] >> 4) & 0x0f;
    byte b2 = (b[i] & 0x0f);

    char c1 = (b1 < 10) ? ('0' + b1) : 'A' + b1 - 10;
    char c2 = (b2 < 10) ? ('0' + b2) : 'A' + b2 - 10;

    Serial.print(c1);
    Serial.print(c2);
  }
}

Body:
Building on Ignacio Vazquez-Abrams's answer,

import binascii
import struct

text='8192323E'
print(struct.unpack('<f',binascii.unhexlify(text))[0])
# 0.17438699305057526


问:
linux capabilities to rename a root owned file
For some component testing, in my C++ testapp on Ubuntu 14.04,
I'd like to rename /sbin/reboot temporarily to prevent my system under test (another big c++ app started inside testapp) from calling
system("/sbin/reboot")
and after the test I want to restore /sbin/reboot to its full glory.

So on the cmd shell I call

```<code>sudo setcap cap_chown,cap_dac_override,cap_setfcap=+ep testapp
</code>```

in order to enable my testapp to call system("chown user /sbin/reboot") furthermore system("chgrp developer /sbin/reboot") and system("mv /sbin/reboot /sbin/reboot.tmp")

But testapp stops with
chown: changing ownership of ‘/sbin/reboot’: Operation not permitted

So, what has to be done to enable renaming this particular file from within an app not running sudo?

答:
For all linux capability experts in the www: the question was - "Which of the linux capabilities does my app need to rename /sbin/reboot withou sudo - to get the same effect as calling sudo mv /sbin/reboot /sbin/reboot.tmp in a shell.

@datenwolf: Without beeing impolite, but if I ask into the crowd "What's the time"? an answer like "you asked the wrong question, because I don't have a watch, but I have a humidity meter, so if you ask about humidity, I am glad to help you" does not help me at all.

The solution to rename a root owned file is, to only set

```<code>sudo setcap cap_dac_override=+ep MyTestApp
</code>```

on commandline, and instead of using

```<code>system("mv file1 file2");
</code>```

in MyTestApp source-code, switch back to

```<code>rename("file1" "file2");
</code>```

Then everything works like a charm.

Body:
For some component testing, in my C++ testapp on Ubuntu 14.04,
I'd like to rename /sbin/reboot temporarily to prevent my system under test (another big c++ app started inside testapp) from calling
system("/sbin/reboot")
and after the test I want to restore /sbin/reboot to its full glory.

So on the cmd shell I call

sudo setcap cap_chown,cap_dac_override,cap_setfcap=+ep testapp

in order to enable my testapp to call system("chown user /sbin/reboot") furthermore system("chgrp developer /sbin/reboot") and system("mv /sbin/reboot /sbin/reboot.tmp")

But testapp stops with
chown: changing ownership of ‘/sbin/reboot’: Operation not permitted

So, what has to be done to enable renaming this particular file from within an app not running sudo?

Body:
For all linux capability experts in the www: the question was - "Which of the linux capabilities does my app need to rename /sbin/reboot withou sudo - to get the same effect as calling sudo mv /sbin/reboot /sbin/reboot.tmp in a shell.

@datenwolf: Without beeing impolite, but if I ask into the crowd "What's the time"? an answer like "you asked the wrong question, because I don't have a watch, but I have a humidity meter, so if you ask about humidity, I am glad to help you" does not help me at all.

The solution to rename a root owned file is, to only set

sudo setcap cap_dac_override=+ep MyTestApp

on commandline, and instead of using

system("mv file1 file2");

in MyTestApp source-code, switch back to

rename("file1" "file2");

Then everything works like a charm.


问:
Python Relations with Sets of Tuples
I'm trying to determine whether or not sets of tuples have a certain type of relation. I'm trying to figure out the transitive relation, and the composite relation.

For the transitive relation:

```<code> # A relation 'Relation' is called transitive when:
 # ∀ (a, b) ∈ Relation, (b, c) ∈ Relation ==> (a, c) ∈ Relation
</code>```

For example:

```<code>>>> {(1,1), (1,2), (1,4), (2,1), (2,2), (3,3), (4,1), (4,4)} # Should be False
>>> {(1,1), (2,1), (3,1), (3,2), (4,1), (4,2), (4,3)} # Should be True
</code>```

For the composite relation:

```<code># The composite of relations 'R1' and 'R2' is the relation consisting
# of tuples (a,c), such that (a,b) ∈ R1 and (b,c) ∈ R2
</code>```

For example:

```<code>{(1,0), (1,1), (2,1), (2,2), (3,0), (3,1)} == R1={(1,1), (1,4), (2,3), (3,1), (3,4)}, R2={(1,0), (2,0), (3,1), (3,2), (4,1)}
# Should return True
</code>```

I am uncertain on how to start coding these functions. Any help to get me started would be greatly appreciated. Thank you!

EDIT:
Here are some other relations I was able to successfully code:

```<code># Reflexive Relation
# A relation 'Relation' on a set 'Set' is called reflexive when:
# ∀ a ∈ Set, (a,a) ∈ Relation
def is_reflexive(Set, Relation):
    newSet = {(a, b) for a in Set for b in Set if a == b}
    if Relation >= newSet:
        return True

    return False

# Symmetric Relation
# A relation 'Relation' is called symmetric when:
#  ∀ (a, b) ∈ Relation, (b, a) ∈ Relation
def is_symmetric(Relation):
    if all(tup[::-1] in Relation for tup in Relation):
        return True

    return False
</code>```

答:
I believe this is a brute force approach that works. First, we are going to use an "adjacency set" representation, then just test explicitly using a deeply nested for-loop:

```<code>In [5]: r1 =  {(1,1), (1,2), (1,4), (2,1), (2,2), (3,3), (4,1), (4,3)}

In [6]: adjacency = {}
    ...: for a,b in r1:
    ...:     adjacency.setdefault(a,set()).add(b)
    ...:

In [7]: transitive = True

In [8]: for a, related in adjacency.items():
    ...:     for b in related:
    ...:         for c in adjacency[b]:
    ...:             if c not in related:
    ...:                 transitive = False
    ...:                 print("({},{}) and ({},{}) but not ({},{})".format(a, b, b, c, a,c))
    ...:
(1,4) and (4,3) but not (1,3)
(2,1) and (1,4) but not (2,4)
(4,1) and (1,2) but not (4,2)
(4,1) and (1,4) but not (4,4)

In [9]: transitive
Out[9]: False
</code>```

However, for your second example:

```<code>In [7]: r2 = {(1,1), (2,1), (3,1), (3,2), (4,1), (4,2), (4,3)}

In [8]: adjacency = {}
    ...: for a,b in r2:
    ...:     adjacency.setdefault(a,set()).add(b)
    ...:

In [9]: transitive = True

In [10]: for a, related in adjacency.items():
    ...:     for b in related:
    ...:         for c in adjacency[b]:
    ...:             if c not in related:
    ...:                 transitive = False
    ...:                 print("({},{}) and ({},{}) but not ({},{})".format(a, b, b, c, a,c))
    ...:

In [11]: transitive
Out[11]: True
</code>```

Using this data structure should make it a little less horrible from a time-complexity POV.

As for constructing the composite:

```<code>In [18]: def make_adjacency_set(R):
    ...:     a = {}
    ...:     for x,y in R:
    ...:         a.setdefault(x, set()).add(y)
    ...:     return a
    ...:

In [19]: def make_composite(R1, R2):
    ...:     adj1 = make_adjacency_set(R1)
    ...:     adj2 = make_adjacency_set(R2)
    ...:     composite = set()
    ...:     for a, related in adj1.items():
    ...:         for b in related:
    ...:             for c in adj2.get(b, []):
    ...:                 composite.add((a, c))
    ...:     return composite
    ...:

In [20]: R1={(1,1), (1,4), (2,3), (3,1), (3,4)}; R2={(1,0), (2,0), (3,1), (3,2), (4,1)}

In [21]: make_composite(R1, R2)
Out[21]: {(1, 0), (1, 1), (2, 1), (2, 2), (3, 0), (3, 1)}
</code>```

Or, just sticking with sets of tuple:

```<code>In [25]: composite = set()
    ...: for a, b in R1:
    ...:     for c, d in R2:
    ...:         if b == c:
    ...:             composite.add((a,d))
    ...:
    ...:

In [26]: composite
Out[26]: {(1, 0), (1, 1), (2, 1), (2, 2), (3, 0), (3, 1)}
</code>```

Title: Python Relations with Sets of Tuples

Body:
I'm trying to determine whether or not sets of tuples have a certain type of relation. I'm trying to figure out the transitive relation, and the composite relation.

For the transitive relation:

 # A relation 'Relation' is called transitive when:
 # ∀ (a, b) ∈ Relation, (b, c) ∈ Relation ==> (a, c) ∈ Relation

For example:

>>> {(1,1), (1,2), (1,4), (2,1), (2,2), (3,3), (4,1), (4,4)} # Should be False
>>> {(1,1), (2,1), (3,1), (3,2), (4,1), (4,2), (4,3)} # Should be True

For the composite relation:

# The composite of relations 'R1' and 'R2' is the relation consisting
# of tuples (a,c), such that (a,b) ∈ R1 and (b,c) ∈ R2

For example:

{(1,0), (1,1), (2,1), (2,2), (3,0), (3,1)} == R1={(1,1), (1,4), (2,3), (3,1), (3,4)}, R2={(1,0), (2,0), (3,1), (3,2), (4,1)}
# Should return True

I am uncertain on how to start coding these functions. Any help to get me started would be greatly appreciated. Thank you!

EDIT:
Here are some other relations I was able to successfully code:

# Reflexive Relation
# A relation 'Relation' on a set 'Set' is called reflexive when:
# ∀ a ∈ Set, (a,a) ∈ Relation
def is_reflexive(Set, Relation):
    newSet = {(a, b) for a in Set for b in Set if a == b}
    if Relation >= newSet:
        return True

    return False

# Symmetric Relation
# A relation 'Relation' is called symmetric when:
#  ∀ (a, b) ∈ Relation, (b, a) ∈ Relation
def is_symmetric(Relation):
    if all(tup[::-1] in Relation for tup in Relation):
        return True

    return False

Body:
I believe this is a brute force approach that works. First, we are going to use an "adjacency set" representation, then just test explicitly using a deeply nested for-loop:

In [5]: r1 =  {(1,1), (1,2), (1,4), (2,1), (2,2), (3,3), (4,1), (4,3)}

In [6]: adjacency = {}
    ...: for a,b in r1:
    ...:     adjacency.setdefault(a,set()).add(b)
    ...:

In [7]: transitive = True

In [8]: for a, related in adjacency.items():
    ...:     for b in related:
    ...:         for c in adjacency[b]:
    ...:             if c not in related:
    ...:                 transitive = False
    ...:                 print("({},{}) and ({},{}) but not ({},{})".format(a, b, b, c, a,c))
    ...:
(1,4) and (4,3) but not (1,3)
(2,1) and (1,4) but not (2,4)
(4,1) and (1,2) but not (4,2)
(4,1) and (1,4) but not (4,4)

In [9]: transitive
Out[9]: False

However, for your second example:

In [7]: r2 = {(1,1), (2,1), (3,1), (3,2), (4,1), (4,2), (4,3)}

In [8]: adjacency = {}
    ...: for a,b in r2:
    ...:     adjacency.setdefault(a,set()).add(b)
    ...:

In [9]: transitive = True

In [10]: for a, related in adjacency.items():
    ...:     for b in related:
    ...:         for c in adjacency[b]:
    ...:             if c not in related:
    ...:                 transitive = False
    ...:                 print("({},{}) and ({},{}) but not ({},{})".format(a, b, b, c, a,c))
    ...:

In [11]: transitive
Out[11]: True

Using this data structure should make it a little less horrible from a time-complexity POV.

As for constructing the composite:

In [18]: def make_adjacency_set(R):
    ...:     a = {}
    ...:     for x,y in R:
    ...:         a.setdefault(x, set()).add(y)
    ...:     return a
    ...:

In [19]: def make_composite(R1, R2):
    ...:     adj1 = make_adjacency_set(R1)
    ...:     adj2 = make_adjacency_set(R2)
    ...:     composite = set()
    ...:     for a, related in adj1.items():
    ...:         for b in related:
    ...:             for c in adj2.get(b, []):
    ...:                 composite.add((a, c))
    ...:     return composite
    ...:

In [20]: R1={(1,1), (1,4), (2,3), (3,1), (3,4)}; R2={(1,0), (2,0), (3,1), (3,2), (4,1)}

In [21]: make_composite(R1, R2)
Out[21]: {(1, 0), (1, 1), (2, 1), (2, 2), (3, 0), (3, 1)}

Or, just sticking with sets of tuple:

In [25]: composite = set()
    ...: for a, b in R1:
    ...:     for c, d in R2:
    ...:         if b == c:
    ...:             composite.add((a,d))
    ...:
    ...:

In [26]: composite
Out[26]: {(1, 0), (1, 1), (2, 1), (2, 2), (3, 0), (3, 1)}


答:
For the transitive test, just convert the math definition in Python:</p>

```<code>def is_transitive(relation):
    for a,b in relation:
        for c,d in relation:
            if b == c and ((a,d) not in relation):
                    # print (a,b),(c,d) # uncomment for tests...
                    return False
    return True
</code>```

Title: Python Relations with Sets of Tuples

Body:
For the transitive test, just convert the math definition in Python:

def is_transitive(relation):
    for a,b in relation:
        for c,d in relation:
            if b == c and ((a,d) not in relation):
                    # print (a,b),(c,d) # uncomment for tests...
                    return False
    return True


问:
Why was function overloading added to C++?
I have a C background. I was just wondering why was function overloading added to C++? C doesn't have function overloading but C++ does, what was the need for it?

What went across the mind of the language designer at that time?

答:
You could get the answer straight from the horse's mouth: The Design and Evolution of C++ by Bjarne Stroustrup devotes an entire chapter to overloading, its history, evolution, design tradeoffs and decisions.

I won't recount the story here, but will mention a couple of interesting historical facts:

operator and function overloading are closely related;

in early C++ there used to be a special keyword (overload) that had to be used to declare an identifier as overloaded;

function overloading requires type-safe linking (i.e. name mangling); when first implemented, it helped discover a surprising number of link-time errors in existing C and C++ code (to quote Stroustrup, it was like "running lint on a C program for the first time -- somewhat embarrassing".)


问:
Is std::vector so much slower than plain arrays?
I've always thought it's the general wisdom that std::vector is "implemented as an array," blah blah blah. Today I went down and tested it, and it seems to be not so:

Here's some test results:

```<code>UseArray completed in 2.619 seconds
UseVector completed in 9.284 seconds
UseVectorPushBack completed in 14.669 seconds
The whole thing completed in 26.591 seconds
</code>```

That's about 3 - 4 times slower! Doesn't really justify for the "vector may be slower for a few nanosecs" comments.

And the code I used:

```<code>#include <cstdlib>
#include <vector>

#include <iostream>
#include <string>

#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/date_time/microsec_time_clock.hpp>

class TestTimer
{
    public:
        TestTimer(const std::string & name) : name(name),
            start(boost::date_time::microsec_clock<boost::posix_time::ptime>::local_time())
        {
        }

        ~TestTimer()
        {
            using namespace std;
            using namespace boost;

            posix_time::ptime now(date_time::microsec_clock<posix_time::ptime>::local_time());
            posix_time::time_duration d = now - start;

            cout << name << " completed in " << d.total_milliseconds() / 1000.0 <<
                " seconds" << endl;
        }

    private:
        std::string name;
        boost::posix_time::ptime start;
};

struct Pixel
{
    Pixel()
    {
    }

    Pixel(unsigned char r, unsigned char g, unsigned char b) : r(r), g(g), b(b)
    {
    }

    unsigned char r, g, b;
};

void UseVector()
{
    TestTimer t("UseVector");

    for(int i = 0; i < 1000; ++i)
    {
        int dimension = 999;

        std::vector<Pixel> pixels;
        pixels.resize(dimension * dimension);

        for(int i = 0; i < dimension * dimension; ++i)
        {
            pixels[i].r = 255;
            pixels[i].g = 0;
            pixels[i].b = 0;
        }
    }
}

void UseVectorPushBack()
{
    TestTimer t("UseVectorPushBack");

    for(int i = 0; i < 1000; ++i)
    {
        int dimension = 999;

        std::vector<Pixel> pixels;
            pixels.reserve(dimension * dimension);

        for(int i = 0; i < dimension * dimension; ++i)
            pixels.push_back(Pixel(255, 0, 0));
    }
}

void UseArray()
{
    TestTimer t("UseArray");

    for(int i = 0; i < 1000; ++i)
    {
        int dimension = 999;

        Pixel * pixels = (Pixel *)malloc(sizeof(Pixel) * dimension * dimension);

        for(int i = 0 ; i < dimension * dimension; ++i)
        {
            pixels[i].r = 255;
            pixels[i].g = 0;
            pixels[i].b = 0;
        }

        free(pixels);
    }
}

int main()
{
    TestTimer t1("The whole thing");

    UseArray();
    UseVector();
    UseVectorPushBack();

    return 0;
}
</code>```

Am I doing it wrong or something? Or have I just busted this performance myth?

I'm using Release mode in Visual Studio 2005.

In Visual C++, #define _SECURE_SCL 0 reduces UseVector by half (bringing it down to 4 seconds). This is really huge, IMO.

答:
I Have to say I'm not an expert in C++. But to add some experiments results:

compile:
    gcc-6.2.0/bin/g++ -O3 -std=c++14 vector.cpp

machine:

```<code>Intel(R) Xeon(R) CPU E5-2690 v2 @ 3.00GHz
</code>```

OS:

```<code>2.6.32-642.13.1.el6.x86_64
</code>```

Output:

```<code>UseArray completed in 0.167821 seconds
UseVector completed in 0.134402 seconds
UseConstructor completed in 0.134806 seconds
UseFillConstructor completed in 1.00279 seconds
UseVectorPushBack completed in 6.6887 seconds
The whole thing completed in 8.12888 seconds
</code>```

Here the only thing I feel strange is that "UseFillConstructor" performance compared with "UseConstructor".

The code:

```<code>void UseConstructor()
{
    TestTimer t("UseConstructor");

    for(int i = 0; i < 1000; ++i)
    {
        int dimension = 999;

        std::vector<Pixel> pixels(dimension*dimension);
        for(int i = 0; i < dimension * dimension; ++i)
        {
            pixels[i].r = 255;
            pixels[i].g = 0;
            pixels[i].b = 0;
        }
    }
}

void UseFillConstructor()
{
    TestTimer t("UseFillConstructor");

    for(int i = 0; i < 1000; ++i)
    {
        int dimension = 999;

        std::vector<Pixel> pixels(dimension*dimension, Pixel(255,0,0));
    }
}
</code>```

So the additional "value" provided slows down performance quite a lot, which I think is due to multiple call to copy constructor. But...

Compile:

```<code>gcc-6.2.0/bin/g++ -std=c++14 -O vector.cpp
</code>```

Output:

```<code>UseArray completed in 1.02464 seconds
UseVector completed in 1.31056 seconds
UseConstructor completed in 1.47413 seconds
UseFillConstructor completed in 1.01555 seconds
UseVectorPushBack completed in 6.9597 seconds
The whole thing completed in 11.7851 seconds
</code>```

So in this case, gcc optimization is very important but it can't help you much when a value is provided as default. This, is against my tuition actually. Hopefully it helps new programmer when choose which vector initialization format.

Body:
I've always thought it's the general wisdom that std::vector is "implemented as an array," blah blah blah. Today I went down and tested it, and it seems to be not so:

Here's some test results:

UseArray completed in 2.619 seconds
UseVector completed in 9.284 seconds
UseVectorPushBack completed in 14.669 seconds
The whole thing completed in 26.591 seconds

That's about 3 - 4 times slower! Doesn't really justify for the "vector may be slower for a few nanosecs" comments.

And the code I used:

#include <cstdlib>
#include <vector>

#include <iostream>
#include <string>

#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/date_time/microsec_time_clock.hpp>

class TestTimer
{
    public:
        TestTimer(const std::string & name) : name(name),
            start(boost::date_time::microsec_clock<boost::posix_time::ptime>::local_time())
        {
        }

        ~TestTimer()
        {
            using namespace std;
            using namespace boost;

            posix_time::ptime now(date_time::microsec_clock<posix_time::ptime>::local_time());
            posix_time::time_duration d = now - start;

            cout << name << " completed in " << d.total_milliseconds() / 1000.0 <<
                " seconds" << endl;
        }

    private:
        std::string name;
        boost::posix_time::ptime start;
};

struct Pixel
{
    Pixel()
    {
    }

    Pixel(unsigned char r, unsigned char g, unsigned char b) : r(r), g(g), b(b)
    {
    }

    unsigned char r, g, b;
};

void UseVector()
{
    TestTimer t("UseVector");

    for(int i = 0; i < 1000; ++i)
    {
        int dimension = 999;

        std::vector<Pixel> pixels;
        pixels.resize(dimension * dimension);

        for(int i = 0; i < dimension * dimension; ++i)
        {
            pixels[i].r = 255;
            pixels[i].g = 0;
            pixels[i].b = 0;
        }
    }
}

void UseVectorPushBack()
{
    TestTimer t("UseVectorPushBack");

    for(int i = 0; i < 1000; ++i)
    {
        int dimension = 999;

        std::vector<Pixel> pixels;
            pixels.reserve(dimension * dimension);

        for(int i = 0; i < dimension * dimension; ++i)
            pixels.push_back(Pixel(255, 0, 0));
    }
}

void UseArray()
{
    TestTimer t("UseArray");

    for(int i = 0; i < 1000; ++i)
    {
        int dimension = 999;

        Pixel * pixels = (Pixel *)malloc(sizeof(Pixel) * dimension * dimension);

        for(int i = 0 ; i < dimension * dimension; ++i)
        {
            pixels[i].r = 255;
            pixels[i].g = 0;
            pixels[i].b = 0;
        }

        free(pixels);
    }
}

int main()
{
    TestTimer t1("The whole thing");

    UseArray();
    UseVector();
    UseVectorPushBack();

    return 0;
}

Am I doing it wrong or something? Or have I just busted this performance myth?

I'm using Release mode in Visual Studio 2005.

In Visual C++, #define _SECURE_SCL 0 reduces UseVector by half (bringing it down to 4 seconds). This is really huge, IMO.

Body:
I Have to say I'm not an expert in C++. But to add some experiments results:

compile:
    gcc-6.2.0/bin/g++ -O3 -std=c++14 vector.cpp

machine:

Intel(R) Xeon(R) CPU E5-2690 v2 @ 3.00GHz

OS:

2.6.32-642.13.1.el6.x86_64

Output:

UseArray completed in 0.167821 seconds
UseVector completed in 0.134402 seconds
UseConstructor completed in 0.134806 seconds
UseFillConstructor completed in 1.00279 seconds
UseVectorPushBack completed in 6.6887 seconds
The whole thing completed in 8.12888 seconds

Here the only thing I feel strange is that "UseFillConstructor" performance compared with "UseConstructor".

The code:

void UseConstructor()
{
    TestTimer t("UseConstructor");

    for(int i = 0; i < 1000; ++i)
    {
        int dimension = 999;

        std::vector<Pixel> pixels(dimension*dimension);
        for(int i = 0; i < dimension * dimension; ++i)
        {
            pixels[i].r = 255;
            pixels[i].g = 0;
            pixels[i].b = 0;
        }
    }
}

void UseFillConstructor()
{
    TestTimer t("UseFillConstructor");

    for(int i = 0; i < 1000; ++i)
    {
        int dimension = 999;

        std::vector<Pixel> pixels(dimension*dimension, Pixel(255,0,0));
    }
}

So the additional "value" provided slows down performance quite a lot, which I think is due to multiple call to copy constructor. But...

Compile:

gcc-6.2.0/bin/g++ -std=c++14 -O vector.cpp

Output:

UseArray completed in 1.02464 seconds
UseVector completed in 1.31056 seconds
UseConstructor completed in 1.47413 seconds
UseFillConstructor completed in 1.01555 seconds
UseVectorPushBack completed in 6.9597 seconds
The whole thing completed in 11.7851 seconds

So in this case, gcc optimization is very important but it can't help you much when a value is provided as default. This, is against my tuition actually. Hopefully it helps new programmer when choose which vector initialization format.


问:
I am trying to follow NetBeans naming conventions, but it won't compile?
The setters with the int values say int cannot be dereferenced, and string value cannot find the method. I may not understand completely, but they look fine to me.

Please advise, thank you!

```<code>    private void setMachineID(int machineID) {
        machineID.set(machineID);
    }

    public int getMachineID(){
        return  machineID.get();
    }

    public IntegerProperty machineIDProperty(){
        return machineID;
    }
}
</code>```

答:
You're using the same identifier for the fields and the method parameters.

If there are more than 1 variable with the same identifier visible in a part of the code, java will use the one that is declared "closer" to this part of the code.

In this case the scope of the method parameter is the method which is "closer" to the method body than the fields. For this reason you must tell java explicitly that you want to use the field, not the method parameter.

You need to add change your setters like this:

Before

```<code>private void setMachineID(int machineID) {
    machineID.set(machineID);
//  ^^^^^^^^^                    references method parameter
//                ^^^^^^^^^      references method parameter
}
</code>```

After

```<code>private void setMachineID(int machineID) {
    this.machineID.set(machineID);
//  ^^^^^^^^^^^^^^                    References field
//                     ^^^^^^^^^      references method parameter
}
</code>```

Body:
The setters with the int values say int cannot be dereferenced, and string value cannot find the method. I may not understand completely, but they look fine to me.

Please advise, thank you!

    private void setMachineID(int machineID) {
        machineID.set(machineID);
    }

    public int getMachineID(){
        return  machineID.get();
    }

    public IntegerProperty machineIDProperty(){
        return machineID;
    }
}

Body:
You're using the same identifier for the fields and the method parameters.

If there are more than 1 variable with the same identifier visible in a part of the code, java will use the one that is declared "closer" to this part of the code.

In this case the scope of the method parameter is the method which is "closer" to the method body than the fields. For this reason you must tell java explicitly that you want to use the field, not the method parameter.

You need to add change your setters like this:

Before

private void setMachineID(int machineID) {
    machineID.set(machineID);
//  ^^^^^^^^^                    references method parameter
//                ^^^^^^^^^      references method parameter
}

After

private void setMachineID(int machineID) {
    this.machineID.set(machineID);
//  ^^^^^^^^^^^^^^                    References field
//                     ^^^^^^^^^      references method parameter
}


问:
Asynchronous Stored Procedure call in C#
I am new to C#. I'm trying to make an Asynchronous Stored Procedure call in my MVC ASP.net application.

This is what my code looks like:

```<code>public void RevalidateRule(int ruleKey)
    {
        var conStr = ConfigurationManager.ConnectionStrings["ValidationModuleEntities"].ConnectionString;

        using (var conn = new SqlConnection(conStr))
        {
            conn.Open();
            SqlCommand command = new SqlCommand("[dbo].[ReValidateQuery]", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@ValidationRuleKey", ruleKey));
            command.CommandTimeout = 50;
            command.ExecuteNonQuery();
        }
    }
</code>```

It has to be triggered whenever I press the save button in my view. However, it doesn't seem to be doing anything.

Does anyone have an idea?

答:
So you want to pass the value from your View to Controller and execute stored procedure. I'll try to explain how to get things done real quick.
Here is the example:

Controller

```<code>public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(string data)
{
    int ruleKey = Convert.ToInt32(data);
    Helper helper = new Helper();
    helper.RevalidateRule(ruleKey);
    return View();
}
</code>```

View

```<code>@using (Html.BeginForm())
{
    <input type="text" name="data" />
    <input type="submit" value="Submit" />
}
</code>```

Helper Class

```<code>public class Helper
{
    public void RevalidateRule(int ruleKey)
    {
        var conStr = ConfigurationManager.ConnectionStrings["ValidationModuleEntities"].ConnectionString;

        using (var conn = new SqlConnection(conStr))
        {
            conn.Open();
            SqlCommand command = new SqlCommand("[dbo].[ReValidateQuery]", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@ValidationRuleKey", ruleKey));
            command.CommandTimeout = 50;
            command.ExecuteNonQuery();
        }
    }
}
</code>```

So, this way you :

create your HelperClass to execute your stored procedure

pass needed value from your View to Controller

Execute your stored procedure.

Body:
I am new to C#. I'm trying to make an Asynchronous Stored Procedure call in my MVC ASP.net application.

This is what my code looks like:

public void RevalidateRule(int ruleKey)
    {
        var conStr = ConfigurationManager.ConnectionStrings["ValidationModuleEntities"].ConnectionString;

        using (var conn = new SqlConnection(conStr))
        {
            conn.Open();
            SqlCommand command = new SqlCommand("[dbo].[ReValidateQuery]", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@ValidationRuleKey", ruleKey));
            command.CommandTimeout = 50;
            command.ExecuteNonQuery();
        }
    }

It has to be triggered whenever I press the save button in my view. However, it doesn't seem to be doing anything.

Does anyone have an idea?

Body:
So you want to pass the value from your View to Controller and execute stored procedure. I'll try to explain how to get things done real quick.
Here is the example:

Controller

public ActionResult Index()
{
    return View();
}

[HttpPost]
public ActionResult Index(string data)
{
    int ruleKey = Convert.ToInt32(data);
    Helper helper = new Helper();
    helper.RevalidateRule(ruleKey);
    return View();
}

View

@using (Html.BeginForm())
{
    <input type="text" name="data" />
    <input type="submit" value="Submit" />
}

Helper Class

public class Helper
{
    public void RevalidateRule(int ruleKey)
    {
        var conStr = ConfigurationManager.ConnectionStrings["ValidationModuleEntities"].ConnectionString;

        using (var conn = new SqlConnection(conStr))
        {
            conn.Open();
            SqlCommand command = new SqlCommand("[dbo].[ReValidateQuery]", conn);
            command.CommandType = CommandType.StoredProcedure;
            command.Parameters.Add(new SqlParameter("@ValidationRuleKey", ruleKey));
            command.CommandTimeout = 50;
            command.ExecuteNonQuery();
        }
    }
}

So, this way you :

create your HelperClass to execute your stored procedure

pass needed value from your View to Controller

Execute your stored procedure.


问:
Testing Facebook Terms of Service Violation Error?
I am writing error handling around a case where users have recently violated terms of service with Facebook, and need a way to test this out. I've been reading through their docs and can't seem to find any tools for doing this. Any advice from someone with experience testing this would be greatly appreciate!</p>

答: Pretty much you have to either get an account temporarily banned or somehow contact Facebook developer support.</p>


问:
"IndexError: list index out of range" error using TensorFlow
I replicate "GoogLeNet" using tensorflow, dataset is oxford flower 17.

Here is my code.

```<code># This code is implementation of GoogLeNet, which is proposed in "https://www.cs.unc.edu/~wliu/papers/GoogLeNet.pdf"
# This code is referred from "https://github.com/tflearn/tflearn/blob/master/examples/images/googlenet.py"

from __future__ import division, print_function, absolute_import

# This code is extracted from "https://github.com/tflearn/tflearn/blob/master/tflearn/datasets/oxflower17.py"
import oxflower17

import tensorflow as tf

import numpy as np

X, Y = oxflower17.load_data(one_hot=True, resize_pics=(227,227))

x = tf.placeholder(tf.float32, [None, 227, 227, 3])
y = tf.placeholder(tf.float32, [None, 17])
keep_prob = tf.placeholder(tf.float32) #dropout (keep probability)

trainX, trainY, testX, testY = X[0:1224], Y[0:1224], X[1224:1360], Y[1224:1360] # Divide training sets and test sets
trainX = trainX.reshape(-1, 227, 227, 3)
testX = testX.reshape(-1, 227, 227, 3)

print (len(trainX))
print (len(testX))

# Parameters
batch_size = 64
test_size = len(testX)

# Create some wrappers
def conv2d(x, W, b, strides):  # Conv2D wrapper, with bias and relu activation
    x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
    x = tf.nn.bias_add(x, b)
    return tf.nn.relu(x)

def maxpool2d(x, k, strides):  # MaxPool2D wrapper
    return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, strides, strides, 1], padding='SAME')

def avgpool2d(x, k, strides):  # AveragePool2D wrapper
    return tf.nn.avg_pool(x, ksize=[1, k, k, 1], strides=[1, strides, strides, 1], padding='SAME')

def local_response_normalization(incoming, depth_radius=5, bias=1.0, alpha=0.0001, beta=0.75,
                                 name="LocalResponseNormalization"):
    return tf.nn.lrn(incoming, depth_radius=depth_radius, bias=bias, alpha=alpha, beta=beta, name=name)

weights = {
    ...
}

biases = {
    ...
}

# Create NN

x = tf.reshape(x, shape=[-1, 227, 227, 1])

conv1_7_7 = conv2d(x, weights['w_c1_77'], biases['b_c1_77'], strides=2)
pool1_3_3 = maxpool2d(conv1_7_7, k=3, strides=2)
pool1_3_3 = local_response_normalization(pool1_3_3)

conv2_1_1 = conv2d(pool1_3_3, weights['w_c2_11'], biases['b_c2_11'], strides=1)
conv2_3_3 = conv2d(conv2_1_1, weights['w_c2_33'], biases['b_c2_33'], strides=1)
conv2_3_3_lrn = local_response_normalization(conv2_3_3)
pool2_3_3 = maxpool2d(conv2_3_3_lrn, k=3, strides=2)

# Inception module (3a)
inception_3a_1_1 = conv2d(pool2_3_3, weights['w_inception_3a_11'], biases['b_inception_3a_11'], strides=1)
inception_3a_3_3_reduce = conv2d(pool2_3_3, weights['w_inception_3a_33_reduce'], biases['b_inception_3a_33_reduce'],
                                 strides=1)
inception_3a_3_3 = conv2d(inception_3a_3_3_reduce, weights['w_inception_3a_33'], biases['b_inception_3a_33'], strides=1)
inception_3a_5_5_reduce = conv2d(pool2_3_3, weights['w_inception_3a_55_reduce'], biases['b_inception_3a_55_reduce'],
                                 strides=1)
inception_3a_5_5 = conv2d(inception_3a_5_5_reduce, weights['w_inception_3a_55'], biases['b_inception_3a_55'], strides=1)
inception_3a_maxpool = maxpool2d(pool2_3_3, k=3, strides=1)
inception_3a_maxpool_reduce = conv2d(inception_3a_maxpool, weights['w_inception_3a_mp_reduce'],
                                     biases['b_inception_3a_mp_reduce'], strides=1)

inception_3a_concat = tf.concat(3, [inception_3a_1_1, inception_3a_3_3, inception_3a_5_5, inception_3a_maxpool_reduce])

...

# Inception module (5b)
inception_5b_1_1 = conv2d(inception_5a_concat, weights['w_inception_5b_11'], biases['b_inception_5b_11'], strides=1)
inception_5b_3_3_reduce = conv2d(inception_5a_concat, weights['w_inception_5b_33_reduce'],
                                 biases['b_inception_5b_33_reduce'], strides=1)
inception_5b_3_3 = conv2d(inception_5b_3_3_reduce, weights['w_inception_5b_33'], biases['b_inception_5b_33'], strides=1)
inception_5b_5_5_reduce = conv2d(inception_5a_concat, weights['w_inception_5b_55_reduce'],
                                 biases['b_inception_5b_55_reduce'], strides=1)
inception_5b_5_5 = conv2d(inception_5b_5_5_reduce, weights['w_inception_5b_55'], biases['b_inception_5b_55'], strides=1)
inception_5b_maxpool = maxpool2d(inception_5a_concat, k=3, strides=1)
inception_5b_maxpool_reduce = conv2d(inception_5b_maxpool, weights['w_inception_5a_mp_reduce'],
                                     biases['b_inception_5a_mp_reduce'], strides=1)

inception_5b_concat = tf.concat(3, [inception_5b_1_1, inception_5b_3_3, inception_5b_5_5, inception_5b_maxpool_reduce])

pool5_7_7 = avgpool2d(inception_5b_concat, 7, 1)

pool5_7_7_dropout = tf.nn.dropout(pool5_7_7, 0.4)

fc = tf.reshape(pool5_7_7_dropout, [-1, weights['w_fc'].get_shape().as_list()[0]])
fc = tf.add(tf.matmul(fc, weights['w_fc']), biases['b_fc'])

#### Network design is finished.

cost_function = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(fc, y))

optimizer = tf.train.MomentumOptimizer(learning_rate=0.001, momentum=0.9)

predict = tf.argmax(fc, 1)

init = tf.initialize_all_variables()

# Launch the graph
# This code is extracted from "http://pythonkim.tistory.com/56"
# Some variables are changed
with tf.Session() as sess:
    sess.run(init)

    for i in range(1):

        training_batch = zip(range(0, len(trainX), batch_size), range(batch_size, len(trainX)+1, batch_size))
        tf.reset_default_graph() # added by minho, from "https://github.com/tensorflow/tensorflow/issues/1470"
        for start, end in training_batch:
            sess.run(optimizer, feed_dict={x: trainX[start:end], y: trainY[start:end], keep_prob: 1.0}) # modified by minho

        test_indices = np.arange(len(testX))  # Get A Test Batch
        np.random.shuffle(test_indices)
        test_indices = test_indices[0:test_size]

        print(len(testX[test_indices]))

        print(i, np.mean(np.argmax(testY[test_indices], axis=1) ==
                         sess.run(predict, feed_dict={x: testX[test_indices], y: testY[test_indices], keep_prob: 1.0}))) # modified by minho
</code>```

Here is an error log.

File "/home/mh0205/GoogLeNet/googlenet.py", line 443, in
      sess.run(predict, feed_dict={x: testX[test_indices], y: testY[test_indices], keep_prob: 1.0}))) # modified by minho   File
  "/home/mh0205/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py",
  line 1159, in exit
      self._default_graph_context_manager.exit(exec_type, exec_value, exec_tb)   File
  "/home/mh0205/anaconda2/lib/python2.7/contextlib.py", line 35, in
  exit
      self.gen.throw(type, value, traceback)   File "/home/mh0205/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py",
  line 3671, in get_controller
      if self.stack[-1] is not default: IndexError: list index out of range

I cannot fix error. Please help me.

答:
Add :

```<code>tf.reset_default_graph()
</code>```

Before your code.

If tensorflow is not already imported, add it:

```<code>import tensorflow as tf
</code>```

Body:
I replicate "GoogLeNet" using tensorflow, dataset is oxford flower 17.

Here is my code.

# This code is implementation of GoogLeNet, which is proposed in "https://www.cs.unc.edu/~wliu/papers/GoogLeNet.pdf"
# This code is referred from "https://github.com/tflearn/tflearn/blob/master/examples/images/googlenet.py"

from __future__ import division, print_function, absolute_import

# This code is extracted from "https://github.com/tflearn/tflearn/blob/master/tflearn/datasets/oxflower17.py"
import oxflower17

import tensorflow as tf

import numpy as np

X, Y = oxflower17.load_data(one_hot=True, resize_pics=(227,227))

x = tf.placeholder(tf.float32, [None, 227, 227, 3])
y = tf.placeholder(tf.float32, [None, 17])
keep_prob = tf.placeholder(tf.float32) #dropout (keep probability)

trainX, trainY, testX, testY = X[0:1224], Y[0:1224], X[1224:1360], Y[1224:1360] # Divide training sets and test sets
trainX = trainX.reshape(-1, 227, 227, 3)
testX = testX.reshape(-1, 227, 227, 3)

print (len(trainX))
print (len(testX))

# Parameters
batch_size = 64
test_size = len(testX)

# Create some wrappers
def conv2d(x, W, b, strides):  # Conv2D wrapper, with bias and relu activation
    x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
    x = tf.nn.bias_add(x, b)
    return tf.nn.relu(x)

def maxpool2d(x, k, strides):  # MaxPool2D wrapper
    return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, strides, strides, 1], padding='SAME')

def avgpool2d(x, k, strides):  # AveragePool2D wrapper
    return tf.nn.avg_pool(x, ksize=[1, k, k, 1], strides=[1, strides, strides, 1], padding='SAME')

def local_response_normalization(incoming, depth_radius=5, bias=1.0, alpha=0.0001, beta=0.75,
                                 name="LocalResponseNormalization"):
    return tf.nn.lrn(incoming, depth_radius=depth_radius, bias=bias, alpha=alpha, beta=beta, name=name)

weights = {
    ...
}

biases = {
    ...
}

# Create NN

x = tf.reshape(x, shape=[-1, 227, 227, 1])

conv1_7_7 = conv2d(x, weights['w_c1_77'], biases['b_c1_77'], strides=2)
pool1_3_3 = maxpool2d(conv1_7_7, k=3, strides=2)
pool1_3_3 = local_response_normalization(pool1_3_3)

conv2_1_1 = conv2d(pool1_3_3, weights['w_c2_11'], biases['b_c2_11'], strides=1)
conv2_3_3 = conv2d(conv2_1_1, weights['w_c2_33'], biases['b_c2_33'], strides=1)
conv2_3_3_lrn = local_response_normalization(conv2_3_3)
pool2_3_3 = maxpool2d(conv2_3_3_lrn, k=3, strides=2)

# Inception module (3a)
inception_3a_1_1 = conv2d(pool2_3_3, weights['w_inception_3a_11'], biases['b_inception_3a_11'], strides=1)
inception_3a_3_3_reduce = conv2d(pool2_3_3, weights['w_inception_3a_33_reduce'], biases['b_inception_3a_33_reduce'],
                                 strides=1)
inception_3a_3_3 = conv2d(inception_3a_3_3_reduce, weights['w_inception_3a_33'], biases['b_inception_3a_33'], strides=1)
inception_3a_5_5_reduce = conv2d(pool2_3_3, weights['w_inception_3a_55_reduce'], biases['b_inception_3a_55_reduce'],
                                 strides=1)
inception_3a_5_5 = conv2d(inception_3a_5_5_reduce, weights['w_inception_3a_55'], biases['b_inception_3a_55'], strides=1)
inception_3a_maxpool = maxpool2d(pool2_3_3, k=3, strides=1)
inception_3a_maxpool_reduce = conv2d(inception_3a_maxpool, weights['w_inception_3a_mp_reduce'],
                                     biases['b_inception_3a_mp_reduce'], strides=1)

inception_3a_concat = tf.concat(3, [inception_3a_1_1, inception_3a_3_3, inception_3a_5_5, inception_3a_maxpool_reduce])

...

# Inception module (5b)
inception_5b_1_1 = conv2d(inception_5a_concat, weights['w_inception_5b_11'], biases['b_inception_5b_11'], strides=1)
inception_5b_3_3_reduce = conv2d(inception_5a_concat, weights['w_inception_5b_33_reduce'],
                                 biases['b_inception_5b_33_reduce'], strides=1)
inception_5b_3_3 = conv2d(inception_5b_3_3_reduce, weights['w_inception_5b_33'], biases['b_inception_5b_33'], strides=1)
inception_5b_5_5_reduce = conv2d(inception_5a_concat, weights['w_inception_5b_55_reduce'],
                                 biases['b_inception_5b_55_reduce'], strides=1)
inception_5b_5_5 = conv2d(inception_5b_5_5_reduce, weights['w_inception_5b_55'], biases['b_inception_5b_55'], strides=1)
inception_5b_maxpool = maxpool2d(inception_5a_concat, k=3, strides=1)
inception_5b_maxpool_reduce = conv2d(inception_5b_maxpool, weights['w_inception_5a_mp_reduce'],
                                     biases['b_inception_5a_mp_reduce'], strides=1)

inception_5b_concat = tf.concat(3, [inception_5b_1_1, inception_5b_3_3, inception_5b_5_5, inception_5b_maxpool_reduce])

pool5_7_7 = avgpool2d(inception_5b_concat, 7, 1)

pool5_7_7_dropout = tf.nn.dropout(pool5_7_7, 0.4)

fc = tf.reshape(pool5_7_7_dropout, [-1, weights['w_fc'].get_shape().as_list()[0]])
fc = tf.add(tf.matmul(fc, weights['w_fc']), biases['b_fc'])

#### Network design is finished.

cost_function = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(fc, y))

optimizer = tf.train.MomentumOptimizer(learning_rate=0.001, momentum=0.9)

predict = tf.argmax(fc, 1)

init = tf.initialize_all_variables()

# Launch the graph
# This code is extracted from "http://pythonkim.tistory.com/56"
# Some variables are changed
with tf.Session() as sess:
    sess.run(init)

    for i in range(1):

        training_batch = zip(range(0, len(trainX), batch_size), range(batch_size, len(trainX)+1, batch_size))
        tf.reset_default_graph() # added by minho, from "https://github.com/tensorflow/tensorflow/issues/1470"
        for start, end in training_batch:
            sess.run(optimizer, feed_dict={x: trainX[start:end], y: trainY[start:end], keep_prob: 1.0}) # modified by minho

        test_indices = np.arange(len(testX))  # Get A Test Batch
        np.random.shuffle(test_indices)
        test_indices = test_indices[0:test_size]

        print(len(testX[test_indices]))

        print(i, np.mean(np.argmax(testY[test_indices], axis=1) ==
                         sess.run(predict, feed_dict={x: testX[test_indices], y: testY[test_indices], keep_prob: 1.0}))) # modified by minho

Here is an error log.

File "/home/mh0205/GoogLeNet/googlenet.py", line 443, in
      sess.run(predict, feed_dict={x: testX[test_indices], y: testY[test_indices], keep_prob: 1.0}))) # modified by minho   File
  "/home/mh0205/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py",
  line 1159, in exit
      self._default_graph_context_manager.exit(exec_type, exec_value, exec_tb)   File
  "/home/mh0205/anaconda2/lib/python2.7/contextlib.py", line 35, in
  exit
      self.gen.throw(type, value, traceback)   File "/home/mh0205/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py",
  line 3671, in get_controller
      if self.stack[-1] is not default: IndexError: list index out of range

I cannot fix error. Please help me.

Body:
Add :

tf.reset_default_graph()

Before your code.

If tensorflow is not already imported, add it:

import tensorflow as tf