问:
Collapsing card view when Recycler View scroll down
How I can put the card below the toolbar and collapse it until it disappear when I scroll down and re open when I scroll up

I am using Xamarin.Android with design libary

Here is my AXML code:

```<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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/coordinatorLayoutMainLayoutPublicationsLayout"
    android:fitsSystemWindows="true">

  <android.support.design.widget.AppBarLayout
         android:id="@+id/main.appbar"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:fitsSystemWindows="true">

    <android.support.design.widget.CollapsingToolbarLayout
          android:id="@+id/collapsing_toolbar"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:fitsSystemWindows="true"
          app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed">

      <android.support.v7.widget.CardView
             xmlns:card_view="http://schemas.android.com/apk/res-auto"
             android:id="@+id/card_view"
             android:layout_gravity="center"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             app:cardCornerRadius="4dp"
             app:cardElevation="4dp"
             app:cardUseCompatPadding="true">

        <Button
         android:layout_width="match_parent"
         android:layout_height="150dp"
         android:text="BOBOBOBOBOBOB"
         app:layout_scrollFlags="scroll|enterAlways"/>

      </android.support.v7.widget.CardView>

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

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

    <android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/swipeContainerPublicationsLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <android.support.v7.widget.RecyclerView
      android:id="@+id/recyclerViewPublicationsLayout"
      android:scrollbars="vertical"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />

  </android.support.v4.widget.SwipeRefreshLayout>

  <android.support.v7.widget.Toolbar
        android:id="@+id/toolbarPublicationsLayout"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />

  <android.support.design.widget.FloatingActionButton
    android:id="@+id/fabPublicationsLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:src="@drawable/icon_add_fab"
    android:layout_margin="15dp" />

</android.support.design.widget.CoordinatorLayout>
</code>```

The output view is like this:

Screenshot of the view

答:
After many hours searching I found the solution, make the recyclerview and the cardview inside a NestedScrollView</p>

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

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical"
    android:id="@+id/linearLayoutMainLayout">

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

<android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/coordinatorLayoutMainLayout">

  <android.support.v4.widget.SwipeRefreshLayout
      android:id="@+id/swipeContainer"
      android:layout_width="match_parent"
      android:layout_height="match_parent"  >

    <android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

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

         <android.support.v7.widget.CardView
   android:id="@+id/card_view"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   app:cardCornerRadius="4dp"
   app:cardElevation="4dp"
   app:cardUseCompatPadding="true">

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

      <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold"
        android:id="@+id/textView1" />
      <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView2" />
      <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView3" />
      <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView4" />
      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button" />

    </LinearLayout>

  </android.support.v7.widget.CardView>

         <android.support.v7.widget.RecyclerView
          android:id="@+id/recyclerView"
          android:scrollbars="vertical"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:nestedScrollingEnabled="false"/>

    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

      </android.support.v4.widget.SwipeRefreshLayout>

<android.support.design.widget.FloatingActionButton
      android:id="@+id/fab"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:src="@drawable/icon_add_fab"
    android:layout_margin="15dp"/>

</android.support.design.widget.CoordinatorLayout>

</LinearLayout>
</code>```

Body:
How I can put the card below the toolbar and collapse it until it disappear when I scroll down and re open when I scroll up

I am using Xamarin.Android with design libary

Here is my AXML 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/coordinatorLayoutMainLayoutPublicationsLayout"
    android:fitsSystemWindows="true">

  <android.support.design.widget.AppBarLayout
         android:id="@+id/main.appbar"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:fitsSystemWindows="true">

    <android.support.design.widget.CollapsingToolbarLayout
          android:id="@+id/collapsing_toolbar"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:fitsSystemWindows="true"
          app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed">

      <android.support.v7.widget.CardView
             xmlns:card_view="http://schemas.android.com/apk/res-auto"
             android:id="@+id/card_view"
             android:layout_gravity="center"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             app:cardCornerRadius="4dp"
             app:cardElevation="4dp"
             app:cardUseCompatPadding="true">

        <Button
         android:layout_width="match_parent"
         android:layout_height="150dp"
         android:text="BOBOBOBOBOBOB"
         app:layout_scrollFlags="scroll|enterAlways"/>

      </android.support.v7.widget.CardView>

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

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

    <android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/swipeContainerPublicationsLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <android.support.v7.widget.RecyclerView
      android:id="@+id/recyclerViewPublicationsLayout"
      android:scrollbars="vertical"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />

  </android.support.v4.widget.SwipeRefreshLayout>

  <android.support.v7.widget.Toolbar
        android:id="@+id/toolbarPublicationsLayout"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />

  <android.support.design.widget.FloatingActionButton
    android:id="@+id/fabPublicationsLayout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:src="@drawable/icon_add_fab"
    android:layout_margin="15dp" />

</android.support.design.widget.CoordinatorLayout>

The output view is like this:

Screenshot of the view

Body:
After many hours searching I found the solution, make the recyclerview and the cardview inside a NestedScrollView

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

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical"
    android:id="@+id/linearLayoutMainLayout">

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

<android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/coordinatorLayoutMainLayout">

  <android.support.v4.widget.SwipeRefreshLayout
      android:id="@+id/swipeContainer"
      android:layout_width="match_parent"
      android:layout_height="match_parent"  >

    <android.support.v4.widget.NestedScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

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

         <android.support.v7.widget.CardView
   android:id="@+id/card_view"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   app:cardCornerRadius="4dp"
   app:cardElevation="4dp"
   app:cardUseCompatPadding="true">

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

      <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textStyle="bold"
        android:id="@+id/textView1" />
      <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView2" />
      <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView3" />
      <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView4" />
      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button" />

    </LinearLayout>

  </android.support.v7.widget.CardView>

         <android.support.v7.widget.RecyclerView
          android:id="@+id/recyclerView"
          android:scrollbars="vertical"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:nestedScrollingEnabled="false"/>

    </LinearLayout>

</android.support.v4.widget.NestedScrollView>

      </android.support.v4.widget.SwipeRefreshLayout>

<android.support.design.widget.FloatingActionButton
      android:id="@+id/fab"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:src="@drawable/icon_add_fab"
    android:layout_margin="15dp"/>

</android.support.design.widget.CoordinatorLayout>

</LinearLayout>


来源: stackexchange

问:
Mysql find value in multiple database (same structure)
With the plan that I have with my hosting, I have size limit for the databases, but I do not have limit in number of database.
To solve this I have thought of dividing my databases by countries and each database has the same structure.
The problem is how to look up data in all these databases.
For example, each database can have a users table.
The problem is how to find a user (for example) in all these databases. (Can be 250 of databases)

```<code>/*This would be for one database*/
SELECT user_name FROM DB1.users WHERE user_name = 'my_user_name' LIMIT 1;
</code>```

Is there any way to search 'my_user_name' from all databases ?
(Users is only one example ... the value to search can be products , city , coordinates etc etc)

答:
As long as they're on the same server you can use the inner join command:

SELECT a.userID, b.usersFirstName, b.usersLastName  FROM databaseA.dbo.TableA a inner join database B.dbo.TableB b  ON a.userID=b.userID

ContentLicense: CC BY-SA 3.0

Body:
With the plan that I have with my hosting, I have size limit for the databases, but I do not have limit in number of database.
To solve this I have thought of dividing my databases by countries and each database has the same structure.
The problem is how to look up data in all these databases.
For example, each database can have a users table.
The problem is how to find a user (for example) in all these databases. (Can be 250 of databases)

/*This would be for one database*/
SELECT user_name FROM DB1.users WHERE user_name = 'my_user_name' LIMIT 1;

Is there any way to search 'my_user_name' from all databases ?
(Users is only one example ... the value to search can be products , city , coordinates etc etc)


问:
caching sql result set in java
I know that caching the resultset of frequently used sql statements is better for the performance I am searching about the best way to cache sql result set in java. I found some codes but, it requires adding new jar files to netbeans.
Can anybody help me how can do that without needing to additional apis?</p>

答: You should cache the resulting objects, not the result sets, because the ResultSet has a reference to the connection (via the statement) which often hold an open database connection or is no longer usable after the connection has been closed!

ContentLicense: CC BY-SA 2.5

Title: caching sql result set in java


问:
Programmatically show Layout to preface an activity
What I want to do:

I want to have multiple activities each prefaced with a page explaining to the user what the activity is about.

What I'm currently doing:

So my main class BaseModuleActivity extends Activity and I am trying to write a function called showTutorial() which will explain the next steps to the users.

Here is my attempt in doing so:

```<code>public void showTutorial(String title, String explanation){
               setContentView(R.layout.tutorial_screen);
        TextView tv1 = (TextView)findViewById(R.id.tutoTextTitle);
        tv1.setText(title);

        TextView tv2 = (TextView)findViewById(R.id.tutoTextExplanation);
        tv2.setText(explanation);

        findViewById(R.id.tutoButton).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                //remove the tutorial's view
                findViewById(R.id.tutoLayout).setVisibility(View.GONE);
            }
        });
    }
</code>```

And this method is called in the following:

```<code>public class myFirstActivity extends BaseModuleActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_first);

        //First show tuto
        super.showTutorial(getString(R.string.upTitle),getString(R.string.upExplanation));

        //TODO then actually do the activity stuff
        /*
        (findViewById(R.id.next_button)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        */
    }
}
</code>```

Problem:

I think the problem is mainly conceptual. I don't know the best approach to do this and the approach I'm taking is not working.

What I'm doing is not working because the view just become empty. I thought setting the visibility of the linearLayout to gone would make it disappear and the actual activity will able to take place.

What I need:

I need to understand if I can do what I want with my approach or not? Or what approach should I take.

I found some similar questions. However, the answer to these questions didn't seem to fit my problem.

I also looked into layout inflater and fragment, but layout inflater seem to be more for listView and fragment uses layout inflater.

答:
Well, there are some approaches to show a guide for your activity (or application).

First one, and probably the easiest, is to show a dialog/TextView when user enters an activity and explain the activity guide in that dialog/TextView using plain text. From your explanation, I think this one is what your are trying to do.

Second one is to use something like slides with pictures to explain about your activity (like Google Sheets application).

Third one is to explain each control in your activity separatly by highlighting them (similar to how Go Launcher explains its feature on first launch)

You can find more info in below links:

How to implement first launch tutorial like Android Lollipop apps: Like Sheets, Slides app?

Android - first launch interactive tutorial

ContentLicense: CC BY-SA 4.0

Body:
What I want to do:

I want to have multiple activities each prefaced with a page explaining to the user what the activity is about.

What I'm currently doing:

So my main class BaseModuleActivity extends Activity and I am trying to write a function called showTutorial() which will explain the next steps to the users.

Here is my attempt in doing so:

public void showTutorial(String title, String explanation){
               setContentView(R.layout.tutorial_screen);
        TextView tv1 = (TextView)findViewById(R.id.tutoTextTitle);
        tv1.setText(title);

        TextView tv2 = (TextView)findViewById(R.id.tutoTextExplanation);
        tv2.setText(explanation);

        findViewById(R.id.tutoButton).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click
                //remove the tutorial's view
                findViewById(R.id.tutoLayout).setVisibility(View.GONE);
            }
        });
    }

And this method is called in the following:

public class myFirstActivity extends BaseModuleActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_first);

        //First show tuto
        super.showTutorial(getString(R.string.upTitle),getString(R.string.upExplanation));

        //TODO then actually do the activity stuff
        /*
        (findViewById(R.id.next_button)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        */
    }
}

Problem:

I think the problem is mainly conceptual. I don't know the best approach to do this and the approach I'm taking is not working.

What I'm doing is not working because the view just become empty. I thought setting the visibility of the linearLayout to gone would make it disappear and the actual activity will able to take place.

What I need:

I need to understand if I can do what I want with my approach or not? Or what approach should I take.

I found some similar questions. However, the answer to these questions didn't seem to fit my problem.

I also looked into layout inflater and fragment, but layout inflater seem to be more for listView and fragment uses layout inflater.


问:
Module can not be imported after installing via cabal
I tried using the primes module in Haskell and after running

```<code>$ cabal install primes

Resolving dependencies...
Notice: installing into a sandbox located at /home/christoph/.cabal-sandbox
Downloading primes-0.2.1.0...
Configuring primes-0.2.1.0...
Building primes-0.2.1.0...
Installed primes-0.2.1.0
</code>```

I tried making a file with

```<code>import Data.Numbers.Primes
</code>```

at the top, but every attempt to load it failed with the error message:

```<code>Could not find module ‘Data.Numbers.Primes’
Use -v to see a list of the files searched for.
</code>```

The question: what am I missing here? there must be something wrong with this way of using it right?

After reading Haskell: where is Data.Numbers.Primes library? I also tried:

```<code>import Data.Primes
import primes
import Primes
</code>```

but none of them worked.

Thank you in advance, any help is most welcome

答:
Because you are installing the primes package to a sandbox, you will need to run the compiler with awareness of the sandbox. cabal offers the exec command for this, so e.g.

```<code>echo import Data.Numbers.Primes >foo.hs
cabal exec ghci foo.hs
</code>```

from within the sandbox should work.

Body:
I tried using the primes module in Haskell and after running

$ cabal install primes

Resolving dependencies...
Notice: installing into a sandbox located at /home/christoph/.cabal-sandbox
Downloading primes-0.2.1.0...
Configuring primes-0.2.1.0...
Building primes-0.2.1.0...
Installed primes-0.2.1.0

I tried making a file with

import Data.Numbers.Primes

at the top, but every attempt to load it failed with the error message:

Could not find module ‘Data.Numbers.Primes’
Use -v to see a list of the files searched for.

The question: what am I missing here? there must be something wrong with this way of using it right?

After reading Haskell: where is Data.Numbers.Primes library? I also tried:

import Data.Primes
import primes
import Primes

but none of them worked.

Thank you in advance, any help is most welcome

Body:
Because you are installing the primes package to a sandbox, you will need to run the compiler with awareness of the sandbox. cabal offers the exec command for this, so e.g.

echo import Data.Numbers.Primes >foo.hs
cabal exec ghci foo.hs

from within the sandbox should work.


问:
NetLogo: getting a patch-set to exclude patches held in turtle's memory
I'm modeling territory selection in NetLogo. As a turtle builds a territory, it also builds a memory of undesirable patches (an agent-set called "blacklist"), and needs to then avoid these patches while selecting new patches for the territory. In deciding on the next patch to claim, a new patch-set is created called "available-destinations," from which "highest-value" is reported based on a couple of factors (see below). I'd like available-destinations to check whether patches are part of the turtle's blacklist, and exclude those patches. I'm having trouble figuring out how to call up the turtle's blacklist while in a patch procedure, however. Any recommendations? Thanks in advance!

Here is my main code:

```<code>patches-own
[
  owner  ;; turtle who claims patch for territory
  benefit  ;; i.e., food
  avoiding ;; turtle who is avoiding this patch
]

turtles-own
[
  start-patch  ;; my territory center
  destination  ;; my next patch to claim
  territory  ;; patches I own
  blacklist  ;; my agentset of patches to avoid
]

to pick-patch
    if patch-here = start-patch [ set destination highest-value ]
    if destination != nobody [ travel ]
end

to travel
     ;; there are a number of actions here, but the relevant one is:
     ;; check if owned, and avoid it:
     if patch-here != destination
          [ if owner != nobody  ;; if it's owned...
            [ if owner != self  ;; and not by me...
              [ avoid-obstacle
                move-to start-patch ]
            ]
          ]
end

to avoid-obstacle
     ask destination [ set avoiding myself ]
     set blacklist (patches with [avoiding = myself])
end

to-report highest-value            ;; <--- source of error since using "blacklist"
     let available-destinations edge-patches with [blacklist != myself]
     report max-one-of available-destinations ([benefit-to-me / cost-to-me])
end

to-report benefit-to-me
     report mean [benefit] of patches in-radius 2
end

to-report cost-to-me
     report distance [start-patch] of myself
end

to-report edge-patches
     report (patch-set [neighbors4] of territory) with [owner = nobody]
end
</code>```

This code results in this error from the reporter of highest-value: this code can't be run by a patch, only a turtle--error while turtle 0 running BLACKLIST. How can I fix this?

My alternative idea was as follows: use the patch-variable "avoiding":

```<code>to-report highest-value
     let available-destinations edge-patches with [avoiding != myself]
     report max-one-of available-destinations ([benefit-to-me / cost-to-me])
end
</code>```

This runs. Trouble is, as currently designed under the "avoid-obstacle" procedure, patches know avoiding as a single turtle and this gets overwritten if multiple turtles decide to avoid the patch.

So, avoiding should also be a patch-set if I am going to use it instead of the turtle's memory. I haven't been able to determine how to code it this way, however. I've tried this:

```<code>to avoid-obstacle
      ask destination
        [ let now-avoiding myself
          set avoiding (turtle-set avoiding now-avoiding) ]
      set blacklist (patch-set blacklist patches with [avoiding = myself])
end
</code>```

Avoiding does appear to become a turtle-set. The turtle's memory of blacklist never gets completed correctly, however--it stays empty. Plus, the highest-value reporter doesn't appear to exclude the patches even though the agent-set avoiding contains the turtle. So, I'm at a loss.

Conclusion: I'd prefer to go with my original method of calling up the turtle's blacklist, if there is a way to do that. In case I decide to go the alternative route, I'm also curious to know what I'm doing wrong in my idea of using "avoiding". Thanks!

And a quick related question: how can I call up an agent-set to show the list of agents within it? I'd like to do this to check that the code is working as intended. From the command center, "show [blacklist] of turtle 0" only returns "(agentset, 50 patches)" rather than the list of those 50 patches, which is what I actually want to see.

答:
Can you use member? to do what you want to exclude your patches? Eg:

```<code>to-report highest-value
     let available-destinations edge-patches with [ member? self blacklist = false ]
     report max-one-of available-destinations ([benefit-to-me / cost-to-me])
end
</code>```

I can't really test that without your setup and everything, but member? reports true if the asking agent (in this case, not the turtle but the potentially available patch) belongs to the agentset. For a simple working example, see:

```<code>to setup
  ca
  ask patches with [pxcor > 0 ] [
    set pcolor white
  ]
  crt 1
end

to go
  ask turtles [
    let blacklist patches with [ pcolor = black ]
    let northpatches patches with [ pycor > 0 ]
    let northred ( northpatches with [ member? self blacklist = false ] )
    ask northred [ set pcolor red ]
    ask northred [
      print self
    ]
  ]
end
</code>```

As far as just showing which patches are available, check out how in the above procedure, the turtle asks turtles in its agentset "northred" to print themselves to the console. That's one simple way!

Body:
I'm modeling territory selection in NetLogo. As a turtle builds a territory, it also builds a memory of undesirable patches (an agent-set called "blacklist"), and needs to then avoid these patches while selecting new patches for the territory. In deciding on the next patch to claim, a new patch-set is created called "available-destinations," from which "highest-value" is reported based on a couple of factors (see below). I'd like available-destinations to check whether patches are part of the turtle's blacklist, and exclude those patches. I'm having trouble figuring out how to call up the turtle's blacklist while in a patch procedure, however. Any recommendations? Thanks in advance!

Here is my main code:

patches-own
[
  owner  ;; turtle who claims patch for territory
  benefit  ;; i.e., food
  avoiding ;; turtle who is avoiding this patch
]

turtles-own
[
  start-patch  ;; my territory center
  destination  ;; my next patch to claim
  territory  ;; patches I own
  blacklist  ;; my agentset of patches to avoid
]

to pick-patch
    if patch-here = start-patch [ set destination highest-value ]
    if destination != nobody [ travel ]
end

to travel
     ;; there are a number of actions here, but the relevant one is:
     ;; check if owned, and avoid it:
     if patch-here != destination
          [ if owner != nobody  ;; if it's owned...
            [ if owner != self  ;; and not by me...
              [ avoid-obstacle
                move-to start-patch ]
            ]
          ]
end

to avoid-obstacle
     ask destination [ set avoiding myself ]
     set blacklist (patches with [avoiding = myself])
end

to-report highest-value            ;; <--- source of error since using "blacklist"
     let available-destinations edge-patches with [blacklist != myself]
     report max-one-of available-destinations ([benefit-to-me / cost-to-me])
end

to-report benefit-to-me
     report mean [benefit] of patches in-radius 2
end

to-report cost-to-me
     report distance [start-patch] of myself
end

to-report edge-patches
     report (patch-set [neighbors4] of territory) with [owner = nobody]
end

This code results in this error from the reporter of highest-value: this code can't be run by a patch, only a turtle--error while turtle 0 running BLACKLIST. How can I fix this?

My alternative idea was as follows: use the patch-variable "avoiding":

to-report highest-value
     let available-destinations edge-patches with [avoiding != myself]
     report max-one-of available-destinations ([benefit-to-me / cost-to-me])
end

This runs. Trouble is, as currently designed under the "avoid-obstacle" procedure, patches know avoiding as a single turtle and this gets overwritten if multiple turtles decide to avoid the patch.

So, avoiding should also be a patch-set if I am going to use it instead of the turtle's memory. I haven't been able to determine how to code it this way, however. I've tried this:

to avoid-obstacle
      ask destination
        [ let now-avoiding myself
          set avoiding (turtle-set avoiding now-avoiding) ]
      set blacklist (patch-set blacklist patches with [avoiding = myself])
end

Avoiding does appear to become a turtle-set. The turtle's memory of blacklist never gets completed correctly, however--it stays empty. Plus, the highest-value reporter doesn't appear to exclude the patches even though the agent-set avoiding contains the turtle. So, I'm at a loss.

Conclusion: I'd prefer to go with my original method of calling up the turtle's blacklist, if there is a way to do that. In case I decide to go the alternative route, I'm also curious to know what I'm doing wrong in my idea of using "avoiding". Thanks!

And a quick related question: how can I call up an agent-set to show the list of agents within it? I'd like to do this to check that the code is working as intended. From the command center, "show [blacklist] of turtle 0" only returns "(agentset, 50 patches)" rather than the list of those 50 patches, which is what I actually want to see.

Body:
Can you use member? to do what you want to exclude your patches? Eg:

to-report highest-value
     let available-destinations edge-patches with [ member? self blacklist = false ]
     report max-one-of available-destinations ([benefit-to-me / cost-to-me])
end

I can't really test that without your setup and everything, but member? reports true if the asking agent (in this case, not the turtle but the potentially available patch) belongs to the agentset. For a simple working example, see:

to setup
  ca
  ask patches with [pxcor > 0 ] [
    set pcolor white
  ]
  crt 1
end

to go
  ask turtles [
    let blacklist patches with [ pcolor = black ]
    let northpatches patches with [ pycor > 0 ]
    let northred ( northpatches with [ member? self blacklist = false ] )
    ask northred [ set pcolor red ]
    ask northred [
      print self
    ]
  ]
end

As far as just showing which patches are available, check out how in the above procedure, the turtle asks turtles in its agentset "northred" to print themselves to the console. That's one simple way!


问:
In this IronPython example what is the @ symbol doing and how is it implemented?
http://www.ironpython.info/index.php/Using_Python_Classes_from_.NET/CSharp_IP_2.6

```<code>   string code = @"
   print 'test = ' + test
   class MyClass:
       def __init__(self):
           pass

       def somemethod(self):
           print 'in some method'

       def isodd(self, n):
           return 1 == n % 2
   ";
</code>```

Is that '@' part of C# or is that something added by IronPython? If the latter, how do you do that in C#, some kind of operator overloading (basically could I then make '@' do whatever I want, etc)? Example implementation would be great. Otherwise, what's going on here?

答: The @ is part of the C# code. It means that the string is a verbatim string literal. The string holds the Python code to be executed. </p>

Body:
http://www.ironpython.info/index.php/Using_Python_Classes_from_.NET/CSharp_IP_2.6

   string code = @"
   print 'test = ' + test
   class MyClass:
       def __init__(self):
           pass

       def somemethod(self):
           print 'in some method'

       def isodd(self, n):
           return 1 == n % 2
   ";

Is that '@' part of C# or is that something added by IronPython? If the latter, how do you do that in C#, some kind of operator overloading (basically could I then make '@' do whatever I want, etc)? Example implementation would be great. Otherwise, what's going on here?


问:
Learning SQL: Need help Using HAVING to get the MIN result from an aggregate
was hoping to get some help. New to SQL and trying to keep my head on straight.

I've been given this assignment:

"Using HAVING, determine whose Direct Reports have the lowest Avg Salary."

My logic was to make a join on a derived table that would calculate the AVG salary of the crew for each Manager that had direct reports. This result would then get filtered to the MIN value by a HAVING clause.

```<code>SELECT Flash.firstname, Flash.lastname, Wally.AVGSalary,
       Wally.[Direct Reports] FROM CrewMembers Flash
    JOIN
    (
        SELECT Barry.crewMemberId, AVG(Zoom.salary) AS 'AVGSalary', COUNT(Zoom.firstname) AS 'Direct Reports'
                    FROM CrewMembers Barry
            JOIN CrewMembers Zoom
                           ON Zoom.managerId = Barry.crewMemberId
        GROUP BY Barry.crewMemberId
    )
    AS Wally ON Wally.crewMemberId = Flash.crewMemberId

GROUP BY Flash.firstname, Flash.lastname, Wally.AVGSalary, Wally.[Direct Reports]

HAVING MIN(Wally.AVGSalary) in (Wally.AVGSalary)

ORDER BY Wally.AVGSalary asc
</code>```

I'm getting this result:

```<code>firstname   lastname    AVGSalary   Direct Reports
Mike        Patton      33666.500000    2
Kurt        Corgan      37300.000000    2
Amber       Bruckner    45851.666666    3
Doug        Adams       86250.000000    2
Montgomery  Scott       92500.000000    2
James       Kirk        132666.750000   3
</code>```

I'm stumped. I need it to give me JUST the row with the minimum value and it's giving me every value. I've stared at this and can't figure out what I'm doing wrong.

I know, from looking at threads online, that using TOP is a way to filter items, but that hasn't been introduced yet and I'd like to stay within the parameters that have been established in the course so far.

Any critique of what I've written or any help would be awesome. Like I said, I'm new and just trying to keep up.

Thanks,

J

答:
You'll need another subquery (if you dont want use top/window function/etc):

```<code>select Flash.firstname,
    Flash.lastname,
    Wally.AVGSalary,
    Wally.[Direct Reports]
from CrewMembers Flash
join (
    select Barry.crewMemberId,
        AVG(Zoom.salary) as 'AVGSalary',
        COUNT(Zoom.firstname) as 'Direct Reports'
    from CrewMembers Barry
    join CrewMembers Zoom on Zoom.managerId = Barry.crewMemberId
    group by Barry.crewMemberId
    having avg(Zoom.salary) = (
            select min(salary)
            from (
                select AVG(Zoom.salary) as salary
                from CrewMembers Barry
                join CrewMembers Zoom on Zoom.managerId = Barry.crewMemberId
                group by Barry.crewMemberId
                ) t
            )
    ) as Wally on Wally.crewMemberId = Flash.crewMemberId
</code>```

You can use top:

```<code>select top 1 Flash.firstname,
    Flash.lastname,
    Wally.AVGSalary,
    Wally.[Direct Reports]
from CrewMembers Flash
join (
    select Barry.crewMemberId,
        AVG(Zoom.salary) as 'AVGSalary',
        COUNT(Zoom.firstname) as 'Direct Reports'
    from CrewMembers Barry
    join CrewMembers Zoom on Zoom.managerId = Barry.crewMemberId
    group by Barry.crewMemberId
    ) as Wally on Wally.crewMemberId = Flash.crewMemberId
order by Wally.AVGSalary
</code>```

Another way is using window function rank:

```<code>select Flash.firstname,
    Flash.lastname,
    Wally.AVGSalary,
    Wally.[Direct Reports]
from CrewMembers Flash
join (
    select Barry.crewMemberId,
        AVG(Zoom.salary) as 'AVGSalary',
        COUNT(Zoom.firstname) as 'Direct Reports',
        rank() over (order by AVG(Zoom.salary)) as rnk
    from CrewMembers Barry
    join CrewMembers Zoom on Zoom.managerId = Barry.crewMemberId
    group by Barry.crewMemberId
    ) as Wally on Wally.crewMemberId = Flash.crewMemberId
where Wally.rnk = 1;
</code>```

Body:
was hoping to get some help. New to SQL and trying to keep my head on straight.

I've been given this assignment:

"Using HAVING, determine whose Direct Reports have the lowest Avg Salary."

My logic was to make a join on a derived table that would calculate the AVG salary of the crew for each Manager that had direct reports. This result would then get filtered to the MIN value by a HAVING clause.

SELECT Flash.firstname, Flash.lastname, Wally.AVGSalary,
       Wally.[Direct Reports] FROM CrewMembers Flash
    JOIN
    (
        SELECT Barry.crewMemberId, AVG(Zoom.salary) AS 'AVGSalary', COUNT(Zoom.firstname) AS 'Direct Reports'
                    FROM CrewMembers Barry
            JOIN CrewMembers Zoom
                           ON Zoom.managerId = Barry.crewMemberId
        GROUP BY Barry.crewMemberId
    )
    AS Wally ON Wally.crewMemberId = Flash.crewMemberId

GROUP BY Flash.firstname, Flash.lastname, Wally.AVGSalary, Wally.[Direct Reports]

HAVING MIN(Wally.AVGSalary) in (Wally.AVGSalary)

ORDER BY Wally.AVGSalary asc

I'm getting this result:

firstname   lastname    AVGSalary   Direct Reports
Mike        Patton      33666.500000    2
Kurt        Corgan      37300.000000    2
Amber       Bruckner    45851.666666    3
Doug        Adams       86250.000000    2
Montgomery  Scott       92500.000000    2
James       Kirk        132666.750000   3

I'm stumped. I need it to give me JUST the row with the minimum value and it's giving me every value. I've stared at this and can't figure out what I'm doing wrong.

I know, from looking at threads online, that using TOP is a way to filter items, but that hasn't been introduced yet and I'd like to stay within the parameters that have been established in the course so far.

Any critique of what I've written or any help would be awesome. Like I said, I'm new and just trying to keep up.

Thanks,

J

Body:
You'll need another subquery (if you dont want use top/window function/etc):

select Flash.firstname,
    Flash.lastname,
    Wally.AVGSalary,
    Wally.[Direct Reports]
from CrewMembers Flash
join (
    select Barry.crewMemberId,
        AVG(Zoom.salary) as 'AVGSalary',
        COUNT(Zoom.firstname) as 'Direct Reports'
    from CrewMembers Barry
    join CrewMembers Zoom on Zoom.managerId = Barry.crewMemberId
    group by Barry.crewMemberId
    having avg(Zoom.salary) = (
            select min(salary)
            from (
                select AVG(Zoom.salary) as salary
                from CrewMembers Barry
                join CrewMembers Zoom on Zoom.managerId = Barry.crewMemberId
                group by Barry.crewMemberId
                ) t
            )
    ) as Wally on Wally.crewMemberId = Flash.crewMemberId

You can use top:

select top 1 Flash.firstname,
    Flash.lastname,
    Wally.AVGSalary,
    Wally.[Direct Reports]
from CrewMembers Flash
join (
    select Barry.crewMemberId,
        AVG(Zoom.salary) as 'AVGSalary',
        COUNT(Zoom.firstname) as 'Direct Reports'
    from CrewMembers Barry
    join CrewMembers Zoom on Zoom.managerId = Barry.crewMemberId
    group by Barry.crewMemberId
    ) as Wally on Wally.crewMemberId = Flash.crewMemberId
order by Wally.AVGSalary

Another way is using window function rank:

select Flash.firstname,
    Flash.lastname,
    Wally.AVGSalary,
    Wally.[Direct Reports]
from CrewMembers Flash
join (
    select Barry.crewMemberId,
        AVG(Zoom.salary) as 'AVGSalary',
        COUNT(Zoom.firstname) as 'Direct Reports',
        rank() over (order by AVG(Zoom.salary)) as rnk
    from CrewMembers Barry
    join CrewMembers Zoom on Zoom.managerId = Barry.crewMemberId
    group by Barry.crewMemberId
    ) as Wally on Wally.crewMemberId = Flash.crewMemberId
where Wally.rnk = 1;


问:
How to replace numbers in a div?
With the following code, I'm getting the values of "id"(almost 35), and then add 1 to each "id", so 1 will be 2 and so on. Where I'm stock, it is on how to replace that id number in the html.

This is the code that use to get the values of each id, then I push them into an array, then I run another "for loop" to add 1 to each value, but I don't how to return them to the html.

var x = document.getElementsByClassName('p-divs');

var portfolio = new Array;

for (var i = 0; i < x.length; i++)
{
    var y = document.getElementsByClassName('p-divs')[i].getAttribute('id');
    portfolio.push(y);
}

console.log(portfolio);

var portfolio2 = new Array;

for (var i = 0; i<portfolio.length; i++)
{
    var newId;
    newId = parseInt(portfolio[i]) + 1;

    portfolio2.push(newId);
}

console.log(portfolio2);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 p-divs" id="1">
  <div class="portfolio">
    <center>
      <img src="images/pace.png" width="230" height="190" alt="" class="img-responsive">
    </center>
  </div>
</div></code>```

答:
```<code>  var j = document.getElementsByClassName('p-divs');
    for (var i = 0; i < x.length; i++) {
      j[i].id = portfolio2[i];
    }
</code>```

Add this to the end of your code. Vanilla JS.

j will be an array of your divs, i will keep count of which div we're on, and we are simply accessing the "id" of each element in the "j" array and updating it to the corresponding value in your pre-populated "portfolio2" array.

Hope this helps!

P.S.- I would also recommend that instead of using 'new Array' to instantiate your arrays, you use the array literal notation '[]'. This is more concise and also avoids needing to put (); after Array.

Title: How to replace numbers in a div?

Body:
  var j = document.getElementsByClassName('p-divs');
    for (var i = 0; i < x.length; i++) {
      j[i].id = portfolio2[i];
    }

Add this to the end of your code. Vanilla JS.

j will be an array of your divs, i will keep count of which div we're on, and we are simply accessing the "id" of each element in the "j" array and updating it to the corresponding value in your pre-populated "portfolio2" array.

Hope this helps!

P.S.- I would also recommend that instead of using 'new Array' to instantiate your arrays, you use the array literal notation '[]'. This is more concise and also avoids needing to put (); after Array.


问:
Efficient algorithm for writing several bits across several words
One of my projects involves drawing text. The project is based around a mid-level 16-bit microcontroller, a dsPIC33FJ128GP802. It is capable of 40 MIPS, but about 92% of that is reserved for background processing (outputting an on screen display), so on average it gets 3 MIPS to render stuff. The processor has hardware multiply, assisted divide (18 cycles) and a full 16-bit barrel shifter.

The original method was simple. It just called the set pixel routine for each pixel that needed to be written, however, this is quite slow: each pixel write requires an address decode, bit mask, and write to memory - on average, around 60 cycles per pixel. Also, two bits need to be written for each pixel to be set: one in the mask array (which determines if the pixel is visible or not), and one in the level array (which determines if the pixel is white or black.) For a single character, 8x14 pixels, this means 13,440 cycles plus overhead. Which is a lot, given the lack of much processing power.

Because of this, I came up with an algorithm for drawing horizontal lines. It could efficiently write up to 16 pixels in about 20 cycles, which is a 60 fold improvement on setting pixels individually; it could also handle lines which did not lie on word boundaries (using some clever bit math), and even lines which lie entirely inside one word. (Note - one word is 16 bits and the video memory is stored as an 4 arrays of 3,072 words, a front buffer and back buffer.) I'm not certain if the algorithm is original - I doubt it - but for those curious, I've documented it here.

Now I'm racking my brains out trying to figure out a way to set multiple distinct pixels across multiple words. Ideally, it would work like this - we want to write this word starting at bit 4 (bits counted from zero) of the first word and allow it to overflow into the next:

```<code>Memory before : 0000 0000 0000 0000   0000 0000 0000 0000
Word to write : 1111 1010 1111 1111
Memory after  : 0000 0111 1101 0111   1111 1000 0000 0000
</code>```

If anyone knows of any such algorithm or has done something in the past similar to this it would be great to know how you did it. I'm having a major brain block right now.

答:
In the days before sophisticated graphics accelerators, people hid whatever they could implement behind an interface such as bitblt. There is a quick write-up of one example of this in passing at http://swtch.com/~rsc/talks/drawtalk.pdf Some of these worked by auto-generating and then executing machine code. The approach from that paper is described as "Effectively, the draw implementation is the above with
enough conditionals and function calls pushed outside
enough loops to make the overhead bearable." One version I saw was quite long, with a variety of common special cases extracted "fast paths".</p>

Body:
One of my projects involves drawing text. The project is based around a mid-level 16-bit microcontroller, a dsPIC33FJ128GP802. It is capable of 40 MIPS, but about 92% of that is reserved for background processing (outputting an on screen display), so on average it gets 3 MIPS to render stuff. The processor has hardware multiply, assisted divide (18 cycles) and a full 16-bit barrel shifter.

The original method was simple. It just called the set pixel routine for each pixel that needed to be written, however, this is quite slow: each pixel write requires an address decode, bit mask, and write to memory - on average, around 60 cycles per pixel. Also, two bits need to be written for each pixel to be set: one in the mask array (which determines if the pixel is visible or not), and one in the level array (which determines if the pixel is white or black.) For a single character, 8x14 pixels, this means 13,440 cycles plus overhead. Which is a lot, given the lack of much processing power.

Because of this, I came up with an algorithm for drawing horizontal lines. It could efficiently write up to 16 pixels in about 20 cycles, which is a 60 fold improvement on setting pixels individually; it could also handle lines which did not lie on word boundaries (using some clever bit math), and even lines which lie entirely inside one word. (Note - one word is 16 bits and the video memory is stored as an 4 arrays of 3,072 words, a front buffer and back buffer.) I'm not certain if the algorithm is original - I doubt it - but for those curious, I've documented it here.

Now I'm racking my brains out trying to figure out a way to set multiple distinct pixels across multiple words. Ideally, it would work like this - we want to write this word starting at bit 4 (bits counted from zero) of the first word and allow it to overflow into the next:

Memory before : 0000 0000 0000 0000   0000 0000 0000 0000
Word to write : 1111 1010 1111 1111
Memory after  : 0000 0111 1101 0111   1111 1000 0000 0000

If anyone knows of any such algorithm or has done something in the past similar to this it would be great to know how you did it. I'm having a major brain block right now.


问:
Integration with OneNote 2016 desktop version
We tried to manage the authentication in federated mode via WS-Federation protocol. In this case it seems that OneNote includes,  Internet Explorer 7  browser to redirect the user towards the passive endpoint of STS, instead of the active endpoint, do you why ?

We’re working also on a connection of our application via ADFS, and we’ve done it thru the passive endpoint of ADFS.
Should we use the active endpoint ADFS ? Why this is not the solution for OneNote ?

In standard cases the authentication is based on usage of browser Web storage that is supported only from IE8 . Why is it so?

Thanks

Eric Vernié

答:
Office SharePoint where you are storing OneNote uses MSOFBA protocol which is a passive protocol that transitions to WS-Fed via a browser dialog. This is different in SPO and potentially different in some future updates to SP2016.

Thanks
//Sam


问:
How to find whether a given commit is on the first-parent chain of a branch
I'm trying to script a way to tell if a given commit is on the first-parent chain of a given branch.  So, for example, merge-base won't fly, as the commit might have been merged in.  I want to know whether the exact commit was ever the tip of the branch.

Note: The branch in question is subject to a no-fast-forward merge strategy.

答:
The no-fast-forward strategy means you can probably grep in git log --first-parent. You probably want only the hashes, so you can use git rev-list instead

```<code>git rev-list --first-parent | grep <commit hash>
</code>```

Otherwise use --format with git log to display the data you want.

Edit: This post could give you some ideas

How can I tell if one commit is an ancestor of another commit (or vice-versa)?

Body:
The no-fast-forward strategy means you can probably grep in git log --first-parent. You probably want only the hashes, so you can use git rev-list instead

git rev-list --first-parent | grep <commit hash>

Otherwise use --format with git log to display the data you want.

Edit: This post could give you some ideas

How can I tell if one commit is an ancestor of another commit (or vice-versa)?


答:
A few things:

$('.sortable') captures nothing.

You want scrollLeft, not left. left refers to the object's position's offset, i.e. it will move the item right by the left value.

You don't need suffix px for the move value.

You don't need guard the animation because it will never scroll past the limits.

Here's the code:

https://jsfiddle.net/cm014krh/5/

Title: Click function to scroll div not working

Body:
Here is the jfiddle of code I have that is suppose to move the div (50px right now) when the right arrow button is clicked. However, I seem to be missing something as it will not scroll when I push the button.  Using chrome inspect I see that the javascript is being executed with 'view' being 15px

https://jsfiddle.net/cm014krh/1/

HTML:

  <svg width="32" height="32" viewBox="0 0 32 32" id="carousel_arrow" x="287" y="384.561">
    <path d="M16 0c8.836 0 16 7.164 16 16s-7.164 16-16 16S0 24.836 0 16 7.164 0 16 0zm0 29c7.168 0 13-5.832 13-13S23.168 3 16 3 3 8.832 3 16s5.832 13 13 13zM13.5 9c.39 0 .743.153 1.01.398l.004-.003 6 5.5a1.5 1.5 0 0 1 0 2.21l-6 5.5-.003-.003c-.267.245-.62.398-1.01.398a1.5 1.5 0 0 1-1.5-1.5c0-.438.19-.828.49-1.102l-.004-.003L17.28 16l-4.794-4.395.003-.003A1.49 1.49 0 0 1 12 10.5 1.5 1.5 0 0 1 13.5 9z"
    fill="#818091" fill-rule="evenodd" />
  </svg>

  <svg width="32" height="32" viewBox="0 0 32 32" id="carousel_arrow" x="287" y="384.561">
    <path d="M16 0c8.836 0 16 7.164 16 16s-7.164 16-16 16S0 24.836 0 16 7.164 0 16 0zm0 29c7.168 0 13-5.832 13-13S23.168 3 16 3 3 8.832 3 16s5.832 13 13 13zM13.5 9c.39 0 .743.153 1.01.398l.004-.003 6 5.5a1.5 1.5 0 0 1 0 2.21l-6 5.5-.003-.003c-.267.245-.62.398-1.01.398a1.5 1.5 0 0 1-1.5-1.5c0-.438.19-.828.49-1.102l-.004-.003L17.28 16l-4.794-4.395.003-.003A1.49 1.49 0 0 1 12 10.5 1.5 1.5 0 0 1 13.5 9z"
    fill="#818091" fill-rule="evenodd" />
  </svg>

CSS:

.sortable {
  min-width: 729px;
}

.sortable-outer {
  overflow-x: scroll;
}

.pc-row {
  width: 1750px;
}

.pc-col-xs-4 {
  width: 320px;
  margin-right: 30px;
  float: left;
  height: 100px;
  background-color: red;
}

.left-arrow-button {
  transform: rotate(180deg);
}

.left-arrow-button:hover, .right-arrow-button:hover {
  background-color: yellow;
}

and the javascript:

$('.right-arrow-button').click(function() {
  var view = $('.sortable');
  var move = "50px";
  var sliderLimit = -234;

  var currentPosition = parseInt($('.sortable').offset().left);
  if (currentPosition >= sliderLimit) $('.sortable').stop(false, true).animate({
    left: "-=" + move
  }, {
    duration: 400
  });
});


问:
Cannot send request to MQSeries service
Im trying to send request with such code

```<code>import com.ibm.mq.jms.*;
import com.ibm.msg.client.wmq.WMQConstants;

import javax.jms.Session;
import javax.jms.TextMessage;

public class MQSend {
  public static void main(String[] args)
    {
            try {
            MQQueueConnectionFactory cf = new MQQueueConnectionFactory();
            cf.setHostName("blabla");
            cf.setPort(15000);

            cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);

            cf.setQueueManager("");
            cf.setChannel("blabla");

            MQQueueConnection connection = (MQQueueConnection) cf.createQueueConnection("blabla","blabla");

            MQQueueSession session = (MQQueueSession) connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            MQQueue queue = (MQQueue) session.createQueue("blabla");

            MQQueueSender sender =  (MQQueueSender) session.createSender(queue);

            long uniqueNumber = System.currentTimeMillis() % 1000;

            TextMessage message = (TextMessage) session.createTextMessage("Basic Queue Test "+ uniqueNumber);

            // Start the connection
            connection.start();
       //     sender.send(message);

            System.out.println("Sent message to Queue MyTestQueue: " + message.getText());
        //   sender.close();
            session.close();
            connection.close();
            System.out.println("Message Sent OK.\n");
        }

        catch (Exception ex) {
            System.out.println(ex);
            System.out.println("Message Send Failure\n");
        }
    }
}
</code>```

I got

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: com/ibm/msg/client/commonservices/trace/Trace
at com.ibm.msg.client.jms.internal.JmsReadablePropertyContextImpl.<clinit>(JmsReadablePropertyContextImpl.java:51)
at com.hsbc.hbfr.test.automation.tools.jrb.plugins.itm.MQSend.main(MQSend.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException: com.ibm.msg.client.commonservices.trace.Trace
</code>```

So issue is that java can't get appropriate jar for com/ibm/msg/client/commonservices/trace/Trace
But I even don't use such dependency in code, any suggestions?
thanks

答: Did you install MQ Client on the server?  Did you put ALL of the MQ jar files in the CLASSPATH as per the docs?  Looks like you missed at least one.</p>

Title: Cannot send request to MQSeries service

Body:
Im trying to send request with such code

import com.ibm.mq.jms.*;
import com.ibm.msg.client.wmq.WMQConstants;

import javax.jms.Session;
import javax.jms.TextMessage;

public class MQSend {
  public static void main(String[] args)
    {
            try {
            MQQueueConnectionFactory cf = new MQQueueConnectionFactory();
            cf.setHostName("blabla");
            cf.setPort(15000);

            cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);

            cf.setQueueManager("");
            cf.setChannel("blabla");

            MQQueueConnection connection = (MQQueueConnection) cf.createQueueConnection("blabla","blabla");

            MQQueueSession session = (MQQueueSession) connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            MQQueue queue = (MQQueue) session.createQueue("blabla");

            MQQueueSender sender =  (MQQueueSender) session.createSender(queue);

            long uniqueNumber = System.currentTimeMillis() % 1000;

            TextMessage message = (TextMessage) session.createTextMessage("Basic Queue Test "+ uniqueNumber);

            // Start the connection
            connection.start();
       //     sender.send(message);

            System.out.println("Sent message to Queue MyTestQueue: " + message.getText());
        //   sender.close();
            session.close();
            connection.close();
            System.out.println("Message Sent OK.\n");
        }

        catch (Exception ex) {
            System.out.println(ex);
            System.out.println("Message Send Failure\n");
        }
    }
}

I got

Exception in thread "main" java.lang.NoClassDefFoundError: com/ibm/msg/client/commonservices/trace/Trace
at com.ibm.msg.client.jms.internal.JmsReadablePropertyContextImpl.<clinit>(JmsReadablePropertyContextImpl.java:51)
at com.hsbc.hbfr.test.automation.tools.jrb.plugins.itm.MQSend.main(MQSend.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException: com.ibm.msg.client.commonservices.trace.Trace

So issue is that java can't get appropriate jar for com/ibm/msg/client/commonservices/trace/Trace
But I even don't use such dependency in code, any suggestions?
thanks


问:
Terraform ebs volume
I am new to terraform,  have created 3 ec2 instances, and i have created 6 ebs volume. How do we attach 2 ebs volumes to each of the three instances?

```<code>#Create 6 EBS volumes and attach 2 per instance.
resource "aws_ebs_volume" "vertica_ebs" {
        count                           = "6"
        availability_zone               = "${var.availability_zone}"
        size                            = "500"
        type                            = "st1"

       }
    }

#Attach ebs volume
resource "aws_volume_attachment" "ebs_att" {
     count = "6"
volume {
     device_name = "/dev/sdf"
     volume_id = "[${element(aws_ebs_volume.vertica_ebs.*.id, count.index)}]"
}
volume{
     device_name = "/dev/sdg"
     volume_id = "[${element(aws_ebs_volume.vertica_ebs.*.id, count.index)}]"
}
     instance_id = "[${element(aws_instance.vertica1.*.id,count.index)}]"
}
</code>```

Errors:

aws_volume_attachment.ebs_att #2: "device_name": required field is not set

aws_volume_attachment.ebs_att #2: "volume_id": required field is not set

aws_volume_attachment.ebs_att #2: : invalid or unknown key: volume

aws_volume_attachment.ebs_att #4: "device_name": required field is not set

aws_volume_attachment.ebs_att #4: "volume_id": required field is not set

aws_volume_attachment.ebs_att #4: : invalid or unknown key: volume

aws_volume_attachment.ebs_att #3: "device_name": required field is not set

aws_volume_attachment.ebs_att #3: "volume_id": required field is not set

aws_volume_attachment.ebs_att #3: : invalid or unknown key: volume

aws_volume_attachment.ebs_att #0: "volume_id": required field is not set

aws_volume_attachment.ebs_att #0: "device_name": required field is not set

aws_volume_attachment.ebs_att #0: : invalid or unknown key: volume

aws_volume_attachment.ebs_att #1: "device_name": required field is not set

aws_volume_attachment.ebs_att #1: "volume_id": required field is not set

aws_volume_attachment.ebs_att #1: : invalid or unknown key: volume

aws_volume_attachment.ebs_att #5: "volume_id": required field is not set

aws_volume_attachment.ebs_att #5: "device_name": required field is not set

aws_volume_attachment.ebs_att #5: : invalid or unknown key: volume

答:
Note: this method will destroy and recreate the servers.  Use 'aws volume attachment' method if this is unacceptable to you.

One way to approach this problem, and how I would solve it, is to attach the ebs volumes directly to the instance resource.

You can do this by adding an 'ebs_block_device' element to each server configuration, then running terraform apply.  For example, each server resource you wished to add 2 ebs block devices to, would look like:

```<code>resource "aws_instance""example_instance"{
#INSTANCE CONFIGURATION VALUES
    ebs_block_device{
      device_name = "/dev/sdf"
      volume_size = 500
      volume_type = "st1"
    }
    ebs_block_device{
      device_name = "/dev/sdg"
      volume_size = 500
      volume_type = "st1"
    }
}
</code>```

Then run terraform plan, see that the block devices will be added to the servers and the servers.  Using this method, the servers WILL BE DESTROYED AND RECREATED. If this is acceptable, run terraform apply to rebuild the servers with the additional volumes.

Check out the documentation around ebs_block_device and aws_instance here.

Title: Terraform ebs volume

Body:
I am new to terraform,  have created 3 ec2 instances, and i have created 6 ebs volume. How do we attach 2 ebs volumes to each of the three instances?

#Create 6 EBS volumes and attach 2 per instance.
resource "aws_ebs_volume" "vertica_ebs" {
        count                           = "6"
        availability_zone               = "${var.availability_zone}"
        size                            = "500"
        type                            = "st1"

       }
    }

#Attach ebs volume
resource "aws_volume_attachment" "ebs_att" {
     count = "6"
volume {
     device_name = "/dev/sdf"
     volume_id = "[${element(aws_ebs_volume.vertica_ebs.*.id, count.index)}]"
}
volume{
     device_name = "/dev/sdg"
     volume_id = "[${element(aws_ebs_volume.vertica_ebs.*.id, count.index)}]"
}
     instance_id = "[${element(aws_instance.vertica1.*.id,count.index)}]"
}

Errors:

aws_volume_attachment.ebs_att #2: "device_name": required field is not set

aws_volume_attachment.ebs_att #2: "volume_id": required field is not set

aws_volume_attachment.ebs_att #2: : invalid or unknown key: volume

aws_volume_attachment.ebs_att #4: "device_name": required field is not set

aws_volume_attachment.ebs_att #4: "volume_id": required field is not set

aws_volume_attachment.ebs_att #4: : invalid or unknown key: volume

aws_volume_attachment.ebs_att #3: "device_name": required field is not set

aws_volume_attachment.ebs_att #3: "volume_id": required field is not set

aws_volume_attachment.ebs_att #3: : invalid or unknown key: volume

aws_volume_attachment.ebs_att #0: "volume_id": required field is not set

aws_volume_attachment.ebs_att #0: "device_name": required field is not set

aws_volume_attachment.ebs_att #0: : invalid or unknown key: volume

aws_volume_attachment.ebs_att #1: "device_name": required field is not set

aws_volume_attachment.ebs_att #1: "volume_id": required field is not set

aws_volume_attachment.ebs_att #1: : invalid or unknown key: volume

aws_volume_attachment.ebs_att #5: "volume_id": required field is not set

aws_volume_attachment.ebs_att #5: "device_name": required field is not set

aws_volume_attachment.ebs_att #5: : invalid or unknown key: volume

Body:
Note: this method will destroy and recreate the servers.  Use 'aws volume attachment' method if this is unacceptable to you.

One way to approach this problem, and how I would solve it, is to attach the ebs volumes directly to the instance resource.

You can do this by adding an 'ebs_block_device' element to each server configuration, then running terraform apply.  For example, each server resource you wished to add 2 ebs block devices to, would look like:

resource "aws_instance""example_instance"{
#INSTANCE CONFIGURATION VALUES
    ebs_block_device{
      device_name = "/dev/sdf"
      volume_size = 500
      volume_type = "st1"
    }
    ebs_block_device{
      device_name = "/dev/sdg"
      volume_size = 500
      volume_type = "st1"
    }
}

Then run terraform plan, see that the block devices will be added to the servers and the servers.  Using this method, the servers WILL BE DESTROYED AND RECREATED. If this is acceptable, run terraform apply to rebuild the servers with the additional volumes.

Check out the documentation around ebs_block_device and aws_instance here.


问:
How to login into Gmail to make an HTTP request using Google AppScript
I have the following code to erase some drafts using the method described here using a HTTP request:

```<code>function cleanUp2() {
  var threads = GmailApp.search("in:trash is:draft");
  Logger.log(threads.length);

  var userId = 'xxxx@gmail.com';
  var options = {
   'method' : 'delete',
   'muteHttpExceptions': true
 };

  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    Logger.log(messages.length);

    for (var j = 0; j < messages.length; j++){
      if (messages[j].isDraft()){
        Logger.log('id msg: ' + messages[j].getId());
        var url = 'https://www.googleapis.com/gmail/v1/users/' + userId + '/messages/' + messages[j].getId();
        var response = UrlFetchApp.fetch(url,options);
        Logger.log(response);
      }
    }
  }
}
</code>```

However, the response of the fetch is the following:

```<code>{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}
</code>```

So my question is how do I login into Gmail to get the HTTP request working?

答:
You need to send an authorization header in your request like so:

```<code>//Code above this remains the same
    var userId = 'kurokirasama@gmail.com';
      var options = {
       'headers':{'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
       'method' : 'DELETE',
       'muteHttpExceptions': true
     };
//the code below remains the same
</code>```

Note ScriptApp.getOAuthToken() works here because you have GmailApp call made by your script, so your script has the token to access GMAIL API. If don't make a call to GmailApp in the script, the token will not have scope to access your Gmail.

Alternatively, you can use advanced services in App scripts; Resoruces>Advance Services > Gmail APi (on) and use the below code to achieve the same result:

```<code>function cleanUp2() {
  var threads = GmailApp.search("in:trash is:draft");
  Logger.log(threads.length);

  var userId = 'kurokirasama@gmail.com';

  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    Logger.log(messages.length);

    for (var j = 0; j < messages.length; j++){
      if (messages[j].isDraft()){
        Logger.log('id msg: ' + messages[j].getId());
        Gmail.Users.Messages.trash(userId, messages[j].getId())
        Logger.log(response);
      }
    }
  }
}
</code>```

Hope this helps!

Body:
I have the following code to erase some drafts using the method described here using a HTTP request:

function cleanUp2() {
  var threads = GmailApp.search("in:trash is:draft");
  Logger.log(threads.length);

  var userId = 'xxxx@gmail.com';
  var options = {
   'method' : 'delete',
   'muteHttpExceptions': true
 };

  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    Logger.log(messages.length);

    for (var j = 0; j < messages.length; j++){
      if (messages[j].isDraft()){
        Logger.log('id msg: ' + messages[j].getId());
        var url = 'https://www.googleapis.com/gmail/v1/users/' + userId + '/messages/' + messages[j].getId();
        var response = UrlFetchApp.fetch(url,options);
        Logger.log(response);
      }
    }
  }
}

However, the response of the fetch is the following:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Login Required",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Login Required"
 }
}

So my question is how do I login into Gmail to get the HTTP request working?

Body:
You need to send an authorization header in your request like so:

//Code above this remains the same
    var userId = 'kurokirasama@gmail.com';
      var options = {
       'headers':{'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
       'method' : 'DELETE',
       'muteHttpExceptions': true
     };
//the code below remains the same

Note ScriptApp.getOAuthToken() works here because you have GmailApp call made by your script, so your script has the token to access GMAIL API. If don't make a call to GmailApp in the script, the token will not have scope to access your Gmail.

Alternatively, you can use advanced services in App scripts; Resoruces>Advance Services > Gmail APi (on) and use the below code to achieve the same result:

function cleanUp2() {
  var threads = GmailApp.search("in:trash is:draft");
  Logger.log(threads.length);

  var userId = 'kurokirasama@gmail.com';

  for (var i = 0; i < threads.length; i++) {
    var messages = threads[i].getMessages();
    Logger.log(messages.length);

    for (var j = 0; j < messages.length; j++){
      if (messages[j].isDraft()){
        Logger.log('id msg: ' + messages[j].getId());
        Gmail.Users.Messages.trash(userId, messages[j].getId())
        Logger.log(response);
      }
    }
  }
}

Hope this helps!


问:
Show error message under another using a Directive. Angular.js
I'm doing a validation on a directive, forcing the user to check the box. If the checkbox is not marked, an error message appears. My problem is that the message shifts to the text of the checkbox.

```<code>style="margin-top:5px;color:red;"
</code>```

I need the validation message at the end of the checkbox.But I do not want it to affect the presentation or that this message is above other elements.

```<code>style="position: absolute;margin-top:5px;color:red;"
</code>```

I need to do this in the directive, I do not want to touch controller or template. How can do it?

```<code>    app.directive('validate', function ($timeout) {

        return {
            restrict: 'AE',
            require: 'ngModel',

            link: function (scope, element, attrs, ngModel) {
              if (!ngModel){
                return;
              }
              ngModel.$setValidity('validation', false);

              scope.directive_function= function(){
                alert("directive function");
              }

              ngModel.$parsers.push(function(val){
                if(val==true){
                  ngModel.$setValidity('validation', true);
                  var elemento_eliminar=(angular.element((document.getElementById('errorchec' ))));
                  elemento_eliminar.remove();
                }else{
                 ngModel.$setValidity('validation', false);
                 var newDirective = angular.element('<div id="errorchec" class="span_wrong" style="margin-top:5px;color:red;">'+"must be required"+'</div>');
                 //style="position: absolute;margin-top:5px;color:red;"
                element.after(newDirective);
                }
              })
           }

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

http://jsfiddle.net/2kt4ukcx/

答: If it's right solution for you, it works     style="position:absolute; top:5px;color:red;

Body:
I'm doing a validation on a directive, forcing the user to check the box. If the checkbox is not marked, an error message appears. My problem is that the message shifts to the text of the checkbox.

style="margin-top:5px;color:red;"

I need the validation message at the end of the checkbox.But I do not want it to affect the presentation or that this message is above other elements.

style="position: absolute;margin-top:5px;color:red;"

I need to do this in the directive, I do not want to touch controller or template. How can do it?

    app.directive('validate', function ($timeout) {

        return {
            restrict: 'AE',
            require: 'ngModel',

            link: function (scope, element, attrs, ngModel) {
              if (!ngModel){
                return;
              }
              ngModel.$setValidity('validation', false);

              scope.directive_function= function(){
                alert("directive function");
              }

              ngModel.$parsers.push(function(val){
                if(val==true){
                  ngModel.$setValidity('validation', true);
                  var elemento_eliminar=(angular.element((document.getElementById('errorchec' ))));
                  elemento_eliminar.remove();
                }else{
                 ngModel.$setValidity('validation', false);
                 var newDirective = angular.element('
'+"must be required"+'
');
                 //style="position: absolute;margin-top:5px;color:red;"
                element.after(newDirective);
                }
              })
           }

        };
    });

http://jsfiddle.net/2kt4ukcx/


问:
How to only make one legend name italic in base R plot?
I want to add a legend to a plot in which only one of the legend names is italicized. I'm using plot() in base R.

However, I need that italicized line to contain variable numbers, so I use bquote.

What I've tried does not work:

```<code>  a <- 2 ; b <- 5
  plot(a,b)
  l1 <- bquote(Italic ~ .(a) + .(b))
  l2 <- bquote(a + b)
  legend(x='topright',legend = bquote(italic(.(l1))))
  legend(x='topleft',legend = c(bquote(italic(.(l1))),l2))
</code>```

Notice that when I leave the expression on its own (RIGHT LEGEND), it italicizes correctly. However, when I add the text for other legend lines, it messes up (LEFT LEGEND).

How do I properly do this?

 Note: I'd rather have a solution that doesn't require multiple calls to legend().

答:
You could use text.font = 3, say:

```<code>legend(x='topleft',legend = c(bquote((.(l1))),l2), text.font=c(3,1))
</code>```

Body:
I want to add a legend to a plot in which only one of the legend names is italicized. I'm using plot() in base R.

However, I need that italicized line to contain variable numbers, so I use bquote.

What I've tried does not work:

  a <- 2 ; b <- 5
  plot(a,b)
  l1 <- bquote(Italic ~ .(a) + .(b))
  l2 <- bquote(a + b)
  legend(x='topright',legend = bquote(italic(.(l1))))
  legend(x='topleft',legend = c(bquote(italic(.(l1))),l2))

Notice that when I leave the expression on its own (RIGHT LEGEND), it italicizes correctly. However, when I add the text for other legend lines, it messes up (LEFT LEGEND).

How do I properly do this?

 Note: I'd rather have a solution that doesn't require multiple calls to legend().

Body:
You could use text.font = 3, say:

legend(x='topleft',legend = c(bquote((.(l1))),l2), text.font=c(3,1))


答:
I believe what's going wrong is here is two-fold:

1. You're trying to animate the inner div, though I believe you should be scrolling the outer div, which is sortable-outer.

2. In such a case where you're trying to scroll, you probably want to use scrollLeft, not just left.

var $view = $('.sortable');
var move = "50px";

$('.right-arrow-button').click(function() {
    var currentPosition = parseInt($view.offset().left);
    $('.sortable-outer').stop(false, true).animate({
        scrollLeft: "+=" + move
    }, {
        duration: 400
    });
});

$('.left-arrow-button').click(function() {
    var currentPosition = parseInt($view.offset().left);
    $('.sortable-outer').stop(false, true).animate({
        scrollLeft: "-=" + move
    }, {
        duration: 400
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sortable {
    min-width: 729px;
}

.sortable-outer {
    overflow-x: scroll;
}

.pc-row {
    width: 1750px;
}

.pc-col-xs-4 {
    width: 320px;
    margin-right: 30px;
    float: left;
    height: 100px;
    background-color: red;
}

.left-arrow-button {
    transform: rotate(180deg);
}

.left-arrow-button:hover,
.right-arrow-button:hover {
    background-color: yellow;
}</code>```

    <svg width="32" height="32" viewBox="0 0 32 32" id="carousel_arrow" x="287" y="384.561">
        <path d="M16 0c8.836 0 16 7.164 16 16s-7.164 16-16 16S0 24.836 0 16 7.164 0 16 0zm0 29c7.168 0 13-5.832 13-13S23.168 3 16 3 3 8.832 3 16s5.832 13 13 13zM13.5 9c.39 0 .743.153 1.01.398l.004-.003 6 5.5a1.5 1.5 0 0 1 0 2.21l-6 5.5-.003-.003c-.267.245-.62.398-1.01.398a1.5 1.5 0 0 1-1.5-1.5c0-.438.19-.828.49-1.102l-.004-.003L17.28 16l-4.794-4.395.003-.003A1.49 1.49 0 0 1 12 10.5 1.5 1.5 0 0 1 13.5 9z"
        fill="#818091" fill-rule="evenodd" />
    </svg>

    <svg width="32" height="32" viewBox="0 0 32 32" id="carousel_arrow" x="287" y="384.561">
        <path d="M16 0c8.836 0 16 7.164 16 16s-7.164 16-16 16S0 24.836 0 16 7.164 0 16 0zm0 29c7.168 0 13-5.832 13-13S23.168 3 16 3 3 8.832 3 16s5.832 13 13 13zM13.5 9c.39 0 .743.153 1.01.398l.004-.003 6 5.5a1.5 1.5 0 0 1 0 2.21l-6 5.5-.003-.003c-.267.245-.62.398-1.01.398a1.5 1.5 0 0 1-1.5-1.5c0-.438.19-.828.49-1.102l-.004-.003L17.28 16l-4.794-4.395.003-.003A1.49 1.49 0 0 1 12 10.5 1.5 1.5 0 0 1 13.5 9z"
        fill="#818091" fill-rule="evenodd" />
    </svg>

```

Body:
I believe what's going wrong is here is two-fold:

1. You're trying to animate the inner div, though I believe you should be scrolling the outer div, which is sortable-outer.

2. In such a case where you're trying to scroll, you probably want to use scrollLeft, not just left.

var $view = $('.sortable');
var move = "50px";

$('.right-arrow-button').click(function() {
    var currentPosition = parseInt($view.offset().left);
    $('.sortable-outer').stop(false, true).animate({
        scrollLeft: "+=" + move
    }, {
        duration: 400
    });
});

$('.left-arrow-button').click(function() {
    var currentPosition = parseInt($view.offset().left);
    $('.sortable-outer').stop(false, true).animate({
        scrollLeft: "-=" + move
    }, {
        duration: 400
    });
});

.sortable {
    min-width: 729px;
}

.sortable-outer {
    overflow-x: scroll;
}

.pc-row {
    width: 1750px;
}

.pc-col-xs-4 {
    width: 320px;
    margin-right: 30px;
    float: left;
    height: 100px;
    background-color: red;
}

.left-arrow-button {
    transform: rotate(180deg);
}

.left-arrow-button:hover,
.right-arrow-button:hover {
    background-color: yellow;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sortable-outer">
    <div class="pc-row sortable">
        <div class="pc-col-xs-4"></div>
        <div class="pc-col-xs-4"></div>
        <div class="pc-col-xs-4"></div>
        <div class="pc-col-xs-4"></div>
    </div>
</div>
<div class="bnr-fpc-fs-controls-control right lg left-arrow-button">
    <svg width="32" height="32" viewBox="0 0 32 32" id="carousel_arrow" x="287" y="384.561">
        <path d="M16 0c8.836 0 16 7.164 16 16s-7.164 16-16 16S0 24.836 0 16 7.164 0 16 0zm0 29c7.168 0 13-5.832 13-13S23.168 3 16 3 3 8.832 3 16s5.832 13 13 13zM13.5 9c.39 0 .743.153 1.01.398l.004-.003 6 5.5a1.5 1.5 0 0 1 0 2.21l-6 5.5-.003-.003c-.267.245-.62.398-1.01.398a1.5 1.5 0 0 1-1.5-1.5c0-.438.19-.828.49-1.102l-.004-.003L17.28 16l-4.794-4.395.003-.003A1.49 1.49 0 0 1 12 10.5 1.5 1.5 0 0 1 13.5 9z"
        fill="#818091" fill-rule="evenodd" />
    </svg>
</div>
<div class="bnr-fpc-fs-controls-control next lg right-arrow-button">
    <svg width="32" height="32" viewBox="0 0 32 32" id="carousel_arrow" x="287" y="384.561">
        <path d="M16 0c8.836 0 16 7.164 16 16s-7.164 16-16 16S0 24.836 0 16 7.164 0 16 0zm0 29c7.168 0 13-5.832 13-13S23.168 3 16 3 3 8.832 3 16s5.832 13 13 13zM13.5 9c.39 0 .743.153 1.01.398l.004-.003 6 5.5a1.5 1.5 0 0 1 0 2.21l-6 5.5-.003-.003c-.267.245-.62.398-1.01.398a1.5 1.5 0 0 1-1.5-1.5c0-.438.19-.828.49-1.102l-.004-.003L17.28 16l-4.794-4.395.003-.003A1.49 1.49 0 0 1 12 10.5 1.5 1.5 0 0 1 13.5 9z"
        fill="#818091" fill-rule="evenodd" />
    </svg>
</div>


问:
Retrieve certain amount of children from Firebase
I am trying to create a tableView that loads only a certain amount of values, let's say like 30 or so from my database.

I've looked at other tutorials for this, but they are in Objective-C or some other language. Swift would be great!

答:
Swift. Get a FIRDatabaseReference to the parent node and then run a query using this function:

```<code>func queryLimited(toFirst limit: UInt) -> FIRDatabaseQuery
</code>```

And then retrieve the resulting children using:

```<code>func observeSingleEvent(of eventType: FIRDataEventType, with block: @escaping (FIRDataSnapshot) -> Void)
</code>```

Body:
Swift. Get a FIRDatabaseReference to the parent node and then run a query using this function:

func queryLimited(toFirst limit: UInt) -> FIRDatabaseQuery

And then retrieve the resulting children using:

func observeSingleEvent(of eventType: FIRDataEventType, with block: @escaping (FIRDataSnapshot) -> Void)


问:
I'm attempting to create a function in python, but I don't think I'm properly understanding how to do it
I'm creating a function to work out the area of a triangle. I have the actual code done because it's quite simple, but I don't know how to implement it into a function.

This is what I have up to now.

```<code>height = int(input("how tall is the triangle?"))

base = int(input("how long is the base of the triangle?"))

prtwaythre = height * base

area = prtwaythre / 2

print("the area is",area)
</code>```

I have tried to implement it into a function by doing this:

```<code>def trianglearea():
    prtwaythre = height * base
    area = prtwaythre / 2
    print("the area is",area)
    return
</code>```

and

```<code>if choice == "1":
    height = int(input("what is the height of the triangle?"))
    base == int(input("what is the length of the base?"))
    trianglearea(height,base)
</code>```

Can anyone explain where I'm going wrong?

Edit: I've realised that my issue now lies with my option choice list, but i cannot notice where I've gone wrong with it either. Can you?

```<code>while True:
        try:
            print("To select a function please choose from below")
            print("1. area of a triangle")
            print("2. area of a circle")
            print("3. circumferance of a circle")
            print("4. calculate the mean")
            print("5. percentage change")
            print("6. perimeter of a shape")
            print("7. square root")
            print("8. times by a power")
            choice = int(input("To select a function please choose from above"))
            break
        except ValueError:
            print("enter a valid option")
</code>```

答:
You have a few minor issues. First, when you write a function, you have to specify which arguments it takes. You can either do this with keyword arguments, or required named arguments.

```<code>def trianglearea(height, base):
    prtwaythre = height * base
    area = prtwaythre / 2
    print("the area is",area)
    return
</code>```

would be the easiest way of doing this, but another option is something like:

```<code>def trianglearea(height=1, base=):
    prtwaythre = height * base
    area = prtwaythre / 2.0
    print("the area is",area)
    return
</code>```

A second issue here is that you are using == for assignment.

```<code>base = int(input("what is the length of the base?"))
</code>```

instead of

```<code>base == int(input("what is the length of the base?"))
</code>```

Body:
I'm creating a function to work out the area of a triangle. I have the actual code done because it's quite simple, but I don't know how to implement it into a function.

This is what I have up to now.

height = int(input("how tall is the triangle?"))

base = int(input("how long is the base of the triangle?"))

prtwaythre = height * base

area = prtwaythre / 2

print("the area is",area)

I have tried to implement it into a function by doing this:

def trianglearea():
    prtwaythre = height * base
    area = prtwaythre / 2
    print("the area is",area)
    return

and

if choice == "1":
    height = int(input("what is the height of the triangle?"))
    base == int(input("what is the length of the base?"))
    trianglearea(height,base)

Can anyone explain where I'm going wrong?

Edit: I've realised that my issue now lies with my option choice list, but i cannot notice where I've gone wrong with it either. Can you?

while True:
        try:
            print("To select a function please choose from below")
            print("1. area of a triangle")
            print("2. area of a circle")
            print("3. circumferance of a circle")
            print("4. calculate the mean")
            print("5. percentage change")
            print("6. perimeter of a shape")
            print("7. square root")
            print("8. times by a power")
            choice = int(input("To select a function please choose from above"))
            break
        except ValueError:
            print("enter a valid option")

Body:
You have a few minor issues. First, when you write a function, you have to specify which arguments it takes. You can either do this with keyword arguments, or required named arguments.

def trianglearea(height, base):
    prtwaythre = height * base
    area = prtwaythre / 2
    print("the area is",area)
    return

would be the easiest way of doing this, but another option is something like:

def trianglearea(height=1, base=):
    prtwaythre = height * base
    area = prtwaythre / 2.0
    print("the area is",area)
    return

A second issue here is that you are using == for assignment.

base = int(input("what is the length of the base?"))

instead of

base == int(input("what is the length of the base?"))


问:
F# WSDL code generation
I'm using VS.NET 2010 integrated shell with F# and I'm trying to consume a soap web service... How do I go about generating F# source? I tried

wsdl l:"C:\Program Files (x86)\FSharpPowerPack-2.0.0.0\bin\FSharp.Compiler.CodeDom.dll" http://localhost/?wsdl

Along with

wsdl /language:"Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider, Microsoft.FSharp.Compiler.CodeDom, Version=1.9.2.9, Culture=neutral, PublicKeyToken=a19089b1c74d0809"

However I can't seem to get the /language switch to work.

EDIT:

taspeotis' answer got me going... This generated F# source for the web service:

```<code>gacutil -i "C:\Program Files (x86)\FSharpPowerPack-2.0.0.0\bin\FSharp.PowerPack.dll"
svcutil /language:"Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider, FSharp.Compiler.CodeDom, Version=2.0.0.0, Culture=neutral, PublicKeyToken=a19089b1c74d0809" http://localhost/?wsdl
</code>```

答:
Have you added FSharp.Compiler.CodeDom.dll to the GAC? Use gacutil.exe to do this.

3rd party edit

Here an example  gacutil.exe /l System.XML.Linq to list certain assemblies.
Besides to FSharp.Compiler.CodeDom (source) an alternative might be the FSharp.Data library

Quote from jizugu: This generated F# source for the web service:

```<code>gacutil -i
   "C:\Program Files (x86)\FSharpPowerPack-2.0.0.0\bin\FSharp.PowerPack.dll"

svcutil
  /language:"Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider
        ,FSharp.Compiler.CodeDom, Version=2.0.0.0, Culture=neutral
        ,PublicKeyToken=a19089b1c74d0809" http://localhost/?wsdl
</code>```

Title: F# WSDL code generation

Body:
I'm using VS.NET 2010 integrated shell with F# and I'm trying to consume a soap web service... How do I go about generating F# source? I tried

wsdl l:"C:\Program Files (x86)\FSharpPowerPack-2.0.0.0\bin\FSharp.Compiler.CodeDom.dll" http://localhost/?wsdl

Along with

wsdl /language:"Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider, Microsoft.FSharp.Compiler.CodeDom, Version=1.9.2.9, Culture=neutral, PublicKeyToken=a19089b1c74d0809"

However I can't seem to get the /language switch to work.

EDIT:

taspeotis' answer got me going... This generated F# source for the web service:

gacutil -i "C:\Program Files (x86)\FSharpPowerPack-2.0.0.0\bin\FSharp.PowerPack.dll"
svcutil /language:"Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider, FSharp.Compiler.CodeDom, Version=2.0.0.0, Culture=neutral, PublicKeyToken=a19089b1c74d0809" http://localhost/?wsdl

Body:
Have you added FSharp.Compiler.CodeDom.dll to the GAC? Use gacutil.exe to do this.

3rd party edit

Here an example  gacutil.exe /l System.XML.Linq to list certain assemblies.
Besides to FSharp.Compiler.CodeDom (source) an alternative might be the FSharp.Data library

Quote from jizugu: This generated F# source for the web service:

gacutil -i
   "C:\Program Files (x86)\FSharpPowerPack-2.0.0.0\bin\FSharp.PowerPack.dll"

svcutil
  /language:"Microsoft.FSharp.Compiler.CodeDom.FSharpCodeProvider
        ,FSharp.Compiler.CodeDom, Version=2.0.0.0, Culture=neutral
        ,PublicKeyToken=a19089b1c74d0809" http://localhost/?wsdl


问:
How do you create a "reverse pivot" in Google Sheets?
I am trying to produce a "reverse pivot" function. I have searched long and hard for such a function, but cannot find one that is already out there.

I have a summary table with anywhere up to 20 columns and hundreds of rows, however I would like to convert it into a flat list so I can import to a database (or even use the flat data to create more pivot tables from!)

So, I have data in this format:

Customer 1
Customer 2
Customer 3

Product 1
1
2
3

Product 2
4
5
6

Product 3
7
8
9

And need to convert it to this format:

```<code> Customer  |  Product  | Qty
-----------+-----------+----
Customer 1 | Product 1 |   1
Customer 1 | Product 2 |   4
Customer 1 | Product 3 |   7
Customer 2 | Product 1 |   2
Customer 2 | Product 2 |   5
Customer 2 | Product 3 |   8
Customer 3 | Product 1 |   3
Customer 3 | Product 2 |   6
Customer 3 | Product 3 |   9
</code>```

I have created a function that will read the range from sheet1 and append the re-formatted rows at the bottom of the same sheet, however I am trying to get it working so I can have the function on sheet2 that will read the whole range from sheet1.

No matter what I try, I can't seem to get it to work, and was wondering if anybody could give me any pointers?

Here is what I have so far:

function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  heads = values[0]

  for (var i = 1; i <= numRows - 1; i++) {
    for (var j = 1; j <= values[0].length - 1; j++) {
       var row = [values[i][0], values[0][j], values[i][j]];
       sheet.appendRow(row)
    }
  }
};
```

答:
If your data has a single unique key column, this spreadsheet may have what you need.

Your unpivot sheet will contain:

The key column =OFFSET(data!$A$1,INT((ROW()-2)/5)+1,0)

The column header column =OFFSET(data!$A$1,0,IF(MOD(ROW()-1,5)=0,5,MOD(ROW()-1,5)))

The cell value column =INDEX(data!$A$1:$F$100,MATCH(A2,data!$A$1:$A$100,FALSE),MATCH(B2,data!$A$1:$F$1,FALSE))

where 5 is the number of columns to unpivot.

I did not make the spreadsheet. I happened across it in the same search that led me to this question.

Body:
I am trying to produce a "reverse pivot" function. I have searched long and hard for such a function, but cannot find one that is already out there.

I have a summary table with anywhere up to 20 columns and hundreds of rows, however I would like to convert it into a flat list so I can import to a database (or even use the flat data to create more pivot tables from!)

So, I have data in this format:

Customer 1
Customer 2
Customer 3

Product 1
1
2
3

Product 2
4
5
6

Product 3
7
8
9

And need to convert it to this format:

 Customer  |  Product  | Qty
-----------+-----------+----
Customer 1 | Product 1 |   1
Customer 1 | Product 2 |   4
Customer 1 | Product 3 |   7
Customer 2 | Product 1 |   2
Customer 2 | Product 2 |   5
Customer 2 | Product 3 |   8
Customer 3 | Product 1 |   3
Customer 3 | Product 2 |   6
Customer 3 | Product 3 |   9

I have created a function that will read the range from sheet1 and append the re-formatted rows at the bottom of the same sheet, however I am trying to get it working so I can have the function on sheet2 that will read the whole range from sheet1.

No matter what I try, I can't seem to get it to work, and was wondering if anybody could give me any pointers?

Here is what I have so far:

function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();

  heads = values[0]

  for (var i = 1; i <= numRows - 1; i++) {
    for (var j = 1; j <= values[0].length - 1; j++) {
       var row = [values[i][0], values[0][j], values[i][j]];
       sheet.appendRow(row)
    }
  }
};