问:
How to mySQL ORDER BY in this case
I have this table and trying to show data ORDER BY but based on multiple column.

Table:

```<code>_______________________________________________
id | title | dis | cityid | dist | queue | date
_______________________________________________
1  |  abc  | 1   |  1     |  0   |  1    | 2017
2  |  cde  | 1   |  1     |  0   |  1    | 2017
3  |  efg  | 1   |  1     |  0   |  1    | 2017
4  |  ghi  | 1   |  1     |  0   |  1    | 2017
5  |title1 | 1   |  1     |  1   |  1    | 2017
6  | title2| 2   |  1     |  2   |  2    | 2017
7  | abc   | 2   |  1     |  0   |  2    | 2017
8  | cde   | 2   |  1     |  0   |  2    | 2017
9  | efg   | 2   |  1     |  0   |  2    | 2017
</code>```

Goal:

```<code>titl1
abc
cde
efg
ghi
titl12
abc
cde
efg
</code>```

Query:

```<code>$sql = "SELECT * FROM district ORDER BY title ASC, queue ASC";
</code>```

Also i tried:

```<code>$sql = "SELECT * FROM district ORDER BY title ASC, dist ASC";
</code>```

But none of these works, any suggestion?
Also i have free ability to add/remove column or change data (like dist, queue) to implement this.

Those data that have dis = 1 are sub group of title 1, and those have dis = 2 are sub group of title 2, title1 and 2 are hading.

For first query result is:

```<code>    abc
    cde
    efg
    ghi
    titl1
    titl12
    abc
    cde
    efg
</code>```

答:
First you want to sort by the main groups dis and show the lowest first:

```<code>ORDER BY dis ASC
</code>```

Then, within that sorting, you want to sort all with the same dis to get the headers (where dist isn't zero) first:

```<code>ORDER BY dis ASC, dist DESC
</code>```

And lastly, you want the rest to come in alphabetic order:

```<code>ORDER BY dis ASC, dist DESC, title ASC
</code>```

Title: How to mySQL ORDER BY in this case

Body:
I have this table and trying to show data ORDER BY but based on multiple column.

Table:

_______________________________________________
id | title | dis | cityid | dist | queue | date
_______________________________________________
1  |  abc  | 1   |  1     |  0   |  1    | 2017
2  |  cde  | 1   |  1     |  0   |  1    | 2017
3  |  efg  | 1   |  1     |  0   |  1    | 2017
4  |  ghi  | 1   |  1     |  0   |  1    | 2017
5  |title1 | 1   |  1     |  1   |  1    | 2017
6  | title2| 2   |  1     |  2   |  2    | 2017
7  | abc   | 2   |  1     |  0   |  2    | 2017
8  | cde   | 2   |  1     |  0   |  2    | 2017
9  | efg   | 2   |  1     |  0   |  2    | 2017

Goal:

titl1
abc
cde
efg
ghi
titl12
abc
cde
efg

Query:

$sql = "SELECT * FROM district ORDER BY title ASC, queue ASC";

Also i tried:

$sql = "SELECT * FROM district ORDER BY title ASC, dist ASC";

But none of these works, any suggestion?
Also i have free ability to add/remove column or change data (like dist, queue) to implement this.

Those data that have dis = 1 are sub group of title 1, and those have dis = 2 are sub group of title 2, title1 and 2 are hading.

For first query result is:

    abc
    cde
    efg
    ghi
    titl1
    titl12
    abc
    cde
    efg

Body:
First you want to sort by the main groups dis and show the lowest first:

ORDER BY dis ASC

Then, within that sorting, you want to sort all with the same dis to get the headers (where dist isn't zero) first:

ORDER BY dis ASC, dist DESC

And lastly, you want the rest to come in alphabetic order:

ORDER BY dis ASC, dist DESC, title ASC


来源: stackexchange

问:
object oriented JavaScript
Is there any error in my code esp var newpoint[0] =  new Point; . I wnat to know on how to do oop in javascript

```<code>function Point()
{
    var x;
    var y;
}

var length = 1;
var arrayindex;
var newpoint[0] =  new Point;
newpoint[0].x = 10;
newpoint[0].y = 10;
for(i=0 ; i<10; i ++)
{
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}
</code>```

EDIT : Thanks all . I have come up with two code need to know which one is better any any sugesstion and protips . both work

```<code>function Point()
{
    this.x;
    this. y;
}

var length = 0;
var newpoint = [];

for(i=0 ; i<10; i ++)
{
    newpoint[length] =new Point();
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}
</code>```

and

```<code>var length = 0;
var newpoint = [];
for(i=0 ; i<10; i ++)
{
    newpoint[length] = {};
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}
for(var arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}
</code>```

答:
You can use a constructor function in order to create points without having to type a lot of things. When is invoked with the new keyword, the this keyword in this function refers to the object being created.

This constructor function takes x and y as arguments and put it in the object.

```<code>function Point(x, y) {
    this.x = x;
    this.y = y;
}
</code>```

Then you want to have an array of points. Before using it, you need to create it first.

```<code>var newpoint = [];
</code>```

Adding new points is easy. With the help of the constructor of function it can be short of concise.

```<code>for (var i = 0; i < 10; i ++) {
    newpoint.push (new Point(10 * i, 10 * i));
}
</code>```

new Point(10 * i, 10 * i) creates a new instance of Point with the specified x and y coordinates.

newpoint.push is used to add the passed argument to the array. So no more length tracking!

Combined, this creates a new point, and adds it to the array.

Then to display it, you can iterate over the array the same way as before. Note that this time I use newpoint.length to mean the length of the array.

If you can the number 10 above you don't have to make any modifications to this loop, because we get the length dynamically.

```<code>for (var i = 0; i < newpoint.length; i ++) {
    alert('x=' + newpoint[i].x + ' y=' + newpoint[i].y);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: object oriented JavaScript

Body:
Is there any error in my code esp var newpoint[0] =  new Point; . I wnat to know on how to do oop in javascript

function Point()
{
    var x;
    var y;
}

var length = 1;
var arrayindex;
var newpoint[0] =  new Point;
newpoint[0].x = 10;
newpoint[0].y = 10;
for(i=0 ; i<10; i ++)
{
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y);
}

EDIT : Thanks all . I have come up with two code need to know which one is better any any sugesstion and protips . both work

function Point()
{
    this.x;
    this. y;
}

var length = 0;
var newpoint = [];

for(i=0 ; i<10; i ++)
{
    newpoint[length] =new Point();
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}

for(arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}

and

var length = 0;
var newpoint = [];
for(i=0 ; i<10; i ++)
{
    newpoint[length] = {};
    newpoint[length].x = 10*i;
    newpoint[length++].y = 10*i;
}
for(var arrayindex in newpoint )
{
    alert('x='+newpoint[arrayindex].x +'y='+newpoint[arrayindex].y)
}

Body:
You can use a constructor function in order to create points without having to type a lot of things. When is invoked with the new keyword, the this keyword in this function refers to the object being created.

This constructor function takes x and y as arguments and put it in the object.

function Point(x, y) {
    this.x = x;
    this.y = y;
}

Then you want to have an array of points. Before using it, you need to create it first.

var newpoint = [];

Adding new points is easy. With the help of the constructor of function it can be short of concise.

for (var i = 0; i < 10; i ++) {
    newpoint.push (new Point(10 * i, 10 * i));
}

new Point(10 * i, 10 * i) creates a new instance of Point with the specified x and y coordinates.

newpoint.push is used to add the passed argument to the array. So no more length tracking!

Combined, this creates a new point, and adds it to the array.

Then to display it, you can iterate over the array the same way as before. Note that this time I use newpoint.length to mean the length of the array.

If you can the number 10 above you don't have to make any modifications to this loop, because we get the length dynamically.

for (var i = 0; i < newpoint.length; i ++) {
    alert('x=' + newpoint[i].x + ' y=' + newpoint[i].y);
}


问:
A better way to run task periodically in Java
I have a method that I want to be invoked periodically: every day on 11 am. It is a simple method in Main:

```<code>public void loadProduct() {
PropertyConfigurator.configure("log4j.properties");
try {
     service.create(product);
     logger.info("Creation started");
} catch (Exception e) {
  // Log Exception
     logger.error(e);
}
}
</code>```

I have almost figured out how to achieve this with the help of Spring context:

```<code><task:scheduler id="scheduler" pool-size="1"/>

<task:scheduled-tasks scheduler="scheduler">
    <task:scheduled ref="productTask" method="loadProduct" cron="0/30 * * * * *"/>
</task:scheduled-tasks>
</code>```

But how to schedule the task to start every 24 hours on 11 am every day?

Or is there a way to achieve this in Java code?

答:
But how to schedule the task to start every 24 hours on 11 am every day?

This can be achieved by using the cron expression: 0 0 11 * * *.

Or is there a way to achieve this in Java code?

Yes, by using the Scheduled (Spring Framework 5.0.1.RELEASE API) annotation, for example:

```<code>@Scheduled(cron = "0 0 11 * * *", zone = "Europe/Moscow")
public void run() {
    // ...
}
</code>```

Additional references:

Integration: 7. Task Execution and Scheduling: 7.4. Annotation Support for Scheduling and Asynchronous Execution, Spring Framework Documentation.

Getting Started · Scheduling Tasks.

ContentLicense: CC BY-SA 3.0

Body:
I have a method that I want to be invoked periodically: every day on 11 am. It is a simple method in Main:

public void loadProduct() {
PropertyConfigurator.configure("log4j.properties");
try {
     service.create(product);
     logger.info("Creation started");
} catch (Exception e) {
  // Log Exception
     logger.error(e);
}
}

I have almost figured out how to achieve this with the help of Spring context:

<task:scheduler id="scheduler" pool-size="1"/>

<task:scheduled-tasks scheduler="scheduler">
    <task:scheduled ref="productTask" method="loadProduct" cron="0/30 * * * * *"/>
</task:scheduled-tasks>

But how to schedule the task to start every 24 hours on 11 am every day?

Or is there a way to achieve this in Java code?

Body:
But how to schedule the task to start every 24 hours on 11 am every day?

This can be achieved by using the cron expression: 0 0 11 * * *.

Or is there a way to achieve this in Java code?

Yes, by using the Scheduled (Spring Framework 5.0.1.RELEASE API) annotation, for example:

@Scheduled(cron = "0 0 11 * * *", zone = "Europe/Moscow")
public void run() {
    // ...
}

Additional references:

Integration: 7. Task Execution and Scheduling: 7.4. Annotation Support for Scheduling and Asynchronous Execution, Spring Framework Documentation.

Getting Started · Scheduling Tasks.


问:
How to get random value of attribute of Enum on each iteration?
I have created such Enum object:

```<code>class Gender(Enum):
    FEMALE = 'female'
    MALE = 'male'
    RANDOM = random.choice([FEMALE, MALE])
</code>```

and i want to get really random value each time, but it does not work:

```<code>>>> class Gender(Enum):
...    MALE = 'male'
...    FEMALE = 'female'
...    RANDOM = choice([MALE, FEMALE])
...
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
</code>```

I have also tried use lambda, but it's looks not so good, although it works:

```<code>Gender.RANDOM()
</code>```

Are there other way to get random values each time, without using lambda expressions?

We use this enum object as default value of the argument of the some method that's why it should be an attribute, not a function, because when we use Gender.FEMALE it is not a function, it's an attribute and Gender.RANDOM should be an attribute too:

```<code>def full_name(gender=Gender.FEMALE):
    ...

def full_name(gender=Gender.RANDOM):
    ...
</code>```

答:
You probably should create a method in your Enum to obtain a random gender:

```<code>import random
import enum

class Gender(enum.Enum):
    FEMALE = 'female'
    MALE = 'male'

    @classmethod
    def get_gender(cls):
        return random.choice([Gender.FEMALE, Gender.MALE])

Gender.get_gender()
</code>```

Body:
I have created such Enum object:

class Gender(Enum):
    FEMALE = 'female'
    MALE = 'male'
    RANDOM = random.choice([FEMALE, MALE])

and i want to get really random value each time, but it does not work:

>>> class Gender(Enum):
...    MALE = 'male'
...    FEMALE = 'female'
...    RANDOM = choice([MALE, FEMALE])
...
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>
>>> Gender.RANDOM
<Gender.MALE: 'male'>

I have also tried use lambda, but it's looks not so good, although it works:

Gender.RANDOM()

Are there other way to get random values each time, without using lambda expressions?

We use this enum object as default value of the argument of the some method that's why it should be an attribute, not a function, because when we use Gender.FEMALE it is not a function, it's an attribute and Gender.RANDOM should be an attribute too:

def full_name(gender=Gender.FEMALE):
    ...

def full_name(gender=Gender.RANDOM):
    ...

Body:
You probably should create a method in your Enum to obtain a random gender:

import random
import enum

class Gender(enum.Enum):
    FEMALE = 'female'
    MALE = 'male'

    @classmethod
    def get_gender(cls):
        return random.choice([Gender.FEMALE, Gender.MALE])

Gender.get_gender()


问:
Minimum supported Gradle version is 2.14.1. Current version is 2.10
I am trying to build my project using gradle command line but it keeps throwing exceptions that

```<code>A problem occurred evaluating project ':app'.
> Failed to apply plugin [id 'com.android.application']
   > Minimum supported Gradle version is 2.14.1. Current version is 2.10. If using the gradle wrapper, try editing the distributionUrl in /mnt/c/Users/USER/Documents/Projects/fdroiddata/build/com.simpledecredwidget/gradle/wrapper/gradle-wrapper.properties to gradle-2.14.1-all.zip
</code>```

Complete error is here

This is my gradle wrapper located at $projectroot/gradle/wrapper and this is the content of my gradle wrapper

```<code>#Mon Dec 28 10:00:20 PST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
</code>```

I have tried all i can but it is not working, as you can see i already modified my distributionUrl and it keeps showing the same error and pointing to the same file, Please help me in any way you can.

Thanks.

答:
You should use the required version of Android Plugin for each gradle version.

If you are using gradle 4.1+, you should use plugin 3.0.0+.

You can specify the Gradle version in either the File > Project Structure > Project menu in Android Studio, or by editing the Gradle distribution reference in the gradle/wrapper/gradle-wrapper.properties file. The following example sets the Gradle version to 4.1 in the gradle-wrapper.properties file.

More information: https://developer.android.com/studio/releases/gradle-plugin.html

Body:
I am trying to build my project using gradle command line but it keeps throwing exceptions that

A problem occurred evaluating project ':app'.
> Failed to apply plugin [id 'com.android.application']
   > Minimum supported Gradle version is 2.14.1. Current version is 2.10. If using the gradle wrapper, try editing the distributionUrl in /mnt/c/Users/USER/Documents/Projects/fdroiddata/build/com.simpledecredwidget/gradle/wrapper/gradle-wrapper.properties to gradle-2.14.1-all.zip

Complete error is here

This is my gradle wrapper located at $projectroot/gradle/wrapper and this is the content of my gradle wrapper

#Mon Dec 28 10:00:20 PST 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip

I have tried all i can but it is not working, as you can see i already modified my distributionUrl and it keeps showing the same error and pointing to the same file, Please help me in any way you can.

Thanks.


问:
How to do a lazy create and set with AtomicReference in a safe and efficient manner?
I'm looking to lazily create something and cache the results as an optimization.  Is the code below safe and efficient, or is there a better way to do this?  Is the compare and set loop needed here?

```<code>...
AtomicReference<V> fCachedValue = new AtomicReference<>();

public V getLazy() {
    V result = fCachedValue.get();
    if (result == null) {
        result = costlyIdempotentOperation();
        fCachedValue.set(result);
    }
    return result;
}
</code>```

edit:  The value being set in my example here from costlyIdempotentOperation() would always be the same no matter what thread called it.

答:
This expands the answer by @TwoThe on how AtomicReference<Future<V>> may be used.

Basically, if you don't mind having (a little bit more expensive) synchronized sections in your code, the easiest (and the most readable) solution would be to use the Double-checked Locking idiom (with volatile).

If you still want to utilize the CAS (this is what the whole family of Atomic* types is about), you have to use AtomicReference<Future<V>>, not AtomicReference<V> (or you may end up having multiple threads computing the same expensive value).

But here's another catch: you may obtain a valid Future<V> instance and share it between multiple threads, but the instance itself may be unusable because your costly computation may have failed. This leads us to the need to re-set the atomic reference we have (fCachedValue.set(null)) in some or all exceptional situations.

The above implies that it's no longer sufficient to call fCachedValue.compareAndSet(null, new FutureTask(...)) once -- you'll have to atomically test whether the reference contains a non-null value and re-initialize it if necessary (on each invocation). Luckily, the AtomicReference class has the getAndUpdate(...) method which merely invokes compareAndSet(...) in a loop. So the resulting code might look like this:

class ConcurrentLazy<V> implements Callable<V> {
    private final AtomicReference<Future<V>> fCachedValue = new AtomicReference<>();

    private final Callable<V> callable;

    public ConcurrentLazy(final Callable<V> callable) {
        this.callable = callable;
    }

    /**
     * {@inheritDoc}
     *
     * @throws Error if thrown by the underlying callable task.
     * @throws RuntimeException if thrown by the underlying callable task,
     *         or the task throws a checked exception,
     *         or the task is interrupted (in this last case, it's the
     *         client's responsibility to process the cause of the
     *         exception).
     * @see Callable#call()
     */
    @Override
    public V call() {
        final RunnableFuture<V> newTask = new FutureTask<>(this.callable);
        final Future<V> oldTask = this.fCachedValue.getAndUpdate(f -> {
            /*
             * If the atomic reference is un-initialised or reset,
             * set it to the new task. Otherwise, return the
             * previous (running or completed) task.
             */
            return f == null ? newTask : f;
        });

        if (oldTask == null) {
            /*
             * Compute the new value on the current thread.
             */
            newTask.run();
        }

        try {
            return (oldTask == null ? newTask : oldTask).get();
        } catch (final ExecutionException ee) {
            /*
             * Re-set the reference.
             */
            this.fCachedValue.set(null);

            final Throwable cause = ee.getCause();
            if (cause instanceof Error) {
                throw (Error) cause;
            }
            throw toUnchecked(cause);
        } catch (final InterruptedException ie) {
            /*
             * Re-set the reference.
             */
            this.fCachedValue.set(null);

            /*
             * It's the client's responsibility to check the cause.
             */
            throw new RuntimeException(ie);
        }
    }

    private static RuntimeException toUnchecked(final Throwable t) {
        return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
    }
}
```
<p>In <em>Kotlin</em>, the above can be expressed in a much simpler way (<code>() -> V</code> denotes your lazy computation):</p>
<pre class="lang-kotlin prettyprint-override"><code>import java.util.concurrent.ExecutionException
import java.util.concurrent.Future
import java.util.concurrent.FutureTask
import java.util.concurrent.atomic.AtomicReference

fun <V> (() -> V).concurrent(): () -> V {
  /*
   * The cached result of the computation.
   */
  val valueRef = AtomicReference<Future<V>?>()

  return {
    val newTask = FutureTask(this)

    val oldTaskOrNull = valueRef.getAndUpdate { oldTaskOrNull ->
      oldTaskOrNull ?: newTask
    }

    if (oldTaskOrNull == null) {
      /*
       * Compute the new value on the current thread.
       */
      newTask.run()
    }

    try {
      (oldTaskOrNull ?: newTask).get()
    }
    catch (ee: ExecutionException) {
      /*
       * Re-set the reference.
       */
      valueRef.set(null)

      /*
       * Don't mask the compilation failure with an ExecutionException.
       */
      throw ee.cause ?: ee
    }
    catch (e: Exception) {
      /*
       * Re-set the reference.
       */
      valueRef.set(null)

      /*
       * Most probably, an InterruptedException.
       */
      throw e
    }
  }
}
</code>```

Usage example:

  val lambda = {
    println("Computing 2x2...")

    val timeNanos = System.nanoTime()
    if (timeNanos % 2L == 0L) {
      throw IOException(timeNanos.toString())
    }

    2 * 2
  }.concurrent()

  val resultSeq = sequence {
    while (true) {
      val element = try {
        lambda().toString()
      }
      catch (ioe: IOException) {
        ioe.toString()
      }

      yield(element)
    }
  }

  resultSeq.take(50).forEach(::println)
```
<p>The above code, when run, produces the following output:</p>
<pre class="lang-none prettyprint-override"><code>Computing 2x2...
java.io.IOException: 93224642168398
Computing 2x2...
4
4
4
4
4
4
...
</code>```

The result of the computation can be re-set multiple times, but once a successful result is reached, it is always returned. At the same time, while the computation is being run, the lambda can be shared between multiple threads (e. g.: cached in a ConcurrentHashMap).

P. S. If you're limited to Java, you might also want to take a look at the CompletableFuture class.

Body:
I'm looking to lazily create something and cache the results as an optimization.  Is the code below safe and efficient, or is there a better way to do this?  Is the compare and set loop needed here?

...
AtomicReference<V> fCachedValue = new AtomicReference<>();

public V getLazy() {
    V result = fCachedValue.get();
    if (result == null) {
        result = costlyIdempotentOperation();
        fCachedValue.set(result);
    }
    return result;
}

edit:  The value being set in my example here from costlyIdempotentOperation() would always be the same no matter what thread called it.

Body:
This expands the answer by @TwoThe on how AtomicReference<Future<V>> may be used.

Basically, if you don't mind having (a little bit more expensive) synchronized sections in your code, the easiest (and the most readable) solution would be to use the Double-checked Locking idiom (with volatile).

If you still want to utilize the CAS (this is what the whole family of Atomic* types is about), you have to use AtomicReference<Future<V>>, not AtomicReference<V> (or you may end up having multiple threads computing the same expensive value).

But here's another catch: you may obtain a valid Future<V> instance and share it between multiple threads, but the instance itself may be unusable because your costly computation may have failed. This leads us to the need to re-set the atomic reference we have (fCachedValue.set(null)) in some or all exceptional situations.

The above implies that it's no longer sufficient to call fCachedValue.compareAndSet(null, new FutureTask(...)) once -- you'll have to atomically test whether the reference contains a non-null value and re-initialize it if necessary (on each invocation). Luckily, the AtomicReference class has the getAndUpdate(...) method which merely invokes compareAndSet(...) in a loop. So the resulting code might look like this:

class ConcurrentLazy<V> implements Callable<V> {
    private final AtomicReference<Future<V>> fCachedValue = new AtomicReference<>();

    private final Callable<V> callable;

    public ConcurrentLazy(final Callable<V> callable) {
        this.callable = callable;
    }

    /**
     * {@inheritDoc}
     *
     * @throws Error if thrown by the underlying callable task.
     * @throws RuntimeException if thrown by the underlying callable task,
     *         or the task throws a checked exception,
     *         or the task is interrupted (in this last case, it's the
     *         client's responsibility to process the cause of the
     *         exception).
     * @see Callable#call()
     */
    @Override
    public V call() {
        final RunnableFuture<V> newTask = new FutureTask<>(this.callable);
        final Future<V> oldTask = this.fCachedValue.getAndUpdate(f -> {
            /*
             * If the atomic reference is un-initialised or reset,
             * set it to the new task. Otherwise, return the
             * previous (running or completed) task.
             */
            return f == null ? newTask : f;
        });

        if (oldTask == null) {
            /*
             * Compute the new value on the current thread.
             */
            newTask.run();
        }

        try {
            return (oldTask == null ? newTask : oldTask).get();
        } catch (final ExecutionException ee) {
            /*
             * Re-set the reference.
             */
            this.fCachedValue.set(null);

            final Throwable cause = ee.getCause();
            if (cause instanceof Error) {
                throw (Error) cause;
            }
            throw toUnchecked(cause);
        } catch (final InterruptedException ie) {
            /*
             * Re-set the reference.
             */
            this.fCachedValue.set(null);

            /*
             * It's the client's responsibility to check the cause.
             */
            throw new RuntimeException(ie);
        }
    }

    private static RuntimeException toUnchecked(final Throwable t) {
        return t instanceof RuntimeException ? (RuntimeException) t : new RuntimeException(t);
    }
}

In Kotlin, the above can be expressed in a much simpler way (() -> V denotes your lazy computation):

import java.util.concurrent.ExecutionException
import java.util.concurrent.Future
import java.util.concurrent.FutureTask
import java.util.concurrent.atomic.AtomicReference

fun <V> (() -> V).concurrent(): () -> V {
  /*
   * The cached result of the computation.
   */
  val valueRef = AtomicReference<Future<V>?>()

  return {
    val newTask = FutureTask(this)

    val oldTaskOrNull = valueRef.getAndUpdate { oldTaskOrNull ->
      oldTaskOrNull ?: newTask
    }

    if (oldTaskOrNull == null) {
      /*
       * Compute the new value on the current thread.
       */
      newTask.run()
    }

    try {
      (oldTaskOrNull ?: newTask).get()
    }
    catch (ee: ExecutionException) {
      /*
       * Re-set the reference.
       */
      valueRef.set(null)

      /*
       * Don't mask the compilation failure with an ExecutionException.
       */
      throw ee.cause ?: ee
    }
    catch (e: Exception) {
      /*
       * Re-set the reference.
       */
      valueRef.set(null)

      /*
       * Most probably, an InterruptedException.
       */
      throw e
    }
  }
}

Usage example:

  val lambda = {
    println("Computing 2x2...")

    val timeNanos = System.nanoTime()
    if (timeNanos % 2L == 0L) {
      throw IOException(timeNanos.toString())
    }

    2 * 2
  }.concurrent()

  val resultSeq = sequence {
    while (true) {
      val element = try {
        lambda().toString()
      }
      catch (ioe: IOException) {
        ioe.toString()
      }

      yield(element)
    }
  }

  resultSeq.take(50).forEach(::println)

The above code, when run, produces the following output:

Computing 2x2...
java.io.IOException: 93224642168398
Computing 2x2...
4
4
4
4
4
4
...

The result of the computation can be re-set multiple times, but once a successful result is reached, it is always returned. At the same time, while the computation is being run, the lambda can be shared between multiple threads (e. g.: cached in a ConcurrentHashMap).

P. S. If you're limited to Java, you might also want to take a look at the CompletableFuture class.

ContentLicense: CC BY-SA 4.0


问:
Receive-Job missing data
I have created a PowerShell script to dump some details from Office 365 into a csv. There are 120,000 accounts in the Azure AD. To speed up the process I have split the script up into 25 jobs.

Everything works apart from the output for MFAState and Errors which return no data.

My script previously without using jobs works perfectly. Any ideas why the data is not being returned by the job?

```<code>#### Editable Section #####
$jobcount = 25                  # Set the maximum jobs
$usersperbatch = 5000           # Users per batch
$username = "user@example.com"  # MSOL Admin account

#### Start Script #####

# Get Credential and connect
$cred = Get-Credential $username

"Connecting to MSOnline"
if (Get-Module MSOnline) {Import-Module MSOnline}

Connect-MsolService -Credential $cred

"Getting MSOL Accounts"
$MSOLUsers = Get-MsolUser -All
"Total Users: $($MSOLUsers.Count)"

# Set counts
$i = 0
$j = $usersperbatch - 1
$batch = 1

while ($i -lt $MSOLUsers.count)
{

    # Pause job creation if jobs equal $jobcount
    $running = @(Get-Job | Where-Object {$_.State -eq 'Running'})
    if ($running.Count -ge $jobcount) {$running | Wait-Job -Any | Out-Null}

    # Create batch of users
    $userbatch = $MSOLUsers[$i..$j]

    # Create Scriptblock for job
    $sb = {
        # Import Arguments
        param ($cred, $MSOLUsers)

        # Connect to AAD
        Connect-MsolService -Credential $cred

        $Results = @()

        Foreach ($m in $MSOLUsers)
        {

            $Result = New-Object PSObject

            $Result | Add-Member -MemberType "NoteProperty" -Name DisplayName -Value $m.DisplayName
            $Result | Add-Member -MemberType "NoteProperty" -Name FirstName -Value $m.FirstName
            $Result | Add-Member -MemberType "NoteProperty" -Name LastName -Value $m.LastName
            $Result | Add-Member -MemberType "NoteProperty" -Name UserPrincipalName -Value $m.UserPrincipalName
            $Result | Add-Member -MemberType "NoteProperty" -Name WhenCreated -Value $m.WhenCreated
            $Result | Add-Member -MemberType "NoteProperty" -Name GUID -Value $m.GUID
            $Result | Add-Member -MemberType "NoteProperty" -Name LastDirSyncTime -Value $m.LastDirSyncTime
            $Result | Add-Member -MemberType "NoteProperty" -Name StrongPWord -Value $m.StrongPasswordRequired
            $Result | Add-Member -MemberType "NoteProperty" -Name Disabled -Value $m.BlockCredential
            $Result | Add-Member -MemberType "NoteProperty" -Name MFAState -Value $m.StrongAuthenticationRequirements.State
            $Result | Add-Member -MemberType "NoteProperty" -Name IsLicensed -Value $m.IsLicensed
            $Result | Add-Member -MemberType "NoteProperty" -Name Valid -Value $m.ValidationStatus
            $Result | Add-Member -MemberType "NoteProperty" -Name Errors -Value $m.Errors.ErrorDetail.ObjectErrors.ErrorRecord.ErrorDescription

            $Results += $Result

        } # End Foreach

        $Results

    } # End Scriptblock

    # Create Job Name based on Range
    $jobname = "$i-$j"

    # Start job
    Start-Job -Name $jobname -ScriptBlock $sb -ArgumentList $cred, $userbatch

    # update counts
    $batch += 1
    $i = $j + 1
    $j += $usersperbatch

    if ($i -gt $MSOLUsers.count) {$i = $MSOLUsers.count}
    if ($j -gt $MSOLUsers.count) {$j = $MSOLUsers.count}

} # End While

# Get Results
$Results = Get-Job | Receive-Job -Wait
</code>```

答:
First of all you don't need to have Connect-MsolService in your while loop since you already have it before the loop.

Also I would define the script block before the loop and use another variable name for the user list parameter.

```<code>#### Editable Section #####
$jobcount = 25                  # Set the maximum jobs
$usersperbatch = 5000           # Users per batch
$username = "user@example.com"  # MSOL Admin account

#### Start Script #####

# Get Credential and connect
$cred = Get-Credential $username

"Connecting to MSOnline"
if (Get-Module MSOnline) {Import-Module MSOnline}

Connect-MsolService -Credential $cred

"Getting MSOL Accounts"
$MSOLUsers = Get-MsolUser -All
"Total Users: $($MSOLUsers.Count)"

# Set counts
$i = 0
$j = $usersperbatch - 1
$batch = 1

# Create Scriptblock for job
$sb = {
    # Import Arguments
    param ($cred, $users)

    # Connect to AAD
    #Connect-MsolService -Credential $cred

    $Results = @()

    Foreach ($m in $users)
    {

        $Result = New-Object PSObject

        $Result | Add-Member -MemberType "NoteProperty" -Name DisplayName -Value $m.DisplayName
        $Result | Add-Member -MemberType "NoteProperty" -Name FirstName -Value $m.FirstName
        $Result | Add-Member -MemberType "NoteProperty" -Name LastName -Value $m.LastName
        $Result | Add-Member -MemberType "NoteProperty" -Name UserPrincipalName -Value $m.UserPrincipalName
        $Result | Add-Member -MemberType "NoteProperty" -Name WhenCreated -Value $m.WhenCreated
        $Result | Add-Member -MemberType "NoteProperty" -Name GUID -Value $m.GUID
        $Result | Add-Member -MemberType "NoteProperty" -Name LastDirSyncTime -Value $m.LastDirSyncTime
        $Result | Add-Member -MemberType "NoteProperty" -Name StrongPWord -Value $m.StrongPasswordRequired
        $Result | Add-Member -MemberType "NoteProperty" -Name Disabled -Value $m.BlockCredential
        $Result | Add-Member -MemberType "NoteProperty" -Name MFAState -Value $m.StrongAuthenticationRequirements.State
        $Result | Add-Member -MemberType "NoteProperty" -Name IsLicensed -Value $m.IsLicensed
        $Result | Add-Member -MemberType "NoteProperty" -Name Valid -Value $m.ValidationStatus
        $Result | Add-Member -MemberType "NoteProperty" -Name Errors -Value $m.Errors.ErrorDetail.ObjectErrors.ErrorRecord.ErrorDescription

        $Results += $Result

    } # End Foreach

    $Results

} # End Scriptblock

while ($i -lt $MSOLUsers.count)
{
    # Pause job creation if jobs equal $jobcount
    $running = @(Get-Job | Where-Object {$_.State -eq 'Running'})
    if ($running.Count -ge $jobcount) {$running | Wait-Job -Any | Out-Null}

    # Create batch of users
    $userbatch = $MSOLUsers[$i..$j]

    # Create Job Name based on Range
    $jobname = "$i-$j"

    # Start job
    Start-Job -Name $jobname -ScriptBlock $sb -ArgumentList $cred, $userbatch

    # update counts
    $batch += 1
    $i = $j + 1
    $j += $usersperbatch

    if ($i -gt $MSOLUsers.count) {$i = $MSOLUsers.count}
    if ($j -gt $MSOLUsers.count) {$j = $MSOLUsers.count}

} # End While

# Get Results
$Results = Get-Job | Receive-Job -Wait
</code>```

Title: Receive-Job missing data

Body:
I have created a PowerShell script to dump some details from Office 365 into a csv. There are 120,000 accounts in the Azure AD. To speed up the process I have split the script up into 25 jobs.

Everything works apart from the output for MFAState and Errors which return no data.

My script previously without using jobs works perfectly. Any ideas why the data is not being returned by the job?

#### Editable Section #####
$jobcount = 25                  # Set the maximum jobs
$usersperbatch = 5000           # Users per batch
$username = "user@example.com"  # MSOL Admin account

#### Start Script #####

# Get Credential and connect
$cred = Get-Credential $username

"Connecting to MSOnline"
if (Get-Module MSOnline) {Import-Module MSOnline}

Connect-MsolService -Credential $cred

"Getting MSOL Accounts"
$MSOLUsers = Get-MsolUser -All
"Total Users: $($MSOLUsers.Count)"

# Set counts
$i = 0
$j = $usersperbatch - 1
$batch = 1

while ($i -lt $MSOLUsers.count)
{

    # Pause job creation if jobs equal $jobcount
    $running = @(Get-Job | Where-Object {$_.State -eq 'Running'})
    if ($running.Count -ge $jobcount) {$running | Wait-Job -Any | Out-Null}

    # Create batch of users
    $userbatch = $MSOLUsers[$i..$j]

    # Create Scriptblock for job
    $sb = {
        # Import Arguments
        param ($cred, $MSOLUsers)

        # Connect to AAD
        Connect-MsolService -Credential $cred

        $Results = @()

        Foreach ($m in $MSOLUsers)
        {

            $Result = New-Object PSObject

            $Result | Add-Member -MemberType "NoteProperty" -Name DisplayName -Value $m.DisplayName
            $Result | Add-Member -MemberType "NoteProperty" -Name FirstName -Value $m.FirstName
            $Result | Add-Member -MemberType "NoteProperty" -Name LastName -Value $m.LastName
            $Result | Add-Member -MemberType "NoteProperty" -Name UserPrincipalName -Value $m.UserPrincipalName
            $Result | Add-Member -MemberType "NoteProperty" -Name WhenCreated -Value $m.WhenCreated
            $Result | Add-Member -MemberType "NoteProperty" -Name GUID -Value $m.GUID
            $Result | Add-Member -MemberType "NoteProperty" -Name LastDirSyncTime -Value $m.LastDirSyncTime
            $Result | Add-Member -MemberType "NoteProperty" -Name StrongPWord -Value $m.StrongPasswordRequired
            $Result | Add-Member -MemberType "NoteProperty" -Name Disabled -Value $m.BlockCredential
            $Result | Add-Member -MemberType "NoteProperty" -Name MFAState -Value $m.StrongAuthenticationRequirements.State
            $Result | Add-Member -MemberType "NoteProperty" -Name IsLicensed -Value $m.IsLicensed
            $Result | Add-Member -MemberType "NoteProperty" -Name Valid -Value $m.ValidationStatus
            $Result | Add-Member -MemberType "NoteProperty" -Name Errors -Value $m.Errors.ErrorDetail.ObjectErrors.ErrorRecord.ErrorDescription

            $Results += $Result

        } # End Foreach

        $Results

    } # End Scriptblock

    # Create Job Name based on Range
    $jobname = "$i-$j"

    # Start job
    Start-Job -Name $jobname -ScriptBlock $sb -ArgumentList $cred, $userbatch

    # update counts
    $batch += 1
    $i = $j + 1
    $j += $usersperbatch

    if ($i -gt $MSOLUsers.count) {$i = $MSOLUsers.count}
    if ($j -gt $MSOLUsers.count) {$j = $MSOLUsers.count}

} # End While

# Get Results
$Results = Get-Job | Receive-Job -Wait

Body:
First of all you don't need to have Connect-MsolService in your while loop since you already have it before the loop.

Also I would define the script block before the loop and use another variable name for the user list parameter.

#### Editable Section #####
$jobcount = 25                  # Set the maximum jobs
$usersperbatch = 5000           # Users per batch
$username = "user@example.com"  # MSOL Admin account

#### Start Script #####

# Get Credential and connect
$cred = Get-Credential $username

"Connecting to MSOnline"
if (Get-Module MSOnline) {Import-Module MSOnline}

Connect-MsolService -Credential $cred

"Getting MSOL Accounts"
$MSOLUsers = Get-MsolUser -All
"Total Users: $($MSOLUsers.Count)"

# Set counts
$i = 0
$j = $usersperbatch - 1
$batch = 1

# Create Scriptblock for job
$sb = {
    # Import Arguments
    param ($cred, $users)

    # Connect to AAD
    #Connect-MsolService -Credential $cred

    $Results = @()

    Foreach ($m in $users)
    {

        $Result = New-Object PSObject

        $Result | Add-Member -MemberType "NoteProperty" -Name DisplayName -Value $m.DisplayName
        $Result | Add-Member -MemberType "NoteProperty" -Name FirstName -Value $m.FirstName
        $Result | Add-Member -MemberType "NoteProperty" -Name LastName -Value $m.LastName
        $Result | Add-Member -MemberType "NoteProperty" -Name UserPrincipalName -Value $m.UserPrincipalName
        $Result | Add-Member -MemberType "NoteProperty" -Name WhenCreated -Value $m.WhenCreated
        $Result | Add-Member -MemberType "NoteProperty" -Name GUID -Value $m.GUID
        $Result | Add-Member -MemberType "NoteProperty" -Name LastDirSyncTime -Value $m.LastDirSyncTime
        $Result | Add-Member -MemberType "NoteProperty" -Name StrongPWord -Value $m.StrongPasswordRequired
        $Result | Add-Member -MemberType "NoteProperty" -Name Disabled -Value $m.BlockCredential
        $Result | Add-Member -MemberType "NoteProperty" -Name MFAState -Value $m.StrongAuthenticationRequirements.State
        $Result | Add-Member -MemberType "NoteProperty" -Name IsLicensed -Value $m.IsLicensed
        $Result | Add-Member -MemberType "NoteProperty" -Name Valid -Value $m.ValidationStatus
        $Result | Add-Member -MemberType "NoteProperty" -Name Errors -Value $m.Errors.ErrorDetail.ObjectErrors.ErrorRecord.ErrorDescription

        $Results += $Result

    } # End Foreach

    $Results

} # End Scriptblock

while ($i -lt $MSOLUsers.count)
{
    # Pause job creation if jobs equal $jobcount
    $running = @(Get-Job | Where-Object {$_.State -eq 'Running'})
    if ($running.Count -ge $jobcount) {$running | Wait-Job -Any | Out-Null}

    # Create batch of users
    $userbatch = $MSOLUsers[$i..$j]

    # Create Job Name based on Range
    $jobname = "$i-$j"

    # Start job
    Start-Job -Name $jobname -ScriptBlock $sb -ArgumentList $cred, $userbatch

    # update counts
    $batch += 1
    $i = $j + 1
    $j += $usersperbatch

    if ($i -gt $MSOLUsers.count) {$i = $MSOLUsers.count}
    if ($j -gt $MSOLUsers.count) {$j = $MSOLUsers.count}

} # End While

# Get Results
$Results = Get-Job | Receive-Job -Wait


问:
Unity2D hide everything that is outside shape defined by edgecollider
I have a 2D polygon that is defined by a edgeCollider. Is there a way to hide everything that is outside of the shape and show only what is inside?

I tried using skyboxes and lights. I thought about creating a mask(but i dont know how to create such a mask).

Is there a way to only show what is inside the shape defined by edge collider?

答:
What about using the colliders trigger events?
Set this polygon as a trigger in the edgeCollider2D component in the inspector. Then you can use the collider OnEnterTrigger2D.

Your gameobjects are all disabled until this edgeCollider collides with in. Then disable the gameobject OnExitTrigger2D.

If you wanted to limit it to a certain number of object only. You would set a layer to only hide/show these object.

```<code>void OnTriggerEnter2D(Collider2D other) {
     if(other.gameObject.layer == "hiddenObject"){
         other.gameObject.enable = true;
     }
}
</code>```

Then the reverse on the OnTriggerExit2D.

I'm not sure the effect that you are aiming for. So another solution could be a postprocessing shader.

I can only give a high level description on this however.

You would take the final screen image texture, and the current position of the polygon and then add the pixels from the screen texture to the polygon texture and output this texture. (this shader has to exists already).

But you want the inverse of these.

https://docs.unity3d.com/Manual/shader-TransparentCutoutFamily.html

You're wanting to keep what's in the hole and get rid of what's outside of it?

You can download the built in shaders to edit them here

https://unity3d.com/get-unity/download/archive

Just find your version of unity and select builtin shaders from the drop down.

Edit:  "SPOTLIGHT!", try this but with your custom shape

http://www.shaderslab.com/demo-49---spotlight.html

Body:
What about using the colliders trigger events?
Set this polygon as a trigger in the edgeCollider2D component in the inspector. Then you can use the collider OnEnterTrigger2D.

Your gameobjects are all disabled until this edgeCollider collides with in. Then disable the gameobject OnExitTrigger2D.

If you wanted to limit it to a certain number of object only. You would set a layer to only hide/show these object.

void OnTriggerEnter2D(Collider2D other) {
     if(other.gameObject.layer == "hiddenObject"){
         other.gameObject.enable = true;
     }
}

Then the reverse on the OnTriggerExit2D.

I'm not sure the effect that you are aiming for. So another solution could be a postprocessing shader.

I can only give a high level description on this however.

You would take the final screen image texture, and the current position of the polygon and then add the pixels from the screen texture to the polygon texture and output this texture. (this shader has to exists already).

But you want the inverse of these.

https://docs.unity3d.com/Manual/shader-TransparentCutoutFamily.html

You're wanting to keep what's in the hole and get rid of what's outside of it?

You can download the built in shaders to edit them here

https://unity3d.com/get-unity/download/archive

Just find your version of unity and select builtin shaders from the drop down.

Edit:  "SPOTLIGHT!", try this but with your custom shape

http://www.shaderslab.com/demo-49---spotlight.html


问:
Uploading files to a folder that is above the current folder
```<code>$result = mysql_query("SELECT * FROM media WHERE path = '$target'");
if($row = mysql_num_rows($result)==1)
{
echo"<br />Sorry, there is already a file with that name on the server.<br     />Please press back on your browser and save the file under a different name.";
}else{

if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
mysql_query("INSERT INTO media (id, related_page_id, type, title, copy, path, position, assets, time) VALUES ('', '$cat','$type','$name','','$target','$position','$id','$today')");

header("Location: edit.php?category=$cat");
exit();
echo $name;
}
else {
echo $today;
echo "<br />";
echo "Sorry, there was a problem uploading your file. Please press back on your browser and try again.";
}
}
</code>```

The above code used to work. Now it will not let me upload files to ../uploads/ but it works fine if i upload to uploads/.
Does anyone have any suggestions as to what i'm doing wrong? Thanks

EDIT

```<code>$target = "../uploads/";
</code>```

答: I know it sounds silly but are the permissions for the folder set up correctly?</p>

OwnerDisplayName: Drew

Body:
$result = mysql_query("SELECT * FROM media WHERE path = '$target'");
if($row = mysql_num_rows($result)==1)
{
echo"
Sorry, there is already a file with that name on the server.
Please press back on your browser and save the file under a different name.";
}else{

if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
{
echo "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded";
mysql_query("INSERT INTO media (id, related_page_id, type, title, copy, path, position, assets, time) VALUES ('', '$cat','$type','$name','','$target','$position','$id','$today')");

header("Location: edit.php?category=$cat");
exit();
echo $name;
}
else {
echo $today;
echo "
";
echo "Sorry, there was a problem uploading your file. Please press back on your browser and try again.";
}
}

The above code used to work. Now it will not let me upload files to ../uploads/ but it works fine if i upload to uploads/.
Does anyone have any suggestions as to what i'm doing wrong? Thanks

EDIT

$target = "../uploads/";

OwnerDisplayName: Spikolynn


问:
C++ dynamic array
I would like to make a dynamic array of a class with a constructor that has paramaters.

Where does the constructor's size parameter go?

ex. twoDArrayInDisguise = new dynamicArray(size)*[size];

Does not work

答: In C++, you cannot dynamically create an array of a class with a constructor that has paramaters!</p>

Title: C++ dynamic array


问:
Finding a set that contains all values of an original set in a SPARQL query
I'm trying to build a SPARQL query that gets the students of one teacher and finds all the teachers with all those students (they can have more students).

This is what I have so far:

```<code>SELECT ?otherTeacher
WHERE {
VALUES ?teacher {$teacher}
  ?teacher hasStudent ?student .
  ?otherTeacher hasStudent ?student .
  FILTER(?teacher <> ?otherTeacher)
}
</code>```

Here are the expected cases with the below data:

 - If teacher1 is given, only teacher3 should show up (teacher3 teaches all the students that teacher1 teaches).

 - If teacher2 is given, both teacher1 and teacher3 should show up (both teacher1 and teacher3 teach all the students teacher2 teaches).

 - If teacher3 is given, no teachers should show up (no other teacher teaches all the students teacher3 teaches).

```<code><teacher1> <hasStudent> "Alice" .
<teacher1> <hasStudent> "Bob" .
<teacher1> <hasStudent> "Charlie" .
<teacher2> <hasStudent> "Alice" .
<teacher2> <hasStudent> "Dan" .
<teacher3> <hasStudent> "Alice" .
<teacher3> <hasStudent> "Bob" .
<teacher3> <hasStudent> "Charlie" .
<teacher3> <hasStudent> "Dan" .
</code>```

How do I add a requirement that ?otherTeacher has all the students that ?teacher has (that the new set contains at least all the elements of the original set)?

答:
If one teacher is given, you could try this query:

SELECT DISTINCT ?otherTeacher
WHERE {
VALUES ?teacher {<teacher1> }
  ?otherTeacher <hasStudent> ?student .
  FILTER(?teacher != ?otherTeacher)
  FILTER NOT EXISTS {
    ?teacher <hasStudent> ?s .
    FILTER NOT EXISTS {?otherTeacher <hasStudent> ?s .}
  }
}
```

It uses "double-negation", i.e. it checks that there exists no student of the given teacher that is not taught by the other teacher.

Body:
I'm trying to build a SPARQL query that gets the students of one teacher and finds all the teachers with all those students (they can have more students).

This is what I have so far:

SELECT ?otherTeacher
WHERE {
VALUES ?teacher {$teacher}
  ?teacher hasStudent ?student .
  ?otherTeacher hasStudent ?student .
  FILTER(?teacher <> ?otherTeacher)
}

Here are the expected cases with the below data:

 - If teacher1 is given, only teacher3 should show up (teacher3 teaches all the students that teacher1 teaches).

 - If teacher2 is given, both teacher1 and teacher3 should show up (both teacher1 and teacher3 teach all the students teacher2 teaches).

 - If teacher3 is given, no teachers should show up (no other teacher teaches all the students teacher3 teaches).

<teacher1> <hasStudent> "Alice" .
<teacher1> <hasStudent> "Bob" .
<teacher1> <hasStudent> "Charlie" .
<teacher2> <hasStudent> "Alice" .
<teacher2> <hasStudent> "Dan" .
<teacher3> <hasStudent> "Alice" .
<teacher3> <hasStudent> "Bob" .
<teacher3> <hasStudent> "Charlie" .
<teacher3> <hasStudent> "Dan" .

How do I add a requirement that ?otherTeacher has all the students that ?teacher has (that the new set contains at least all the elements of the original set)?

Body:
If one teacher is given, you could try this query:

SELECT DISTINCT ?otherTeacher
WHERE {
VALUES ?teacher {<teacher1> }
  ?otherTeacher <hasStudent> ?student .
  FILTER(?teacher != ?otherTeacher)
  FILTER NOT EXISTS {
    ?teacher <hasStudent> ?s .
    FILTER NOT EXISTS {?otherTeacher <hasStudent> ?s .}
  }
}

It uses "double-negation", i.e. it checks that there exists no student of the given teacher that is not taught by the other teacher.


问:
Stop os.walk going down further at a specific directory name
I need to stop os.walk from going down further if the path contains both "release" and "arm-linux". I have a bunch of these at different levels of directories. So I can't simply dictate the level. So far I have the following and it unnecessarily dive past directories in 'arm-linux'.

```<code>def main(argv):
        for root, dirs, files in os.walk("."):
                path = root.split(os.sep)
                if "release" and "arm-linux" in path:
                        print(os.path.abspath(root))
                        getSharedLib(argv)
</code>```

[update] This is my solution

```<code>def main(argv):
        for root, dirs, files in os.walk("."):
                path = root.split(os.sep)
                if "release" in path and "arm-linux" in path:
                        print(os.path.abspath(root))
                        getSharedLib(argv)
                        del dirs[:]
</code>```

答:
From the documentation

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames;

Note that topdown is True by default.

Edit

To delete all the elements of dirs, you will need something like del dirs[:].  That will delete all the elements of the list object that is referred to as dirs in your code, but is referred to by another name in the os.walk code.

Just using del dirs will stop dirs in your code from referring to the list, but won't do anything to the os.walk reference.  Similarly dirs = [] will replace what dirs in your code refers to, but won't affect os.walk code.

Body:
I need to stop os.walk from going down further if the path contains both "release" and "arm-linux". I have a bunch of these at different levels of directories. So I can't simply dictate the level. So far I have the following and it unnecessarily dive past directories in 'arm-linux'.

def main(argv):
        for root, dirs, files in os.walk("."):
                path = root.split(os.sep)
                if "release" and "arm-linux" in path:
                        print(os.path.abspath(root))
                        getSharedLib(argv)

[update] This is my solution

def main(argv):
        for root, dirs, files in os.walk("."):
                path = root.split(os.sep)
                if "release" in path and "arm-linux" in path:
                        print(os.path.abspath(root))
                        getSharedLib(argv)
                        del dirs[:]


问:
Set Stripe checkout custom amount from GET parameter
I can't figure out, just want to pass to checkout page a value as GET parameter

so that https://xxxxxx/?setAmount=200000 did go to a page with this script

```<code><form action="custom action" method="POST">
  <script
  let params = new URLSearchParams(document.location.search.substring(1));
  let amount=params.get(setAmount);
    src="https://checkout.stripe.com/checkout.js" class="stripe-button"
    data-key="pk_test_UUbDY16wDCECOujIs0vQ2vTi"
    data-amount=amount;
    data-name="Company"
    data-description="Widget"
    data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
    data-locale="auto"
    data-zip-code="true"
    data-currency="eur">
  </script>
</form>
</code>```

The checkout button show out but didn't get the amount parameter, so that no amount is defined.
I didn't have access to server side on the server hosting the website with the button so I need to go forth and back to another site using Podio Globiflow.

答:
Stripe Checkout supports two modes -- Simple and Custom. Custom lets you control what pops up using javascript instead of data properties set on the server. To get the behavior you seek, you could do something like this:

```<code>$('#customButton').on('click', function(e) {
  const params = new URLSearchParams(document.location.search)
  const amountInCents = params.get("amount")
  const displayAmount = parseFloat(amountInCents / 100).toFixed(2);
  // Open Checkout with further options
  handler.open({
    name: 'Demo Site',
    description: 'Custom amount ($' + displayAmount + ')',
    amount: amountInCents,
  });
  e.preventDefault();
});

// Close Checkout on page navigation
$(window).on('popstate', function() {
  handler.close();
});
</code>```

It is worth noting, that this amount has no impact on how much you actually Charge your Customer and is only for display purposes. Checkout tokenizes the Card details; the amount Charged is entirely controlled by server side logic as outlined in the official Stripe docs.

Body:
I can't figure out, just want to pass to checkout page a value as GET parameter

so that https://xxxxxx/?setAmount=200000 did go to a page with this script

<form action="custom action" method="POST">

</form>

The checkout button show out but didn't get the amount parameter, so that no amount is defined.
I didn't have access to server side on the server hosting the website with the button so I need to go forth and back to another site using Podio Globiflow.

Body:
Stripe Checkout supports two modes -- Simple and Custom. Custom lets you control what pops up using javascript instead of data properties set on the server. To get the behavior you seek, you could do something like this:

$('#customButton').on('click', function(e) {
  const params = new URLSearchParams(document.location.search)
  const amountInCents = params.get("amount")
  const displayAmount = parseFloat(amountInCents / 100).toFixed(2);
  // Open Checkout with further options
  handler.open({
    name: 'Demo Site',
    description: 'Custom amount ($' + displayAmount + ')',
    amount: amountInCents,
  });
  e.preventDefault();
});

// Close Checkout on page navigation
$(window).on('popstate', function() {
  handler.close();
});

It is worth noting, that this amount has no impact on how much you actually Charge your Customer and is only for display purposes. Checkout tokenizes the Card details; the amount Charged is entirely controlled by server side logic as outlined in the official Stripe docs.


问:
jQuery to loop through elements with the same class
I have a load of divs with the class testimonial and I want to use jquery to loop through them to check for each div if a specific condition is true. If it is true, it should perform an action.

Does anyone know how I would do this?

答:
I may be missing part of the question, but I believe you can simply do this:

```<code>$('.testimonial').each((index, element) => {
    if (/* Condition */) {
        // Do Something
    }
});
</code>```

This uses jQuery's each method: https://learn.jquery.com/using-jquery-core/iterating/

Body:
I may be missing part of the question, but I believe you can simply do this:

$('.testimonial').each((index, element) => {
    if (/* Condition */) {
        // Do Something
    }
});

This uses jQuery's each method: https://learn.jquery.com/using-jquery-core/iterating/


答:
From the documentation : "An enumeration is a set of symbolic names (members) bound to unique, constant values."
You need to switch to another representation like a class.

Title: How to get random value of attribute of Enum on each iteration?


问:
to save docx as pdf in c# (.net) with policy label
i'm converting .docx files to .pdf with Microsoft.Office.Interop.Word library in C# (.Net Framework 4.6.2)

my code is:

```<code>    public static void DOCtoPDF(string docFullPath, string pdfFullPath)
    {
        Application appWord = new Application();
        var wordDocument = appWord.Documents.Open(docFullPath);

        wordDocument.SaveAs2(pdfFullPath, WdSaveFormat.wdFormatPDF);
        wordDocument.Close();
        appWord.Quit();
    }
</code>```

i'm taking this error while i am saving doc file:

how to solve this problem?

答:
I solved my problem..

it's trying to save wordDocument so it show me that dialog..

i wrote

```<code>wordDocument.Close(false);
</code>```

instead of

```<code>wordDocument.Close();
</code>```

now, it is not trying to save my original word document.
it only convert to pdf. :)

Body:
i'm converting .docx files to .pdf with Microsoft.Office.Interop.Word library in C# (.Net Framework 4.6.2)

my code is:

    public static void DOCtoPDF(string docFullPath, string pdfFullPath)
    {
        Application appWord = new Application();
        var wordDocument = appWord.Documents.Open(docFullPath);

        wordDocument.SaveAs2(pdfFullPath, WdSaveFormat.wdFormatPDF);
        wordDocument.Close();
        appWord.Quit();
    }

i'm taking this error while i am saving doc file:

how to solve this problem?

Body:
I solved my problem..

it's trying to save wordDocument so it show me that dialog..

i wrote

wordDocument.Close(false);

instead of

wordDocument.Close();

now, it is not trying to save my original word document.
it only convert to pdf. :)


问:
How to handle 404s in an observable request Angular
Problem i'm trying to fix:
I'm getting a lot of 404 not found in the console and I want to handle these.

I have these 2 methods in my angular code:

```<code>getUserByEmailAddress(email: string): Observable<User> {
    return this._http.get<User>("http://webapi.local/api/v2.0/users?email=" + email);
}

isEmailAddressAvailable(email: string) {
    var user: User;
    var response = this.getUserByEmailAddress(email);
    response.subscribe(
       usr => user == usr,
       error => user == undefined);
  if (user === undefined) {
  return true;
  }
  else {
  return false;
  }
}
</code>```

This works as expected, when you call the end point if no user is found a 404 not found it returned.

What I am trying to do

I want to add a .catch() to the .get() request in getUserByEmailAddress()to handle these 404s and mask them from appearing in the console, however when i try to add it, I don't understand what i need to return for the observable, I've tried:

```<code>.catch(err => { return Observable.of(undefined)})
</code>```

but i don't think this is quite right.

Thanks for the help!

答:
For handling the 404 error in my app what I do is in catch block

```<code>  if(err.status == 404)
         return  Observable.throw(new NotFoundError())
   else
          return Observable.throw(new AppError(err))
</code>```

but first you will have to make two classes called AppError which will be assigned to all the errors while notfoundError will be assigned to 404 error which will be an instance of AppError
IN apperror.ts

```<code>export class AppError {
    constructor(public err?:any){
        console.log(err);
       }
}
</code>```

and in notFound.ts

```<code>import { AppError } from "./apperror";

export class NotFoundError extends AppError {

}
</code>```

then in subscribe you can handle these error like this

```<code>response.subscribe(
       usr => user == usr,
      ((err:Error)=>{
        if(err instanceof NotFoundError){
          alert(err)
        }
      })
</code>```

Body:
Problem i'm trying to fix:
I'm getting a lot of 404 not found in the console and I want to handle these.

I have these 2 methods in my angular code:

getUserByEmailAddress(email: string): Observable<User> {
    return this._http.get<User>("http://webapi.local/api/v2.0/users?email=" + email);
}

isEmailAddressAvailable(email: string) {
    var user: User;
    var response = this.getUserByEmailAddress(email);
    response.subscribe(
       usr => user == usr,
       error => user == undefined);
  if (user === undefined) {
  return true;
  }
  else {
  return false;
  }
}

This works as expected, when you call the end point if no user is found a 404 not found it returned.

What I am trying to do

I want to add a .catch() to the .get() request in getUserByEmailAddress()to handle these 404s and mask them from appearing in the console, however when i try to add it, I don't understand what i need to return for the observable, I've tried:

.catch(err => { return Observable.of(undefined)})

but i don't think this is quite right.

Thanks for the help!

Body:
For handling the 404 error in my app what I do is in catch block

  if(err.status == 404)
         return  Observable.throw(new NotFoundError())
   else
          return Observable.throw(new AppError(err))

but first you will have to make two classes called AppError which will be assigned to all the errors while notfoundError will be assigned to 404 error which will be an instance of AppError
IN apperror.ts

export class AppError {
    constructor(public err?:any){
        console.log(err);
       }
}

and in notFound.ts

import { AppError } from "./apperror";

export class NotFoundError extends AppError {

}

then in subscribe you can handle these error like this

response.subscribe(
       usr => user == usr,
      ((err:Error)=>{
        if(err instanceof NotFoundError){
          alert(err)
        }
      })


问:
Why Does OAuth v2 Have Both Access and Refresh Tokens?
Section 4.2 of the draft OAuth 2.0 protocol indicates that an authorization server can return both an access_token (which is used to authenticate oneself with a resource) as well as a refresh_token, which is used purely to create a new access_token:

https://www.rfc-editor.org/rfc/rfc6749#section-4.2

Why have both? Why not just make the access_token last as long as the refresh_token and not have a refresh_token?

答:
While refresh token is retained by the Authorization server. Access token are self-contained so resource server can verify it without storing it which saves the effort of retrieval in case of validation.
Another point missing in discussion is from rfc6749#page-55

"For example, the authorization server could employ refresh token
  rotation in which a new refresh token is issued with every access
  token refresh response.The previous refresh token is invalidated but
  retained by the authorization server.  If a refresh token is
  compromised and subsequently used by both the attacker and the
  legitimate client, one of them will present an invalidated refresh
  token, which will inform the authorization server of the breach."

I think the whole point of using refresh token is that even if attacker somehow manages to get refresh token, client ID and secret combination. With subsequent calls to get new access token from attacker can be tracked in case if every request for refresh result in new access token and refresh token.


问:
Calculate all value from recycler adapter viewholder textlistener?
My Recycle code :

```<code>public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    @BindView(R.id.tvName) TextView tvName;
    @BindView(R.id.tvRank) TextView tvRank;

    public ViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
        itemView.setOnClickListener(this);

    tvName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //blabla
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //blabla
            }

            @Override
            public void afterTextChanged(Editable s) {
                //blabla
            }
        });
}
</code>```

The result from recycleview above will be like this :

```<code>-----------------
Jack           10
-----------------
Jason          14
-----------------
Rony           11
-----------------
</code>```

I want to calculate all value from "rank" when textview "rank" is on change, it is possible? I have done to try, but only can one value, how to calculate all value? so, the result what i want is

```<code>Jack, Rony, Jason = 35
</code>```

答:
What you want to do is iterate over every value inside of the RecyclerView's Adapter data set, you'd access the each rank value and add it to some int variable that stores the total. Once you've added all of the totals return the value. Example:

```<code>public class RankAdapter extends RecyclerView.Adapter {

    public static class RankData {
        public String name;
        public int rank;
    }
    // This gets set either in a constructor or a setter method.
    private ArrayList<RankData> rankDatas;

    public int getTotalRank() {
        int totalRank = 0;
        for(RankData data : rankDatas){
            totalRank += data.rank;
        }
        return totalRank;
    }

    @Override
    public RankViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        return new RankViewHolder(inflater.inflate(R.layout.checkable_item_layout_view, parent, false));
    }

    @Override
    public void onBindViewHolder(RankViewHolder holder, int position) {
        RankData data = rankDatas.get(position);
        holder.name.setText(data.name);
        holder.rank.setText(data.rank);
    }

    public class RankViewHolder extends RecyclerView.ViewHolder {
        public TextView name;
        public TextView rank;

         public RankViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(id.nameTxtVw);
            rank = itemView.findViewById(id.rankTxtVw);
        }
    }
}
</code>```

If you're are storing your rank as a value as a string you can convert it into int by doing the following:

```<code>int rankInt = Integer.valueOf(rankStr).intValue();
</code>```

And you'd then add rankInt to the 'totalRank' variable like above.

Body:
My Recycle code :

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    @BindView(R.id.tvName) TextView tvName;
    @BindView(R.id.tvRank) TextView tvRank;

    public ViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
        itemView.setOnClickListener(this);

    tvName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //blabla
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //blabla
            }

            @Override
            public void afterTextChanged(Editable s) {
                //blabla
            }
        });
}

The result from recycleview above will be like this :

-----------------
Jack           10
-----------------
Jason          14
-----------------
Rony           11
-----------------

I want to calculate all value from "rank" when textview "rank" is on change, it is possible? I have done to try, but only can one value, how to calculate all value? so, the result what i want is

Jack, Rony, Jason = 35

Body:
What you want to do is iterate over every value inside of the RecyclerView's Adapter data set, you'd access the each rank value and add it to some int variable that stores the total. Once you've added all of the totals return the value. Example:

public class RankAdapter extends RecyclerView.Adapter {

    public static class RankData {
        public String name;
        public int rank;
    }
    // This gets set either in a constructor or a setter method.
    private ArrayList<RankData> rankDatas;

    public int getTotalRank() {
        int totalRank = 0;
        for(RankData data : rankDatas){
            totalRank += data.rank;
        }
        return totalRank;
    }

    @Override
    public RankViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        return new RankViewHolder(inflater.inflate(R.layout.checkable_item_layout_view, parent, false));
    }

    @Override
    public void onBindViewHolder(RankViewHolder holder, int position) {
        RankData data = rankDatas.get(position);
        holder.name.setText(data.name);
        holder.rank.setText(data.rank);
    }

    public class RankViewHolder extends RecyclerView.ViewHolder {
        public TextView name;
        public TextView rank;

         public RankViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(id.nameTxtVw);
            rank = itemView.findViewById(id.rankTxtVw);
        }
    }
}

If you're are storing your rank as a value as a string you can convert it into int by doing the following:

int rankInt = Integer.valueOf(rankStr).intValue();

And you'd then add rankInt to the 'totalRank' variable like above.


问:
difference between document.cookie and res.cookie
When making cookies in the client computer,

All I know was res.cookie

for example (in nodejs-express),

```<code>app.get('/', (req, res) => {
    res.cookie('count', 1);
    res.send('something');
}
</code>```

but I found that I can also make cookies with using document.cookie.

So what is the major difference between those two when making cookies?

(likewise when reading cookies, req.cookies vs document.cookie)

Is document.cookie more bigger concept than res.cookies or req.cookies?
without need of any req, res parameter, so whenever want to make cookies then I can just using document.cookie?

I`ve already read the articles of w3school about what the document.cookies, req.cookies, res.cookies. but cannot figure out the differences existing between those.

thanks.

答:
In the context of Express.js, the Node server does not have access to the document object. So usually with the cookie-parser middleware, we are able to access the request cookies.

Based on the Express.js documentation,

res.cookie(name, value [, options]):

Sets cookie name to value. The value parameter may be a string or
  object converted to JSON.

req.cookies:

When using cookie-parser middleware, this property is an object that
  contains cookies sent by the request. If the request contains no
  cookies, it defaults to {}.

Body:
When making cookies in the client computer,

All I know was res.cookie

for example (in nodejs-express),

app.get('/', (req, res) => {
    res.cookie('count', 1);
    res.send('something');
}

but I found that I can also make cookies with using document.cookie.

So what is the major difference between those two when making cookies?

(likewise when reading cookies, req.cookies vs document.cookie)

Is document.cookie more bigger concept than res.cookies or req.cookies?
without need of any req, res parameter, so whenever want to make cookies then I can just using document.cookie?

I`ve already read the articles of w3school about what the document.cookies, req.cookies, res.cookies. but cannot figure out the differences existing between those.

thanks.


问:
Cordova: Error: The WIFI_SERVICE must be looked up on the Application context or memory will leak on devices < Android N
I'm getting the follwoing error when trying to build my app:

```<code>Error: The WIFI_SERVICE must be looked up on the Application context or memory will leak on devices < Android N. Try changing this.cordova.getActivity() to this.cordova.getActivity().getApplicationContext() [WifiManagerLeak]
    Intent settingsIntent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                 ^

Explanation for issues of type "WifiManagerLeak":
On versions prior to Android N (24), initializing the WifiManager via
Context#getSystemService can cause a memory leak if the context is not the
application context. Change context.getSystemService(...) to
context.getApplicationContext().getSystemService(...).

2 errors, 0 warnings
</code>```

I'm using node v6.11.2, cordova 6.5.0 and cordova-android 6.4.0 and gradle 4.1

答:
As explained in the Github issue, using the deprecated api-22 branch of the plugin will result in this error because it's no longer maintained. Switch to using releases from the master branch and it will build fine with cordova-android@6.4.0 and Gradle 4.

Both the master branch of cordova-diagnostic-plugin and cordova-android@6.4.0 are backwardly-compatible to API 16.

Body:
I'm getting the follwoing error when trying to build my app:

Error: The WIFI_SERVICE must be looked up on the Application context or memory will leak on devices < Android N. Try changing this.cordova.getActivity() to this.cordova.getActivity().getApplicationContext() [WifiManagerLeak]
    Intent settingsIntent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                 ^

Explanation for issues of type "WifiManagerLeak":
On versions prior to Android N (24), initializing the WifiManager via
Context#getSystemService can cause a memory leak if the context is not the
application context. Change context.getSystemService(...) to
context.getApplicationContext().getSystemService(...).

2 errors, 0 warnings

I'm using node v6.11.2, cordova 6.5.0 and cordova-android 6.4.0 and gradle 4.1


问:
How to train pytorch model with numpy data and batch size?
I am learning the basics of pytorch and thought to create a simple 4 layer nerual network with dropout to train IRIS dataset for classification. After refering to many tutorials I wrote this code.

```<code>import pandas as pd
from sklearn.datasets import load_iris
import torch
from torch.autograd import Variable

epochs=300
batch_size=20
lr=0.01

#loading data as numpy array
data = load_iris()
X=data.data
y=pd.get_dummies(data.target).values

#convert to tensor
X= Variable(torch.from_numpy(X), requires_grad=False)
y=Variable(torch.from_numpy(y), requires_grad=False)
print(X.size(),y.size())

#neural net model
model = torch.nn.Sequential(
    torch.nn.Linear(4, 10),
    torch.nn.ReLU(),
    torch.nn.Dropout(),
    torch.nn.Linear(10, 5),
    torch.nn.ReLU(),
    torch.nn.Dropout(),
    torch.nn.Linear(5, 3),
    torch.nn.Softmax()
)

print(model)

# Loss and Optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
loss_func = torch.nn.CrossEntropyLoss()

for i in range(epochs):
    # Forward pass
    y_pred = model(X)

    # Compute and print loss.
    loss = loss_func(y_pred, y)
    print(i, loss.data[0])

    # Before the backward pass, use the optimizer object to zero all of the
    # gradients for the variables it will update (which are the learnable weights
    # of the model)
    optimizer.zero_grad()

    # Backward pass
    loss.backward()

    # Calling the step function on an Optimizer makes an update to its parameters
    optimizer.step()
</code>```

There are currently two problems I am facing.

I want to set a batch size of 20. How should I do this?

At this step y_pred = model(X) its showing this error

Error

```<code> TypeError: addmm_ received an invalid combination of arguments - got (int, int, torch.DoubleTensor, torch.FloatTensor), but expected one of:
 * (torch.DoubleTensor mat1, torch.DoubleTensor mat2)
 * (torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2)
 * (float beta, torch.DoubleTensor mat1, torch.DoubleTensor mat2)
 * (float alpha, torch.DoubleTensor mat1, torch.DoubleTensor mat2)
 * (float beta, torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2)
 * (float alpha, torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2)
 * (float beta, float alpha, torch.DoubleTensor mat1, torch.DoubleTensor mat2)
      didn't match because some of the arguments have invalid types: (int, int, torch.DoubleTensor, !torch.FloatTensor!)
 * (float beta, float alpha, torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2)
      didn't match because some of the arguments have invalid types: (int, int, !torch.DoubleTensor!, !torch.FloatTensor!)
</code>```

答:
I want to set a batch size of 20. How should I do this?

For data processing and loading, PyTorch provide two classes, one is Dataset, which is used to represent your dataset. Specifically, Dataset provide the interface to get one sample from the whole dataset using the sample index.

But Dataset is not enough, for large dataset, we need to do batch processing. So PyTorch provide a second class Dataloader, which is used to generate batches from the Dataset given the batch size and other parameters.

For your specific case, I think you should try TensorDataset. Then use a Dataloader to set batch size to 20. Just look through the PyTorch official examples to get a sense how to do it.

At this step y_pred = model(X) its showing this error

The error message is pretty informative. Your input X to the model is type DoubleTensor. But your model parameters have type FloatTensor. In PyTorch, you can not do operation between Tensors of different types. What you should do is replace the line

```<code>X= Variable(torch.from_numpy(X), requires_grad=False)
</code>```

with

```<code>X= Variable(torch.from_numpy(X).float(), requires_grad=False)
</code>```

Now, X has type FloatTensor, the error message should disappear.

Also, as a gentle reminder, there are pretty much materials on the Internet about your question which can sufficiently solve your problem. You should try hard to solve it by yourself.

Body:
I am learning the basics of pytorch and thought to create a simple 4 layer nerual network with dropout to train IRIS dataset for classification. After refering to many tutorials I wrote this code.

import pandas as pd
from sklearn.datasets import load_iris
import torch
from torch.autograd import Variable

epochs=300
batch_size=20
lr=0.01

#loading data as numpy array
data = load_iris()
X=data.data
y=pd.get_dummies(data.target).values

#convert to tensor
X= Variable(torch.from_numpy(X), requires_grad=False)
y=Variable(torch.from_numpy(y), requires_grad=False)
print(X.size(),y.size())

#neural net model
model = torch.nn.Sequential(
    torch.nn.Linear(4, 10),
    torch.nn.ReLU(),
    torch.nn.Dropout(),
    torch.nn.Linear(10, 5),
    torch.nn.ReLU(),
    torch.nn.Dropout(),
    torch.nn.Linear(5, 3),
    torch.nn.Softmax()
)

print(model)

# Loss and Optimizer
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
loss_func = torch.nn.CrossEntropyLoss()

for i in range(epochs):
    # Forward pass
    y_pred = model(X)

    # Compute and print loss.
    loss = loss_func(y_pred, y)
    print(i, loss.data[0])

    # Before the backward pass, use the optimizer object to zero all of the
    # gradients for the variables it will update (which are the learnable weights
    # of the model)
    optimizer.zero_grad()

    # Backward pass
    loss.backward()

    # Calling the step function on an Optimizer makes an update to its parameters
    optimizer.step()

There are currently two problems I am facing.

I want to set a batch size of 20. How should I do this?

At this step y_pred = model(X) its showing this error

Error

 TypeError: addmm_ received an invalid combination of arguments - got (int, int, torch.DoubleTensor, torch.FloatTensor), but expected one of:
 * (torch.DoubleTensor mat1, torch.DoubleTensor mat2)
 * (torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2)
 * (float beta, torch.DoubleTensor mat1, torch.DoubleTensor mat2)
 * (float alpha, torch.DoubleTensor mat1, torch.DoubleTensor mat2)
 * (float beta, torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2)
 * (float alpha, torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2)
 * (float beta, float alpha, torch.DoubleTensor mat1, torch.DoubleTensor mat2)
      didn't match because some of the arguments have invalid types: (int, int, torch.DoubleTensor, !torch.FloatTensor!)
 * (float beta, float alpha, torch.SparseDoubleTensor mat1, torch.DoubleTensor mat2)
      didn't match because some of the arguments have invalid types: (int, int, !torch.DoubleTensor!, !torch.FloatTensor!)

Body:
I want to set a batch size of 20. How should I do this?

For data processing and loading, PyTorch provide two classes, one is Dataset, which is used to represent your dataset. Specifically, Dataset provide the interface to get one sample from the whole dataset using the sample index.

But Dataset is not enough, for large dataset, we need to do batch processing. So PyTorch provide a second class Dataloader, which is used to generate batches from the Dataset given the batch size and other parameters.

For your specific case, I think you should try TensorDataset. Then use a Dataloader to set batch size to 20. Just look through the PyTorch official examples to get a sense how to do it.

At this step y_pred = model(X) its showing this error

The error message is pretty informative. Your input X to the model is type DoubleTensor. But your model parameters have type FloatTensor. In PyTorch, you can not do operation between Tensors of different types. What you should do is replace the line

X= Variable(torch.from_numpy(X), requires_grad=False)

with

X= Variable(torch.from_numpy(X).float(), requires_grad=False)

Now, X has type FloatTensor, the error message should disappear.

Also, as a gentle reminder, there are pretty much materials on the Internet about your question which can sufficiently solve your problem. You should try hard to solve it by yourself.


问:
C# Rhino.Mocks - How do I write test code without repeating myself?
I wish to stub all dependencies out in my Rhino.Mocks unit tests, but I end up repeating myself. As the number of dependencies keeps increasing, I need to revisit my existing unit tests and need to add the dependencies. It's unsatisfying and also a signal that I should be doing it in another way.

If I just move initialization to a separate method, I pass into it all the mocks and I have achieved nothing.

Is there a way to initialize and then pass the Using(mocks.Record) into a method as a lambda expression? Or how do you do it?!

Thanks in advance for any comments,

Anders, Denmark

```<code>    [Test, Category("UnitTest")]
    public void TestThatApplicationCanExitByDefault()
    {
        var mocks = new MockRepository();

        var workspaceViewModelProvider = mocks.StrictMock<IWorkspaceViewModelProvider>();
        var workspaceRepository = mocks.StrictMock<IWorkspaceService>();
        var userResponseProvider = mocks.StrictMock<IUserResponseProvider>();
        var versionProvider = mocks.StrictMock<IVersionProvider>();
        var eventAggregator = mocks.StrictMock<IEventAggregator>();
        var allowedLegacyImportProvider = mocks.StrictMock<IAllowedLegacyImportProvider>();
        var stateManager = mocks.StrictMock<IStateManager>();
        var currentWorkspaceChangedEvent = mocks.StrictMock<CurrentWorkspaceChangedEvent>();

        using (mocks.Record())
        {
            // constructor fires:
            eventAggregator
                .Stub(x => x.GetEvent<CurrentWorkspaceChangedEvent>())
                .Return(currentWorkspaceChangedEvent);

            currentWorkspaceChangedEvent
                .Stub(x => x.Subscribe(null))
                .IgnoreArguments();
        }

        var target = new MainWindowViewModel(
            workspaceViewModelProvider,
            workspaceRepository,
            userResponseProvider,
            versionProvider, eventAggregator, allowedLegacyImportProvider, stateManager);

        var canAppExit = target.CanAppExit();

        Assert.IsTrue(canAppExit);

        mocks.VerifyAll();
    }

    [Test, Category("UnitTest")]
    public void TestThatInsertProjectWorks()
    {
        var mocks = new MockRepository();

        var workspaceViewModelProvider = mocks.StrictMock<IWorkspaceViewModelProvider>();
        var workspaceRepository = mocks.StrictMock<IWorkspaceService>();
        var userResponseProvider = mocks.StrictMock<IUserResponseProvider>();
        var versionProvider = mocks.StrictMock<IVersionProvider>();
        var eventAggregator = mocks.StrictMock<IEventAggregator>();
        var allowedLegacyImportProvider = mocks.StrictMock<IAllowedLegacyImportProvider>();
        var stateManager = mocks.StrictMock<IStateManager>();
        var currentWorkspaceChangedEvent = mocks.StrictMock<CurrentWorkspaceChangedEvent>();
        var workspaceViewModel = mocks.StrictMock<IWorkspaceViewModel>();

        using (mocks.Record())
        {
            // constructor fires:
            eventAggregator
                .Stub(x => x.GetEvent<CurrentWorkspaceChangedEvent>())
                .Return(currentWorkspaceChangedEvent);

            currentWorkspaceChangedEvent
                .Stub(x => x.Subscribe(null))
                .IgnoreArguments();

            workspaceViewModelProvider
                .Stub(x => x.GetViewModel())
                .Return(workspaceViewModel);

            workspaceViewModel
                .Stub(x => x.InsertProject());
        }

        var target = new MainWindowViewModel(
            workspaceViewModelProvider,
            workspaceRepository,
            userResponseProvider,
            versionProvider, eventAggregator, allowedLegacyImportProvider, stateManager);

        target.InsertProject();

        mocks.VerifyAll();
    }
</code>```

答:
I tend to have a helper method which is responsible for building my mocks, and this method takes a lambda. The lambda can then communicate the mocks to a test. I have overloads of the test helper method to form an API and thus restrict what mocks are available to the test. In this way mock building can be centralized and so minimize dependency tramping across your tests.

It's more obvious with an example. This uses Moq, but the technique is general.

```<code>    private static void RunTest(Action<IThing1> test)
    {
        RunTest(test: (thing1, thing2, thing3) => test(thing1));
    }

    private static void RunTest(Action<IThing1, IThing2> test)
    {
        RunTest(test: (thing1, thing2, thing3) => test(thing1, thing2));
    }

    private static void RunTest(Action<IThing1, IThing2, IThing3> test)
    {
        IThing1 thing1 = new Mock<IThing1>().Object;
        IThing2 thing2 = new Mock<IThing2>().Object;
        IThing3 thing3 = new Mock<IThing3>().Object;

        test(thing1, thing2, thing3);
    }

    [Test]
    public void do_some_stuff_to_a_thing()
    {
        RunTest(test: thing1 => {
            //Do some testing....
        });
    }

    [Test]
    public void do_some_stuff_to_things()
    {
        RunTest(test: (thing1, thing2) => {
            //Do some testing....
        });
    }
</code>```

Body:
I wish to stub all dependencies out in my Rhino.Mocks unit tests, but I end up repeating myself. As the number of dependencies keeps increasing, I need to revisit my existing unit tests and need to add the dependencies. It's unsatisfying and also a signal that I should be doing it in another way.

If I just move initialization to a separate method, I pass into it all the mocks and I have achieved nothing.

Is there a way to initialize and then pass the Using(mocks.Record) into a method as a lambda expression? Or how do you do it?!

Thanks in advance for any comments,

Anders, Denmark

    [Test, Category("UnitTest")]
    public void TestThatApplicationCanExitByDefault()
    {
        var mocks = new MockRepository();

        var workspaceViewModelProvider = mocks.StrictMock<IWorkspaceViewModelProvider>();
        var workspaceRepository = mocks.StrictMock<IWorkspaceService>();
        var userResponseProvider = mocks.StrictMock<IUserResponseProvider>();
        var versionProvider = mocks.StrictMock<IVersionProvider>();
        var eventAggregator = mocks.StrictMock<IEventAggregator>();
        var allowedLegacyImportProvider = mocks.StrictMock<IAllowedLegacyImportProvider>();
        var stateManager = mocks.StrictMock<IStateManager>();
        var currentWorkspaceChangedEvent = mocks.StrictMock<CurrentWorkspaceChangedEvent>();

        using (mocks.Record())
        {
            // constructor fires:
            eventAggregator
                .Stub(x => x.GetEvent<CurrentWorkspaceChangedEvent>())
                .Return(currentWorkspaceChangedEvent);

            currentWorkspaceChangedEvent
                .Stub(x => x.Subscribe(null))
                .IgnoreArguments();
        }

        var target = new MainWindowViewModel(
            workspaceViewModelProvider,
            workspaceRepository,
            userResponseProvider,
            versionProvider, eventAggregator, allowedLegacyImportProvider, stateManager);

        var canAppExit = target.CanAppExit();

        Assert.IsTrue(canAppExit);

        mocks.VerifyAll();
    }

    [Test, Category("UnitTest")]
    public void TestThatInsertProjectWorks()
    {
        var mocks = new MockRepository();

        var workspaceViewModelProvider = mocks.StrictMock<IWorkspaceViewModelProvider>();
        var workspaceRepository = mocks.StrictMock<IWorkspaceService>();
        var userResponseProvider = mocks.StrictMock<IUserResponseProvider>();
        var versionProvider = mocks.StrictMock<IVersionProvider>();
        var eventAggregator = mocks.StrictMock<IEventAggregator>();
        var allowedLegacyImportProvider = mocks.StrictMock<IAllowedLegacyImportProvider>();
        var stateManager = mocks.StrictMock<IStateManager>();
        var currentWorkspaceChangedEvent = mocks.StrictMock<CurrentWorkspaceChangedEvent>();
        var workspaceViewModel = mocks.StrictMock<IWorkspaceViewModel>();

        using (mocks.Record())
        {
            // constructor fires:
            eventAggregator
                .Stub(x => x.GetEvent<CurrentWorkspaceChangedEvent>())
                .Return(currentWorkspaceChangedEvent);

            currentWorkspaceChangedEvent
                .Stub(x => x.Subscribe(null))
                .IgnoreArguments();

            workspaceViewModelProvider
                .Stub(x => x.GetViewModel())
                .Return(workspaceViewModel);

            workspaceViewModel
                .Stub(x => x.InsertProject());
        }

        var target = new MainWindowViewModel(
            workspaceViewModelProvider,
            workspaceRepository,
            userResponseProvider,
            versionProvider, eventAggregator, allowedLegacyImportProvider, stateManager);

        target.InsertProject();

        mocks.VerifyAll();
    }

Body:
I tend to have a helper method which is responsible for building my mocks, and this method takes a lambda. The lambda can then communicate the mocks to a test. I have overloads of the test helper method to form an API and thus restrict what mocks are available to the test. In this way mock building can be centralized and so minimize dependency tramping across your tests.

It's more obvious with an example. This uses Moq, but the technique is general.

    private static void RunTest(Action<IThing1> test)
    {
        RunTest(test: (thing1, thing2, thing3) => test(thing1));
    }

    private static void RunTest(Action<IThing1, IThing2> test)
    {
        RunTest(test: (thing1, thing2, thing3) => test(thing1, thing2));
    }

    private static void RunTest(Action<IThing1, IThing2, IThing3> test)
    {
        IThing1 thing1 = new Mock<IThing1>().Object;
        IThing2 thing2 = new Mock<IThing2>().Object;
        IThing3 thing3 = new Mock<IThing3>().Object;

        test(thing1, thing2, thing3);
    }

    [Test]
    public void do_some_stuff_to_a_thing()
    {
        RunTest(test: thing1 => {
            //Do some testing....
        });
    }

    [Test]
    public void do_some_stuff_to_things()
    {
        RunTest(test: (thing1, thing2) => {
            //Do some testing....
        });
    }


问:
How to reference earlier activity in PlantUML UML Activity Diagram
I am trying to make an activity diagram with PlantUML (new beta syntax).

So far I came up with (simplified):

```<code>@startuml
start
:A;
if (Q1) then (yes)
  :B;

  if (Q2) then (yes)
    :D;
  else (no)
    :E;
  endif

else (no)
  :C;
endif
stop
@enduml
</code>```

It means, do A, if yes on first question do B otherwise C.
After B ask question 2, if yes do D if no do E.

Instead of pointing to E when the answer on question 2 is no I want to go to activity C, however I don't know how to reference it. If I put :C; there (instead of :E; it is just interpreted as a new activity (however it's flow should continue from C there). I assume there is a way to draw a flow like this with PlantUML but I don't see it yet.

What would be the best way to reference an already defined activity?

答:
This is what I found worked...

```<code>|Main|
start
  :SomeClass constructor called;
  :buildTreeListOpts called;
if (hasOptions()) then (yes)
else (no)
    :require DataLoader;
    :call getData;
|#Cyan|DataLoader|
 :getData;
if (hasDataInLocalStorage()) then (yes)
else (no)
|DataLoader|
    :XHR fetch options;
    :callback;
endif
|Main|
endif
  :finalize;
stop
</code>```

Keep practicing on their live demo until you find something that works.
http://plantuml.com/

Good luck.

Body:
I am trying to make an activity diagram with PlantUML (new beta syntax).

So far I came up with (simplified):

@startuml
start
:A;
if (Q1) then (yes)
  :B;

  if (Q2) then (yes)
    :D;
  else (no)
    :E;
  endif

else (no)
  :C;
endif
stop
@enduml

It means, do A, if yes on first question do B otherwise C.
After B ask question 2, if yes do D if no do E.

Instead of pointing to E when the answer on question 2 is no I want to go to activity C, however I don't know how to reference it. If I put :C; there (instead of :E; it is just interpreted as a new activity (however it's flow should continue from C there). I assume there is a way to draw a flow like this with PlantUML but I don't see it yet.

What would be the best way to reference an already defined activity?

Body:
This is what I found worked...

|Main|
start
  :SomeClass constructor called;
  :buildTreeListOpts called;
if (hasOptions()) then (yes)
else (no)
    :require DataLoader;
    :call getData;
|#Cyan|DataLoader|
 :getData;
if (hasDataInLocalStorage()) then (yes)
else (no)
|DataLoader|
    :XHR fetch options;
    :callback;
endif
|Main|
endif
  :finalize;
stop

Keep practicing on their live demo until you find something that works.
http://plantuml.com/

Good luck.