问:
ConstraintLayout with Barriers; How to constraint to bottom / top of barrier depending on size
I am trying out the new Barrier feature in the 1.1.0-beta1. It works as expected however there is this use-case I cant seem to figure or (or is possible ConstraintLayout at all?)

What I am trying to accomplish is: I have a imageview to the left, and title and subtitle textviews to the right of the imageview. Imageview is fixed height. I have a button, that is bottom constrained to the bottom of the imageview  however should be top constrained to the bottom of the subtitle textview, if subtitletextview is taller than imageview.

(Btw I also tried having it bottom constrained to bottom of imageview, and topconstrained to bottom of textview and giving it  1.0 bias towards bottom, but didnt work with large text case)

With barriers I am only able to get button top constrained to bottom of barrier (or top, seemed to to the same)

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

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@color/blue"/>

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="0dp"
        android:layout_height="150dp"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginTop="0dp"
        android:scaleType="centerCrop"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/books"/>

    <ImageView
        android:id="@+id/imageView6"
        android:layout_width="124dp"
        android:layout_height="156dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView4"
        app:srcCompat="@android:drawable/radiobutton_on_background"/>

    <TextView
        android:id="@+id/textView4"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toRightOf="@+id/imageView6"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView4"/>

    <TextView
        android:id="@+id/textView5"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Lorem Ipsum je fiktívny text, používaný pri návrhu tlačovín a typografie. Lorem Ipsum je štandardným výplňovým textom už od 16. storočia, keď neznámy tlačiar zobral sadzobnicu plnú tlačových znakov a pomiešal ich, aby tak vytvoril vzorkovú knihu. Prežil nielen päť storočí, ale aj skok do elektronickej sadzby, a pritom zostal v podstate nezmenený. Spopularizovaný bol v 60-tych rokoch 20.storočia, vydaním hárkov Letraset, ktoré obsahovali pasáže Lorem Ipsum, a neskôr aj publikačným softvérom"
        app:layout_constraintLeft_toLeftOf="@+id/textView4"
        app:layout_constraintRight_toRightOf="@+id/textView4"
        app:layout_constraintTop_toBottomOf="@+id/textView4"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintTop_toBottomOf="@+id/textView5"
        app:layout_constraintRight_toRightOf="parent"/>

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

Both states in images:

答:
Here is a layout that will work for you. It is a little complicated but does what you want. Here is how it works and is set up:

Define an invisible button, blockingButton, that has the same dimensions as your other button. Constrain this button to the bottom of your left ImageView.

On top of blockingButton, place a Space widget. The location of this Space widget will define the maximum height that the bottom button will float to.

Define a barrier that floats below the Space widget and the large TextView.

Finally, constrain the top of your floating button to the barrier.

As the size of the text changes in the large TextView, the button will float up as far as the Space widget but no farther. As the TextView grows, it will push down the barrier and the bottom button.

Here is a short video.

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

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@color/blue" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="0dp"
        android:layout_height="150dp"
        android:scaleType="centerCrop"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/books" />

    <ImageView
        android:id="@+id/imageView6"
        android:layout_width="124dp"
        android:layout_height="156dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView4"
        app:srcCompat="@android:drawable/radiobutton_on_background"
        android:layout_marginStart="8dp" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toRightOf="@+id/imageView6"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView4" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="17dp"
        android:text="Lorem Ipsum je fiktívny text, používaný pri návrhu tlačovín a typografie. Lorem Ipsum je štandardným výplňovým textom už od 16. storočia, keď neznámy tlačiar zobral sadzobnicu plnú tlačových znakov a pomiešal ich, aby tak vytvoril vzorkovú knihu. Prežil nielen päť storočí, ale aj skok do elektronickej sadzby, a pritom zostal v podstate nezmenený. Spopularizovaný bol v 60-tych rokoch 20.storočia, vydaním hárkov Letraset, ktoré obsahovali pasáže Lorem Ipsum, a neskôr aj publikačným softvérom"
        app:layout_constraintLeft_toLeftOf="@+id/textView4"
        app:layout_constraintRight_toRightOf="@+id/textView4"
        app:layout_constraintTop_toBottomOf="@+id/textView4"
        app:layout_constraintHorizontal_bias="0.0" />

<!-- This is the start of the changes. -->
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/barrier" />

    <Button
        android:id="@+id/blockingButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:visibility="invisible"
        app:layout_constraintBottom_toBottomOf="@+id/imageView6"
        app:layout_constraintLeft_toLeftOf="@+id/imageView6" />

    <android.support.v4.widget.Space
        android:id="@+id/spacer"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/blockingButton" />

    <android.support.constraint.Barrier
        android:id="@+id/barrier"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:barrierDirection="bottom"
        app:constraint_referenced_ids="spacer, textView5" />

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

Body:
I am trying out the new Barrier feature in the 1.1.0-beta1. It works as expected however there is this use-case I cant seem to figure or (or is possible ConstraintLayout at all?)

What I am trying to accomplish is: I have a imageview to the left, and title and subtitle textviews to the right of the imageview. Imageview is fixed height. I have a button, that is bottom constrained to the bottom of the imageview  however should be top constrained to the bottom of the subtitle textview, if subtitletextview is taller than imageview.

(Btw I also tried having it bottom constrained to bottom of imageview, and topconstrained to bottom of textview and giving it  1.0 bias towards bottom, but didnt work with large text case)

With barriers I am only able to get button top constrained to bottom of barrier (or top, seemed to to the same)

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

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@color/blue"/>

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="0dp"
        android:layout_height="150dp"
        android:layout_marginLeft="0dp"
        android:layout_marginRight="0dp"
        android:layout_marginTop="0dp"
        android:scaleType="centerCrop"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/books"/>

    <ImageView
        android:id="@+id/imageView6"
        android:layout_width="124dp"
        android:layout_height="156dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView4"
        app:srcCompat="@android:drawable/radiobutton_on_background"/>

    <TextView
        android:id="@+id/textView4"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toRightOf="@+id/imageView6"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView4"/>

    <TextView
        android:id="@+id/textView5"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Lorem Ipsum je fiktívny text, používaný pri návrhu tlačovín a typografie. Lorem Ipsum je štandardným výplňovým textom už od 16. storočia, keď neznámy tlačiar zobral sadzobnicu plnú tlačových znakov a pomiešal ich, aby tak vytvoril vzorkovú knihu. Prežil nielen päť storočí, ale aj skok do elektronickej sadzby, a pritom zostal v podstate nezmenený. Spopularizovaný bol v 60-tych rokoch 20.storočia, vydaním hárkov Letraset, ktoré obsahovali pasáže Lorem Ipsum, a neskôr aj publikačným softvérom"
        app:layout_constraintLeft_toLeftOf="@+id/textView4"
        app:layout_constraintRight_toRightOf="@+id/textView4"
        app:layout_constraintTop_toBottomOf="@+id/textView4"/>

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintTop_toBottomOf="@+id/textView5"
        app:layout_constraintRight_toRightOf="parent"/>

</android.support.constraint.ConstraintLayout>

Both states in images:

Body:
Here is a layout that will work for you. It is a little complicated but does what you want. Here is how it works and is set up:

Define an invisible button, blockingButton, that has the same dimensions as your other button. Constrain this button to the bottom of your left ImageView.

On top of blockingButton, place a Space widget. The location of this Space widget will define the maximum height that the bottom button will float to.

Define a barrier that floats below the Space widget and the large TextView.

Finally, constrain the top of your floating button to the barrier.

As the size of the text changes in the large TextView, the button will float up as far as the Space widget but no farther. As the TextView grows, it will push down the barrier and the bottom button.

Here is a short video.

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

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@color/blue" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="0dp"
        android:layout_height="150dp"
        android:scaleType="centerCrop"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/books" />

    <ImageView
        android:id="@+id/imageView6"
        android:layout_width="124dp"
        android:layout_height="156dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView4"
        app:srcCompat="@android:drawable/radiobutton_on_background"
        android:layout_marginStart="8dp" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:text="TextView"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toRightOf="@+id/imageView6"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView4" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="17dp"
        android:text="Lorem Ipsum je fiktívny text, používaný pri návrhu tlačovín a typografie. Lorem Ipsum je štandardným výplňovým textom už od 16. storočia, keď neznámy tlačiar zobral sadzobnicu plnú tlačových znakov a pomiešal ich, aby tak vytvoril vzorkovú knihu. Prežil nielen päť storočí, ale aj skok do elektronickej sadzby, a pritom zostal v podstate nezmenený. Spopularizovaný bol v 60-tych rokoch 20.storočia, vydaním hárkov Letraset, ktoré obsahovali pasáže Lorem Ipsum, a neskôr aj publikačným softvérom"
        app:layout_constraintLeft_toLeftOf="@+id/textView4"
        app:layout_constraintRight_toRightOf="@+id/textView4"
        app:layout_constraintTop_toBottomOf="@+id/textView4"
        app:layout_constraintHorizontal_bias="0.0" />

<!-- This is the start of the changes. -->
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/barrier" />

    <Button
        android:id="@+id/blockingButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:visibility="invisible"
        app:layout_constraintBottom_toBottomOf="@+id/imageView6"
        app:layout_constraintLeft_toLeftOf="@+id/imageView6" />

    <android.support.v4.widget.Space
        android:id="@+id/spacer"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/blockingButton" />

    <android.support.constraint.Barrier
        android:id="@+id/barrier"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:barrierDirection="bottom"
        app:constraint_referenced_ids="spacer, textView5" />

</android.support.constraint.ConstraintLayout>


来源: stackexchange

问:
Traverse simple javascript object
I'm having a mental block. How may I access the data inside this javascript object that's returned from an ajax function?

I was thinking something like this would work:

```<code>data[0].id would return 1
data[1].category.description would return "MEN"
</code>```

Help would be appreciated!

```<code>"[ {
  "id" : 1,
  "description" : "PANTS",
  "price" : 10.99,
  "category" : {
    "id" : 1,
    "description" : "MEN"
  },
  "customerType" : {
    "id" : 1,
    "type" : "COUNTER"
  }
}, {
  "id" : 2,
  "description" : "SHIRT",
  "price" : 4.99,
  "category" : {
    "id" : 1,
    "description" : "MEN"
  },
  "customerType" : {
    "id" : 1,
    "type" : "COUNTER"
  }
} ]"
</code>```

答:
That should work, just loop over it</p>

```<code>dataLength=data.length;
for(var i=0;i<dataLength;i++){
    var dataID = data[i].id;
    var dataCatagory = data[i].category.description;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Traverse simple javascript object

Body:
I'm having a mental block. How may I access the data inside this javascript object that's returned from an ajax function?

I was thinking something like this would work:

data[0].id would return 1
data[1].category.description would return "MEN"

Help would be appreciated!

"[ {
  "id" : 1,
  "description" : "PANTS",
  "price" : 10.99,
  "category" : {
    "id" : 1,
    "description" : "MEN"
  },
  "customerType" : {
    "id" : 1,
    "type" : "COUNTER"
  }
}, {
  "id" : 2,
  "description" : "SHIRT",
  "price" : 4.99,
  "category" : {
    "id" : 1,
    "description" : "MEN"
  },
  "customerType" : {
    "id" : 1,
    "type" : "COUNTER"
  }
} ]"

Body:
That should work, just loop over it

dataLength=data.length;
for(var i=0;i<dataLength;i++){
    var dataID = data[i].id;
    var dataCatagory = data[i].category.description;
}


问:
Upgrading Django Version: Best Practice
I've pretty big code base written on Django 1.5, it's about time to upgrade to the newest version (1.11.2) as many stuff don't work well.

I'm wondering if it's best to upgrade step by step: 1.5->1.6->1.7...
or just jump to 1.11.2

what method should be better and make the (hard) process easier? as my project has many dependencies?

Also what are good practices to do? I'm using virtualenv and aware of this Django article about upgrading

答:
It depends on two things. How many people are using the Django app, and the extend of your test coverage.

If you are the only user, no worries, upgrade all the way. But if you have a lot of users you will quickly find out by upgrading all the way to 1.11.2 that some edge cases may not be covered by your tests.

Expect a lot of error 500 along the way.

If your coverage is close to 100% on all your apps, you may not have that problem.

Note that a lot has changed since 1.5.

Title: Upgrading Django Version: Best Practice


问:
how to compare the text field values with database values which is entered in the text field
Actually, I don't want to accept the same name which is already entered in the text field (i.e; unique values) stored in database.

For example, I entered a name "health" in text field and saved it. If again enter the same name then it won't accept.

I tried below but it's not working. Please help me.

```<code>boolean ifExisting(String cat)
     {
      Cursor c = db.rawQuery("SELECT * FROM " + "restaurants" + "WHERE" + "category" + "=" + cat, null);
         if(c.getCount() == 0)
         {
          return;
         }
          else
          {
           return;
          }
     }
       insert();
</code>```

答:
Three issues in your code:

Your function  has a boolean return type, but in both cases of your if statement you return nothing. Perhaps you should try returning an appropriate boolean value?

You should be checking all sqlite operations for errors. Otherwise they will fail silently on you and your code will simply assume that there were no matching rows in the DB - if it gets that far without an error.

Building SQL queries by concatenating strings should be illegal. It is a very unsafe practice and it opens up your code to SQL injection attacks and the like. What would happen if your user entered "italian"; delete from restaurants in the cat text field? You should be using hosted parameters to guard against this.

EDIT:

As per LadaRaider's answer, you also seem to be missing a few spaces in your SQL query. Yet another reason not to concatenate strings to build it.

Body:
Actually, I don't want to accept the same name which is already entered in the text field (i.e; unique values) stored in database.

For example, I entered a name "health" in text field and saved it. If again enter the same name then it won't accept.

I tried below but it's not working. Please help me.

boolean ifExisting(String cat)
     {
      Cursor c = db.rawQuery("SELECT * FROM " + "restaurants" + "WHERE" + "category" + "=" + cat, null);
         if(c.getCount() == 0)
         {
          return;
         }
          else
          {
           return;
          }
     }
       insert();

ContentLicense: CC BY-SA 2.5


问:
Could not find phantomjs
Getting the following error when trying to use phantomjs from ruby on Ubuntu:

```<code> Failure/Error: visit root_path
 Cliver::Dependency::NotFound:
   Could not find an executable ["phantomjs"] on your path.
 # ./spec/features/search_spec.rb:17:in `block (2 levels) in <top (required)>'
 # ./spec/support/vcr.rb:23:in `block (3 levels) in <top (required)>'
 # ./spec/support/vcr.rb:23:in `block (2 levels) in <top (required)>'
</code>```

phantomjs was built locally and added to PATH. How do I make ruby find phantomjs?

答:
Other possible solution is to add executable rights to file:

```<code># download phantomjs
$ curl --output /home/user/.rvm/bin/phantomjs https://s3.amazonaws.com/circle-downloads/phantomjs-2.1.1
# set rights
$ chmod +x /home/user/.rvm/bin/phantomjs
# check
$ which phantomjs
/home/user/.rvm/bin/phantomjs
</code>```

And also it is not recommended by poltergeist to use phantomjs from official Ubuntu repos:

DO NOT use phantomjs from the official Ubuntu repositories, since it
  doesn't work well with poltergeist.

Title: Could not find phantomjs

Body:
Getting the following error when trying to use phantomjs from ruby on Ubuntu:

 Failure/Error: visit root_path
 Cliver::Dependency::NotFound:
   Could not find an executable ["phantomjs"] on your path.
 # ./spec/features/search_spec.rb:17:in `block (2 levels) in <top (required)>'
 # ./spec/support/vcr.rb:23:in `block (3 levels) in <top (required)>'
 # ./spec/support/vcr.rb:23:in `block (2 levels) in <top (required)>'

phantomjs was built locally and added to PATH. How do I make ruby find phantomjs?

Body:
Other possible solution is to add executable rights to file:

# download phantomjs
$ curl --output /home/user/.rvm/bin/phantomjs https://s3.amazonaws.com/circle-downloads/phantomjs-2.1.1
# set rights
$ chmod +x /home/user/.rvm/bin/phantomjs
# check
$ which phantomjs
/home/user/.rvm/bin/phantomjs

And also it is not recommended by poltergeist to use phantomjs from official Ubuntu repos:

DO NOT use phantomjs from the official Ubuntu repositories, since it
  doesn't work well with poltergeist.


问:
docker change cgroup driver to systemd
I want Docker to start with systemd cgroup driver. For some reason it is using only cgroupfs on my CentOS 7 server.

Here is startup config file.

```<code># systemctl cat docker
# /usr/lib/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=http://docs.docker.com
After=network.target
Wants=docker-storage-setup.service
Requires=docker-cleanup.timer

[Service]
Type=notify
NotifyAccess=all
EnvironmentFile=-/etc/sysconfig/docker
EnvironmentFile=-/etc/sysconfig/docker-storage
EnvironmentFile=-/etc/sysconfig/docker-network
Environment=GOTRACEBACK=crash
Environment=DOCKER_HTTP_HOST_COMPAT=1
Environment=PATH=/usr/libexec/docker:/usr/bin:/usr/sbin
ExecStart=/usr/bin/dockerd-current \
          --add-runtime docker-runc=/usr/libexec/docker/docker-runc-current \
          --default-runtime=docker-runc \
          --exec-opt native.cgroupdriver=systemd \
          --userland-proxy-path=/usr/libexec/docker/docker-proxy-current \
          $OPTIONS \
          $DOCKER_STORAGE_OPTIONS \
          $DOCKER_NETWORK_OPTIONS \
          $ADD_REGISTRY \
          $BLOCK_REGISTRY \
          $INSECURE_REGISTRY
ExecReload=/bin/kill -s HUP $MAINPID
LimitNOFILE=1048576
LimitNPROC=1048576
LimitCORE=infinity
TimeoutStartSec=0
Restart=on-abnormal
MountFlags=slave

[Install]
WantedBy=multi-user.target

# /etc/systemd/system/docker.service.d/docker-thinpool.conf
 [Service]
 ExecStart=
 ExecStart=/usr/bin/dockerd --storage-driver=devicemapper --storage-opt=dm.thinpooldev=/dev/mapper/docker-thinpool \
 --storage-opt=dm.use_deferred_removal=true --storage-opt=dm.use_deferred_deletion=true
 EOF
</code>```

When I start Docker, it's running like this:

```<code># ps -fed | grep docker
root      8436     1  0 19:13 ?        00:00:00 /usr/bin/dockerd-current --storage-driver=devicemapper --storage-opt=dm.thinpooldev=/dev/mapper/docker-thinpool --storage-opt=dm.use_deferred_removal=true --storage-opt=dm.use_deferred_deletion=true
root      8439  8436  0 19:13 ?        00:00:00 /usr/bin/docker-containerd-current -l unix:///var/run/docker/libcontainerd/docker-containerd.sock --shim docker-containerd-shim --metrics-interval=0 --start-timeout 2m --state-dir /var/run/docker/libcontainerd/containerd --runtime docker-runc
</code>```

Here is the output of docker info:

```<code># docker info
Containers: 0
 Running: 0
 Paused: 0
 Stopped: 0
Images: 1
Server Version: 1.12.6
Storage Driver: devicemapper
 Pool Name: docker-thinpool
 Pool Blocksize: 524.3 kB
 Base Device Size: 10.74 GB
 Backing Filesystem: xfs
 Data file:
 Metadata file:
 Data Space Used: 185.6 MB
 Data Space Total: 1.015 GB
 Data Space Available: 829.4 MB
 Metadata Space Used: 77.82 kB
 Metadata Space Total: 8.389 MB
 Metadata Space Available: 8.311 MB
 Thin Pool Minimum Free Space: 101.2 MB
 Udev Sync Supported: true
 Deferred Removal Enabled: true
 Deferred Deletion Enabled: true
 Deferred Deleted Device Count: 0
 Library Version: 1.02.135-RHEL7 (2016-11-16)
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: null bridge overlay host
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Security Options: seccomp
Kernel Version: 3.10.0-514.16.1.el7.x86_64
Operating System: CentOS Linux 7 (Core)
OSType: linux
Architecture: x86_64
Number of Docker Hooks: 2
CPUs: 1
Total Memory: 992.7 MiB
Name: master
ID: 6CFR:H7SN:MEU7:PNJH:UMSO:6MNE:43Q5:SF4K:Z25I:BKHP:53U4:63SO
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Insecure Registries:
 127.0.0.0/8
Registries: docker.io (secure)
</code>```

How can I make it run with systemd?

Thanks
SR

答:
Try to restart the docker service:</p>

```<code>systemctl daemon-reload
systemctl restart docker.service
</code>```

ContentLicense: CC BY-SA 4.0

Title: docker change cgroup driver to systemd

Body:
I want Docker to start with systemd cgroup driver. For some reason it is using only cgroupfs on my CentOS 7 server.

Here is startup config file.

# systemctl cat docker
# /usr/lib/systemd/system/docker.service
[Unit]
Description=Docker Application Container Engine
Documentation=http://docs.docker.com
After=network.target
Wants=docker-storage-setup.service
Requires=docker-cleanup.timer

[Service]
Type=notify
NotifyAccess=all
EnvironmentFile=-/etc/sysconfig/docker
EnvironmentFile=-/etc/sysconfig/docker-storage
EnvironmentFile=-/etc/sysconfig/docker-network
Environment=GOTRACEBACK=crash
Environment=DOCKER_HTTP_HOST_COMPAT=1
Environment=PATH=/usr/libexec/docker:/usr/bin:/usr/sbin
ExecStart=/usr/bin/dockerd-current \
          --add-runtime docker-runc=/usr/libexec/docker/docker-runc-current \
          --default-runtime=docker-runc \
          --exec-opt native.cgroupdriver=systemd \
          --userland-proxy-path=/usr/libexec/docker/docker-proxy-current \
          $OPTIONS \
          $DOCKER_STORAGE_OPTIONS \
          $DOCKER_NETWORK_OPTIONS \
          $ADD_REGISTRY \
          $BLOCK_REGISTRY \
          $INSECURE_REGISTRY
ExecReload=/bin/kill -s HUP $MAINPID
LimitNOFILE=1048576
LimitNPROC=1048576
LimitCORE=infinity
TimeoutStartSec=0
Restart=on-abnormal
MountFlags=slave

[Install]
WantedBy=multi-user.target

# /etc/systemd/system/docker.service.d/docker-thinpool.conf
 [Service]
 ExecStart=
 ExecStart=/usr/bin/dockerd --storage-driver=devicemapper --storage-opt=dm.thinpooldev=/dev/mapper/docker-thinpool \
 --storage-opt=dm.use_deferred_removal=true --storage-opt=dm.use_deferred_deletion=true
 EOF

When I start Docker, it's running like this:

# ps -fed | grep docker
root      8436     1  0 19:13 ?        00:00:00 /usr/bin/dockerd-current --storage-driver=devicemapper --storage-opt=dm.thinpooldev=/dev/mapper/docker-thinpool --storage-opt=dm.use_deferred_removal=true --storage-opt=dm.use_deferred_deletion=true
root      8439  8436  0 19:13 ?        00:00:00 /usr/bin/docker-containerd-current -l unix:///var/run/docker/libcontainerd/docker-containerd.sock --shim docker-containerd-shim --metrics-interval=0 --start-timeout 2m --state-dir /var/run/docker/libcontainerd/containerd --runtime docker-runc

Here is the output of docker info:

# docker info
Containers: 0
 Running: 0
 Paused: 0
 Stopped: 0
Images: 1
Server Version: 1.12.6
Storage Driver: devicemapper
 Pool Name: docker-thinpool
 Pool Blocksize: 524.3 kB
 Base Device Size: 10.74 GB
 Backing Filesystem: xfs
 Data file:
 Metadata file:
 Data Space Used: 185.6 MB
 Data Space Total: 1.015 GB
 Data Space Available: 829.4 MB
 Metadata Space Used: 77.82 kB
 Metadata Space Total: 8.389 MB
 Metadata Space Available: 8.311 MB
 Thin Pool Minimum Free Space: 101.2 MB
 Udev Sync Supported: true
 Deferred Removal Enabled: true
 Deferred Deletion Enabled: true
 Deferred Deleted Device Count: 0
 Library Version: 1.02.135-RHEL7 (2016-11-16)
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: null bridge overlay host
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Security Options: seccomp
Kernel Version: 3.10.0-514.16.1.el7.x86_64
Operating System: CentOS Linux 7 (Core)
OSType: linux
Architecture: x86_64
Number of Docker Hooks: 2
CPUs: 1
Total Memory: 992.7 MiB
Name: master
ID: 6CFR:H7SN:MEU7:PNJH:UMSO:6MNE:43Q5:SF4K:Z25I:BKHP:53U4:63SO
Docker Root Dir: /var/lib/docker
Debug Mode (client): false
Debug Mode (server): false
Registry: https://index.docker.io/v1/
Insecure Registries:
 127.0.0.0/8
Registries: docker.io (secure)

How can I make it run with systemd?

Thanks
SR

Body:
Try to restart the docker service:

systemctl daemon-reload
systemctl restart docker.service


问:
malloc() with heap overflow explanation
I have the following code:

```<code>int main(int argc, char *argv[]) {

    int bufferSize = 8;
    //Setting the buffer size here, which can cause a heap overflow
    char *argsStr = malloc(bufferSize);
    char *anotherStr = malloc(bufferSize);

    //If argv[1] is greater than the buffer size, we will have an overflow
    strcpy(argsStr, argv[1]);

    printf("String 1: %s String 2: %s", argsStr, anotherStr);

}
</code>```

I want to cause a heap overflow, so I import the param 'testtesttesttesttesttesttesttesttest'.

I would expect, since argsStr is only of size 8, it would be 'testtest' and the rest would overflow into anotherStr (for 8 bytes), but instead I see:

so argsStr is 'testtesttesttesttesttesttesttesttest' and anotherStr is 'testtesttesttesttest'

Why is this? Am I missing something with heap overflows or malloc()?

答:
As you know, when you do a malloc, it gives you a pointer to a block of memory in the heap.  The exact structure of the heap is implementation dependent.  As others have observed, you may or may not get sequential memory and you may or may not get exactly the amount of memory you asked for.  There are debug implementations malloc that give you the memory you asked for plus a big area at the end with markers to allow finding when you overwrite the end of your allocated block.  Something else to keep in mind is the second malloc could be either before or after the memory for the first malloc. Like MM observed, you could do a %p to see where the blocks are located to get an idea if they can run into each other.

This is what is called undefined behavior.  Exploring undefined behavior is great fun and allows you to get insights into the implementation but don't be surprised if it changes with a different version.  You can almost be guaranteed that it will change substantially on different systems, even with the same (GCC) compiler.

If you are really interested, you could find the source for the GCC run time library malloc routine on the web and see what goes on inside.  I just searched for "gcc runtime library malloc source" and found something that will take more than a few minutes examination to make sense out of.  It is pretty awesome code.  A lot of very smart people spent a long time working on it.

Title: malloc() with heap overflow explanation

Body:
I have the following code:

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

    int bufferSize = 8;
    //Setting the buffer size here, which can cause a heap overflow
    char *argsStr = malloc(bufferSize);
    char *anotherStr = malloc(bufferSize);

    //If argv[1] is greater than the buffer size, we will have an overflow
    strcpy(argsStr, argv[1]);

    printf("String 1: %s String 2: %s", argsStr, anotherStr);

}

I want to cause a heap overflow, so I import the param 'testtesttesttesttesttesttesttesttest'.

I would expect, since argsStr is only of size 8, it would be 'testtest' and the rest would overflow into anotherStr (for 8 bytes), but instead I see:

so argsStr is 'testtesttesttesttesttesttesttesttest' and anotherStr is 'testtesttesttesttest'

Why is this? Am I missing something with heap overflows or malloc()?


问:
Dynamic variable names for an array in bash
I have an array called "loop".

For each element in "loop" I want to create an array whose name contains the text of the current element.

I then want to loop through each new array and print every element from each array.

This post seems to have a good solution for variables but I do not know how to adapt it to work for arrays.

My Script

```<code>#!/bin/bash
loop=(
first
second
third
)

for word in "${loop[@]}"
do
        declare "${word}_holder=( hello world )"
        var="${word}_holder"
        echo "$var"
        for i in "${!var}[@]"
        do
                echo "$i"
        done
done
</code>```

Current output

```<code>first_holder
( hello world )[@]
second_holder
( hello world )[@]
third_holder
( hello world )[@]
</code>```

Desired Output

```<code>first_holder
hello
world
second_holder
hello
world
third_holder
hello
world
</code>```

答:
```<code>for word in "${loop[@]}";
do
   name="${word}_holder";
   declare -a "$name";
   declare -n arr="$name";
   echo $name;
   arr=(hello world);
   arr_ref="$name[@]";
   for w in "${!arr_ref}";
   do
      echo $w;
   done;
done;

first_holder
hello
world
second_holder
hello
world
third_holder
hello
world
</code>```

Of course there is no point of doing all this if you are not going to refer to the dynamically generated arrays (first_holder, etc) ever.

Body:
I have an array called "loop".

For each element in "loop" I want to create an array whose name contains the text of the current element.

I then want to loop through each new array and print every element from each array.

This post seems to have a good solution for variables but I do not know how to adapt it to work for arrays.

My Script

#!/bin/bash
loop=(
first
second
third
)

for word in "${loop[@]}"
do
        declare "${word}_holder=( hello world )"
        var="${word}_holder"
        echo "$var"
        for i in "${!var}[@]"
        do
                echo "$i"
        done
done

Current output

first_holder
( hello world )[@]
second_holder
( hello world )[@]
third_holder
( hello world )[@]

Desired Output

first_holder
hello
world
second_holder
hello
world
third_holder
hello
world

Body:
for word in "${loop[@]}";
do
   name="${word}_holder";
   declare -a "$name";
   declare -n arr="$name";
   echo $name;
   arr=(hello world);
   arr_ref="$name[@]";
   for w in "${!arr_ref}";
   do
      echo $w;
   done;
done;

first_holder
hello
world
second_holder
hello
world
third_holder
hello
world

Of course there is no point of doing all this if you are not going to refer to the dynamically generated arrays (first_holder, etc) ever.


问:
Center Labels in Filled Bar Chart using geom_text
I am new to ggplot2 (and R) and am trying to make a filled bar chart with labels in each box indicating the percentage composing that block.

Here is an example of my current figure to which I would like to add labels:

```<code>##ggplot figure
library(gpplot2)
library(scales)

#specify order I want in plots
ZIU$Affinity=factor(ZIU$Affinity, levels=c("High", "Het", "Low"))
ZIU$Group=factor(ZIU$Group, levels=c("ZUM", "ZUF", "ZIM", "ZIF"))

ggplot(ZIU, aes(x=Group))+
geom_bar(aes(fill=Affinity), position="fill", width=1, color="black")+
scale_y_continuous(labels=percent_format())+
scale_fill_manual("Affinity", values=c("High"="blue", "Het"="lightblue", "Low"="gray"))+
labs(x="Group", y="Percent Genotype within Group")+
ggtitle("Genotype Distribution", "by Group")
</code>```

I would like to add labels centered in each box with the percentage that box represents

I have tried to add labels using this code, but it keeps producing the error message "Error: geom_text requires the following missing aesthetics: y" but my plot has no y aesthetic, does this mean I cannot use geom_text? (Also, I am not sure if once the y aesthetic issue is resolved, if the remainder of the geom_text statement will accomplish what I desire, centered white labels in each box.)

```<code>ggplot(ZIU, aes(x=Group)) +
geom_bar(aes(fill=Affinity), position="fill", width=1, color="black")+
geom_text(aes(label=paste0(sprintf("%.0f", ZIU$Affinity),"%")),
    position=position_fill(vjust=0.5), color="white")+
scale_y_continuous(labels=percent_format())+
scale_fill_manual("Affinity", values=c("High"="blue", "Het"="lightblue", "Low"="gray"))+
labs(x="Group", y="Percent Genotype within Group")+
ggtitle("Genotype Distribution", "by Group")
</code>```

Also if anyone has suggestions for eliminating the NA values that would be appreciated! I tried

```<code>geom_bar(aes(fill=na.omit(Affinity)), position="fill", width=1, color="black")
</code>```

but was getting the error "Error: Aesthetics must be either length 1 or the same as the data (403): fill, x"

```<code> dput(sample)
 structure(list(Group = structure(c(3L, 3L, 3L, 3L, 3L, 3L, 3L,
 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L,
 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
 2L), .Label = c("ZUM", "ZUF", "ZIM", "ZIF"), class = "factor"),
StudyCode = c(1, 2, 3, 4, 5, 6, 20, 21, 22, 23, 143, 144,
145, 191, 192, 193, 194, 195, 196, 197, 10, 24, 25, 26, 27,
28, 71, 72, 73, 74, 274, 275, 276, 277, 278, 279, 280, 290,
291, 292), Affinity = structure(c(3L, 2L, 1L, 2L, 3L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 3L, 2L, 3L, 2L, 3L, 1L, 1L, 1L, 3L,
2L, 1L, 2L, 2L, 1L, 2L, 2L, 3L, 3L, 2L, 1L, 3L, 2L, 1L, 3L,
3L, 2L, 2L, 2L), .Label = c("High", "Het", "Low"), class = "factor")), .Names = c("Group",
"StudyCode", "Affinity"), row.names = c(NA, 40L), class = c("tbl_df",
"tbl", "data.frame"))
</code>```

Thank you so much!

答:
The linked examples have a y aesthetic, because the data are pre-summarized, rather than having ggplot do the counting internally. With your data, the analogous approach would be:

```<code>library(scales)
library(tidyverse)

# Summarize data to get counts and percentages
ZIU %>% group_by(Group, Affinity) %>%
  tally %>%
  mutate(percent=n/sum(n)) %>%   # Pipe summarized data into ggplot
  ggplot(aes(x=Group, y=percent, fill=Affinity)) +
   geom_bar(stat="identity", width=1, color="black") +
   geom_text(aes(label=paste0(sprintf("%1.1f", percent*100),"%")),
             position=position_stack(vjust=0.5), colour="white") +
   scale_y_continuous(labels=percent_format()) +
   scale_fill_manual("Affinity", values=c("High"="blue", "Het"="lightblue", "Low"="gray")) +
   labs(x="Group", y="Percent Genotype within Group") +
   ggtitle("Genotype Distribution", "by Group")
</code>```

Another option would be to use a line plot, which might make the relative values more clear. Assuming the Group values don't form a natural sequence, the lines are just there as a guide for differentiating the Affinity values across different values of Group.

```<code>ZIU %>% group_by(Group, Affinity) %>%
  tally %>%
  mutate(percent=n/sum(n)) %>%   # Pipe summarized data into ggplot
  ggplot(aes(x=Group, y=percent, colour=Affinity, group=Affinity)) +
  geom_line(alpha=0.4) +
  geom_text(aes(label=paste0(sprintf("%1.1f", percent*100),"%")), show.legend=FALSE) +
  scale_y_continuous(labels=percent_format(), limits=c(0,1)) +
  labs(x="Group", y="Percent Genotype within Group") +
  ggtitle("Genotype Distribution", "by Group") +
  guides(colour=guide_legend(override.aes=list(alpha=1, size=1))) +
  theme_classic()
</code>```

Body:
I am new to ggplot2 (and R) and am trying to make a filled bar chart with labels in each box indicating the percentage composing that block.

Here is an example of my current figure to which I would like to add labels:

##ggplot figure
library(gpplot2)
library(scales)

#specify order I want in plots
ZIU$Affinity=factor(ZIU$Affinity, levels=c("High", "Het", "Low"))
ZIU$Group=factor(ZIU$Group, levels=c("ZUM", "ZUF", "ZIM", "ZIF"))

ggplot(ZIU, aes(x=Group))+
geom_bar(aes(fill=Affinity), position="fill", width=1, color="black")+
scale_y_continuous(labels=percent_format())+
scale_fill_manual("Affinity", values=c("High"="blue", "Het"="lightblue", "Low"="gray"))+
labs(x="Group", y="Percent Genotype within Group")+
ggtitle("Genotype Distribution", "by Group")

I would like to add labels centered in each box with the percentage that box represents

I have tried to add labels using this code, but it keeps producing the error message "Error: geom_text requires the following missing aesthetics: y" but my plot has no y aesthetic, does this mean I cannot use geom_text? (Also, I am not sure if once the y aesthetic issue is resolved, if the remainder of the geom_text statement will accomplish what I desire, centered white labels in each box.)

ggplot(ZIU, aes(x=Group)) +
geom_bar(aes(fill=Affinity), position="fill", width=1, color="black")+
geom_text(aes(label=paste0(sprintf("%.0f", ZIU$Affinity),"%")),
    position=position_fill(vjust=0.5), color="white")+
scale_y_continuous(labels=percent_format())+
scale_fill_manual("Affinity", values=c("High"="blue", "Het"="lightblue", "Low"="gray"))+
labs(x="Group", y="Percent Genotype within Group")+
ggtitle("Genotype Distribution", "by Group")

Also if anyone has suggestions for eliminating the NA values that would be appreciated! I tried

geom_bar(aes(fill=na.omit(Affinity)), position="fill", width=1, color="black")

but was getting the error "Error: Aesthetics must be either length 1 or the same as the data (403): fill, x"

 dput(sample)
 structure(list(Group = structure(c(3L, 3L, 3L, 3L, 3L, 3L, 3L,
 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L,
 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
 2L), .Label = c("ZUM", "ZUF", "ZIM", "ZIF"), class = "factor"),
StudyCode = c(1, 2, 3, 4, 5, 6, 20, 21, 22, 23, 143, 144,
145, 191, 192, 193, 194, 195, 196, 197, 10, 24, 25, 26, 27,
28, 71, 72, 73, 74, 274, 275, 276, 277, 278, 279, 280, 290,
291, 292), Affinity = structure(c(3L, 2L, 1L, 2L, 3L, 1L,
1L, 2L, 2L, 2L, 2L, 2L, 3L, 2L, 3L, 2L, 3L, 1L, 1L, 1L, 3L,
2L, 1L, 2L, 2L, 1L, 2L, 2L, 3L, 3L, 2L, 1L, 3L, 2L, 1L, 3L,
3L, 2L, 2L, 2L), .Label = c("High", "Het", "Low"), class = "factor")), .Names = c("Group",
"StudyCode", "Affinity"), row.names = c(NA, 40L), class = c("tbl_df",
"tbl", "data.frame"))

Thank you so much!

Body:
The linked examples have a y aesthetic, because the data are pre-summarized, rather than having ggplot do the counting internally. With your data, the analogous approach would be:

library(scales)
library(tidyverse)

# Summarize data to get counts and percentages
ZIU %>% group_by(Group, Affinity) %>%
  tally %>%
  mutate(percent=n/sum(n)) %>%   # Pipe summarized data into ggplot
  ggplot(aes(x=Group, y=percent, fill=Affinity)) +
   geom_bar(stat="identity", width=1, color="black") +
   geom_text(aes(label=paste0(sprintf("%1.1f", percent*100),"%")),
             position=position_stack(vjust=0.5), colour="white") +
   scale_y_continuous(labels=percent_format()) +
   scale_fill_manual("Affinity", values=c("High"="blue", "Het"="lightblue", "Low"="gray")) +
   labs(x="Group", y="Percent Genotype within Group") +
   ggtitle("Genotype Distribution", "by Group")

Another option would be to use a line plot, which might make the relative values more clear. Assuming the Group values don't form a natural sequence, the lines are just there as a guide for differentiating the Affinity values across different values of Group.

ZIU %>% group_by(Group, Affinity) %>%
  tally %>%
  mutate(percent=n/sum(n)) %>%   # Pipe summarized data into ggplot
  ggplot(aes(x=Group, y=percent, colour=Affinity, group=Affinity)) +
  geom_line(alpha=0.4) +
  geom_text(aes(label=paste0(sprintf("%1.1f", percent*100),"%")), show.legend=FALSE) +
  scale_y_continuous(labels=percent_format(), limits=c(0,1)) +
  labs(x="Group", y="Percent Genotype within Group") +
  ggtitle("Genotype Distribution", "by Group") +
  guides(colour=guide_legend(override.aes=list(alpha=1, size=1))) +
  theme_classic()


问:
FPGA efficient (a)synchronous resets
I remember reading a while ago that either asynchronous or synchronous resets are more efficiently implemented in FPGAs since the flip flops already have one, but the other would require additional logic.

Does anyone know which way round this is? Is this the same for Xilinx, Altera, Other..

When learning, I used to add an asynchronous clear and a synchronous reset to every FSM, just in case. Is there any benefit at all to this?

Thanks for any feedback!

答:
Well, your best bet is to consult your specific FPGA vendor's documentation and white papers.  In most of the professional design teams I've worked on, we used asynchronous resets to maintain maximum control.  The choice between synchronous and asynchronous resets really depends on your design and application, however.

By the way, you might find this paper on the topic of resets from Sunburst Design interesting.  Though it primarily addresses ASIC design and Verilog, it is a useful paper for understanding reset decisions in general.

Title: FPGA efficient (a)synchronous resets


问:
How to select the file in native os pop using protractor
I am using protractor to automate my website. I have a scenario where need to upload the file clicking on upload button. When clicked on upload button then it renders the native os popup to select the file.

I tried to upload using below code without clicking on upload button.I think this approach is not correct as the user has to click on upload button and then select the file from native os popup.But still no luck

```<code>var fileToUpload = 'filePath';
var absolutePath = path.resolve(__dirname, fileToUpload);
element(by.id("creator--add-a-piece-empty")).sendKeys(absolutePath);
</code>```

How to select the file in native os pop ? Is there any way to upload

Operating system - Mac siera

I have tried all the possible solution provided on How to upload file in angularjs e2e protractor testing But no luck . I have added the code below s ,that will redirect you to the problem page ,where i need to upload the file.Thanks in Advance.

```<code>describe('NeonMob', function() {
it('LoginUsingInvalidEmail', function() {
browser.get('https://staging.neonmob.com/login');
element(by.id('form-field-username')).click();
element(by.id('field-username')).sendKeys("sharif");
element(by.id('field-password')).sendKeys("1234");
element(by.id('signin-btn')).click();
element(by.css("a[id='primary-navigation--create']")).click();
element(by.id("create-new-amateur-series")).click();
element(by.id("confirm-btn")).click();
element(by.id("creator--add-a-piece-empty")).click();//to click on Add

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

答:
var sitepath = "site-100M.zip";
element(by.css('#siteTemplateUploadFile')).sendKeys("D:/localresources/"+sitepath);

This is my code which works fine.

Body:
I am using protractor to automate my website. I have a scenario where need to upload the file clicking on upload button. When clicked on upload button then it renders the native os popup to select the file.

I tried to upload using below code without clicking on upload button.I think this approach is not correct as the user has to click on upload button and then select the file from native os popup.But still no luck

var fileToUpload = 'filePath';
var absolutePath = path.resolve(__dirname, fileToUpload);
element(by.id("creator--add-a-piece-empty")).sendKeys(absolutePath);

How to select the file in native os pop ? Is there any way to upload

Operating system - Mac siera

I have tried all the possible solution provided on How to upload file in angularjs e2e protractor testing But no luck . I have added the code below s ,that will redirect you to the problem page ,where i need to upload the file.Thanks in Advance.

describe('NeonMob', function() {
it('LoginUsingInvalidEmail', function() {
browser.get('https://staging.neonmob.com/login');
element(by.id('form-field-username')).click();
element(by.id('field-username')).sendKeys("sharif");
element(by.id('field-password')).sendKeys("1234");
element(by.id('signin-btn')).click();
element(by.css("a[id='primary-navigation--create']")).click();
element(by.id("create-new-amateur-series")).click();
element(by.id("confirm-btn")).click();
element(by.id("creator--add-a-piece-empty")).click();//to click on Add

});
});


答:
ah jeez.. I figured out a simple way to get the data out. I can do something like this:

```<code>currentrow = data[i];
id = currentrow.id;
</code>```

Or use id or the other values as such. Nevermind my posting, I'm an idiot sometimes

Title: Traverse simple javascript object

Body:
ah jeez.. I figured out a simple way to get the data out. I can do something like this:

currentrow = data[i];
id = currentrow.id;

Or use id or the other values as such. Nevermind my posting, I'm an idiot sometimes


问:
Bootstrap Carousel Event Listiner Not Working
I'm trying to adjust the intervals between carousel slides by using js to update the timeout using the following code:

```<code>**var t;
var start = $('#carousel').find('.active').attr('data-interval');
t = setTimeout("$('#carousel').carousel({interval: 3500});", start-3500);
$('#carousel').on('slid.bs.carousel', function () {
     clearTimeout(t);

     var duration = $(this).find('.active').attr('data-interval');
        alert("slide event");

     $('#carousel').carousel('pause');
     t = setTimeout("$('#carousel').carousel();", duration-3500);
})**

As you can see, I even added and alert to let me know the code was invoked, but it never is and I don't know why.

I even added the following code in an attempt to confirm the slide.bs.carousel event but to no avail:

**$('#carousel').bind('slide.bs.carousel', function (e) {
    console.log('slide event!');
    alert("invoked");
});**

The html looks like this:

**
<div id="carousel" class="carousel slide">

    <!-- Carousel items -->
    <div class="carousel-inner">
        <div class="active item" data-interval="3000">
            <img src="image2" />
        </div>
        <div class="item" data-interval="6000">
            <img src="image3" />
        </div>
        <div class="item" data-interval="9000">
            <img src="image1" />
        </div>
    </div>
</div>**
</code>```

Can anyone please tell me what it is I am doing wrong here?

Thank you....

Rick

答:
Once you started(initiated) the carousel, the correct way to reset interval should be:

```<code>$('#carousel').data("bs.carousel").options.interval =  500;
</code>```

var t;
var start = $('#carousel').find('.active').attr('data-interval');
t = setTimeout(function() {
  $('#carousel').carousel({
    interval: 3500
  });
}, start - 3500);

var counter = 0;
$('#carousel').on('slide.bs.carousel', function(e) {

  counter++;
  console.log('interval -> ' + counter*500);
  $('#carousel').data("bs.carousel").options.interval = counter * 500;
})

$('#carousel').bind('slide.bs.carousel', function(e) {
  console.log('slide event!');
  // alert("invoked");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id="carousel" class="carousel slide">
  <!-- Carousel items -->
  <div class="carousel-inner">
    <div class="active item">
      <img src="http://via.placeholder.com/100x100" />
    </div>
    <div class="item">
      <img src="http://via.placeholder.com/200x200" />
    </div>
    <div class="item">
      <img src="http://via.placeholder.com/300x300" />
    </div>
  </div>
</div></code>```

Body:
I'm trying to adjust the intervals between carousel slides by using js to update the timeout using the following code:

**var t;
var start = $('#carousel').find('.active').attr('data-interval');
t = setTimeout("$('#carousel').carousel({interval: 3500});", start-3500);
$('#carousel').on('slid.bs.carousel', function () {
     clearTimeout(t);

     var duration = $(this).find('.active').attr('data-interval');
        alert("slide event");

     $('#carousel').carousel('pause');
     t = setTimeout("$('#carousel').carousel();", duration-3500);
})**

As you can see, I even added and alert to let me know the code was invoked, but it never is and I don't know why.

I even added the following code in an attempt to confirm the slide.bs.carousel event but to no avail:

**$('#carousel').bind('slide.bs.carousel', function (e) {
    console.log('slide event!');
    alert("invoked");
});**

The html looks like this:

**

**

Can anyone please tell me what it is I am doing wrong here?

Thank you....

Rick

Body:
Once you started(initiated) the carousel, the correct way to reset interval should be:

$('#carousel').data("bs.carousel").options.interval =  500;

var t;
var start = $('#carousel').find('.active').attr('data-interval');
t = setTimeout(function() {
  $('#carousel').carousel({
    interval: 3500
  });
}, start - 3500);

var counter = 0;
$('#carousel').on('slide.bs.carousel', function(e) {

  counter++;
  console.log('interval -> ' + counter*500);
  $('#carousel').data("bs.carousel").options.interval = counter * 500;
})

$('#carousel').bind('slide.bs.carousel', function(e) {
  console.log('slide event!');
  // alert("invoked");
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div id="carousel" class="carousel slide">
  <!-- Carousel items -->
  <div class="carousel-inner">
    <div class="active item">
      <img src="http://via.placeholder.com/100x100" />
    </div>
    <div class="item">
      <img src="http://via.placeholder.com/200x200" />
    </div>
    <div class="item">
      <img src="http://via.placeholder.com/300x300" />
    </div>
  </div>
</div>


问:
How to deploy NodeJS App to Heroku?
I am creating a chat app with NodeJS, and I want to deploy to Heroku. However,  I get an error: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. by using the Github deployment. Does anyone know what is going on?

Here is some code to see what I have done.

```<code>    {
  "name": "chat",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./lib/index.js",
    "test": "jasmine"
  },
  "dependencies": {
    "express": "~4.13.1",
    "firebase": "^3.9.0",
    "request-promise": "^2.0.1",
    "socket.io": "^1.4.5"
  },
  "devDependencies": {
    "jasmine-sinon": "^0.4.0",
    "jscs": "^2.11.0",
    "proxyquire": "^1.7.4",
    "rewire": "^2.5.1",
    "sinon": "^1.17.3"
  }
}
</code>```

index.js (Server)

```<code>    var express = require('express');
var app = express();
var path = require('path');
var http = require('http').Server(app);
var io = require('socket.io')(http);

var routes = require('./routes');
var chats = require('./chat');

app.use(express.static(path.join(__dirname, '../public')));

routes.load(app);
chats.load(io);

var port = process.env.PORT || 3000;
app.listen(port);
console.log('Server is listening at port:' + port);
</code>```

答:
I got the app working in a Heroku. The issue in your code is that you're not setting the correct port for heroku to work. In the code you provided you're setting the correct port by doing

```<code>var port = process.env.PORT || 3000;
</code>```

However, in your GitHub project you're hardcoding the port to 3000

```<code>http.listen(3000, function () {
  console.log('listening on *:3000');
});
</code>```

Instead what you want to do is allow Heroku to define the port or default to 3000 for development like so..

```<code>var process = require('process');

var port = process.env.PORT || 3000;
http.listen(port, function() {
  console.log("Server is listening on port: " + port);
});
</code>```

Once you have that, deploy to Heroku and you should see your app running.

Title: How to deploy NodeJS App to Heroku?

Body:
I am creating a chat app with NodeJS, and I want to deploy to Heroku. However,  I get an error: An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. by using the Github deployment. Does anyone know what is going on?

Here is some code to see what I have done.

    {
  "name": "chat",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./lib/index.js",
    "test": "jasmine"
  },
  "dependencies": {
    "express": "~4.13.1",
    "firebase": "^3.9.0",
    "request-promise": "^2.0.1",
    "socket.io": "^1.4.5"
  },
  "devDependencies": {
    "jasmine-sinon": "^0.4.0",
    "jscs": "^2.11.0",
    "proxyquire": "^1.7.4",
    "rewire": "^2.5.1",
    "sinon": "^1.17.3"
  }
}

index.js (Server)

    var express = require('express');
var app = express();
var path = require('path');
var http = require('http').Server(app);
var io = require('socket.io')(http);

var routes = require('./routes');
var chats = require('./chat');

app.use(express.static(path.join(__dirname, '../public')));

routes.load(app);
chats.load(io);

var port = process.env.PORT || 3000;
app.listen(port);
console.log('Server is listening at port:' + port);

Body:
I got the app working in a Heroku. The issue in your code is that you're not setting the correct port for heroku to work. In the code you provided you're setting the correct port by doing

var port = process.env.PORT || 3000;

However, in your GitHub project you're hardcoding the port to 3000

http.listen(3000, function () {
  console.log('listening on *:3000');
});

Instead what you want to do is allow Heroku to define the port or default to 3000 for development like so..

var process = require('process');

var port = process.env.PORT || 3000;
http.listen(port, function() {
  console.log("Server is listening on port: " + port);
});

Once you have that, deploy to Heroku and you should see your app running.


问:
E/ReactNativeJS: undefined is not an object (evaluating 'b.default.sync')
add codePush into my project with Error:

```<code>E/ReactNativeJS: undefined is not an object (evaluating 'b.default.sync')
</code>```

when I use a new react project with module app, install code push as the document says https://github.com/Microsoft/react-native-code-push/blob/master/docs/setup-android.md

everything is fine.

But When I add code push into my existing project, the module named "passenger", not "app", I follow the step with the document, add code push Manual.

also add code into index.android.js

```<code>import CodePush from "react-native-code-push";

componentDidMount(){
        console.log("CodePush");
        CodePush.sync();
    }
</code>```

When I run my module, this error come across. CodePush undefined.
Is anybody know what wrong with it?

答:
Finally I solved this problem by add some line in my MainActivity:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mReactRootView = new ReactRootView(this);
    mReactInstanceManager = ReactInstanceManager.builder()
            .setApplication(getApplication())
            .setBundleAssetName("main.bundle")
            .setJSMainModuleName("TingBadgeManager")
            .addPackage(new SQLitePluginPackage())
            .addPackage(new CodePush("xxx", getApplicationContext(), com.xxx.xxx.BuildConfig.DEBUG))       // register CodePush Plugin here
            .addPackage(new MainReactPackage())
            .setUseDeveloperSupport(true)
            .setInitialLifecycleState(LifecycleState.RESUMED)
            .build();
    mReactRootView.startReactApplication(mReactInstanceManager, "TingBadgeManager", null);
    setContentView(mReactRootView);
}
</code>```

Key point is that if you create your RN in an Activity you should add CodePush with addPackage in mReactInstanceManager.
Hope this can help.

Issue related : https://github.com/Microsoft/react-native-code-push/issues/871

Body:
add codePush into my project with Error:

E/ReactNativeJS: undefined is not an object (evaluating 'b.default.sync')

when I use a new react project with module app, install code push as the document says https://github.com/Microsoft/react-native-code-push/blob/master/docs/setup-android.md

everything is fine.

But When I add code push into my existing project, the module named "passenger", not "app", I follow the step with the document, add code push Manual.

also add code into index.android.js

import CodePush from "react-native-code-push";

componentDidMount(){
        console.log("CodePush");
        CodePush.sync();
    }

When I run my module, this error come across. CodePush undefined.
Is anybody know what wrong with it?

Body:
Finally I solved this problem by add some line in my MainActivity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mReactRootView = new ReactRootView(this);
    mReactInstanceManager = ReactInstanceManager.builder()
            .setApplication(getApplication())
            .setBundleAssetName("main.bundle")
            .setJSMainModuleName("TingBadgeManager")
            .addPackage(new SQLitePluginPackage())
            .addPackage(new CodePush("xxx", getApplicationContext(), com.xxx.xxx.BuildConfig.DEBUG))       // register CodePush Plugin here
            .addPackage(new MainReactPackage())
            .setUseDeveloperSupport(true)
            .setInitialLifecycleState(LifecycleState.RESUMED)
            .build();
    mReactRootView.startReactApplication(mReactInstanceManager, "TingBadgeManager", null);
    setContentView(mReactRootView);
}

Key point is that if you create your RN in an Activity you should add CodePush with addPackage in mReactInstanceManager.
Hope this can help.

Issue related : https://github.com/Microsoft/react-native-code-push/issues/871


问:
Select element with selenium python
Consider the following HTML:

```<code> <div class="nav-category__col" id="category_nav_level_3" style="display: block;">
   <input type="hidden" value="1" name="videogame_type" id="videogame_type">
   <ul class="nav-category__list" adparam_name="videogame_type" role="radiogroup">
      <li class="nav-category__list-item  nav-category__list-item--selected" id="1" tabindex="-1" role="radio" aria-checked="true">
         <p class="nav-category__name">Consoles</p>
      </li>
      <li class="nav-category__list-item " id="2" tabindex="-1" role="radio" aria-checked="false">
         <p class="nav-category__name">Jogos</p>
      </li>
      <li class="nav-category__list-item " id="3" tabindex="-1" role="radio" aria-checked="false">
         <p class="nav-category__name">Acessórios</p>
      </li>
   </ul>
</div>
</code>```

I want to click on
Consoles
 so I tried doing this:

```<code>    elem = driver.find_element_by_xpath("//*[@id="1"]/p")
    elem.click()
</code>```

I found this xpath by inspecting the element and copying the xpath from it, but it says "Unable to locate element" anyway. How could I do it right?

I don't know very much of HTML, but I am capable of finding other elements by id or by name.

答:
Yo don't need to know any HTML attribute for Selenium IDE,

```<code>https://addons.mozilla.org/en-US/firefox/addon/selenium-ide/
</code>```

install this exention in your Firefox Browser (It works just work with Firefox). And then open it, push the record button, and then do your scenerio. Finally stop and export your code for Python, or other language. If you look around to ide you can see any attribute type, like to 'name, id, cssSelector, Xpath...' and you can change which one you want.

Or your question,

```<code>elem = driver.find_element_by_name("q") // Name
elem = driver.find_element_by_id("q") // ID
menu = driver.find_element_by_css_selector(".nav") // CssSelector
</code>```

you got it :)

```<code>find_element_by_*methods
</code>```

Have a nice code :)

Title: Select element with selenium python

Body:
Consider the following HTML:

   <input type="hidden" value="1" name="videogame_type" id="videogame_type">

Consoles

Jogos

Acessórios

I want to click on
Consoles
 so I tried doing this:

    elem = driver.find_element_by_xpath("//*[@id="1"]/p")
    elem.click()

I found this xpath by inspecting the element and copying the xpath from it, but it says "Unable to locate element" anyway. How could I do it right?

I don't know very much of HTML, but I am capable of finding other elements by id or by name.

Body:
Yo don't need to know any HTML attribute for Selenium IDE,

https://addons.mozilla.org/en-US/firefox/addon/selenium-ide/

install this exention in your Firefox Browser (It works just work with Firefox). And then open it, push the record button, and then do your scenerio. Finally stop and export your code for Python, or other language. If you look around to ide you can see any attribute type, like to 'name, id, cssSelector, Xpath...' and you can change which one you want.

Or your question,

elem = driver.find_element_by_name("q") // Name
elem = driver.find_element_by_id("q") // ID
menu = driver.find_element_by_css_selector(".nav") // CssSelector

you got it :)

find_element_by_*methods

Have a nice code :)


问:
split a string using javascript
I have a string like ";a;b;c;;e". Notice that there is an extra semicolon before e. I want the string to be split in a, b, c;, e. But it gets split like a, b, c, ;e.

My code is

```<code>var new_arr = str.split(';');
</code>```

What can I do over here to get the result I want?

Regards

答:
Interesting, I get ["", "a", "b", "c", "", "e"] with your code.

```<code>var new_array = ";a;b;c;;e".split(/;(?!;)/);
new_array.shift();
</code>```

This works in Firefox, but I think it's correct.  You might need this cross-browser split for other browsers.

Title: split a string using javascript

Body:
I have a string like ";a;b;c;;e". Notice that there is an extra semicolon before e. I want the string to be split in a, b, c;, e. But it gets split like a, b, c, ;e.

My code is

var new_arr = str.split(';');

What can I do over here to get the result I want?

Regards

Body:
Interesting, I get ["", "a", "b", "c", "", "e"] with your code.

var new_array = ";a;b;c;;e".split(/;(?!;)/);
new_array.shift();

This works in Firefox, but I think it's correct.  You might need this cross-browser split for other browsers.


问:
javascript - if/else never returns true?
I need to do this without using parseInt but I'm not sure how to do it. I'm trying to check the answer against the actual value of a * b. I think what's wrong is that I'm not actually able to retrieve the textbox value. What is the best way to do that?

var answer = document.getElementById('answer');
var a = Math.floor((Math.random() * 12) + 1);
var b = Math.floor((Math.random() * 12) + 1);
document.getElementById('question').innerHTML = "What is " + a + " times " + b + "?";

function wrongRight() {
  if (a * b == answer) {
    document.getElementById('response').innerHTML = "Very good.";
  } else {
    document.getElementById('response').innerHTML = "No, please try again.";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="response"></p>
<p id="question"></p>
<!-- this is where the x * x = ? will be asked-->
<p> your answer </p>
<input type="text" id="answer">
<input type="button" value="Click" onClick="wrongRight()"></code>```

答:
Yea, as mentioned in the comments you're comparing a number to a DOM node.
In your function wrongRight replace the answer with +answer.value. The plus converts it into an integer from a string. e.g.

```<code>function wrongRight() {
    if(a * b == +answer.value) {
        document.getElementById('response').innerHTML = "Very good.";
    } else{
        document.getElementById('response').innerHTML = "No, please try again.";
    }
}
</code>```

Body:
I need to do this without using parseInt but I'm not sure how to do it. I'm trying to check the answer against the actual value of a * b. I think what's wrong is that I'm not actually able to retrieve the textbox value. What is the best way to do that?

var answer = document.getElementById('answer');
var a = Math.floor((Math.random() * 12) + 1);
var b = Math.floor((Math.random() * 12) + 1);
document.getElementById('question').innerHTML = "What is " + a + " times " + b + "?";

function wrongRight() {
  if (a * b == answer) {
    document.getElementById('response').innerHTML = "Very good.";
  } else {
    document.getElementById('response').innerHTML = "No, please try again.";
  }
}

 your answer

<input type="text" id="answer">
<input type="button" value="Click" onClick="wrongRight()">

Body:
Yea, as mentioned in the comments you're comparing a number to a DOM node.
In your function wrongRight replace the answer with +answer.value. The plus converts it into an integer from a string. e.g.

function wrongRight() {
    if(a * b == +answer.value) {
        document.getElementById('response').innerHTML = "Very good.";
    } else{
        document.getElementById('response').innerHTML = "No, please try again.";
    }
}


问:
$(...).tabs() is not a function using Spring MVC and jQuery 3.1.0
I'm running a web portal locally using Spring MVC and I'm having difficulty getting the jQuery tabs to work properly. I always get the error $(...).tabs() is not a function.

Here is my jsp:

```<code><!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
  <spring:url value="/resources/css/style.css" var="css" />
  <spring:url value="/resources/js/main.js" var="js" />
  <link rel='stylesheet' type='text/css' href="${css}">
  <script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
  <script src="${js}"></script>
  <title>Title</title>
</head>
<body>

  <h1>Title</h1>
  <div id="tabs">
    <ul>
      <li><a href='#current-projects'>Current Projects</a></li>
      <li><a href='#our-vision'>Our Vision</a></li>
      <li><a href='#description'>About Us</a></li>
    </ul>
    <div id='current-projects' class='skill-block'>
      <h2>Current Projects</h2>
      <p class='description'>
        <div class='projects-button'>Show</div>
        <ul class='projects'>
          <li>Broadway</li>
          <li>MOVE</li>
        </ul>
      </p>
    </div>
    <div id='our-vision' class='skill-block'>
      <h2>Our Vision</h2>
      <p class='description'>
        <div class='projects-button'>Show</div>
        <ul class='projects'>
          <li>Password Validator</li>
          <li>Whale Talk</li>
        </ul>
      </p>
    </div>
    <div id='description' class='skill-block'>
      <h2>About Us</h2>
      <p class='description'>
        <div class='projects-button'>Show</div>
        <ul class='projects'>
          <li>Coming soon...</li>
        </ul>
      </p>
    </div>
  </div>

</body>

</html>
</code>```

Here is my main.js (Note that all the other jQuery functionalities work, it's just the tabs() that has the error):

```<code>(function() {
    $(document).ready(function() {
        $('#tabs').tabs();
        $('.projects').hide();
        $('.projects-button').on('click', function(){
            var button = $(this);
            button.next().slideToggle(400);
            button.toggleClass('active');
            button.text(button.hasClass('active') ? 'Hide' : 'Show');
        })
    });
})();
</code>```

I've also tried downloading the jQuery file to load it locally but the same error occurs.

答:
.tabs() is a jquery ui function .. you need to include jquery ui .. So after the line for include jquery insert this line

```<code><script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
</code>```

(function() {
    $(document).ready(function() {
        $('#tabs').tabs();
        $('.projects').hide();
        $('.projects-button').on('click', function(){
            var button = $(this);
            button.next().slideToggle(400);
            button.toggleClass('active');
            button.text(button.hasClass('active') ? 'Hide' : 'Show');
        })
    });
})();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

<h1>Title</h1>
<div id="tabs">
  <ul>
    <li>Current Projects</li>
    <li>Our Vision</li>
    <li>About Us</li>
  </ul>
  <div id='current-projects' class='skill-block'>
    <h2>Current Projects</h2>
    <p class='description'>
      <div class='projects-button'>Show</div>
      <ul class='projects'>
        <li>Broadway</li>
        <li>MOVE</li>
      </ul>
    </p>
  </div>
  <div id='our-vision' class='skill-block'>
    <h2>Our Vision</h2>
    <p class='description'>
      <div class='projects-button'>Show</div>
      <ul class='projects'>
        <li>Password Validator</li>
        <li>Whale Talk</li>
      </ul>
    </p>
  </div>
  <div id='description' class='skill-block'>
    <h2>About Us</h2>
    <p class='description'>
      <div class='projects-button'>Show</div>
      <ul class='projects'>
        <li>Coming soon...</li>
      </ul>
    </p>
  </div>
</div></code>```

Body:
I'm running a web portal locally using Spring MVC and I'm having difficulty getting the jQuery tabs to work properly. I always get the error $(...).tabs() is not a function.

Here is my jsp:

<!DOCTYPE html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

  <spring:url value="/resources/css/style.css" var="css" />
  <spring:url value="/resources/js/main.js" var="js" />
  <link rel='stylesheet' type='text/css' href="${css}">

  <title>Title</title>

Title

Current Projects

Our Vision

About Us

Current Projects

Show

Broadway

MOVE

Our Vision

Show

Password Validator

Whale Talk

About Us

Show

Coming soon...

Here is my main.js (Note that all the other jQuery functionalities work, it's just the tabs() that has the error):

(function() {
    $(document).ready(function() {
        $('#tabs').tabs();
        $('.projects').hide();
        $('.projects-button').on('click', function(){
            var button = $(this);
            button.next().slideToggle(400);
            button.toggleClass('active');
            button.text(button.hasClass('active') ? 'Hide' : 'Show');
        })
    });
})();

I've also tried downloading the jQuery file to load it locally but the same error occurs.

Body:
.tabs() is a jquery ui function .. you need to include jquery ui .. So after the line for include jquery insert this line

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

(function() {
    $(document).ready(function() {
        $('#tabs').tabs();
        $('.projects').hide();
        $('.projects-button').on('click', function(){
            var button = $(this);
            button.next().slideToggle(400);
            button.toggleClass('active');
            button.text(button.hasClass('active') ? 'Hide' : 'Show');
        })
    });
})();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

<h1>Title</h1>
<div id="tabs">
  <ul>
    <li><a href='#current-projects'>Current Projects</a></li>
    <li><a href='#our-vision'>Our Vision</a></li>
    <li><a href='#description'>About Us</a></li>
  </ul>
  <div id='current-projects' class='skill-block'>
    <h2>Current Projects</h2>
    <p class='description'>
      <div class='projects-button'>Show</div>
      <ul class='projects'>
        <li>Broadway</li>
        <li>MOVE</li>
      </ul>
    </p>
  </div>
  <div id='our-vision' class='skill-block'>
    <h2>Our Vision</h2>
    <p class='description'>
      <div class='projects-button'>Show</div>
      <ul class='projects'>
        <li>Password Validator</li>
        <li>Whale Talk</li>
      </ul>
    </p>
  </div>
  <div id='description' class='skill-block'>
    <h2>About Us</h2>
    <p class='description'>
      <div class='projects-button'>Show</div>
      <ul class='projects'>
        <li>Coming soon...</li>
      </ul>
    </p>
  </div>
</div>


问:
Lodash - Retrieve an array of values for all object properties
I have something like

```<code>const payload = [{'name':'john doe', 'company': 'abc', 'age': 35},
                 {'name':'jane doe', 'company': 'def', 'age': 36}]

_.map(users, "name") => ['john doe', 'jane doe']
_.map(users, "company") => ['abc', 'def']
</code>```

I want to have one call to retrieve the name, company and age from the payload. I don't want to make 3 calls with the map function. How can I do this? Because my payload is huge with a lot of properties.

Thanks!

答:
You can use lodash#pick wrapped inside a lodash#partial as the iteratee for lodash#map.

```<code>const result = _.map(payload, _.partial(_.pick, _, ['name', 'company']));
</code>```

const payload = [{
    'name': 'john doe',
    'company': 'abc',
    'age': 35
  },
  {
    'name': 'jane doe',
    'company': 'def',
    'age': 36
  }
];

const result = _.map(payload, _.partial(_.pick, _, ['name', 'company']));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body > div { min-height: 100%; top: 0; }</code>```

```

Body:
I have something like

const payload = [{'name':'john doe', 'company': 'abc', 'age': 35},
                 {'name':'jane doe', 'company': 'def', 'age': 36}]

_.map(users, "name") => ['john doe', 'jane doe']
_.map(users, "company") => ['abc', 'def']

I want to have one call to retrieve the name, company and age from the payload. I don't want to make 3 calls with the map function. How can I do this? Because my payload is huge with a lot of properties.

Thanks!

Body:
You can use lodash#pick wrapped inside a lodash#partial as the iteratee for lodash#map.

const result = _.map(payload, _.partial(_.pick, _, ['name', 'company']));

const payload = [{
    'name': 'john doe',
    'company': 'abc',
    'age': 35
  },
  {
    'name': 'jane doe',
    'company': 'def',
    'age': 36
  }
];

const result = _.map(payload, _.partial(_.pick, _, ['name', 'company']));

console.log(result);

body > div { min-height: 100%; top: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>


问:
Retrieval of multiple author affiliations using RISmed from Medline object
In using the RISmed- R-package for automating data(abstract/author/affiliation etc.) retrieval from Medline, I can't retrieve multiple affiliations using the Affiliation() method. Only a first author's affiliation is retrieved  even through multiple are available. From the https://www.nlm.nih.gov/bsd/mms/medlineelements.html#ad
it appears that after Dec 2014 multiple affiliations are included in the affiliation field. Analogously the Author() method retrieves a list that contains multiple data frames accounting for all author data. Does anyone know if the Affiliation() method can do the same?

For example:
In retrieving affiliations for : https://www.ncbi.nlm.nih.gov/pubmed/28578058
note from the link that there are 4 different affiliations. When executing the code below only first one is returned:

```<code>      library(RISmed)
      RetrievePub <- EUtilsGet(28578058)

         #Retrieve authorship
         AData <- data.frame(Author(RetrievePub))
         Results_Authors = paste(paste(AData$ForeName, AData$LastName),
          collapse = " | ") #flatten data frame into string
         print(Results_Authors)

         #Retrieve affiliation
         Results_PubAffiliation = Affiliation(RetrievePub)
         print(Results_PubAffiliation)
</code>```

答: RISmed Version 2.1.6 only returned the Affiliation for the first author. The latest version (2.1.7) now provides the list of all affiliations in the same order as the author list. This is now available at https://github.com/skoval/RISmed and can be installed with devtools. It should be available from CRAN in the next day or so.</p>

Body:
In using the RISmed- R-package for automating data(abstract/author/affiliation etc.) retrieval from Medline, I can't retrieve multiple affiliations using the Affiliation() method. Only a first author's affiliation is retrieved  even through multiple are available. From the https://www.nlm.nih.gov/bsd/mms/medlineelements.html#ad
it appears that after Dec 2014 multiple affiliations are included in the affiliation field. Analogously the Author() method retrieves a list that contains multiple data frames accounting for all author data. Does anyone know if the Affiliation() method can do the same?

For example:
In retrieving affiliations for : https://www.ncbi.nlm.nih.gov/pubmed/28578058
note from the link that there are 4 different affiliations. When executing the code below only first one is returned:

      library(RISmed)
      RetrievePub <- EUtilsGet(28578058)

         #Retrieve authorship
         AData <- data.frame(Author(RetrievePub))
         Results_Authors = paste(paste(AData$ForeName, AData$LastName),
          collapse = " | ") #flatten data frame into string
         print(Results_Authors)

         #Retrieve affiliation
         Results_PubAffiliation = Affiliation(RetrievePub)
         print(Results_PubAffiliation)


答: Well, I am dumb: I was trying to select an element before it was on the page. Solved by adding time.sleep(3) before elem = driver.find_element_by_xpath("//*[@id="1"]/p")

Title: Select element with selenium python


问:
How to parse a weirdly formatted data file?
How to read a weirdly formatted data file?

For example if there are different types of seperators (, : |) all used together?

Looking at a dataframe example, something along these lines:

答:
A monstrous response to the monstrous data. First, split each column containing k:v pairs and convert them to pandas Series. Combine the results for all three "Other" columns into one dataframe:

```<code>others = pd.concat(data[x].str.split(':').apply(pd.Series)
                   for x in ('Other1', 'Other2', 'Other3')).dropna(how='all')

#                  0                  1
#0          Hospital   Awesome Hospital
#1           Hobbies            Cooking
#2          Hospital   Awesome Hospital
#0       Maiden Name              Rubin
#1  Hobby Experience           10 years
#2       Maiden Name            Simpson
#0               DOB         2015/04/09
#2               DOB         2015/04/16
</code>```

Do some index manipulations (we want the keys to become column names):

```<code>others = others.reset_index().set_index(['index',0]).unstack()
#                 1
#0              DOB   Hobbies Hobby Experience           Hospital Maiden Name
#index
#0       2015/04/09      None             None   Awesome Hospital       Rubin
#1             None   Cooking         10 years               None        None
#2       2015/04/16      None             None   Awesome Hospital     Simpson
</code>```

Remove the hierarchical column index produced by unstack():

```<code>others.columns = others.columns.get_level_values(0)
</code>```

Put the pieces together again:

```<code>pd.concat([data[["Full Name","Town"]], others], axis=1)
</code>```

Body:
A monstrous response to the monstrous data. First, split each column containing k:v pairs and convert them to pandas Series. Combine the results for all three "Other" columns into one dataframe:

others = pd.concat(data[x].str.split(':').apply(pd.Series)
                   for x in ('Other1', 'Other2', 'Other3')).dropna(how='all')

#                  0                  1
#0          Hospital   Awesome Hospital
#1           Hobbies            Cooking
#2          Hospital   Awesome Hospital
#0       Maiden Name              Rubin
#1  Hobby Experience           10 years
#2       Maiden Name            Simpson
#0               DOB         2015/04/09
#2               DOB         2015/04/16

Do some index manipulations (we want the keys to become column names):

others = others.reset_index().set_index(['index',0]).unstack()
#                 1
#0              DOB   Hobbies Hobby Experience           Hospital Maiden Name
#index
#0       2015/04/09      None             None   Awesome Hospital       Rubin
#1             None   Cooking         10 years               None        None
#2       2015/04/16      None             None   Awesome Hospital     Simpson

Remove the hierarchical column index produced by unstack():

others.columns = others.columns.get_level_values(0)

Put the pieces together again:

pd.concat([data[["Full Name","Town"]], others], axis=1)


答:
```<code>var myArr = new Array();

var myString = new String();

myString = ";a;b;c;;e";

myArr = myString.split(";");

for(var i=0;i<myArr.length;i++)
{
    document.write( myArr[i] );
}
</code>```

Title: split a string using javascript


问:
?? Operator - Using in one liner condition
Can someone explain how the below statement operates. I know that the ?? operator returns the first argument if it is not null. But I was a little confused when I saw the ? following the 'file' variable.</p>

```<code>return file?.ImportStatus ?? ImportStatusEnum.Unknown;
</code>```

答:
This is a combination of null propagation and null coalesce operators.

It will produce ImportStatusEnum.Unknown in the following cases:

file is null - In this case, .ImportStatus is not evaluated, and the left side of ?? becomes null, or

file is not null, but ImportStatus is null - in this case, the left side of ?? is also null, so the right side is used.

If neither file nor its ImportStatus are null, then the value of file.ImportStatus will be used as the result of the overall expression.

Body:
Can someone explain how the below statement operates. I know that the ?? operator returns the first argument if it is not null. But I was a little confused when I saw the ? following the 'file' variable.

return file?.ImportStatus ?? ImportStatusEnum.Unknown;


问:
How to get authentication for /QNTC/{windows Share drive IP} in AS400?

 I am trying to sync the share drive content say X:(IP)of windows , and access the contents of share drive X: from AS400 terminal using WRKLNK '/qntc/{IPADDRESS}' .

As per the forum FTP Jar file from share path on windows to IFS location in AS400? the authentication of MKDIR '/QNTC/{IPADDRESS}' require separate question . So please provide solutions.

答:
Sorry for late response. Time of year and other stuff have been very distracting.

What are the OS versions of IBM i and Windows? As Windows changes between releases, networking also changes. Both ends need to maintain compatible networking levels. Other elements can also be important, but which questions can depend on the OS releases.

For perhaps the simplest approach, an IBM i user profile may be set with a password and a same-named user can be created on the Windows system with the same password. Password rules at their simplest would have 10-character maximum length on IBM i and would be all upper-case. The Windows password should match upper-case, but all lower-case also works most often. The Windows user should be created as a local machine (not domain) user.

A job on IBM i would run under the matching user. That might be due to logging on as that user, running a SBMJOB that specifies that user or using one of the security APIs to switch the job temporarily to that user while the connection is used.

From that basic level, a couple more complex (and more secure) methods are possible. All will be easier if the simplest is already working. There might be PTFs or configuration changes needed to get Windows and IBM i working together, and those will be easier to determine before looking for more secure connections.

Nowadays, it can be better to leave Windows networking behind and start using NFS instead. That means ignoring /QNTC and making sure that NFS is installed and active on the Windows system. It can also mean that management of user uids and guids needs to be started. Few AS/400s and later systems have paid any attention to those, but the time might have arrived to get started.


问:
Asp.Net Core performance issues when started under load
I'm experiencing an issue with an asp.net core application that virtually hangs when started under load.  Once started, the application can handle the load no problem. It feels like initialization is happening for every concurrent request. Is anyone else experiencing similar behavior?

test scenario:

start a test application that hits the service with 50 simultaneous tasks

start the service

notice the requests getting started, but extremely long delays before any start to finish and most will time out

As a temporary work around, I created middleware that throttles subsequent requests until the very first finishes. This effectively lets asp.net mvc initialize before processing the bulk of the requests. This particular app is asp.net core 1.1 (web api) with EF core.

答:
When using a real database located halfway across the country, I experience a good 900ms delay for the first request to my ASP.NET Core WebAPI. This is because it needs to get a connection pool established for use with connecting to said database, and I do not eagerly create a connection pool when running the service. Instead, it gets initialized lazily when I request a connection via a connection factory that is registered as a singleton in the services container.

Perhaps you're experiencing the same type of delay as you stated you're using Entity Framework Core, which is presumably backed by SQL Server. Is a connection pool with the database being initiated lazily as part of this initial request?

Try making a controller that does not have any dependencies that returns a vanilla 200 OK. Assuming you do not have global filters that have expensive services to hydrate, you should see the baseline initialization performance of your web service.


问:
Getting NaN in Javascript With Simple Calculation
```<code><script>
function runCals() {
   var milesRun = document.getElementById("runDist")
   var runCals = Number(milesRun) * 96
   document.getElementById("cals").innerHTML = runCals
}

</script>
</code>```

I am getting NaN and I do not understand why. I visited many stack questions but none I found had my specific problem.

Why am I getting NaN and how do I fix it?

答:
milesRun is not a number, it's a DOM node, so you can't convert it to a number. If it's an input box just add .value to the end of the selector to extract the value inputted into it. e.g.

```<code>function runCals() {
   var milesRun = document.getElementById("runDist").value
   var runCals = Number(milesRun) * 96
   document.getElementById("cals").innerHTML = runCals
}
</code>```

Body:
milesRun is not a number, it's a DOM node, so you can't convert it to a number. If it's an input box just add .value to the end of the selector to extract the value inputted into it. e.g.

function runCals() {
   var milesRun = document.getElementById("runDist").value
   var runCals = Number(milesRun) * 96
   document.getElementById("cals").innerHTML = runCals
}


问:
Perform Action on Navigation Header - Xamarin
I am performing an action on the Navigation header where i have a text called "log in user". The "log in user" text is in a layout file called navheader.

On my home page(main activty), is where i want to perform the activity. When i draw out the navigation drawer and click on the "log in user", i get an exception thrown Object reference not set to an instance of an object.

nav_header.axml

```<code><TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="LOG IN"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:textColor="#FFFFFF"
        android:textSize="16dp"
        android:id="@+id/login"/>
</code>```

Main Activity.cs

```<code>loginUser = FindViewById<TextView>(Resource.Id.login);

loginUser.Click += login_User;

 private void login_User(object sender, EventArgs e)
    {
        Intent intent = new Intent(this, typeof(loginPage));
        this.StartActivity(intent);

    }
</code>```

答:
If you are using android.support.design.widget.NavigationView you can't directly access to the views inside your header view from MainActivity because your header view is not direct part of your xml code for MainActivity. You will have to do something like this:

```<code>var navigationView = FindViewById<NavigationView>(Resource.Id.nav_view); //whatever your Id for navigationview is
var headerView = navigationView.GetHeaderView(0);
var loginUser = headerView.FindViewById<TextView>(Resource.Id.login);

loginUser.Click += login_User;

private void login_User(object sender, EventArgs e)
{
    Intent intent = new Intent(this, typeof(loginPage));
    this.StartActivity(intent);
}
</code>```

Body:
I am performing an action on the Navigation header where i have a text called "log in user". The "log in user" text is in a layout file called navheader.

On my home page(main activty), is where i want to perform the activity. When i draw out the navigation drawer and click on the "log in user", i get an exception thrown Object reference not set to an instance of an object.

nav_header.axml

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="LOG IN"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1"
        android:textColor="#FFFFFF"
        android:textSize="16dp"
        android:id="@+id/login"/>

Main Activity.cs

loginUser = FindViewById<TextView>(Resource.Id.login);

loginUser.Click += login_User;

 private void login_User(object sender, EventArgs e)
    {
        Intent intent = new Intent(this, typeof(loginPage));
        this.StartActivity(intent);

    }

Body:
If you are using android.support.design.widget.NavigationView you can't directly access to the views inside your header view from MainActivity because your header view is not direct part of your xml code for MainActivity. You will have to do something like this:

var navigationView = FindViewById<NavigationView>(Resource.Id.nav_view); //whatever your Id for navigationview is
var headerView = navigationView.GetHeaderView(0);
var loginUser = headerView.FindViewById<TextView>(Resource.Id.login);

loginUser.Click += login_User;

private void login_User(object sender, EventArgs e)
{
    Intent intent = new Intent(this, typeof(loginPage));
    this.StartActivity(intent);
}