问:
Instaling laravel on linux mint
I am kinda a new one with laravel and mint. I just cn't get the stuff out - whats is going on. I need some answer like for a monkey actually. So whatever i will accept any question thanks a lot for any help.</p>

```<code>Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - laravel/framework v5.4.9 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.8 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.7 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.6 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.5 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.4 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.3 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.25 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.24 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.23 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.22 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.21 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.20 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.2 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.19 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.18 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.17 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.16 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.15 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.14 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.13 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.12 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.11 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.10 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.1 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.0 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - Installation request for laravel/framework 5.4.* -> satisfiable by laravel/framework[v5.4.0, v5.4.1, v5.4.10, v5.4.11, v5.4.12, v5.4.13, v5.4.14, v5.4.15, v5.4.16, v5.4.17, v5.4.18, v5.4.19, v5.4.2, v5.4.20, v5.4.21, v5.4.22, v5.4.23, v5.4.24, v5.4.25, v5.4.3, v5.4.4, v5.4.5, v5.4.6, v5.4.7, v5.4.8, v5.4.9].

  To enable extensions, verify that they are enabled in your .ini files:
    - /etc/php/7.0/cli/php.ini
    - /etc/php/7.0/cli/conf.d/10-opcache.ini
    - /etc/php/7.0/cli/conf.d/10-pdo.ini
    - /etc/php/7.0/cli/conf.d/15-xml.ini
    - /etc/php/7.0/cli/conf.d/20-calendar.ini
    - /etc/php/7.0/cli/conf.d/20-ctype.ini
    - /etc/php/7.0/cli/conf.d/20-dom.ini
    - /etc/php/7.0/cli/conf.d/20-exif.ini
    - /etc/php/7.0/cli/conf.d/20-fileinfo.ini
    - /etc/php/7.0/cli/conf.d/20-ftp.ini
    - /etc/php/7.0/cli/conf.d/20-gettext.ini
    - /etc/php/7.0/cli/conf.d/20-gmp.ini
    - /etc/php/7.0/cli/conf.d/20-iconv.ini
    - /etc/php/7.0/cli/conf.d/20-json.ini
    - /etc/php/7.0/cli/conf.d/20-mcrypt.ini
    - /etc/php/7.0/cli/conf.d/20-phar.ini
    - /etc/php/7.0/cli/conf.d/20-posix.ini
    - /etc/php/7.0/cli/conf.d/20-readline.ini
    - /etc/php/7.0/cli/conf.d/20-shmop.ini
    - /etc/php/7.0/cli/conf.d/20-simplexml.ini
    - /etc/php/7.0/cli/conf.d/20-sockets.ini
    - /etc/php/7.0/cli/conf.d/20-sysvmsg.ini
    - /etc/php/7.0/cli/conf.d/20-sysvsem.ini
    - /etc/php/7.0/cli/conf.d/20-sysvshm.ini
    - /etc/php/7.0/cli/conf.d/20-tokenizer.ini
    - /etc/php/7.0/cli/conf.d/20-wddx.ini
    - /etc/php/7.0/cli/conf.d/20-xmlreader.ini
    - /etc/php/7.0/cli/conf.d/20-xmlwriter.ini
    - /etc/php/7.0/cli/conf.d/20-xsl.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.
</code>```

答:
You're missing the mbstring extension in PHP. I'm not sure if Mint uses apt or some other package manager, buy try:

```<code>sudo apt-get install php7.0-mbstring
</code>```

and

```<code>phpenmod mbstring
</code>```

You may have to play around with those commands to match your PHP version, but that should get you started.

Title: Instaling laravel on linux mint

Body:
I am kinda a new one with laravel and mint. I just cn't get the stuff out - whats is going on. I need some answer like for a monkey actually. So whatever i will accept any question thanks a lot for any help.

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - laravel/framework v5.4.9 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.8 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.7 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.6 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.5 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.4 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.3 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.25 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.24 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.23 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.22 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.21 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.20 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.2 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.19 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.18 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.17 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.16 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.15 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.14 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.13 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.12 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.11 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.10 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.1 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.4.0 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - Installation request for laravel/framework 5.4.* -> satisfiable by laravel/framework[v5.4.0, v5.4.1, v5.4.10, v5.4.11, v5.4.12, v5.4.13, v5.4.14, v5.4.15, v5.4.16, v5.4.17, v5.4.18, v5.4.19, v5.4.2, v5.4.20, v5.4.21, v5.4.22, v5.4.23, v5.4.24, v5.4.25, v5.4.3, v5.4.4, v5.4.5, v5.4.6, v5.4.7, v5.4.8, v5.4.9].

  To enable extensions, verify that they are enabled in your .ini files:
    - /etc/php/7.0/cli/php.ini
    - /etc/php/7.0/cli/conf.d/10-opcache.ini
    - /etc/php/7.0/cli/conf.d/10-pdo.ini
    - /etc/php/7.0/cli/conf.d/15-xml.ini
    - /etc/php/7.0/cli/conf.d/20-calendar.ini
    - /etc/php/7.0/cli/conf.d/20-ctype.ini
    - /etc/php/7.0/cli/conf.d/20-dom.ini
    - /etc/php/7.0/cli/conf.d/20-exif.ini
    - /etc/php/7.0/cli/conf.d/20-fileinfo.ini
    - /etc/php/7.0/cli/conf.d/20-ftp.ini
    - /etc/php/7.0/cli/conf.d/20-gettext.ini
    - /etc/php/7.0/cli/conf.d/20-gmp.ini
    - /etc/php/7.0/cli/conf.d/20-iconv.ini
    - /etc/php/7.0/cli/conf.d/20-json.ini
    - /etc/php/7.0/cli/conf.d/20-mcrypt.ini
    - /etc/php/7.0/cli/conf.d/20-phar.ini
    - /etc/php/7.0/cli/conf.d/20-posix.ini
    - /etc/php/7.0/cli/conf.d/20-readline.ini
    - /etc/php/7.0/cli/conf.d/20-shmop.ini
    - /etc/php/7.0/cli/conf.d/20-simplexml.ini
    - /etc/php/7.0/cli/conf.d/20-sockets.ini
    - /etc/php/7.0/cli/conf.d/20-sysvmsg.ini
    - /etc/php/7.0/cli/conf.d/20-sysvsem.ini
    - /etc/php/7.0/cli/conf.d/20-sysvshm.ini
    - /etc/php/7.0/cli/conf.d/20-tokenizer.ini
    - /etc/php/7.0/cli/conf.d/20-wddx.ini
    - /etc/php/7.0/cli/conf.d/20-xmlreader.ini
    - /etc/php/7.0/cli/conf.d/20-xmlwriter.ini
    - /etc/php/7.0/cli/conf.d/20-xsl.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

Body:
You're missing the mbstring extension in PHP. I'm not sure if Mint uses apt or some other package manager, buy try:

sudo apt-get install php7.0-mbstring

and

phpenmod mbstring

You may have to play around with those commands to match your PHP version, but that should get you started.


来源: stackexchange

问:
How can I create a unique session ID like in JSFiddle?
I would like to create a unique session url for each connection on my website  like on JSFiddle

I'm using NodeJS and Express.

The result should be as follow:

for members:

```<code>https://mywebsite.com/user/uniqueID/
*eg : https://mywebsite.com/user/o2gxgz9r/*
</code>```

for guests:

```<code>https://mywebsite.com/uniqueID/
eg : *https://mywebsite.com/k36yot0z/*
</code>```

How can I achieve that and is there any specific frameworks for this kind of job?

答: there are many libraries for generating random id, to name a few: nid, uuid, hyperid, hashids, shortid, etc..</p>

ContentLicense: CC BY-SA 3.0

Body:
I would like to create a unique session url for each connection on my website  like on JSFiddle

I'm using NodeJS and Express.

The result should be as follow:

for members:

https://mywebsite.com/user/uniqueID/
*eg : https://mywebsite.com/user/o2gxgz9r/*

for guests:

https://mywebsite.com/uniqueID/
eg : *https://mywebsite.com/k36yot0z/*

How can I achieve that and is there any specific frameworks for this kind of job?


问:
How to make text that slides horizontally on the screen?
I'm trying to make a text that slides horizontally on the screen, and the text mustn't stop moving. Here's what I have so far:

setInterval(showQuote, 5000);

function showQuote() {
  $('.hey').fadeOut(function() {
    // remove visible class from old quote and add it to new
    // get next quote and fadeIn() when fadeout finishes
  });
}```
<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>

<div class="hey">
  <blockquote>Quote goes here</blockquote>
  <p class="quoteBy">Author</p>
</div>

<div class="quote">
  <blockquote>Second Quote goes here</blockquote>
  <p class="quoteBy">Author</p>
</div></code>```

Can you help me please?

答:
Using pure CSS animations and some JS magic

I have made this with the help of JQuery and Animate.css is it what you are looking for?

You can visit the Animate.css library here.

***I have changed the original code a little bit.

function animateElementsOneByOne(selector, action, interval) {
  var elements = $(selector).toArray();
  var index = 0;
  var timeout = function() {
    setTimeout(function() {
      action(elements[index]);
      if (index + 1 < elements.length) {
        index++;
        timeout();
      }
    }, interval);
  }
  if (elements.length > 0)
    timeout();
}

animateElementsOneByOne('.quote', function(element) {
  element.style.visibility = 'visible';
  $(element).addClass('animated slideInLeft');
}, 1000);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.quote {
  visibility: hidden;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css" rel="stylesheet" />

Quote goes here

Author

Second Quote goes here

Author

Third Quote goes here

Author

```

Body:
I'm trying to make a text that slides horizontally on the screen, and the text mustn't stop moving. Here's what I have so far:

setInterval(showQuote, 5000);

function showQuote() {
  $('.hey').fadeOut(function() {
    // remove visible class from old quote and add it to new
    // get next quote and fadeIn() when fadeout finishes
  });
}

Quote goes here

Author

Second Quote goes here

Author

Can you help me please?

Body:
Using pure CSS animations and some JS magic

I have made this with the help of JQuery and Animate.css is it what you are looking for?

You can visit the Animate.css library here.

***I have changed the original code a little bit.

function animateElementsOneByOne(selector, action, interval) {
  var elements = $(selector).toArray();
  var index = 0;
  var timeout = function() {
    setTimeout(function() {
      action(elements[index]);
      if (index + 1 < elements.length) {
        index++;
        timeout();
      }
    }, interval);
  }
  if (elements.length > 0)
    timeout();
}

animateElementsOneByOne('.quote', function(element) {
  element.style.visibility = 'visible';
  $(element).addClass('animated slideInLeft');
}, 1000);

.quote {
  visibility: hidden;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="quote">
  <blockquote>
    <p>Quote goes here</p>
    <p class="quote-by">Author</p>
  </blockquote>
</div>

<div class="quote">
  <blockquote>
    <p>Second Quote goes here</p>
    <p class="quote-by">Author</p>
  </blockquote>
</div>

<div class="quote">
  <blockquote>
    <p>Third Quote goes here</p>
    <p class="quote-by">Author</p>
  </blockquote>
</div>


问:
Callback listener not working properly
I'm using the Realm library for my app.
I do an asynchronous request to get object like this :

```<code>    public static void getMissions(final List<StatutMission> listStatus, final SListener<List<RMission>> listener) {

    final String[] statesCode = new String[listStatus.size()];

    for (int i = 0; i < listStatus.size(); i++) {
        statesCode[i] = listStatus.get(i).getStateCode();
    }

    final RealmResults<RMission> results = Realm.getDefaultInstance().where(RMission.class).in("state", statesCode).findAllAsync();
    results.addChangeListener(new RealmChangeListener<RealmResults<RMission>>() {
        @Override
        public void onChange(RealmResults<RMission> element) {

            Log.d(TAG, element.size() + " mission(s) found in database with states " + StringUtils.arrayToString(statesCode, ","));
            listener.onResponse(Realm.getDefaultInstance().copyFromRealm(element));
            results.removeChangeListener(this);

        }
    });

}
</code>```

The listener class :

```<code>public interface SListener<T> {

void onResponse(@Nullable T result);
</code>```

}

i tested my code in multiple device but only on one device (samsung tablet) the problem.

Problem code:

```<code>   MissionManager.getMissions(listStatus, new SListener<List<RMission>>() {
        @Override
        public void onResponse(List<RMission> result) {
</code>```

Can anyone help me to solve this issue?

Thanks in advance.

答:
1.) Realm.getDefaultInstance().where(... and Realm.getDefaultInstance().copyFromRealm(... you are opening Realm instances that you will never be able to close, read the docs

2.) you're not preserving the RealmResults as a field reference therefore the finalizer will destroy it before the asynchronous query is evaluated, therefore callback won't be called, read the docs here and here

From javadoc:

Registering a change listener will not prevent the underlying RealmResults from being garbage collected. If the RealmResults is garbage collected, the change listener will stop being triggered. To avoid this, keep a strong reference for as long as appropriate e.g. in a class variable.

```<code>public class MyActivity extends Activity {

    private RealmResults<Person> results; // Strong reference to keep listeners alive

    @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         results = realm.where(Person.class).findAllAsync();
         results.addChangeListener(new RealmChangeListener<RealmResults<Person>>() {
           @Override
           public void onChange(RealmResults<Person> persons) {
               // React to change
           }
       });
     }
     // remove change listeners, and close Realm in onDestroy()
 }
</code>```

3.)  all this hassle for an asynchronously evaluated query is kinda meaningless if you copy every single lazy-evaluated element inside the lazy-evaluated RealmResults EAGERLY, ON THE UI THREAD, so you should reevaluate your logic, specifically after you've read the relevant docs on how Realm queries work.

All fetches (including queries) are lazy in Realm, and the data is never copied.

As the data is never copied, there is no reason for you to use copyFromRealm().

Title: Callback listener not working properly

Body:
I'm using the Realm library for my app.
I do an asynchronous request to get object like this :

    public static void getMissions(final List<StatutMission> listStatus, final SListener<List<RMission>> listener) {

    final String[] statesCode = new String[listStatus.size()];

    for (int i = 0; i < listStatus.size(); i++) {
        statesCode[i] = listStatus.get(i).getStateCode();
    }

    final RealmResults<RMission> results = Realm.getDefaultInstance().where(RMission.class).in("state", statesCode).findAllAsync();
    results.addChangeListener(new RealmChangeListener<RealmResults<RMission>>() {
        @Override
        public void onChange(RealmResults<RMission> element) {

            Log.d(TAG, element.size() + " mission(s) found in database with states " + StringUtils.arrayToString(statesCode, ","));
            listener.onResponse(Realm.getDefaultInstance().copyFromRealm(element));
            results.removeChangeListener(this);

        }
    });

}

The listener class :

public interface SListener<T> {

void onResponse(@Nullable T result);

}

i tested my code in multiple device but only on one device (samsung tablet) the problem.

Problem code:

   MissionManager.getMissions(listStatus, new SListener<List<RMission>>() {
        @Override
        public void onResponse(List<RMission> result) {

Can anyone help me to solve this issue?

Thanks in advance.

Body:
1.) Realm.getDefaultInstance().where(... and Realm.getDefaultInstance().copyFromRealm(... you are opening Realm instances that you will never be able to close, read the docs

2.) you're not preserving the RealmResults as a field reference therefore the finalizer will destroy it before the asynchronous query is evaluated, therefore callback won't be called, read the docs here and here

From javadoc:

Registering a change listener will not prevent the underlying RealmResults from being garbage collected. If the RealmResults is garbage collected, the change listener will stop being triggered. To avoid this, keep a strong reference for as long as appropriate e.g. in a class variable.

public class MyActivity extends Activity {

    private RealmResults<Person> results; // Strong reference to keep listeners alive

    @Override
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         results = realm.where(Person.class).findAllAsync();
         results.addChangeListener(new RealmChangeListener<RealmResults<Person>>() {
           @Override
           public void onChange(RealmResults<Person> persons) {
               // React to change
           }
       });
     }
     // remove change listeners, and close Realm in onDestroy()
 }

3.)  all this hassle for an asynchronously evaluated query is kinda meaningless if you copy every single lazy-evaluated element inside the lazy-evaluated RealmResults EAGERLY, ON THE UI THREAD, so you should reevaluate your logic, specifically after you've read the relevant docs on how Realm queries work.

All fetches (including queries) are lazy in Realm, and the data is never copied.

As the data is never copied, there is no reason for you to use copyFromRealm().


问:
For loop containing Scala Futures modifying a List
Let's say I have a ListBuffer[Int] and I iterate it with a foreach loop, and each loop will modify this list from inside a Future (removing the current element), and will do something special when the list is empty. Example code:

```<code>import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.collection.mutable.ListBuffer

val l = ListBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
l.foreach(n => Future {
  println(s"Processing $n")
  Future {
    l -= n
    println(s"Removed $n")
    if (l.isEmpty) println("List is empty!")
  }
})
</code>```

This is probably going to end very badly. I have a more complex code with similar structure and same needs, but I do not know how to structure it so I can achieve same functionality in a more reliable way.

答:
The way you present your problem is really not in the functional paradigm that scala is intended for.

What you seem to want, is to do a list of asynchronous computations, do something at the end of each one, and something else when every one is finished. This is pretty simple if you use continuations, which are simple to implement with map and flatMap methods on Future.

```<code>val fa: Future[Int] = Future { 1 }
// will apply the function to the result when it becomes available
val fb: Future[Int] = fa.map(a => a + 1)
// will start the asynchronous computation using the result when it will become available
val fc: Future[Int] = fa.flatMap(a => Future { a + 2 })
</code>```

Once you have all this, you can easily do something when each of your Future completes (successfully):

```<code>val myFutures: List[Future[Int]] = ???
myFutures.map(futInt => futInt.map(int => int + 2))
</code>```

Here, I will add 2 to each value I get from the different asynchronous computations in the List.

You can also choose to wait for all the Futures in your list to complete by using Future.sequence:

```<code>val myFutureList: Future[List[Int]] = Future.sequence(myFutures)
</code>```

Once again, you get a Future, which will be resolved when each of the Futures  inside the input list are successfully resolved, or will fail whenever one of your Futures fails. You'll then be able to use map or flatMap on this new Future, to use all the computed values at once.

So here's how I would write the code you proposed:

```<code>val l = 1 to 10

val processings: Seq[Future[Unit]] = l.map {n =>
  Future(println(s"processing $n")).map {_ =>
    println(s"finished processing $n")
  }
}

val processingOver: Future[Unit] =
  Future.sequence(processings).map { (lu: Seq[Unit]) =>
    println(s"Finished processing ${lu.size} elements")
  }
</code>```

Of course, I would recommend having real functions rather than procedures (returning Unit), so that you can have values to do something with. I used println to have a code which will produce the same output as yours (except for the prints, which have a slightly different meaning, since we are not mutating anything anymore).

Body:
Let's say I have a ListBuffer[Int] and I iterate it with a foreach loop, and each loop will modify this list from inside a Future (removing the current element), and will do something special when the list is empty. Example code:

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.collection.mutable.ListBuffer

val l = ListBuffer(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
l.foreach(n => Future {
  println(s"Processing $n")
  Future {
    l -= n
    println(s"Removed $n")
    if (l.isEmpty) println("List is empty!")
  }
})

This is probably going to end very badly. I have a more complex code with similar structure and same needs, but I do not know how to structure it so I can achieve same functionality in a more reliable way.

Body:
The way you present your problem is really not in the functional paradigm that scala is intended for.

What you seem to want, is to do a list of asynchronous computations, do something at the end of each one, and something else when every one is finished. This is pretty simple if you use continuations, which are simple to implement with map and flatMap methods on Future.

val fa: Future[Int] = Future { 1 }
// will apply the function to the result when it becomes available
val fb: Future[Int] = fa.map(a => a + 1)
// will start the asynchronous computation using the result when it will become available
val fc: Future[Int] = fa.flatMap(a => Future { a + 2 })

Once you have all this, you can easily do something when each of your Future completes (successfully):

val myFutures: List[Future[Int]] = ???
myFutures.map(futInt => futInt.map(int => int + 2))

Here, I will add 2 to each value I get from the different asynchronous computations in the List.

You can also choose to wait for all the Futures in your list to complete by using Future.sequence:

val myFutureList: Future[List[Int]] = Future.sequence(myFutures)

Once again, you get a Future, which will be resolved when each of the Futures  inside the input list are successfully resolved, or will fail whenever one of your Futures fails. You'll then be able to use map or flatMap on this new Future, to use all the computed values at once.

So here's how I would write the code you proposed:

val l = 1 to 10

val processings: Seq[Future[Unit]] = l.map {n =>
  Future(println(s"processing $n")).map {_ =>
    println(s"finished processing $n")
  }
}

val processingOver: Future[Unit] =
  Future.sequence(processings).map { (lu: Seq[Unit]) =>
    println(s"Finished processing ${lu.size} elements")
  }

Of course, I would recommend having real functions rather than procedures (returning Unit), so that you can have values to do something with. I used println to have a code which will produce the same output as yours (except for the prints, which have a slightly different meaning, since we are not mutating anything anymore).


问:
Is there an iOS library to help me detect higher-level accelerometer gestures?
For example, let's say I want to detect if the user made a circle gesture so I can trigger something in my game. Is there a library that would allow me to just listen for some sort of "circleDectected" event?

If there isn't, would anyone find value in something like this if I developed it? Thanks!

答: Unreal Engine seems to have support for it - Infinity Blade uses a lot of gestures for casting spells.</p>

ContentLicense: CC BY-SA 2.5


问:
Extract substrings from a list into a list in Python
I have a Python list like:

```<code>['user@gmail.com', 'someone@hotmail.com'...]
</code>```

And I want to extract only the strings after @ into another list directly, such as:

```<code>mylist = ['gmail.com', 'hotmail.com'...]
</code>```

Is it possible? split() doesn't seem to be working with lists.

This is my try:

```<code>for x in range(len(mylist)):
  mylist[x].split("@",1)[1]
</code>```

But it didn't give me a list of the output.

答:
You're close, try these small tweaks:

Lists are iterables, which means its easier to use for-loops than you think:

```<code>for x in mylist:
  #do something
</code>```

Now, the thing you want to do is 1) split x at '@' and 2) add the result to another list.

```<code>#In order to add to another list you need to make another list
newlist = []
for x in mylist:
     split_results = x.split('@')
     # Now you have a tuple of the results of your split
     # add the second item to the new list
     newlist.append(split_results[1])
</code>```

Once you understand that well, you can get fancy and use list comprehension:

```<code>newlist = [x.split('@')[1] for x in mylist]
</code>```

Body:
I have a Python list like:

['user@gmail.com', 'someone@hotmail.com'...]

And I want to extract only the strings after @ into another list directly, such as:

mylist = ['gmail.com', 'hotmail.com'...]

Is it possible? split() doesn't seem to be working with lists.

This is my try:

for x in range(len(mylist)):
  mylist[x].split("@",1)[1]

But it didn't give me a list of the output.

Body:
You're close, try these small tweaks:

Lists are iterables, which means its easier to use for-loops than you think:

for x in mylist:
  #do something

Now, the thing you want to do is 1) split x at '@' and 2) add the result to another list.

#In order to add to another list you need to make another list
newlist = []
for x in mylist:
     split_results = x.split('@')
     # Now you have a tuple of the results of your split
     # add the second item to the new list
     newlist.append(split_results[1])

Once you understand that well, you can get fancy and use list comprehension:

newlist = [x.split('@')[1] for x in mylist]


问:
Computational Efficiency of Forward Mode Automatic vs Numeric vs Symbolic Differentiation
I am trying to solve a problem of finding the roots of a function using the Newton-Raphson (NR) method in the C language. The functions in which I would like to find the roots are mostly polynomial functions but may also contain trigonometric and logarithmic.

The NR method requires finding the differential of the function. There are 3 ways to implement differentiation:

Symbolic

Numerical

Automatic (with sub types being forward mode and reverse mode. For this particular question, I would like to focus on forward mode)

I have thousands of these functions all requiring finding roots in the quickest time possible.

From the little that I do know, Automatic differentiation is in general quicker than symbolic because it handles the problem of "expression swell" alot more efficiently.

My question therefore is, all other things being equal, which method of differentiation is more computationally efficient: Automatic Differentiation (and more specifically, forward mode) or Numeric differentiation?

答:
If the derivative is not available, you should consider using the secant or regula falsi methods. They have very decent convergence speed (φ-order instead of quadratic). An additional benefit of regula falsi, is that the iterations remains confined to the initial interval, which allows reliable root separation (which Newton does not).

Also note than in the case of numerical evaluation of the derivatives, you will require several computations of the functions, at best two of them. Then the actual convergence speed drops to √2, which is outperformed by the derivative-less methods.

Also note that the symbolic expression of the derivatives is often more costly to evaluate than the functions themselves. So one iteration of Newton costs at least two function evaluations, spoiling the benefit of the convergence rate.


问:
mysqli search like only works with 1 parameter
I'm trying to do a mysqli search like query to search based on first and last name. When I type the first and last name into the search, I get no results. However, when I type just the first name or just the last name, I get results.

Here's my code:

```<code><?php
if (isset($_POST['search'])) {
$name = $_POST['search'];
$sql = "SELECT * FROM users WHERE fname LIKE '%$name%' OR lname LIKE '%$name%'";
$res = mysqli_query($conn, $sql);

}
while ($row = mysqli_fetch_assoc($res)) {
    $fname = $row['fname'];
    $lname = $row['lname'];
    $city = $row['city'];
    $state = $row['state'];
    $id = $row['id'];
    $url = '<a href ="profile/?id='.$id.'">';
    if ($id !== ($_SESSION['id'])){
    $pic = "SELECT profilephotopatch FROM users WHERE id = '$id'";
    $res = mysqli_query($conn, $pic);
    $row = mysqli_fetch_assoc($res);
    $picloc = $row['profilephotopatch'];
    $displaypic = '<div id="userphoto"><img src="../'.$picloc. '"style="width: 100%;max-height: 100%"></div>';
    $output = $displaypic. $url. '<div id="name">'. $fname. ' '. $lname. ' '. $city. $state. '</a></div><br>';
 echo ($output);
}
 }
 ?>
</code>```

Thanks in advance for the help!

答:
Mysql's LIKE construct looks for similar entries, such as "LIKE 'bob'" succesfully returning 'bobbette'.  'bob smith' is not like 'bob' (it's the space, it always fails the test) and will not return a row.  Try something like this:

```<code>if(isset($_POST['search'])){
    $names = explode(" ", $_POST['search']);
    $search_fname = array_shift($names);
    $search_lname = array_pop($names);
    if($search_lname != ''){
        $sql = "SELECT * FROM users WHERE fname LIKE '%$search_fname%' OR lname LIKE '%$search_lname%'";
    } else {
        $sql = "SELECT * FROM users WHERE fname LIKE '%$search_fname%' OR lname LIKE '%$search_fname%'";
    }
    ...
}
</code>```

If your search was "bob smith", this would return all rows with a first name similar to "bob" or a last name similar to "smith".  Might be many rows.  For example, "bob jones", "bob smith", "dan smith" would all be returned.  If your search was only "bob" and you had entries for "bob smith" and "john bobbett" you'd get both of those.  Is that what you expected?

If you expected just (for example) one row when you searched for "bob smith" then your query should be looking for AND rather than OR.

Body:
I'm trying to do a mysqli search like query to search based on first and last name. When I type the first and last name into the search, I get no results. However, when I type just the first name or just the last name, I get results.

Here's my code:

<?php
if (isset($_POST['search'])) {
$name = $_POST['search'];
$sql = "SELECT * FROM users WHERE fname LIKE '%$name%' OR lname LIKE '%$name%'";
$res = mysqli_query($conn, $sql);

}
while ($row = mysqli_fetch_assoc($res)) {
    $fname = $row['fname'];
    $lname = $row['lname'];
    $city = $row['city'];
    $state = $row['state'];
    $id = $row['id'];
    $url = '';
    if ($id !== ($_SESSION['id'])){
    $pic = "SELECT profilephotopatch FROM users WHERE id = '$id'";
    $res = mysqli_query($conn, $pic);
    $row = mysqli_fetch_assoc($res);
    $picloc = $row['profilephotopatch'];
    $displaypic = '

';
    $output = $displaypic. $url. '
'. $fname. ' '. $lname. ' '. $city. $state. '

';
 echo ($output);
}
 }
 ?>

Thanks in advance for the help!

Body:
Mysql's LIKE construct looks for similar entries, such as "LIKE 'bob'" succesfully returning 'bobbette'.  'bob smith' is not like 'bob' (it's the space, it always fails the test) and will not return a row.  Try something like this:

if(isset($_POST['search'])){
    $names = explode(" ", $_POST['search']);
    $search_fname = array_shift($names);
    $search_lname = array_pop($names);
    if($search_lname != ''){
        $sql = "SELECT * FROM users WHERE fname LIKE '%$search_fname%' OR lname LIKE '%$search_lname%'";
    } else {
        $sql = "SELECT * FROM users WHERE fname LIKE '%$search_fname%' OR lname LIKE '%$search_fname%'";
    }
    ...
}

If your search was "bob smith", this would return all rows with a first name similar to "bob" or a last name similar to "smith".  Might be many rows.  For example, "bob jones", "bob smith", "dan smith" would all be returned.  If your search was only "bob" and you had entries for "bob smith" and "john bobbett" you'd get both of those.  Is that what you expected?

If you expected just (for example) one row when you searched for "bob smith" then your query should be looking for AND rather than OR.


问:
How do I focus a foreign window?
I have an application which may only have one instance of itself open at a time. To enforce this, I use this code:

```<code>System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses();
System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
foreach (System.Diagnostics.Process p in myProcesses)
{
    if (p.ProcessName == me.ProcessName)
        if (p.Id != me.Id)
        {
            //if already running, abort this copy.
            return;
        }
}
//launch the application.
//...
</code>```

It works fine. I would also like it to be able to focus the form of the already-running copy.  That is, before returning, I want to bring the other instance of this application into the foreground.

How do I do that?

SetForegroundWindow works, to a point:

```<code>[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

// ...
if (p.Id != me.Id)
{
    //if already running, focus it, and then abort this copy.
    SetForegroundWindow(p.MainWindowHandle);
    return;
}
// ...
</code>```

This does bring the window to the foreground if it is not minimized.  Awesome.
If the window IS minimized, however, it remains minimized.

It needs to un-minimize.

Solution via SwitchToThisWindow (Works!):

```<code>[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

[STAThread]
static void Main()
{
    System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
    System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(me.ProcessName);
    foreach (System.Diagnostics.Process p in myProcesses)
    {
        if (p.Id != me.Id)
        {
            SwitchToThisWindow(p.MainWindowHandle, true);
            return;
        }
    }
    //now go ahead and start our application ;-)
}
</code>```

答: Can you grab MainWindowHandle property of the Process object and send it a WM_USER message that you can interpret as "some other instance wants to bring me to the front".</p>

OwnerDisplayName: Blinky

ContentLicense: CC BY-SA 4.0

Title: How do I focus a foreign window?

Body:
I have an application which may only have one instance of itself open at a time. To enforce this, I use this code:

System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses();
System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
foreach (System.Diagnostics.Process p in myProcesses)
{
    if (p.ProcessName == me.ProcessName)
        if (p.Id != me.Id)
        {
            //if already running, abort this copy.
            return;
        }
}
//launch the application.
//...

It works fine. I would also like it to be able to focus the form of the already-running copy.  That is, before returning, I want to bring the other instance of this application into the foreground.

How do I do that?

SetForegroundWindow works, to a point:

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

// ...
if (p.Id != me.Id)
{
    //if already running, focus it, and then abort this copy.
    SetForegroundWindow(p.MainWindowHandle);
    return;
}
// ...

This does bring the window to the foreground if it is not minimized.  Awesome.
If the window IS minimized, however, it remains minimized.

It needs to un-minimize.

Solution via SwitchToThisWindow (Works!):

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

[STAThread]
static void Main()
{
    System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
    System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(me.ProcessName);
    foreach (System.Diagnostics.Process p in myProcesses)
    {
        if (p.Id != me.Id)
        {
            SwitchToThisWindow(p.MainWindowHandle, true);
            return;
        }
    }
    //now go ahead and start our application ;-)
}

LastEditorDisplayName: Blinky

OwnerDisplayName: plinth


问:
Why does ASP.NET web site reference assembly from GAC, when adding local reference?
When you use ASP.NET web site (instead of web application model) and add reference to an assembly from local folder, Visual Studio, it seems, understands that this local assembly is also in GAC and so does NOT copy this assembly to bin folder (as it does with non-GAC assemblies), but simply adds new record in web.config file.

Why such a behaviour? Is it possible to force copy to bin folder (I need this since .dll is not on target environment)? I can add assembly to bin folder as file and it will work, but in this case bin folder contents will be in source control, which is not good.

答:
For information on how to set the Copy Local Property of a Reference for a web project (not a web application), see:

http://msdn.microsoft.com/en-us/library/t1zz5y8c(v=VS.100).aspx


问:
How to execute some code after Cucumber report is built?
I use Cucumber for jUnit runner to run BDD tests like this:

```<code>@RunWith(Cucumber.class)
@CucumberOptions(
    format = {"pretty", "json:target/cucumber.json"},
    glue = {"com.company.bdd.steps"},
    features = {"classpath:bdd-scenarios"},
    tags = {"~@skip"}
)
public class CucumberTests {
}
</code>```

I would like to have beautiful HTML reports from https://github.com/damianszczepanik/cucumber-reporting

And i made jUnit @AfterClass method:

```<code>@AfterClass
public static void buildReport() throws Exception {
    List<String> srcReportJson = Collections.singletonList("target/cucumber.json");
    Configuration configuration = new Configuration(new File("target"), "AEOS BDD Integration Tests");
    new ReportBuilder(srcReportJson, configuration).generateReports();
}
</code>```

The problem is that cucumber.json is empty when @AfterClass method executes. Hence i can't build pretty HTML report.

Is there any hook which i can use to execute some code after cucumber json report is already built?

PS: Cucumber v.1.1.8 is used and Java 1.7 so i was not able to try ExtendedCucumberRunner

答:
wjpowell posted this suggestion in the cucumber-jvm issues:

"You don't need to do this in cucumber. Use the @beforeclass and @afterclass annotation from within the JUnit test used to run the cucumber tests. This has the benefit of running only for the features specified by the paths or tags options.

```<code>@RunWith(Cucumber.class)
@Cucumber.Options(format = {"html:target/cucumber-html-report", "json-pretty:target/cucumber-json-report.json"})
public class RunCukesTest {

    @BeforeClass
    public static void setup() {
        System.out.println("Ran the before");
    }

    @AfterClass
    public static void teardown() {
        System.out.println("Ran the after");
    }
}
</code>```

"

Body:
I use Cucumber for jUnit runner to run BDD tests like this:

@RunWith(Cucumber.class)
@CucumberOptions(
    format = {"pretty", "json:target/cucumber.json"},
    glue = {"com.company.bdd.steps"},
    features = {"classpath:bdd-scenarios"},
    tags = {"~@skip"}
)
public class CucumberTests {
}

I would like to have beautiful HTML reports from https://github.com/damianszczepanik/cucumber-reporting

And i made jUnit @AfterClass method:

@AfterClass
public static void buildReport() throws Exception {
    List<String> srcReportJson = Collections.singletonList("target/cucumber.json");
    Configuration configuration = new Configuration(new File("target"), "AEOS BDD Integration Tests");
    new ReportBuilder(srcReportJson, configuration).generateReports();
}

The problem is that cucumber.json is empty when @AfterClass method executes. Hence i can't build pretty HTML report.

Is there any hook which i can use to execute some code after cucumber json report is already built?

PS: Cucumber v.1.1.8 is used and Java 1.7 so i was not able to try ExtendedCucumberRunner

Body:
wjpowell posted this suggestion in the cucumber-jvm issues:

"You don't need to do this in cucumber. Use the @beforeclass and @afterclass annotation from within the JUnit test used to run the cucumber tests. This has the benefit of running only for the features specified by the paths or tags options.

@RunWith(Cucumber.class)
@Cucumber.Options(format = {"html:target/cucumber-html-report", "json-pretty:target/cucumber-json-report.json"})
public class RunCukesTest {

    @BeforeClass
    public static void setup() {
        System.out.println("Ran the before");
    }

    @AfterClass
    public static void teardown() {
        System.out.println("Ran the after");
    }
}

"


问:
How to automate django_haystack's rebuild_index command on production or live
I have used Django_Haystack with Whoosh for effective search on an application I worked on, which worked fine for what I need it for.

To build index on development mode, Django_Haystack documentation advised to run the following command:

python manage.py rebuild_index

However, after deploy, I figured out that all new details input to that site are not indexed and they fall out of search because there is no measures that automatically build those details into index.

Kindly assist me, how do I automate django_haystack's building index on production such that new details gets indexed automatically?

答:
You can use the HAYSTACK_SIGNAL_PROCESSOR setting. By setting it to the real time processor, the index will be updated when an instance of in indexed model is updated, created, or deleted.

```<code>HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
</code>```

Body:
You can use the HAYSTACK_SIGNAL_PROCESSOR setting. By setting it to the real time processor, the index will be updated when an instance of in indexed model is updated, created, or deleted.

HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'


问:
Unable to copy/paste in MinGW shell
I just installed MinGW on Windows and I'm unable to copy/paste as I am used to on Linux or even PuTTY. What is the trick for copying and pasting text (e.g. from chrome) into MinGW shell?</p>

答:
Win7 running MINGW64 (mintty 2.7.3) which came with the current version of Git Bash 2.1.3.0 from date of this comment.

Right click title bar of shell > Mouse >  under Click actions > Right mouse button > select the Paste radio button.

However, I was surprised to find this didn't allow me to paste using my right click on my mouse.

I had to also select Application mouse mode > Default click target > Window

After changing both settings I was able to paste.

So it seems the new shell that comes with the current version of Git bash has new features.  It also seems to be a bit buggy.  For instance running an an executable via cli (e.g. php -version results in empty output and forces me to restart the shell).  Waiting for a new update, hopefully which will fix this.

Title: Unable to copy/paste in MinGW shell


问:
Virtualenv Command Not Found
I couldn't get virtualenv to work despite various attempts. I installed virtualenv on MAC OS X using:

```<code>pip install virtualenv
</code>```

and have also added the PATH into my .bash_profile. Every time I try to run the virtualenv command, it returns:

```<code>-bash: virtualenv: command not found
</code>```

Every time I run pip install virtualenv, it returns:

```<code>Requirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
</code>```

I understand that in mac, the virtualenv should be correctly installed in

```<code>/usr/local/bin
</code>```

The virtualenv is indeed installed in /usr/local/bin, but whenever I try to run the virtualenv command, the command is not found. I've also tried to run the virtualenv command in the directory /usr/local/bin, and it gives me the same result:

```<code>-bash: virtualenv: command not found
</code>```

These are the PATHs I added to my .bash_profile

```<code>export PATH=$PATH:/usr/local/bin
export PATH=$PATH:/usr/local/bin/python
export PATH=$PATH:/Library/Framework/Python.framework/Version/2.7/lib/site-packages
</code>```

Any workarounds for this? Why is this the case?

答:
I think your problem can be solved using a simple symbolic link, but you are creating the symbolic link to the wrong file. As far as I know virtualenv is installed to /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv, (you can change the numbers for your Python version) so the command for creating the symbolic link should be:

```<code>ln -s /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv /usr/local/bin/virtualenv
</code>```

Title: Virtualenv Command Not Found

Body:
I couldn't get virtualenv to work despite various attempts. I installed virtualenv on MAC OS X using:

pip install virtualenv

and have also added the PATH into my .bash_profile. Every time I try to run the virtualenv command, it returns:

-bash: virtualenv: command not found

Every time I run pip install virtualenv, it returns:

Requirement already satisfied (use --upgrade to upgrade): virtualenv in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages

I understand that in mac, the virtualenv should be correctly installed in

/usr/local/bin

The virtualenv is indeed installed in /usr/local/bin, but whenever I try to run the virtualenv command, the command is not found. I've also tried to run the virtualenv command in the directory /usr/local/bin, and it gives me the same result:

-bash: virtualenv: command not found

These are the PATHs I added to my .bash_profile

export PATH=$PATH:/usr/local/bin
export PATH=$PATH:/usr/local/bin/python
export PATH=$PATH:/Library/Framework/Python.framework/Version/2.7/lib/site-packages

Any workarounds for this? Why is this the case?

Body:
I think your problem can be solved using a simple symbolic link, but you are creating the symbolic link to the wrong file. As far as I know virtualenv is installed to /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv, (you can change the numbers for your Python version) so the command for creating the symbolic link should be:

ln -s /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenv /usr/local/bin/virtualenv


问:
How can i use the mouse wheel to select each time another Tool/s?
```<code>private void OnEnable()
{
    Tools.current = Tool.View;
    Tools.viewTool = ViewTool.FPS;
}
</code>```

The Tool have some properties like Rect,Scale,Rotate...
I want to use the mouse wheel up down to select between the Tool properties.

答:
Not really complicated.

1.Read mouse scroll input with Input.GetAxisRaw instead Input.GetAxis because using Input.GetAxis will smooth the scroll value over time which you don't need.

2.Check if the scroll value is more than some threshold value. If it is, then the mouse wheel is scrolling up. If it is less than that -value  then it is scrolling down.

3.From result #2, create a global integer called "level" you can increment or decrement depending on the direction of the scroll wheel.

4.The Tool enum values starts from -1 to 4 because it is declared like this:

```<code>public enum Tool
{
    None = -1,
    View = 0,
    Move = 1,
    Rotate = 2,
    Scale = 3,
    Rect = 4
}
</code>```

Clamp the "level" variable from #3 to values between -1 and 4 with Mathf.Clamp(level, -1, 4);.

5.Finally, cast the int "level" variable to the Tool enum and assign the result to Tools.current.

The use of int to cast to Tool enum prevents the use of many if or switch statement.

```<code>float wheelThreshold = 0.09f;
int level = -1;

void Update()
{
    level = (int)Tools.current;

    float mouseScrollDir = Input.GetAxisRaw("Mouse ScrollWheel");

    if (mouseScrollDir > wheelThreshold)
    {
        Debug.Log("Scroll Up");
        level++;
        level = Mathf.Clamp(level, -1, 4);
        Tools.current = (Tool)level;
    }
    else if (mouseScrollDir < -wheelThreshold)
    {
        Debug.Log("Scroll Down");
        level--;
        level = Mathf.Clamp(level, -1, 4);
        Tools.current = (Tool)level;
    }
}
</code>```

Result:

Body:
private void OnEnable()
{
    Tools.current = Tool.View;
    Tools.viewTool = ViewTool.FPS;
}

The Tool have some properties like Rect,Scale,Rotate...
I want to use the mouse wheel up down to select between the Tool properties.

Body:
Not really complicated.

1.Read mouse scroll input with Input.GetAxisRaw instead Input.GetAxis because using Input.GetAxis will smooth the scroll value over time which you don't need.

2.Check if the scroll value is more than some threshold value. If it is, then the mouse wheel is scrolling up. If it is less than that -value  then it is scrolling down.

3.From result #2, create a global integer called "level" you can increment or decrement depending on the direction of the scroll wheel.

4.The Tool enum values starts from -1 to 4 because it is declared like this:

public enum Tool
{
    None = -1,
    View = 0,
    Move = 1,
    Rotate = 2,
    Scale = 3,
    Rect = 4
}

Clamp the "level" variable from #3 to values between -1 and 4 with Mathf.Clamp(level, -1, 4);.

5.Finally, cast the int "level" variable to the Tool enum and assign the result to Tools.current.

The use of int to cast to Tool enum prevents the use of many if or switch statement.

float wheelThreshold = 0.09f;
int level = -1;

void Update()
{
    level = (int)Tools.current;

    float mouseScrollDir = Input.GetAxisRaw("Mouse ScrollWheel");

    if (mouseScrollDir > wheelThreshold)
    {
        Debug.Log("Scroll Up");
        level++;
        level = Mathf.Clamp(level, -1, 4);
        Tools.current = (Tool)level;
    }
    else if (mouseScrollDir < -wheelThreshold)
    {
        Debug.Log("Scroll Down");
        level--;
        level = Mathf.Clamp(level, -1, 4);
        Tools.current = (Tool)level;
    }
}

Result:


问:
make loop read clearer
within my while loop I am doing a test, but it seems really redundant and I think there may be a better solution to implement this such as a "case" structure possibly? If anyone can recommend how to cut down on the redundancy that would be wonderful, thanks! Basically, how can I restructure this loop to be better?

the loop:

```<code> if [ "$cursor" -eq "1" ]
    then
        Links="Links: $(ls -ld / | cut -d" " -f2)"
        Owner="Owner: $(ls -ld / | cut -d" " -f3)"
        Group="Group: $(ls -ld / | cut -d" " -f4)"
        Size="Size: $(ls -ld / | cut -d" " -f5)"
        Modified="Modified: $(ls -ld / | cut -d" " -f6-8)"
        echo "$Links  $Owner  $Group  $Size  $Modified"
    elif [ "$cursor" -eq "2" ]
    then
        Links="Links: $(ls -ld /home | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld /home | cut -d" " -f3)"
                    Group="Group: $(ls -ld /home | cut -d" " -f4)"
                    Size="Size: $(ls -ld /home | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld /home | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
        elif [ "$cursor" -eq "3" ]
    then
        Links="Links: $(ls -ld ~ | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld ~ | cut -d" " -f3)"
                    Group="Group: $(ls -ld ~ | cut -d" " -f4)"
                    Size="Size: $(ls -ld ~ | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld ~ | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
    else
        temp=`expr $cursor - 1`
        curDir=${currentdir[$temp]}
        Links="Links: $(ls -ld $curDir | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld $curDir | cut -d" " -f3)"
                    Group="Group: $(ls -ld $curDir | cut -d" " -f4)"
                    Size="Size: $(ls -ld $curDir | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld $curDir | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
fi
</code>```

答:
I concur, scraping ls is not the best, but I'm not sure what your use-case is. Here's a solution I came up with:

```<code>#!/bin/bash

my_stat()
{
  path="$1"

  IFS=":" read links owner group size modified <<<$(ls -ld $path | awk '{print $2":"$3":"$4":"$5":"$6" "$7" "$8}')
  echo "$links $owner $group $size $modified"
}

case $cursor in
  1) my_stat /;;
  2) my_stat /home;;
  3) my_stat ~;;
  *) temp=$((cursor - 1))
     curDir="${currentdir[$temp]}"
     my_stat "$curDir"
  ;;
esac
</code>```

Even this is is probably not the most optimal way to accomplish your goal. One thing that sticks out at me is the $cursor variable. That's an enigma to me of what you're trying to accomplish here. At any rate, hopefully, this helps a little.

Title: make loop read clearer

Body:
within my while loop I am doing a test, but it seems really redundant and I think there may be a better solution to implement this such as a "case" structure possibly? If anyone can recommend how to cut down on the redundancy that would be wonderful, thanks! Basically, how can I restructure this loop to be better?

the loop:

 if [ "$cursor" -eq "1" ]
    then
        Links="Links: $(ls -ld / | cut -d" " -f2)"
        Owner="Owner: $(ls -ld / | cut -d" " -f3)"
        Group="Group: $(ls -ld / | cut -d" " -f4)"
        Size="Size: $(ls -ld / | cut -d" " -f5)"
        Modified="Modified: $(ls -ld / | cut -d" " -f6-8)"
        echo "$Links  $Owner  $Group  $Size  $Modified"
    elif [ "$cursor" -eq "2" ]
    then
        Links="Links: $(ls -ld /home | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld /home | cut -d" " -f3)"
                    Group="Group: $(ls -ld /home | cut -d" " -f4)"
                    Size="Size: $(ls -ld /home | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld /home | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
        elif [ "$cursor" -eq "3" ]
    then
        Links="Links: $(ls -ld ~ | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld ~ | cut -d" " -f3)"
                    Group="Group: $(ls -ld ~ | cut -d" " -f4)"
                    Size="Size: $(ls -ld ~ | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld ~ | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
    else
        temp=`expr $cursor - 1`
        curDir=${currentdir[$temp]}
        Links="Links: $(ls -ld $curDir | cut -d" " -f2)"
                    Owner="Owner: $(ls -ld $curDir | cut -d" " -f3)"
                    Group="Group: $(ls -ld $curDir | cut -d" " -f4)"
                    Size="Size: $(ls -ld $curDir | cut -d" " -f5)"
                    Modified="Modified: $(ls -ld $curDir | cut -d" " -f6-8)"
                    echo "$Links  $Owner  $Group  $Size  $Modified"
fi

Body:
I concur, scraping ls is not the best, but I'm not sure what your use-case is. Here's a solution I came up with:

#!/bin/bash

my_stat()
{
  path="$1"

  IFS=":" read links owner group size modified <<<$(ls -ld $path | awk '{print $2":"$3":"$4":"$5":"$6" "$7" "$8}')
  echo "$links $owner $group $size $modified"
}

case $cursor in
  1) my_stat /;;
  2) my_stat /home;;
  3) my_stat ~;;
  *) temp=$((cursor - 1))
     curDir="${currentdir[$temp]}"
     my_stat "$curDir"
  ;;
esac

Even this is is probably not the most optimal way to accomplish your goal. One thing that sticks out at me is the $cursor variable. That's an enigma to me of what you're trying to accomplish here. At any rate, hopefully, this helps a little.


问:
Javascript es6 array mapping
I need help creating a function that gonna return me 3 elements from an array each time with time interval of 3 seconds.
Let say I have an array

```<code>const Array = [{name:'A'},{name:'B'},{name:'C'},{name:'D'},{name:'E'},{name:'F'},{name:'G'},{name:'H'},{name:'I'}];
</code>```

It should return array like

```<code> [{name:'A'},{name:'B'},{name:'C'}]
</code>```

then after 3 seconds it should return array

```<code> [{name:'D'},{name:'E'},{name:'F'}]
</code>```

And so on also when the arrays gets end repeat the loop again.

I tried using chunk where i used slice and filter but that just return me an array of chunks together.

Thanks so much

答:
```<code>const array = [{name:'A'},{name:'B'},{name:'C'},{name:'D'},{name:'E'},
{name:'F'},{name:'G'},{name:'H'},{name:'I'}];

let i = 0
setInterval(() => {
  console.log(array.slice(i,i+3))
  i*3 > array.length ? i=0 : i += 3
}, 3000)
</code>```

The jsbin: https://jsbin.com/yoqelu/edit?html,js,console,output

Title: Javascript es6 array mapping

Body:
I need help creating a function that gonna return me 3 elements from an array each time with time interval of 3 seconds.
Let say I have an array

const Array = [{name:'A'},{name:'B'},{name:'C'},{name:'D'},{name:'E'},{name:'F'},{name:'G'},{name:'H'},{name:'I'}];

It should return array like

 [{name:'A'},{name:'B'},{name:'C'}]

then after 3 seconds it should return array

 [{name:'D'},{name:'E'},{name:'F'}]

And so on also when the arrays gets end repeat the loop again.

I tried using chunk where i used slice and filter but that just return me an array of chunks together.

Thanks so much

Body:
const array = [{name:'A'},{name:'B'},{name:'C'},{name:'D'},{name:'E'},
{name:'F'},{name:'G'},{name:'H'},{name:'I'}];

let i = 0
setInterval(() => {
  console.log(array.slice(i,i+3))
  i*3 > array.length ? i=0 : i += 3
}, 3000)

The jsbin: https://jsbin.com/yoqelu/edit?html,js,console,output


问:
How can I get TFS 2017 to copy only the files in my Release folder to a UNC, and not the \drop\Project\bin\Release folder structure?
Right now I have a build definition setup in TFS 2017 that uses the Publish Artifact:drop build step.

In that build step I have $(build.artifactstagingdirectory) as the 'Path to Publish' and \\server\share\folder as the Path.

This works, but I get \\server\share\folder\drop\AppName\bin\Release with my files inside of the Release folder.

How can I tell TFS to just output the files right into \\server\share\folder?

答:
Rather than modifying your Publish Artifact step you want to arrange the files in your $(build.artifactstagingdirectory) in the way you want them published to your drop folder.

Given you likely have a Copy Files to: $(build.artifactstagingdirectory) step, in TFS 2017 (Update 1) you can check Flatten Folders under Advanced and this will drop the file contents into the root of your artifact staging directory.

I don't believe there is a way to get around having the artifact name ("drop" in your case) forming part of the path, but with Flatten Folders all files should be dropped in the root of \\server\share\folder\drop

Edit

An alternative is to specify something like the below in the copy files step. Provide the relative path to your bin\release directory, then use the minimatch ** pattern in the contents field to copy everything in that directory


问:
How to provide an initial plotting platform to add additional plots in R?
I'm trying to use a for loop to draw 3 side by side curves in R but without getting any error message nothing shows?

I suspect something should provide an initial plotting platform for the first curve, and then the second and the third plots can be added. Can the initial plotting platform be plot.new() for example?

Note: I'm definitely trying to avoid using long if else statements as a solution.

Here is my R code:

```<code>for(i in 1:3){

  p = c(.1, .5, .9)[i]
col = c("red3", "green3", "blue")[i]

curve( dbinom(x, size = 100, prob = p), add = T, ty = "h", xlim = c(0, 100),
   col = col, xlab = "Number of Agreements", ylab = "Probability", las = 1 )

}
</code>```

答:
The first insertion occurs error because the curve does not exist. If you want a simple solution, follow the one below:</p>

```<code>for(i in 1:3){

  if(i == 1){
  p = c(.1, .5, .9)[i]
  col = c("red", "green", "blue")[i]

  curve( dbinom(x, size = 100, prob = p), ty = "h", xlim = c(0, 100),
         col = col, xlab = "Number of Agreements", ylab = "Probability", las = 1 )
  }else{
    p = c(.1, .5, .9)[i]
    col = c("red", "green", "blue")[i]

    curve( dbinom(x, size = 100, prob = p), add = T, ty = "h", xlim = c(0, 100),
           col = col, xlab = "Number of Agreements", ylab = "Probability", las = 1 )
  }

}
</code>```

Body:
I'm trying to use a for loop to draw 3 side by side curves in R but without getting any error message nothing shows?

I suspect something should provide an initial plotting platform for the first curve, and then the second and the third plots can be added. Can the initial plotting platform be plot.new() for example?

Note: I'm definitely trying to avoid using long if else statements as a solution.

Here is my R code:

for(i in 1:3){

  p = c(.1, .5, .9)[i]
col = c("red3", "green3", "blue")[i]

curve( dbinom(x, size = 100, prob = p), add = T, ty = "h", xlim = c(0, 100),
   col = col, xlab = "Number of Agreements", ylab = "Probability", las = 1 )

}

Body:
The first insertion occurs error because the curve does not exist. If you want a simple solution, follow the one below:

for(i in 1:3){

  if(i == 1){
  p = c(.1, .5, .9)[i]
  col = c("red", "green", "blue")[i]

  curve( dbinom(x, size = 100, prob = p), ty = "h", xlim = c(0, 100),
         col = col, xlab = "Number of Agreements", ylab = "Probability", las = 1 )
  }else{
    p = c(.1, .5, .9)[i]
    col = c("red", "green", "blue")[i]

    curve( dbinom(x, size = 100, prob = p), add = T, ty = "h", xlim = c(0, 100),
           col = col, xlab = "Number of Agreements", ylab = "Probability", las = 1 )
  }

}


问:
How to connect Native iOS App <-> Azure B2C?
I am currently trying to connect Azure's B2C with a Native iOS Application. I have been able to get a Safari popup to return the email/id/response (using AppAuth), but I was looking to actually use an API to complete this while using native iOS elements, not a web page hosted by Microsoft which looks and feels tacky. Is there a better way to do this?

```<code>  NSURL *authorizationEndpoint = [NSURL URLWithString:[NSString stringWithFormat:kEndpoint, kTenantName, kSignupOrSigninPolicy, @"authorize"]];
    NSURL *tokenEndpoint = [NSURL URLWithString:[NSString stringWithFormat:kEndpoint, kTenantName, kSignupOrSigninPolicy, @"token"]];

    OIDServiceConfiguration *configuration = [[OIDServiceConfiguration alloc] initWithAuthorizationEndpoint:authorizationEndpoint tokenEndpoint:tokenEndpoint];

    OIDAuthorizationRequest *request = [[OIDAuthorizationRequest alloc] initWithConfiguration:configuration clientId:kClientId scopes:@[OIDScopeOpenID, OIDScopeProfile] redirectURL:[NSURL URLWithString:kRedirectUri] responseType:OIDResponseTypeCode additionalParameters:nil];

    currentAuthorizationFlow = [OIDAuthState authStateByPresentingAuthorizationRequest:request presentingViewController:presentingVC callback:callback];
</code>```

答:
At this time your only option is to customize the Azure AD B2C UI.

Creating your own native UIs requires the resource owner password credentials flow which Azure AD B2C does not yet support. You can vote for this feature ask in the Azure AD B2C feedback forum: Support the resource password credential flow.

Body:
I am currently trying to connect Azure's B2C with a Native iOS Application. I have been able to get a Safari popup to return the email/id/response (using AppAuth), but I was looking to actually use an API to complete this while using native iOS elements, not a web page hosted by Microsoft which looks and feels tacky. Is there a better way to do this?

  NSURL *authorizationEndpoint = [NSURL URLWithString:[NSString stringWithFormat:kEndpoint, kTenantName, kSignupOrSigninPolicy, @"authorize"]];
    NSURL *tokenEndpoint = [NSURL URLWithString:[NSString stringWithFormat:kEndpoint, kTenantName, kSignupOrSigninPolicy, @"token"]];

    OIDServiceConfiguration *configuration = [[OIDServiceConfiguration alloc] initWithAuthorizationEndpoint:authorizationEndpoint tokenEndpoint:tokenEndpoint];

    OIDAuthorizationRequest *request = [[OIDAuthorizationRequest alloc] initWithConfiguration:configuration clientId:kClientId scopes:@[OIDScopeOpenID, OIDScopeProfile] redirectURL:[NSURL URLWithString:kRedirectUri] responseType:OIDResponseTypeCode additionalParameters:nil];

    currentAuthorizationFlow = [OIDAuthState authStateByPresentingAuthorizationRequest:request presentingViewController:presentingVC callback:callback];


问:
crontab Failed to import the site module
I want crontab to run the python script for a public welfare project.

I can successfully run the script in Pycharm.

When I run it with crontab, there is an error.

Environment: Mac OS, python3.5

After I type 'crontab -e', it shows that:

```<code>SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/Users/yy/anaconda/bin/python3:/Users/yy/anaconda/bin/

32 14 * * * PATH=$PATH:/Users/yy/anaconda/bin/ cd /Users/yy/PycharmProjects/selenium_test/ &&  /Users/yy/anaconda/bin/python3 /Users/yy/PycharmProjects/selenium_test/selenium_test.py >> /Users/yy/PycharmProjects/selenium_test/log.txt
</code>```

I got an error as follows in the /var/mail/username:

```<code>From yy@YY.local  Thu Jun  8 14:32:00 2017
Return-Path: <yy@YY.local>
X-Original-To: yy
Delivered-To: yy@YY.local
Received: by YY.local (Postfix, from userid 501)
    id A7F1F38FFFCC; Thu,  8 Jun 2017 14:32:00 -0500 (CDT)
From: yy@YY.local (Cron Daemon)
To: yy@YY.local
Subject: Cron <yy@YY> PATH=$PATH:/Users/yy/anaconda/bin/ cd /Users/yy/PycharmProjects/selenium_test/ &&  /Users/yy/anaconda/bin/python3 /Users/yy/PycharmProjects/selenium_test/selenium_test.py >> /Users/yy/PycharmProjects/selenium_test/log.txt
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/Users/yy/anaconda/bin/python3:/Users/yy/anaconda/bin/>
X-Cron-Env: <LOGNAME=yy>
X-Cron-Env: <USER=yy>
X-Cron-Env: <HOME=/Users/yy>
Message-Id: <20170608193200.A7F1F38FFFCC@YY.local>
Date: Thu,  8 Jun 2017 14:32:00 -0500 (CDT)

Failed to import the site module
Traceback (most recent call last):
  File "/Users/yy/anaconda/lib/python3.5/site.py", line 567, in <module>
    main()
  File "/Users/yy/anaconda/lib/python3.5/site.py", line 550, in main
    known_paths = addsitepackages(known_paths)
  File "/Users/yy/anaconda/lib/python3.5/site.py", line 327, in addsitepackages
    addsitedir(sitedir, known_paths)
  File "/Users/yy/anaconda/lib/python3.5/site.py", line 206, in addsitedir
    addpackage(sitedir, name, known_paths)
  File "/Users/yy/anaconda/lib/python3.5/site.py", line 162, in addpackage
    for n, line in enumerate(f):
  File "/Users/yy/anaconda/lib/python3.5/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 127: ordinal not in range(128)
</code>```

I spent two hours on this error.
However, No solutions work...
Please help.
Thanks!

#

I use python3.5, so the default encoding is utf-8. The
  UnicodeDecodeError is strange...

答:
The problem is about encoding.
The default of Python3.5 is utf-8.

However, some packages I installed is encoded with Unicode.

I solve the problem by modifying the site.py file in path=/Users/user_name/anaconda/lib/python3.5/site.py.

Line 158:

```<code>    f = open(fullname, "rb") ->  f = open(fullname, "rb")
</code>```

Line 163:

```<code>    if line.startswith("#"): ->  if line.startswith(b"#"):
</code>```

Line 166:

if line.startswith(("import ", "import\t")): -> if line.startswith((b"import ", b"import\t")):

Line 170:

dir, dircase = makepath(sitedir, line) -> dir, dircase = makepath(sitedir, str(line))

I don't think it's a good idea to modify the "site.py" in anaconda...

But this fix the problem.
Hope it will be helpful.

Body:
I want crontab to run the python script for a public welfare project.

I can successfully run the script in Pycharm.

When I run it with crontab, there is an error.

Environment: Mac OS, python3.5

After I type 'crontab -e', it shows that:

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/Users/yy/anaconda/bin/python3:/Users/yy/anaconda/bin/

32 14 * * * PATH=$PATH:/Users/yy/anaconda/bin/ cd /Users/yy/PycharmProjects/selenium_test/ &&  /Users/yy/anaconda/bin/python3 /Users/yy/PycharmProjects/selenium_test/selenium_test.py >> /Users/yy/PycharmProjects/selenium_test/log.txt

I got an error as follows in the /var/mail/username:

From yy@YY.local  Thu Jun  8 14:32:00 2017
Return-Path: <yy@YY.local>
X-Original-To: yy
Delivered-To: yy@YY.local
Received: by YY.local (Postfix, from userid 501)
    id A7F1F38FFFCC; Thu,  8 Jun 2017 14:32:00 -0500 (CDT)
From: yy@YY.local (Cron Daemon)
To: yy@YY.local
Subject: Cron <yy@YY> PATH=$PATH:/Users/yy/anaconda/bin/ cd /Users/yy/PycharmProjects/selenium_test/ &&  /Users/yy/anaconda/bin/python3 /Users/yy/PycharmProjects/selenium_test/selenium_test.py >> /Users/yy/PycharmProjects/selenium_test/log.txt
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/Users/yy/anaconda/bin/python3:/Users/yy/anaconda/bin/>
X-Cron-Env: <LOGNAME=yy>
X-Cron-Env: <USER=yy>
X-Cron-Env: <HOME=/Users/yy>
Message-Id: <20170608193200.A7F1F38FFFCC@YY.local>
Date: Thu,  8 Jun 2017 14:32:00 -0500 (CDT)

Failed to import the site module
Traceback (most recent call last):
  File "/Users/yy/anaconda/lib/python3.5/site.py", line 567, in <module>
    main()
  File "/Users/yy/anaconda/lib/python3.5/site.py", line 550, in main
    known_paths = addsitepackages(known_paths)
  File "/Users/yy/anaconda/lib/python3.5/site.py", line 327, in addsitepackages
    addsitedir(sitedir, known_paths)
  File "/Users/yy/anaconda/lib/python3.5/site.py", line 206, in addsitedir
    addpackage(sitedir, name, known_paths)
  File "/Users/yy/anaconda/lib/python3.5/site.py", line 162, in addpackage
    for n, line in enumerate(f):
  File "/Users/yy/anaconda/lib/python3.5/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 127: ordinal not in range(128)

I spent two hours on this error.
However, No solutions work...
Please help.
Thanks!

#

I use python3.5, so the default encoding is utf-8. The
  UnicodeDecodeError is strange...

Body:
The problem is about encoding.
The default of Python3.5 is utf-8.

However, some packages I installed is encoded with Unicode.

I solve the problem by modifying the site.py file in path=/Users/user_name/anaconda/lib/python3.5/site.py.

Line 158:

    f = open(fullname, "rb") ->  f = open(fullname, "rb")

Line 163:

    if line.startswith("#"): ->  if line.startswith(b"#"):

Line 166:

if line.startswith(("import ", "import\t")): -> if line.startswith((b"import ", b"import\t")):

Line 170:

dir, dircase = makepath(sitedir, line) -> dir, dircase = makepath(sitedir, str(line))

I don't think it's a good idea to modify the "site.py" in anaconda...

But this fix the problem.
Hope it will be helpful.


问:
Ionic 2 - Dynamically change the color of the Status Bar
I'm trying to change in a page in the ionic the status bar color depending on the parameter that is get.

Only the colorStatusBar variable inside the onDeviceReady() function appears as undefined.

Could someone help me with this problem?

```<code>typeColor: string;
colorStatusBar: string;

constructor(public navCtrl: NavController, public navParams: NavParams, statusBar: StatusBar){
    this.typeColor = this.navParams.get('type');
    if(this.typeColor == "value1"){
      this.colorStatusBar = "#F44336";
    }
    if(this.typeColor == "value2"){
      this.colorStatusBar = "#66BB6A";
    }
    if(this.typeColor == "value3"){
      this.colorStatusBar = "#9E9E9E";
    }

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
          console.log(this.colorStatusBar) // undefined
          statusBar.backgroundColorByHexString(this.colorStatusBar);
    }
}
</code>```

答:
You could do it by moving your logic inside an ionViewDidLoad() (runs after the constructior) and using platform.ready() to ensure Cordova has booted up:

ionViewDidLoad() {
    this.typeColor = this.navParams.get('type');

    this.platform.ready().then(() => {
        if(this.typeColor == "value1"){
            this.statusBar.backgroundColorByHexString("#F44336");
        }
        if(this.typeColor == "value2"){
            this.statusBar.backgroundColorByHexString("#66BB6A");
        }
        if(this.typeColor == "value3"){
            this.statusBar.backgroundColorByHexString(#9E9E9E");
        }
    }
}
```

<p>In which case your constructor changes to this:</p>

<pre class="lang-js prettyprint-override"><code>constructor(public navCtrl: NavController, public navParams: NavParams, public statusBar: StatusBar, public platform: Platfom){
    // empty :), but notice the dependency injection of Platform
}
</code>```

Don't forget to import Platform on the top:

import { Platform } from 'ionic-angular';
```

<p>For your specific example to work, you need to make sure that you are invoking this present page from a parent page <em>and also</em> passing in the param <code>type</code>!</p>

<p>So in the parent page (you haven't shared the code for that) you need to have something like this:</p>

<pre class="lang-js prettyprint-override"><code>export class ParentPage {
  constructor(public navCtrl: NavController) {
  }

  pushPage(){
    // push another page onto the navigation stack
    // causing the nav controller to transition to the new page
    // optional data can also be passed to the pushed page.
    this.navCtrl.push(MyStackOverflowSharedPage, {
      type: "value2"
    });
  }
}
</code>```

For more info on that read the documentation on NavController.

Body:
I'm trying to change in a page in the ionic the status bar color depending on the parameter that is get.

Only the colorStatusBar variable inside the onDeviceReady() function appears as undefined.

Could someone help me with this problem?

typeColor: string;
colorStatusBar: string;

constructor(public navCtrl: NavController, public navParams: NavParams, statusBar: StatusBar){
    this.typeColor = this.navParams.get('type');
    if(this.typeColor == "value1"){
      this.colorStatusBar = "#F44336";
    }
    if(this.typeColor == "value2"){
      this.colorStatusBar = "#66BB6A";
    }
    if(this.typeColor == "value3"){
      this.colorStatusBar = "#9E9E9E";
    }

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
          console.log(this.colorStatusBar) // undefined
          statusBar.backgroundColorByHexString(this.colorStatusBar);
    }
}

Body:
You could do it by moving your logic inside an ionViewDidLoad() (runs after the constructior) and using platform.ready() to ensure Cordova has booted up:

ionViewDidLoad() {
    this.typeColor = this.navParams.get('type');

    this.platform.ready().then(() => {
        if(this.typeColor == "value1"){
            this.statusBar.backgroundColorByHexString("#F44336");
        }
        if(this.typeColor == "value2"){
            this.statusBar.backgroundColorByHexString("#66BB6A");
        }
        if(this.typeColor == "value3"){
            this.statusBar.backgroundColorByHexString(#9E9E9E");
        }
    }
}

In which case your constructor changes to this:

constructor(public navCtrl: NavController, public navParams: NavParams, public statusBar: StatusBar, public platform: Platfom){
    // empty :), but notice the dependency injection of Platform
}

Don't forget to import Platform on the top:

import { Platform } from 'ionic-angular';

For your specific example to work, you need to make sure that you are invoking this present page from a parent page and also passing in the param type!

So in the parent page (you haven't shared the code for that) you need to have something like this:

export class ParentPage {
  constructor(public navCtrl: NavController) {
  }

  pushPage(){
    // push another page onto the navigation stack
    // causing the nav controller to transition to the new page
    // optional data can also be passed to the pushed page.
    this.navCtrl.push(MyStackOverflowSharedPage, {
      type: "value2"
    });
  }
}

For more info on that read the documentation on NavController.


问:
How do I get a Refresh_Token from a ADFS 3.0 end point in C# MVC?
I have been securing a webapi using Rob Sander's instructions, found here: Securing a web api with adfs 3.0 and jwt tokens

I have successfully performed a login via ADFS using the usernamemixed end point, and have received the encoded Json Web Token (JWT). That's fine, and I can successfully validate the token with the X509 certificate found in the federation data xml found on the ADFS server.

I have implemented a DelegatingHandler so that any Authorize attributes added to methods will be checked.

The final piece of the puzzle is where I can get the refresh_token from. It would make sense to come from an ADFS endpoint, and I thought it would be in the response from the usernamemixed end point, but it doesn't appear to be there. Also, how do I make a call to request a new access_token if I provide a refresh_token?

答:
Normally, there's another OAuth endpoint. You would have /authorize, /token and /refresh.

Not sure in ADFS 3.0 implements this?

You can get it via:

Set-AdfsRelyingPartyTrust -TargetName "RPT Name" -IssueOAuthRefreshTokensTo AllDevices

More details here.


问:
How to set up theano config
I'm new to Theano.
Trying to set up a config file.

First of all, I notice that I have no .theanorc file:

locate .theanorc - returns nothing

echo $THEANORC - returns nothing

theano.test() - passes ok

I'm guessing some default configuration was created wen i installed theano. Where is it?

答:
This worked for me:

```<code>nano ~/.theanorc
</code>```

Then I entered:

```<code>[global]
floatX = float32
device = cuda
</code>```

Code to check if Theano is using the GPU is on the Theano doc page.

(I am using Ubuntu 14.04, Theano 0.9.0 (conda), NVIDIA 1080 Ti GPU).

Title: How to set up theano config

Body:
This worked for me:

nano ~/.theanorc

Then I entered:

[global]
floatX = float32
device = cuda

Code to check if Theano is using the GPU is on the Theano doc page.

(I am using Ubuntu 14.04, Theano 0.9.0 (conda), NVIDIA 1080 Ti GPU).


问:
modify and replace value in char array in C
As the program showed, I don't know what is wrong for printing out the new result.
e.g. when I finished calling modify_str() function with position=0, value=v,
it won't appear "vello" as result but throw a short gibberish.
Can anyone identify the error!? Thanks:)</p>

```<code>#include<stdio.h>
void print_(char *abc);
void modify_str(char *a);

void main(){
    char c[20]="Hello";
    print_(c);

    modify_str(c);

}

void print_(char *str){
    int i=0;
    while(*(str+i) != '\0'){
        printf("%c", str[i]);
        i++;
    }
    printf("\n");
}

void modify_str(char *c){
    char q[]="Position of char to modify (0-n): ";
    print_(q);
    int pos;
    scanf("%d", &pos);

    printf("value to replace: ");
    char w;
    scanf("%s", &w);

    int index=0;
    while(*(c+index) !='\0'){
        if(index==pos){
            c[index]=w;
            printf("New Result: %c\n", c);
        }
        index++;
    }
}
</code>```

答:
Instead of this call with the incorrect format specifier

```<code>scanf("%s", &w);
</code>```

use

```<code>scanf(" %c", &w);
       ^^^
</code>```

The while loop should look like

```<code>while( *(c+index) !='\0' && index != pos ) ++index;

if ( index == pos && *( c + index ) != '\0' )
{
        c[index]=w;
        printf("New Result: %s\n", c);
                            ^^
}
</code>```

Also it is a bad idea to name a string with the identifier c that is usually used for naming objects of type char. It is better to use identifier s.

Take into account that according to the C Standard the function main without parameters shall be declared like

```<code>int main( void )
</code>```

By the way the function print_ can be implemented like

```<code>void print_( const char *str )
{
    puts( str );
}
</code>```

And do not use trailing underscores in identifiers.  It is just a bad programming style.

Body:
As the program showed, I don't know what is wrong for printing out the new result.
e.g. when I finished calling modify_str() function with position=0, value=v,
it won't appear "vello" as result but throw a short gibberish.
Can anyone identify the error!? Thanks:)

#include<stdio.h>
void print_(char *abc);
void modify_str(char *a);

void main(){
    char c[20]="Hello";
    print_(c);

    modify_str(c);

}

void print_(char *str){
    int i=0;
    while(*(str+i) != '\0'){
        printf("%c", str[i]);
        i++;
    }
    printf("\n");
}

void modify_str(char *c){
    char q[]="Position of char to modify (0-n): ";
    print_(q);
    int pos;
    scanf("%d", &pos);

    printf("value to replace: ");
    char w;
    scanf("%s", &w);

    int index=0;
    while(*(c+index) !='\0'){
        if(index==pos){
            c[index]=w;
            printf("New Result: %c\n", c);
        }
        index++;
    }
}

Body:
Instead of this call with the incorrect format specifier

scanf("%s", &w);

use

scanf(" %c", &w);
       ^^^

The while loop should look like

while( *(c+index) !='\0' && index != pos ) ++index;

if ( index == pos && *( c + index ) != '\0' )
{
        c[index]=w;
        printf("New Result: %s\n", c);
                            ^^
}

Also it is a bad idea to name a string with the identifier c that is usually used for naming objects of type char. It is better to use identifier s.

Take into account that according to the C Standard the function main without parameters shall be declared like

int main( void )

By the way the function print_ can be implemented like

void print_( const char *str )
{
    puts( str );
}

And do not use trailing underscores in identifiers.  It is just a bad programming style.


问:
Spark - calculate the sum of features for each sample
If I have a RDD which looks like below then I know how to calculate the sum of my features per sample data:

```<code>import numpy as np
from pyspark import SparkContext

x = np.arange(10) # first sample with 10 features [0 1 2 3 4 5 6 7 8 9]
y = np.arange(10) # second sample with 10 features [0 1 2 3 4 5 6 7 8 9]
z = (x,y)
sc = SparkContext()
rdd1 = sc.parallelize(z)
rdd1.sum()
</code>```

The output will be an array like this: ([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18]), which is what I want.

My Question is:
If I construct a RDD by parsing a csv file as below, in which each element of the RDD is a tuple or list. How can I calculate the sum of each tuple/list elements (each feature) like above? If I use the sum I get this error:

```<code>Rdd :  [(0.00217010083485, 0.00171658370653), (7.24521659993e-05, 4.18413109325e-06), ....]

TypeError: unsupported operand type(s) for +: 'int' and 'tuple'
</code>```

[EDIT] To be more specific:

```<code>rdd = sc.parallelize([(1,3),(2,4)])
</code>```

I want my output to be [3,7].  Each tuple is a data instance that I have, and each element of tuple is my feature.  I want to calculate the sum of each feature per all data samples.

答:
Here, I just add the solution using PySpark dataframe for larger rdd that you have</p>

```<code>rdd = sc.parallelize([(1, 3),(2, 4)])
df = rdd.toDF() # tranform rdd to dataframe
col_sum = df.groupby().sum().rdd.map(lambda x: x.asDict()).collect()[0]
[v for k, v in col_sum.asDict().items()] # sum of columns: [3, 7]
</code>```

Body:
If I have a RDD which looks like below then I know how to calculate the sum of my features per sample data:

import numpy as np
from pyspark import SparkContext

x = np.arange(10) # first sample with 10 features [0 1 2 3 4 5 6 7 8 9]
y = np.arange(10) # second sample with 10 features [0 1 2 3 4 5 6 7 8 9]
z = (x,y)
sc = SparkContext()
rdd1 = sc.parallelize(z)
rdd1.sum()

The output will be an array like this: ([ 0,  2,  4,  6,  8, 10, 12, 14, 16, 18]), which is what I want.

My Question is:
If I construct a RDD by parsing a csv file as below, in which each element of the RDD is a tuple or list. How can I calculate the sum of each tuple/list elements (each feature) like above? If I use the sum I get this error:

Rdd :  [(0.00217010083485, 0.00171658370653), (7.24521659993e-05, 4.18413109325e-06), ....]

TypeError: unsupported operand type(s) for +: 'int' and 'tuple'

[EDIT] To be more specific:

rdd = sc.parallelize([(1,3),(2,4)])

I want my output to be [3,7].  Each tuple is a data instance that I have, and each element of tuple is my feature.  I want to calculate the sum of each feature per all data samples.

Body:
Here, I just add the solution using PySpark dataframe for larger rdd that you have

rdd = sc.parallelize([(1, 3),(2, 4)])
df = rdd.toDF() # tranform rdd to dataframe
col_sum = df.groupby().sum().rdd.map(lambda x: x.asDict()).collect()[0]
[v for k, v in col_sum.asDict().items()] # sum of columns: [3, 7]


问:
Using multiple ivy:retrieve patterns in my build.xml to associate with multiple artifact patterns
I have files in two different directories that I would like to publish.  One set of files has a .jar extension the other set doesn't have any extension at all.

In my build.xml file under publish I have the following code:

```<code><ivy:publish resolver="public-publisher" conf="default"
   deliverivypattern="${build}/${delivery.pattern}">
  <artifacts pattern="${build}/[artifact].[ext]"/>
  <artifacts pattern="${misc}/bin/[artifact]"/>
</ivy:publish>
</code>```

then when I do my retrieve I tried to do something like:

```<code><ivy:retrieve pattern="ivyLib/[artifact].[ext]" conf="default" />
<ivy:retrieve pattern="ivyLib/[artifact]" conf="default"/>
</code>```

but that didn't work.  It puts a . after my files that don't have any extensions on them.  Now I'm all out of ideas and any help would be greatly appreciated.

Thanks in advance,

Josh

答:
try this instead

```<code><ivy:retrieve pattern="ivyLib/[artifact](.[ext])" conf="default" />
</code>```

the () makes the contents of the () optional so it should match ivyLib/Foo and ivyLib/Foo.jar

Body:
I have files in two different directories that I would like to publish.  One set of files has a .jar extension the other set doesn't have any extension at all.

In my build.xml file under publish I have the following code:

<ivy:publish resolver="public-publisher" conf="default"
   deliverivypattern="${build}/${delivery.pattern}">
  <artifacts pattern="${build}/[artifact].[ext]"/>
  <artifacts pattern="${misc}/bin/[artifact]"/>
</ivy:publish>

then when I do my retrieve I tried to do something like:

<ivy:retrieve pattern="ivyLib/[artifact].[ext]" conf="default" />
<ivy:retrieve pattern="ivyLib/[artifact]" conf="default"/>

but that didn't work.  It puts a . after my files that don't have any extensions on them.  Now I'm all out of ideas and any help would be greatly appreciated.

Thanks in advance,

Josh

Body:
try this instead

<ivy:retrieve pattern="ivyLib/[artifact](.[ext])" conf="default" />

the () makes the contents of the () optional so it should match ivyLib/Foo and ivyLib/Foo.jar


问:
Python Networkx to R igraph conversion with errors
I am attempting to translate the following Python code (for Networkx) into R (for igraph).

```<code># Python code

import csv
import networkx as nx
import urllib

DG=nx.DiGraph()

dogcsv=csv.DictReader(open("dogs.csv","rU"))

dogid=0

nodeStr=['id', 'species',   'Location 1', 'Location 2']

nodeInt=['sumflu']

fluCols=['Influenza-1', 'Influenza-2', 'Influenza-3', 'Influenza-4',
'Influenza-5', 'Influenza-6', 'Influenza-7', 'Influenza-8', 'Influenza-9']

for flu in fluCols:
    DG.add_node(flu,typ="species")

for row in dogcsv:
    dogID='animal'+str(dogid)
    DG.add_node(dogID,typ='animal')
    for dog in nodeStr:
        DG.node[dogID][dog]=row[dog]
    for dog in nodeInt:
        DG.node[dogID][dog]=int(row[dog])
    for flu in fluCols:
        if str(row[flu])=='1':
            DG.add_edge(dogID,flu)
    dogid=dogid+1
</code>```

The following is my attempt at a partial conversion of from Python to R.

```<code># R code

library("data.table")
library("igraph")

dogs <- make_empty_graph()

dogcsv <- fread("dogs.csv")

dogid <- 0

nodeStr <- c("id", "species", "Location 1", "Location 2")

nodeInt <- "sumflu"

fluCols <- c("Influenza-1", "Influenza-2", "Influenza-3", "Influenza-4",
"Influenza-5", "Influenza-6", "Influenza-7", "Influenza-8")

for(flu in fluCols) {
dogs[flu] <- dogs %>% add_vertices(8) %>% add_vertices(dogs[flu], typ = "host")
    }
</code>```

This is the error code that I receive when I run the last portion of R code:

```<code>Error in intI(i, n = x@Dim[1], dn[[1]], give.dn = FALSE) :
  no 'dimnames[[.]]': cannot use character indexing
</code>```

In Python Networkx, the graph can be called out by graphname.function (ex. DG.add_node(dogID,typ='animal')).

Is there an equivalent in R's igraph?

Is there any way to call out the nodes in R's igraph without having to define the number of nodes?

Also, will you offer hints or suggestions on completing the translation to R?

Thank you.

The following contains the .csv data:

id,species,Location 1,Location 2,animal id,sumvirus,Influenza-1,Influenza-2,Influenza-3,Influenza-4,Influenza-5,Influenza-6,Influenza-7,Influenza-8,Influenza-9

YUI-4322,host1,Park 4,Park,MW 391,1,0,0,0,0,0,0,0,0,0

YUI-4321,host2,Park 4,Park,MW 390,0,0,0,0,0,0,0,0,0,0

YUI-4320,host2,Park 4,Park,MW 389,1,0,0,0,0,0,0,0,0,0

YUI-4319,host2,Park 4,Park,MW 388,0,0,0,0,0,0,0,0,0,0

YUI-7318,host2,Park 4,Park,MW 387,1,0,0,0,0,0,0,0,0,0

YUI-4317,host1,Park 4,Park,MW 386,0,0,0,0,0,0,0,0,0,0

YUI-4316,host2,Park 4,Park,MW 385,1,1,0,0,0,0,0,0,0,0

YUI-2315,host1,Shelter 2,Shelter,MV319,1,0,0,0,0,0,0,1,0,0

YUI-4314,host1,Shelter 2,Shelter,MV 332,1,0,0,0,0,0,0,1,0,0

答:
I'm confused with what you are doing, but I can tell you that dogs is a graph object, and you are trying to do multiple things in a line that don't make sense together.

Calling dogs[flu] gives all vertices connected to flu.

add_vertices(8) is adding 8 new vertices to the graph.

add_vertices(dogs[flu], typ="host") is adding the same nodes into the graph that would already exist if dogs[flu] is callable.

Just add the nodes all before (add_vertices[fluCols], although it may need ints instead of strings) and then modify those nodes after.

Body:
I am attempting to translate the following Python code (for Networkx) into R (for igraph).

# Python code

import csv
import networkx as nx
import urllib

DG=nx.DiGraph()

dogcsv=csv.DictReader(open("dogs.csv","rU"))

dogid=0

nodeStr=['id', 'species',   'Location 1', 'Location 2']

nodeInt=['sumflu']

fluCols=['Influenza-1', 'Influenza-2', 'Influenza-3', 'Influenza-4',
'Influenza-5', 'Influenza-6', 'Influenza-7', 'Influenza-8', 'Influenza-9']

for flu in fluCols:
    DG.add_node(flu,typ="species")

for row in dogcsv:
    dogID='animal'+str(dogid)
    DG.add_node(dogID,typ='animal')
    for dog in nodeStr:
        DG.node[dogID][dog]=row[dog]
    for dog in nodeInt:
        DG.node[dogID][dog]=int(row[dog])
    for flu in fluCols:
        if str(row[flu])=='1':
            DG.add_edge(dogID,flu)
    dogid=dogid+1

The following is my attempt at a partial conversion of from Python to R.

# R code

library("data.table")
library("igraph")

dogs <- make_empty_graph()

dogcsv <- fread("dogs.csv")

dogid <- 0

nodeStr <- c("id", "species", "Location 1", "Location 2")

nodeInt <- "sumflu"

fluCols <- c("Influenza-1", "Influenza-2", "Influenza-3", "Influenza-4",
"Influenza-5", "Influenza-6", "Influenza-7", "Influenza-8")

for(flu in fluCols) {
dogs[flu] <- dogs %>% add_vertices(8) %>% add_vertices(dogs[flu], typ = "host")
    }

This is the error code that I receive when I run the last portion of R code:

Error in intI(i, n = x@Dim[1], dn[[1]], give.dn = FALSE) :
  no 'dimnames[[.]]': cannot use character indexing

In Python Networkx, the graph can be called out by graphname.function (ex. DG.add_node(dogID,typ='animal')).

Is there an equivalent in R's igraph?

Is there any way to call out the nodes in R's igraph without having to define the number of nodes?

Also, will you offer hints or suggestions on completing the translation to R?

Thank you.

The following contains the .csv data:

id,species,Location 1,Location 2,animal id,sumvirus,Influenza-1,Influenza-2,Influenza-3,Influenza-4,Influenza-5,Influenza-6,Influenza-7,Influenza-8,Influenza-9

YUI-4322,host1,Park 4,Park,MW 391,1,0,0,0,0,0,0,0,0,0

YUI-4321,host2,Park 4,Park,MW 390,0,0,0,0,0,0,0,0,0,0

YUI-4320,host2,Park 4,Park,MW 389,1,0,0,0,0,0,0,0,0,0

YUI-4319,host2,Park 4,Park,MW 388,0,0,0,0,0,0,0,0,0,0

YUI-7318,host2,Park 4,Park,MW 387,1,0,0,0,0,0,0,0,0,0

YUI-4317,host1,Park 4,Park,MW 386,0,0,0,0,0,0,0,0,0,0

YUI-4316,host2,Park 4,Park,MW 385,1,1,0,0,0,0,0,0,0,0

YUI-2315,host1,Shelter 2,Shelter,MV319,1,0,0,0,0,0,0,1,0,0

YUI-4314,host1,Shelter 2,Shelter,MV 332,1,0,0,0,0,0,0,1,0,0