问:
Why doesn't my free dyno hours decrease? (Picture included)
My question is "why my free dyno hours are not decreasing".

As the image below shows, I am using heroku to take cryptocurrencies price data from Binance via API. My python codes to use Binance is uploaded on github and deployed to heroku. The price data imported is sent to telegram, whose chatbot sends me messages.

Does anyone know why my free dyno hours are not decreasing?

答: My free dyno hour turns out to decrease, but it just takes time to get reflected on the dashboard.</p>


来源: stackexchange

问:
Why Commons Lang Pair implements Map Entry?
I think I once knew, but I might have ever since forgottoen, or maybe never knew. Do you know why?

http://commons.apache.org/proper/commons-lang/javadocs/api-3.10/org/apache/commons/lang3/tuple/Pair.html

答:
First let's have a look in to the class Pair at the overridden methods, it's nothing but delegations on the "native" getLeft() and getRight()

```<code>@Override
public final L getKey() {
    return getLeft();
}

@Override
public R getValue() {
    return getRight();
}
</code>```

And now take a look at the static method of class ImmutablePair

```<code>/**
 * <p>Creates an immutable pair from an existing pair.</p>
 *
 * <p>This factory allows the pair to be created using inference to
 * obtain the generic types.</p>
 *
 * @param <L> the left element type
 * @param <R> the right element type
 * @param pair the existing pair.
 * @return a pair formed from the two parameters, not null
 * @since 3.10
 */
public static <L, R> ImmutablePair<L, R> of(final Map.Entry<L, R> pair) {
    final L left;
    final R right;
    if (pair != null) {
        left = pair.getKey();
        right = pair.getValue();
    } else {
        left = null;
        right = null;
    }
    return new ImmutablePair<>(left, right);
}
</code>```

So no matter if you pass a type of the interface Map.Entry you will get a ImmutablePair back. The library can handle not only MutablePair, ImmutablePair but also what ever which is subtype of Map.Entry. Maybe it could be your custom implementation of Map.Entry.

ContentLicense: CC BY-SA 4.0

Body:
First let's have a look in to the class Pair at the overridden methods, it's nothing but delegations on the "native" getLeft() and getRight()

@Override
public final L getKey() {
    return getLeft();
}

@Override
public R getValue() {
    return getRight();
}

And now take a look at the static method of class ImmutablePair

/**
 * <p>Creates an immutable pair from an existing pair.</p>
 *
 * <p>This factory allows the pair to be created using inference to
 * obtain the generic types.</p>
 *
 * @param <L> the left element type
 * @param <R> the right element type
 * @param pair the existing pair.
 * @return a pair formed from the two parameters, not null
 * @since 3.10
 */
public static <L, R> ImmutablePair<L, R> of(final Map.Entry<L, R> pair) {
    final L left;
    final R right;
    if (pair != null) {
        left = pair.getKey();
        right = pair.getValue();
    } else {
        left = null;
        right = null;
    }
    return new ImmutablePair<>(left, right);
}

So no matter if you pass a type of the interface Map.Entry you will get a ImmutablePair back. The library can handle not only MutablePair, ImmutablePair but also what ever which is subtype of Map.Entry. Maybe it could be your custom implementation of Map.Entry.


问:
Search an ordered array in a CUDA kernel
I'm writing a CUDA kernel and each thread has to complete the following task: suppose I have an ordered array a of n unsigned integers (the first one is always 0) stored in shared memory, each thread has to find the array index i such that a[i] ≤ threadIdx.x and a[i + 1] > threadIdx.x.

A naive solution could be:

```<code>for (i = 0; i < n - 1; i++)
    if (a[i + 1] > threadIdx.x) break;
</code>```

but I suppose this is not the optimal way to do it... can anyone suggest anything better?

答:
This is the best algorithm so far. It's called: LPW Indexed Search

```<code>__global__ void find_position_lpw(int *a, int n)
{
    int idx = threadIdx.x;

    __shared__ int aux[ MAX_THREADS_PER_BLOCK /*1024*/ ];

    aux[idx] = 0;

    if (idx < n)
        atomicAdd( &aux[a[idx]], 1); // atomics in case there are duplicates

    __syncthreads();

    int tmp;

    for (int j = 1; j <= MAX_THREADS_PER_BLOCK / 2; j <<= 1)
    {
        if( idx >= j ) tmp = aux[idx - j];
        __syncthreads();
        if( idx >= j ) aux[idx] += tmp;
        __syncthreads();
    }

    // result in "i"
    int i = aux[idx] - 1;

    // use "i" here...
    // ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a CUDA kernel and each thread has to complete the following task: suppose I have an ordered array a of n unsigned integers (the first one is always 0) stored in shared memory, each thread has to find the array index i such that a[i] ≤ threadIdx.x and a[i + 1] > threadIdx.x.

A naive solution could be:

for (i = 0; i < n - 1; i++)
    if (a[i + 1] > threadIdx.x) break;

but I suppose this is not the optimal way to do it... can anyone suggest anything better?

Body:
This is the best algorithm so far. It's called: LPW Indexed Search

__global__ void find_position_lpw(int *a, int n)
{
    int idx = threadIdx.x;

    __shared__ int aux[ MAX_THREADS_PER_BLOCK /*1024*/ ];

    aux[idx] = 0;

    if (idx < n)
        atomicAdd( &aux[a[idx]], 1); // atomics in case there are duplicates

    __syncthreads();

    int tmp;

    for (int j = 1; j <= MAX_THREADS_PER_BLOCK / 2; j <<= 1)
    {
        if( idx >= j ) tmp = aux[idx - j];
        __syncthreads();
        if( idx >= j ) aux[idx] += tmp;
        __syncthreads();
    }

    // result in "i"
    int i = aux[idx] - 1;

    // use "i" here...
    // ...
}


问:
R: Selenium server signals port = 4567 is already in use
It seems this is a recurrent question, but I haven't found the solution to my problem.

I am running the following:

```<code>link <- 'https://www.google.com/'

rD <- rsDriver(verbose = TRUE,
               port=4567L,
               browserName = 'chrome',
               chromever = '83.0.4103.39',
               check = TRUE)
remDr <- rD$client
remDr$navigate(link)
</code>```

When I run the first I get the error:

Error in wdman::selenium(port = port, verbose = verbose, version = version,  :
  Selenium server signals port = 4567 is already in use.

I have the chrome driver in the same folder as of my R project.

How do I make this work?
I have literally followed the documentation and nothing seems to work!!!

Any help would be much appreciated!

Br

答: I had this issue recently, I just assigned a random portal number i.e. port= 4837L and then reran the code and it worked fine for me. Hope it works!</p>

Body:
It seems this is a recurrent question, but I haven't found the solution to my problem.

I am running the following:

link <- 'https://www.google.com/'

rD <- rsDriver(verbose = TRUE,
               port=4567L,
               browserName = 'chrome',
               chromever = '83.0.4103.39',
               check = TRUE)
remDr <- rD$client
remDr$navigate(link)

When I run the first I get the error:

Error in wdman::selenium(port = port, verbose = verbose, version = version,  :
  Selenium server signals port = 4567 is already in use.

I have the chrome driver in the same folder as of my R project.

How do I make this work?
I have literally followed the documentation and nothing seems to work!!!

Any help would be much appreciated!

Br


问:
How Do I Correctly Deploy A Bean - JNDI, Weblogic 12C
I am trying to create a bean for a weblogic 12C server. The bean is just going to hold a couple values that at least one (possibly more) application(s) can reference (specifically - a bearer token, the duration of the token, and when it was retrieved)

I'm kind of new to this (hence my boggle)

I am running the latest version of Eclipse and have installed the Weblogic tools. I build my bean and deployed it to the local server. At this point, I am just trying to get my context and lookup my bean. When I run the client all I get this:

```<code>java.lang.ClassCastException: weblogic.jndi.internal.WLContextImpl cannot be cast to com.salientcrgt.chums.oAuthToken
    at TestRemoteLoading.TestClass.getBean(TestClass.java:46)
    at TestRemoteLoading.TestClass.main(TestClass.java:27)
</code>```

If I go the the Weblogic console and look up my deployment, I see this in the "Test" tab:

```<code>oAuthTokenBeanEAR oAuthTokenBeanEAR
Classloader Analysis Tool   Classloader Analysis Tool on server AdminServer
oAuthToken
oAuthToken      Test points for this EJB module.
oAuthToken  AdminServer No test point since this EJB's home does not have a JNDI name.
</code>```

BEAN PROJECT:

ejb-jar.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd" version="3.2">
  <display-name>oAuthTokenBean </display-name>
  <ejb-client-jar>oAuthTokenBeanClient.jar</ejb-client-jar>
</ejb-jar>
</code>```

weblogic-ejb-jar.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-ejb-jar xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-ejb-jar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd http://xmlns.oracle.com/weblogic/weblogic-ejb-jar http://xmlns.oracle.com/weblogic/weblogic-ejb-jar/1.7/weblogic-ejb-jar.xsd">
    <!--weblogic-version:12.2.1.3-->
    <wls:weblogic-enterprise-bean>
        <wls:ejb-name>oAuthToken</wls:ejb-name>
        <wls:stateless-session-descriptor></wls:stateless-session-descriptor>
        <wls:jndi-name>oAuthToken</wls:jndi-name>
        <wls:local-jndi-name>oAuthToken</wls:local-jndi-name>
        <wls:jndi-binding>
            <wls:class-name>com.salientcrgt.chums.oAuthToken</wls:class-name>
        </wls:jndi-binding>
    </wls:weblogic-enterprise-bean>
</wls:weblogic-ejb-jar>
</code>```

oAuthToken.java

```<code>/**
 * Session Bean implementation class oAuthToken
 */
@Stateless(name = "oAuthToken", mappedName = "oAuthToken")
@Remote ({com.salientcrgt.chums.oAuthTokenOBJ.class})
public class oAuthToken implements oAuthTokenOBJ, Serializable {

    public oAuthToken() {
    }

    private static final long serialVersionUID = 1L;

    private String service = "default";
    private String bearerToken;
    private int duration;
    private Date timeStamp;
...
</code>```

oAuthtokenOBJ.java

```<code>package com.salientcrgt.chums;

import java.util.Date;

public interface oAuthTokenOBJ {
    public String getService();
    public String getBearerToken();
    public int getDuration();
    public Date getTimeStamp();
    public boolean Expired();
}
</code>```

BEAN EAR PROJECT

application.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-application xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-application" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/javaee_6.xsd http://xmlns.oracle.com/weblogic/weblogic-application http://xmlns.oracle.com/weblogic/weblogic-application/1.8/weblogic-application.xsd">
    <!--weblogic-version:12.2.1.3-->
    <wls:application-param>
        <wls:param-name>webapp.encoding.default</wls:param-name>
        <wls:param-value>UTF-8</wls:param-value>
    </wls:application-param>
</wls:weblogic-application>
</code>```

Client Application:

Here are the methods where I am trying to get the bean

```<code>   @SuppressWarnings("unchecked")
    private static Context getInitialContext() throws NamingException {
        @SuppressWarnings("rawtypes")
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
        env.put(Context.PROVIDER_URL, "t3://127.0.0.1:7001");
        return new InitialContext(env);
    }

    public static void getBean() {
        try {
            final Context c = getInitialContext();
            /** print list of jndi names in context */
            NamingEnumeration<NameClassPair> list = c.list("");
            while (list.hasMore()) {
              System.out.println(list.next().getName());
            }
            // get the bean
            setTokenBean((oAuthToken) c.lookup("oAuthToken#com"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
</code>```

I think I am doing the correct thing in the client but have not assembled/deployed the bean correctly in some way.  I hope this is enough information to show what I have screwed up here.

This produced the following output:

```<code>mejbmejb_jarMejb_EO
oAuthToken#com
oAuthTokenBeanEARoAuthTokenBean_jaroAuthToken_Home
jmx
javax
oAuthTokenBeanEARoAuthTokenBean_jaroAuthToken_oAuthTokenOBJ
weblogic
__WL_GlobalJavaApp
_WL_internal_0N2TL1pYAVfZYdsOf5bIz5NXR1UAnTtG7gYEw8eSpFDasIK4NdrDolV9ZtejElAL
ejb
java:global
eis
java.lang.ClassCastException: weblogic.jndi.internal.WLContextImpl cannot be cast to com.salientcrgt.chums.oAuthToken
    at TestRemoteLoading.TestClass.getBean(TestClass.java:46)
    at TestRemoteLoading.TestClass.main(TestClass.java:27)
</code>```

答:
Got it sorted.

The above code is mostly correct. Here is what I ended up with:

```<code>    public static void getBean() {
        try {
            final Context c = getInitialContext();
            setTokenBean( (oAuthTokenOBJ)
                   c.lookup("oAuthToken#com.salientcrgt.chums.oAuthTokenOBJ"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
</code>```

oAuthTokenOBJ is the interface.

I went to the main in my test class and did this:

```<code>    public static void main(String Arg[]) throws IOException  {
        getBean();
        String myService = tokenBean.getService();
        System.out.println(myService);
    }
</code>```

It prints "default", which is the initial value in the bean for that field.
Hope this helps someone else.

(I can't be the only one who finds Oracle documentation to be a smidge obtuse.) lol

Body:
I am trying to create a bean for a weblogic 12C server. The bean is just going to hold a couple values that at least one (possibly more) application(s) can reference (specifically - a bearer token, the duration of the token, and when it was retrieved)

I'm kind of new to this (hence my boggle)

I am running the latest version of Eclipse and have installed the Weblogic tools. I build my bean and deployed it to the local server. At this point, I am just trying to get my context and lookup my bean. When I run the client all I get this:

java.lang.ClassCastException: weblogic.jndi.internal.WLContextImpl cannot be cast to com.salientcrgt.chums.oAuthToken
    at TestRemoteLoading.TestClass.getBean(TestClass.java:46)
    at TestRemoteLoading.TestClass.main(TestClass.java:27)

If I go the the Weblogic console and look up my deployment, I see this in the "Test" tab:

oAuthTokenBeanEAR oAuthTokenBeanEAR
Classloader Analysis Tool   Classloader Analysis Tool on server AdminServer
oAuthToken
oAuthToken      Test points for this EJB module.
oAuthToken  AdminServer No test point since this EJB's home does not have a JNDI name.

BEAN PROJECT:

ejb-jar.xml

<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/ejb-jar_3_2.xsd" version="3.2">
  <display-name>oAuthTokenBean </display-name>
  <ejb-client-jar>oAuthTokenBeanClient.jar</ejb-client-jar>
</ejb-jar>

weblogic-ejb-jar.xml

<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-ejb-jar xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-ejb-jar" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd http://xmlns.oracle.com/weblogic/weblogic-ejb-jar http://xmlns.oracle.com/weblogic/weblogic-ejb-jar/1.7/weblogic-ejb-jar.xsd">

    <wls:weblogic-enterprise-bean>
        <wls:ejb-name>oAuthToken</wls:ejb-name>
        <wls:stateless-session-descriptor></wls:stateless-session-descriptor>
        <wls:jndi-name>oAuthToken</wls:jndi-name>
        <wls:local-jndi-name>oAuthToken</wls:local-jndi-name>
        <wls:jndi-binding>
            <wls:class-name>com.salientcrgt.chums.oAuthToken</wls:class-name>
        </wls:jndi-binding>
    </wls:weblogic-enterprise-bean>
</wls:weblogic-ejb-jar>

oAuthToken.java

/**
 * Session Bean implementation class oAuthToken
 */
@Stateless(name = "oAuthToken", mappedName = "oAuthToken")
@Remote ({com.salientcrgt.chums.oAuthTokenOBJ.class})
public class oAuthToken implements oAuthTokenOBJ, Serializable {

    public oAuthToken() {
    }

    private static final long serialVersionUID = 1L;

    private String service = "default";
    private String bearerToken;
    private int duration;
    private Date timeStamp;
...

oAuthtokenOBJ.java

package com.salientcrgt.chums;

import java.util.Date;

public interface oAuthTokenOBJ {
    public String getService();
    public String getBearerToken();
    public int getDuration();
    public Date getTimeStamp();
    public boolean Expired();
}

BEAN EAR PROJECT

application.xml

<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-application xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-application" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/javaee_6.xsd http://xmlns.oracle.com/weblogic/weblogic-application http://xmlns.oracle.com/weblogic/weblogic-application/1.8/weblogic-application.xsd">

    <wls:application-param>
        <wls:param-name>webapp.encoding.default</wls:param-name>
        <wls:param-value>UTF-8</wls:param-value>
    </wls:application-param>
</wls:weblogic-application>

Client Application:

Here are the methods where I am trying to get the bean

   @SuppressWarnings("unchecked")
    private static Context getInitialContext() throws NamingException {
        @SuppressWarnings("rawtypes")
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
        env.put(Context.PROVIDER_URL, "t3://127.0.0.1:7001");
        return new InitialContext(env);
    }

    public static void getBean() {
        try {
            final Context c = getInitialContext();
            /** print list of jndi names in context */
            NamingEnumeration<NameClassPair> list = c.list("");
            while (list.hasMore()) {
              System.out.println(list.next().getName());
            }
            // get the bean
            setTokenBean((oAuthToken) c.lookup("oAuthToken#com"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

I think I am doing the correct thing in the client but have not assembled/deployed the bean correctly in some way.  I hope this is enough information to show what I have screwed up here.

This produced the following output:

mejbmejb_jarMejb_EO
oAuthToken#com
oAuthTokenBeanEARoAuthTokenBean_jaroAuthToken_Home
jmx
javax
oAuthTokenBeanEARoAuthTokenBean_jaroAuthToken_oAuthTokenOBJ
weblogic
__WL_GlobalJavaApp
_WL_internal_0N2TL1pYAVfZYdsOf5bIz5NXR1UAnTtG7gYEw8eSpFDasIK4NdrDolV9ZtejElAL
ejb
java:global
eis
java.lang.ClassCastException: weblogic.jndi.internal.WLContextImpl cannot be cast to com.salientcrgt.chums.oAuthToken
    at TestRemoteLoading.TestClass.getBean(TestClass.java:46)
    at TestRemoteLoading.TestClass.main(TestClass.java:27)

Body:
Got it sorted.

The above code is mostly correct. Here is what I ended up with:

    public static void getBean() {
        try {
            final Context c = getInitialContext();
            setTokenBean( (oAuthTokenOBJ)
                   c.lookup("oAuthToken#com.salientcrgt.chums.oAuthTokenOBJ"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

oAuthTokenOBJ is the interface.

I went to the main in my test class and did this:

    public static void main(String Arg[]) throws IOException  {
        getBean();
        String myService = tokenBean.getService();
        System.out.println(myService);
    }

It prints "default", which is the initial value in the bean for that field.
Hope this helps someone else.

(I can't be the only one who finds Oracle documentation to be a smidge obtuse.) lol


问:
Why doesn't this program end? The game goes on forever if i don't input the correct number
I am new to code and I was trying to create a guessing game as one of my first projects. I think i'm nearly done but this program doesn't end. Instead of ending when the there are 0 tries left it just continues the game even with the minus, Ps.(I made the number fixed for now, but will generate a random number when this issue is resolved)

I am new to code and I was trying to create a guessing game as one of my first projects. I think i'm nearly done but this program doesn't end. Instead of ending when the there are 0 tries left it just continues the game even with the minus, Ps.(I made the number fixed for now, but will generate a random number when this issue is resolved)

```<code>print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")

Magic_number = 7
guess = int(input("Enter your guess:"))
guess_limit = 5
guess_counter = 1
out_of_guesses = False
print("You have", str(guess_limit - guess_counter), "tries left")

while guess != Magic_number and not out_of_guesses:
    while guess < Magic_number:
        print("That number is too small, try again")
        guess = int(input("Enter guess: "))
        guess_counter += 1
        print("You have", str(guess_limit - guess_counter), "tries left")

    while guess > Magic_number:
        print("That number is too high try again")
        guess = int(input("Enter guess: "))
        guess_counter += 1
        print("You have", str(guess_limit - guess_counter), "tries left")

    if guess == Magic_number:
        print("Well done you got it!!")

if out_of_guesses:
    print("Game over, sorry")
</code>```

答:
Few mistakes:

The while loops inside the main loop should be if statements.

The out_of_guesses was completely unused in your code

Tip:

You may get out of a while (or for) loop using break

print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")

Magic_number = 7
guess_limit = 5
guess_counter = 1
guess = None

while guess != Magic_number:

    guesses_left = guess_limit - guess_counter + 1

    if guesses_left == 0:
        print("Game over, sorry")
        break

    print("You have", guesses_left, "tries left")
    guess = int(input("Enter guess: "))
    guess_counter += 1

    if guess < Magic_number:
        print("That number is too small, try again")

    elif guess > Magic_number:
        print("That number is too high try again")

    elif guess == Magic_number:
        print("Well done you got it!!")
        break

```

Body:
I am new to code and I was trying to create a guessing game as one of my first projects. I think i'm nearly done but this program doesn't end. Instead of ending when the there are 0 tries left it just continues the game even with the minus, Ps.(I made the number fixed for now, but will generate a random number when this issue is resolved)

I am new to code and I was trying to create a guessing game as one of my first projects. I think i'm nearly done but this program doesn't end. Instead of ending when the there are 0 tries left it just continues the game even with the minus, Ps.(I made the number fixed for now, but will generate a random number when this issue is resolved)

print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")

Magic_number = 7
guess = int(input("Enter your guess:"))
guess_limit = 5
guess_counter = 1
out_of_guesses = False
print("You have", str(guess_limit - guess_counter), "tries left")

while guess != Magic_number and not out_of_guesses:
    while guess < Magic_number:
        print("That number is too small, try again")
        guess = int(input("Enter guess: "))
        guess_counter += 1
        print("You have", str(guess_limit - guess_counter), "tries left")

    while guess > Magic_number:
        print("That number is too high try again")
        guess = int(input("Enter guess: "))
        guess_counter += 1
        print("You have", str(guess_limit - guess_counter), "tries left")

    if guess == Magic_number:
        print("Well done you got it!!")

if out_of_guesses:
    print("Game over, sorry")


问:
API header parameters returns "SyntaxError: Unexpected token"
I am working a small webapp to teach myself some gcloud and js. currently am trying to send a get request from a google cloud function using axios to a web api.  any guidance would be greatly appreciated.

the web api needs the following parameters in the header
Accept:application/json
APIKey: APIKEY

I've been trying to use the code in How to set header and options in axios?
and axios info, but I keep getting errors (SyntaxError: Unexpected token)

Index.JS currently looks like so

```<code>const axios = require("axios");

exports.run = async(req, res) => {

    axios.get('APIURL', {
     headers: {
       'Accept': 'application/json';
       'APIKey': 'KEY'
     }
    }).then((response) => {
        res.status(200).send(response.data);
        console.log(response);
      }, (error) => {
        res.status(500).send(response.data);
        console.log(error);
      });

     };
</code>```

package.json

```<code>{
  "name": "YOUR_NAME",
  "version": "0.0.1",
  "dependencies": {
    "axios": "^0.19.2"
  }
}
</code>```

答:
This is not a valid JSON object:

```<code>     headers: {
       'Accept': 'application/json';
       'APIKey': 'KEY'
     }
</code>```

The semicolon is out of place.  Use a comma instead:

```<code>     headers: {
       'Accept': 'application/json',
       'APIKey': 'KEY'
     }
</code>```

Body:
I am working a small webapp to teach myself some gcloud and js. currently am trying to send a get request from a google cloud function using axios to a web api.  any guidance would be greatly appreciated.

the web api needs the following parameters in the header
Accept:application/json
APIKey: APIKEY

I've been trying to use the code in How to set header and options in axios?
and axios info, but I keep getting errors (SyntaxError: Unexpected token)

Index.JS currently looks like so

const axios = require("axios");

exports.run = async(req, res) => {

    axios.get('APIURL', {
     headers: {
       'Accept': 'application/json';
       'APIKey': 'KEY'
     }
    }).then((response) => {
        res.status(200).send(response.data);
        console.log(response);
      }, (error) => {
        res.status(500).send(response.data);
        console.log(error);
      });

     };

package.json

{
  "name": "YOUR_NAME",
  "version": "0.0.1",
  "dependencies": {
    "axios": "^0.19.2"
  }
}

Body:
This is not a valid JSON object:

     headers: {
       'Accept': 'application/json';
       'APIKey': 'KEY'
     }

The semicolon is out of place.  Use a comma instead:

     headers: {
       'Accept': 'application/json',
       'APIKey': 'KEY'
     }


问:
PyBind11: Returning a const reference to std::vector of std::unique_ptr
I am attempting to return a const reference to a vector of unique ptrs from a C++ library to a python interface. I am trying code similar to the below, but I am getting compilation errors when trying to call py::bind_vector<std::vector<std::unique_ptr>>

```<code>#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>

class A
{
  public:
    A( int x ){ i = x; }
    A(const A&) = delete;
    A& operator=(const A&) = delete;
    int getI() { return i; }

  private:
    int i;
};

class Test
{
  public:
    Test(){
      for(int i = 0; i < 10; ++i) {
        avec_.emplace_back( std::make_unique<A>(i));
      }
    }
    Test( const Test& ) = delete;
    Test& operator=(const Test& ) = delete;

    const std::vector<std::unique_ptr<A>>& getVec() const { return avec_; }

  private:
    std::vector<std::unique_ptr<A>> avec_;
};

PYBIND11_MODULE(UniqContainer, m) {

  py::bind_vector<std::vector<std::unique_ptr<A>>>(m, "VecA", py::module_local() );

  py::class_<A>(m, "A")
    .def( py::init<int>() )
    .def( "getI", &A::getI );

  py::class_<Test>(m, "Test" )
    .def( py::init<>() )
    .def( "getVec", &Test::getVec, py::return_value_policy::reference_internal );
}
</code>```

My question is - is it possible to return a const reference to std::vector<std::unique_ptr> in python bindings?

EDIT:
Added:

copy ctor and assignment operator delete

py::return_value_policy::reference_internal

答:
So this is the best I can come up with. It might have life-span issues, if you save handles to the instances of A in python and then delete them in c++. You can't use reference_internal in the context that I'm using it because it doesn't know what lifespan is being referred to. You might be able to explicitly add py::keep_alive to the function def as well to keep things in scope. I don't know what you're lifetime requirements are and I'm still a little hazy on that part of the API.

```<code>  py::class_<Test>(m, "Test" )
    .def( py::init<>() )
    .def( "getVec",
          [](const Test& obj) {
            auto pylist = py::list();
            for (auto& ptr : obj.getVec()) {
              auto pyobj = py::cast(*ptr, py::return_value_policy::reference);
              pylist.append(pyobj);
            }
            return pylist;
          });
}
</code>```

Basically, have to manually create the py::list and then cast the smart pointers in it to py::object by reference to populate the list.

(note, I also removed the py::bind_vector to make everything compile)

Body:
I am attempting to return a const reference to a vector of unique ptrs from a C++ library to a python interface. I am trying code similar to the below, but I am getting compilation errors when trying to call py::bind_vector<std::vector<std::unique_ptr>>

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>

class A
{
  public:
    A( int x ){ i = x; }
    A(const A&) = delete;
    A& operator=(const A&) = delete;
    int getI() { return i; }

  private:
    int i;
};

class Test
{
  public:
    Test(){
      for(int i = 0; i < 10; ++i) {
        avec_.emplace_back( std::make_unique(i));
      }
    }
    Test( const Test& ) = delete;
    Test& operator=(const Test& ) = delete;

    const std::vector<std::unique_ptr>& getVec() const { return avec_; }

  private:
    std::vector<std::unique_ptr> avec_;
};

PYBIND11_MODULE(UniqContainer, m) {

  py::bind_vector<std::vector<std::unique_ptr>>(m, "VecA", py::module_local() );

  py::class_(m, "A")
    .def( py::init<int>() )
    .def( "getI", &A::getI );

  py::class_<Test>(m, "Test" )
    .def( py::init<>() )
    .def( "getVec", &Test::getVec, py::return_value_policy::reference_internal );
}

My question is - is it possible to return a const reference to std::vector<std::unique_ptr> in python bindings?

EDIT:
Added:

copy ctor and assignment operator delete

py::return_value_policy::reference_internal

Body:
So this is the best I can come up with. It might have life-span issues, if you save handles to the instances of A in python and then delete them in c++. You can't use reference_internal in the context that I'm using it because it doesn't know what lifespan is being referred to. You might be able to explicitly add py::keep_alive to the function def as well to keep things in scope. I don't know what you're lifetime requirements are and I'm still a little hazy on that part of the API.

  py::class_<Test>(m, "Test" )
    .def( py::init<>() )
    .def( "getVec",
          [](const Test& obj) {
            auto pylist = py::list();
            for (auto& ptr : obj.getVec()) {
              auto pyobj = py::cast(*ptr, py::return_value_policy::reference);
              pylist.append(pyobj);
            }
            return pylist;
          });
}

Basically, have to manually create the py::list and then cast the smart pointers in it to py::object by reference to populate the list.

(note, I also removed the py::bind_vector to make everything compile)


问:
Gatsby + React Booking Calendar: "WebpackError: ReferenceError: self is not defined "on 'gatsby build' but 'gatsby develop' works fine
I'm using Gatsby to build a website. I've added React Booking Calendar to display some calendar data.

Running 'gatsby develop' works fine but running 'gatsby build' yields the following error:

```<code>WebpackError: ReferenceError: self is not defined

  - index.js:13
    node_modules/react-booking-calendar/lib/index.js:13:10310

  - index.js:13
    node_modules/react-booking-calendar/lib/index.js:13:10234

  - index.js:13 e.exports
    node_modules/react-booking-calendar/lib/index.js:13:10505

  - index.js:13 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:13:11026

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:12 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:12:5444

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:1 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:1:519

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:401

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:437

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:65

  - index.js:1 Object../node_modules/react-booking-calendar/lib/index.js
    node_modules/react-booking-calendar/lib/index.js:1:211
</code>```

It prints the whole minified version of react-booking-calendar index.js before the error. Searching in that blob, I can see 'self' appears once:

```<code>f=h(function(){return/msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase())})
</code>```

I would appreciate any advice on this issue. Thanks.

Gatsby version: Gatsby CLI version: 2.12.8
Node version: v13.13.0
React booking calendar: ^1.0.3

答:
As @Hades points out, Gatsby's behavior may differ between develop and build due to the assets compilation and JavaScript bundling. You can check for further information in Gatsby's documentation about debugging.

To bypass your error and compile you have a few options:

Wait until window is defined in your component/function where you use f=h(function(){return/msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase())}). using something like this:

if (typeof window !== 'undefined') {
  f=h(function(){return/msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase())})
}

Change webpack's configuration to use a null loader for your third-party library, using in your gatsby-node.js:

exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
  if (stage === "build-html") {
    actions.setWebpackConfig({
      module: {
        rules: [
          {
            test: /react-booking-calendar/,
            use: loaders.null(),
          },
        ],
      },
    })
  }
}

Place your code inside a componentDidMount lifecycle or useEffect hook to ensure that the window is already defined when you execute the code.

Body:
I'm using Gatsby to build a website. I've added React Booking Calendar to display some calendar data.

Running 'gatsby develop' works fine but running 'gatsby build' yields the following error:

WebpackError: ReferenceError: self is not defined

  - index.js:13
    node_modules/react-booking-calendar/lib/index.js:13:10310

  - index.js:13
    node_modules/react-booking-calendar/lib/index.js:13:10234

  - index.js:13 e.exports
    node_modules/react-booking-calendar/lib/index.js:13:10505

  - index.js:13 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:13:11026

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:12 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:12:5444

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:1 Object.<anonymous>
    node_modules/react-booking-calendar/lib/index.js:1:519

  - index.js:1 t
    node_modules/react-booking-calendar/lib/index.js:1:328

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:401

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:437

  - index.js:1
    node_modules/react-booking-calendar/lib/index.js:1:65

  - index.js:1 Object../node_modules/react-booking-calendar/lib/index.js
    node_modules/react-booking-calendar/lib/index.js:1:211

It prints the whole minified version of react-booking-calendar index.js before the error. Searching in that blob, I can see 'self' appears once:

f=h(function(){return/msie [6-9]\b/.test(self.navigator.userAgent.toLowerCase())})

I would appreciate any advice on this issue. Thanks.

Gatsby version: Gatsby CLI version: 2.12.8
Node version: v13.13.0
React booking calendar: ^1.0.3


问:
Guide to use Sqlite on xcode?
Does anyone know a guide to use sqlite on the latest version on xcode (11.5)?

I'm learning how to build an IOS app and need to use a database in my project. However, most of the guides I found are old and doesn't work anymore.

答:
It hasn't really changed that much from version to version.

The Ray Wenderlich tutorial covers pretty much everything: https://www.raywenderlich.com/6620276-sqlite-with-swift-tutorial-getting-started

The only bit missing is adding the library if you don't use their sample project, but you can find that here (up to the initialising database section): https://www.appcoda.com/sqlite-database-ios-app-tutorial/

If it's your first app on iOS, I'd recommend using an SQLite library, or CoreData/other DB. The SQLite API you get just talking straight to the library is pretty ugly and doesn't bridge to Swift super nicely.

Title: Guide to use Sqlite on xcode?


问:
C# move cursor on screen based on where text appears on desktop
So I have searched and can't seem to find the right resources or tools for what I am wanting to do so I thought I'd ask for some help. Below is what I am wanting to do.

I am making a .Net core application that will simulate some key strokes and that is all working fine, but I want to also move the mouse based on where certain text appears on the screen, however, I will not have control over the application where the text appears, so I will need to somehow either be streaming the desktop view and using something to analyze it, or constantly taking a screen shot every 10 seconds or so and analyzing that screen shot if the text is there and then move the mouse to that position of text and simulate a left click.

I am not really confident in the screenshot approach as I am not sure how I'd get the mouse coordinates, so I have a feeling I will need to feed a desktop stream into something in order to get the image I am analyzing and then overlay my own transparent overlay on top of that in order to move the cursor to appropriate position.

I hope this makes sense and any libraries or whatever that is recommended to do this is appreciated. I know how to move the cursor on the screen and left click, just haven't found on google the right library for analyzing a desktop screen in real time and getting coordinates based on searching conditions.

Thank you everyone.

答:
Depending on the application there are a number of approaches you might want to try.

For example, using Application Insights and UI Automation, you might be able to capture the text directly.

If you have the exe file, then you might be able to decompile it with something like dotPeek and then use Visual Studio's Live debugging feature to access the text.

You might be able to inspect the heap of the running process via a tool like HeapMemView.

Optical Character Recognition might be an option worth considering. In that case Tesseract is an open source OCR engine worth considering. This can be used in conjunction with screenshots to extract text.


问:
Omit certain characters from Rows in SQL
I have a column that has Serial Numbers but some of them has unwanted characters attached with the Serial Number:-

```<code>8009914407
MCO
8558201722
US2
US3
MCO
7272950703
US2
MCO
NULL
8558201722
7272505721_R2C
8002094684
8558088363_AAC
NULL
US2
</code>```

These are some of the entries from a Column in a SQL Table.

I want to omit all the characters including and after the Underscore. For example, these values would become this:-

8558088363_AAC = 8558088363

7272505721_R2C = 7272505721

And keep rest of the rows as is.

答:
You an use substring_index():

```<code>select substring_index(serial_number, '_', 1)
</code>```

Here is a db<>fiddle.

In SQL Server, the code is:

```<code>select left(serial_number, charindex('_', serial_number + '_') - 1)
</code>```

Body:
I have a column that has Serial Numbers but some of them has unwanted characters attached with the Serial Number:-

8009914407
MCO
8558201722
US2
US3
MCO
7272950703
US2
MCO
NULL
8558201722
7272505721_R2C
8002094684
8558088363_AAC
NULL
US2

These are some of the entries from a Column in a SQL Table.

I want to omit all the characters including and after the Underscore. For example, these values would become this:-

8558088363_AAC = 8558088363

7272505721_R2C = 7272505721

And keep rest of the rows as is.

Body:
You an use substring_index():

select substring_index(serial_number, '_', 1)

Here is a db<>fiddle.

In SQL Server, the code is:

select left(serial_number, charindex('_', serial_number + '_') - 1)


问:
Finding the intersection point of a bundle of planes (3) in three.js
I'm Trying to implement 3-plane intersection using the formula at the bottom of this wolfram page here: http://mathworld.wolfram.com/Plane-PlaneIntersection.html

```<code>If the three planes are each specified by a point xk and a unit normal vector
nk, then the unique point of intersection  x is given by

x = (|n1 n2 n3|)^(-1) [(x1 · n1)(n2 x n3)+(x2 · n2)(n3 x n1)+(x3 · n3)(n3 x n2)],

where |n1 n2 n3| is the determinant of the matrix formed by writing the
vectors ni side-by-side. If two of the planes are parallel, then

|n1 n2 n3| = 0,
</code>```

But this is as far as I can get, my matrix math is awful and I'm not that good with three.js matrices

```<code>var x1, x2, x3; // all clones
var n1, n2, n3; // all clones, normalized

var f1 = (x1.dot(n1)).something(n2.cross(n3));
var f2 = (x2.dot(n2)).something(n3.cross(n1));
var f3 = (x3.dot(n3)).something(n1.cross(n2));

var full = f1.add(f2).add(f3);
</code>```

First off, what is '(x1 · n1)(n2 x n3)' supposed to mean? I know the first one is dot product and the section is cross product, what do I do to combine them

Second, how do I write the matrix portion in three.js

答:
Here's a ready to use function (assembled from the answer from robertl below):

arguments: Planes p1,p2,p3
return: Vector3

```<code>function vertIntersectPlanes(p1, p2, p3)
{
  let n1 = p1.normal, n2 = p2.normal, n3 = p3.normal;
  let x1 = p1.coplanarPoint(new THREE.Vector3());
  let x2 = p2.coplanarPoint(new THREE.Vector3());
  let x3 = p3.coplanarPoint(new THREE.Vector3());
  let f1 = new THREE.Vector3().crossVectors(n2, n3).multiplyScalar(x1.dot(n1));
  let f2 = new THREE.Vector3().crossVectors(n3, n1).multiplyScalar(x2.dot(n2));
  let f3 = new THREE.Vector3().crossVectors(n1, n2).multiplyScalar(x3.dot(n3));
  let det = new THREE.Matrix3().set(n1.x, n1.y, n1.z, n2.x, n2.y, n2.z, n3.x, n3.y, n3.z).determinant();
  let vectorSum = new THREE.Vector3().add(f1).add(f2).add(f3);
  let planeIntersection = new THREE.Vector3(vectorSum.x / det, vectorSum.y / det, vectorSum.z / det);
  return planeIntersection;
}
</code>```

Body:
I'm Trying to implement 3-plane intersection using the formula at the bottom of this wolfram page here: http://mathworld.wolfram.com/Plane-PlaneIntersection.html

If the three planes are each specified by a point xk and a unit normal vector
nk, then the unique point of intersection  x is given by

x = (|n1 n2 n3|)^(-1) [(x1 · n1)(n2 x n3)+(x2 · n2)(n3 x n1)+(x3 · n3)(n3 x n2)],

where |n1 n2 n3| is the determinant of the matrix formed by writing the
vectors ni side-by-side. If two of the planes are parallel, then

|n1 n2 n3| = 0,

But this is as far as I can get, my matrix math is awful and I'm not that good with three.js matrices

var x1, x2, x3; // all clones
var n1, n2, n3; // all clones, normalized

var f1 = (x1.dot(n1)).something(n2.cross(n3));
var f2 = (x2.dot(n2)).something(n3.cross(n1));
var f3 = (x3.dot(n3)).something(n1.cross(n2));

var full = f1.add(f2).add(f3);

First off, what is '(x1 · n1)(n2 x n3)' supposed to mean? I know the first one is dot product and the section is cross product, what do I do to combine them

Second, how do I write the matrix portion in three.js

Body:
Here's a ready to use function (assembled from the answer from robertl below):

arguments: Planes p1,p2,p3
return: Vector3

function vertIntersectPlanes(p1, p2, p3)
{
  let n1 = p1.normal, n2 = p2.normal, n3 = p3.normal;
  let x1 = p1.coplanarPoint(new THREE.Vector3());
  let x2 = p2.coplanarPoint(new THREE.Vector3());
  let x3 = p3.coplanarPoint(new THREE.Vector3());
  let f1 = new THREE.Vector3().crossVectors(n2, n3).multiplyScalar(x1.dot(n1));
  let f2 = new THREE.Vector3().crossVectors(n3, n1).multiplyScalar(x2.dot(n2));
  let f3 = new THREE.Vector3().crossVectors(n1, n2).multiplyScalar(x3.dot(n3));
  let det = new THREE.Matrix3().set(n1.x, n1.y, n1.z, n2.x, n2.y, n2.z, n3.x, n3.y, n3.z).determinant();
  let vectorSum = new THREE.Vector3().add(f1).add(f2).add(f3);
  let planeIntersection = new THREE.Vector3(vectorSum.x / det, vectorSum.y / det, vectorSum.z / det);
  return planeIntersection;
}


问:
Azure Spatial Anchor Region Avalability
I want to create a wayfinding app for a specific building using AR Core.
Because Google Cloud Anchor service has a 24-hour limit, I thought the Azure Spatial Anchor Service might do the job.
But my location is in East Europe. According to the docs, East Europe is not yet supported.

Has anyone tried these services from my location?

答:
I'd try using either West Europe or North Europe. They're the closest regions that we have Azure Spatial Anchors in to eastern Europe. (You can get a sense for the Azure network's RTT to various points on the global from the Azure network round trip latency statistics page. It's between Azure data centers, so it doesn't take into account things like the app user's cell provider/ISP.)

Also, take a look at the effective anchor experience guidelines for some recommendation about building your UX. For example, consider designing the locating experience assuming the user will spend a few seconds doing that and may need to create a new anchor if an existing one cannot be found. Also, look for opportunities to create a watcher while something else is happening in your app so that you can overlap multiple operations that the user needs to wait for.

For example, in one of our apps, we start loading 3D assets and create a watcher at the same time. When the assets are done loading, we switch to an AR view, and, often, the anchor has also been located by the time the assets have loaded. If not, the UX can handle that case too.

Title: Azure Spatial Anchor Region Avalability


问:
Deriving values based on result of the query and grouping the data
I am writing a sql where I am trying to pull out information of the status of the courses the user has enrolled. I am trying to return single record for each user. Two fields in the select list would derive the value in the following manner

CourseResultStatusId -
If the status of all the courses is passed then return the status as passed otherwise.
If any status is fail, the overall status is fail.
If any of the status is expired, then overall status is expired.
If any of the status is in-progress then overall status is in-progress

ExpiryDateTime - Training expiring (nearest date)
I need to apply the following logic on courses he has been assigned.
cr.ExpiryDateTime > GetDate() and cr.ExpiryDateTime <= dateadd(dd,30,getdate()) )

If you see below , the query I have written so far pulls the courses that each user has been enrolled but it is not a cumulative result. Do I need to group, if yes would need help.

```<code>DECLARE @Rep1 INT;
SET @Rep1 = 13119;

        SELECT
                     cr.[CourseID]
                    ,cr.[UserID]
                    ,u.[Code]
                    ,u.[DisplayName]
                    ,t.[Name]
                    ,cr.[CourseResultStatusID]  AS [CourseResultStatusID]
                    ,crs.[Description]          AS [CourseResultStatusDescription]
                    ,c.[PointsRequired]
                    ,cr.[ExpiryDateTime]

        FROM        [training].[CourseResult] cr
        INNER JOIN  [training].[Course] c
            ON      cr.[CourseID] = c.[ID] and c.[IsOptional] = 0 -- and cr.ExpiryDateTime > GetDate() and cr.ExpiryDateTime <= dateadd(dd,30,getdate())
        INNER JOIN  [training].[CourseResultStatus] crs
            ON      cr.[CourseResultStatusID] = crs.[ID]
        INNER JOIN org.RepresentativeTierHistory rth on rth.RepresentativeID = cr.[UserID] and GetDate() between rth.StartDate and rth.EndDate
        INNER JOIN  org.tier t on t.ID = rth.TierID
        LEFT JOIN   [org].[User] u
            ON      u.[ID] = cr.[UserID]

      WHERE cr.[UserID] IN (
        SELECT hd.DescendantId FROM org.HierarchyDescendant hd WHERE hd.RepresentativeId = @Rep1 UNION ALL SELECT @Rep1 -- for management exchange info
      )
      order by UserID
</code>```

The result of the query is as follows. I have circled to show you records that belong to a particular user and the columns that I am interested in  . I need help in getting single record for each user based on the of logic that I mentioned above.

答:
If I followed you correctly, you can implement the priorization rules on the overall result of each user using conditional aggregation.

Starting from your existing query, the logic would be:

```<code>select
    cr.[UserID],
    case
        when min(case when crs.[Description] = 'Complete' then 1 else 0 end) = 1
            then 'Complete'
        when max(case when crs.[Description] = 'Fail' then 1 else 0 end) = 1
            then 'Fail'
        when max(case when crs.[Description] = 'Expired' then 1 else 0 end) = 1
            then 'Expired'
        when max(case when crs.[Description] = 'In Progress' then 1 else 0 end) = 1
            then 'In Progress'
    end as ResultStatus
from ...
where ...
group by cr.[UserID]
</code>```

As for the date filtering logic, you should be able to implement it directly in the where clause.

It is possible that other parts of your query can be optimized - you might want to ask a new question for this, providing proper sample data and desired results.

Body:
I am writing a sql where I am trying to pull out information of the status of the courses the user has enrolled. I am trying to return single record for each user. Two fields in the select list would derive the value in the following manner

CourseResultStatusId -
If the status of all the courses is passed then return the status as passed otherwise.
If any status is fail, the overall status is fail.
If any of the status is expired, then overall status is expired.
If any of the status is in-progress then overall status is in-progress

ExpiryDateTime - Training expiring (nearest date)
I need to apply the following logic on courses he has been assigned.
cr.ExpiryDateTime > GetDate() and cr.ExpiryDateTime <= dateadd(dd,30,getdate()) )

If you see below , the query I have written so far pulls the courses that each user has been enrolled but it is not a cumulative result. Do I need to group, if yes would need help.

DECLARE @Rep1 INT;
SET @Rep1 = 13119;

        SELECT
                     cr.[CourseID]
                    ,cr.[UserID]
                    ,u.[Code]
                    ,u.[DisplayName]
                    ,t.[Name]
                    ,cr.[CourseResultStatusID]  AS [CourseResultStatusID]
                    ,crs.[Description]          AS [CourseResultStatusDescription]
                    ,c.[PointsRequired]
                    ,cr.[ExpiryDateTime]

        FROM        [training].[CourseResult] cr
        INNER JOIN  [training].[Course] c
            ON      cr.[CourseID] = c.[ID] and c.[IsOptional] = 0 -- and cr.ExpiryDateTime > GetDate() and cr.ExpiryDateTime <= dateadd(dd,30,getdate())
        INNER JOIN  [training].[CourseResultStatus] crs
            ON      cr.[CourseResultStatusID] = crs.[ID]
        INNER JOIN org.RepresentativeTierHistory rth on rth.RepresentativeID = cr.[UserID] and GetDate() between rth.StartDate and rth.EndDate
        INNER JOIN  org.tier t on t.ID = rth.TierID
        LEFT JOIN   [org].[User] u
            ON      u.[ID] = cr.[UserID]

      WHERE cr.[UserID] IN (
        SELECT hd.DescendantId FROM org.HierarchyDescendant hd WHERE hd.RepresentativeId = @Rep1 UNION ALL SELECT @Rep1 -- for management exchange info
      )
      order by UserID

The result of the query is as follows. I have circled to show you records that belong to a particular user and the columns that I am interested in  . I need help in getting single record for each user based on the of logic that I mentioned above.

Body:
If I followed you correctly, you can implement the priorization rules on the overall result of each user using conditional aggregation.

Starting from your existing query, the logic would be:

select
    cr.[UserID],
    case
        when min(case when crs.[Description] = 'Complete' then 1 else 0 end) = 1
            then 'Complete'
        when max(case when crs.[Description] = 'Fail' then 1 else 0 end) = 1
            then 'Fail'
        when max(case when crs.[Description] = 'Expired' then 1 else 0 end) = 1
            then 'Expired'
        when max(case when crs.[Description] = 'In Progress' then 1 else 0 end) = 1
            then 'In Progress'
    end as ResultStatus
from ...
where ...
group by cr.[UserID]

As for the date filtering logic, you should be able to implement it directly in the where clause.

It is possible that other parts of your query can be optimized - you might want to ask a new question for this, providing proper sample data and desired results.


问:
Python numpy.random.choice in C# with non/uniform probability distribution
I am trying to put into place some code that will do the same as Python, Numpy.random.Choice

The critical part is: probability

The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a.

Some Test Code:

```<code>import numpy as np

n = 5

vocab_size = 3

p = np.array( [[ 0.65278451], [ 0.0868038725], [ 0.2604116175]])

print('Sum: ', repr(sum(p)))

for t in range(n):
    x = np.random.choice(range(vocab_size), p=p.ravel())
    print('x: %s x[x]: %s' % (x, p.ravel()[x]))

print(p.ravel())
</code>```

This gives an output of:

```<code>Sum:  array([ 1.])
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
[ 0.65278451  0.08680387  0.26041162]
</code>```

Sometimes.

There is a Distribution here, and it is a partially Random one, but there is also Structure there.

I want to implement this in C#, and to be honest, I am not sure on an efficient way to do it.

Some 4 Years ago there was a good question asked: Emulate Python's random.choice in .NET

Being this is quite old now and also does not really go into depth on the uniform probability distribution, I thought I would ask for some elaboration?

Now times have changed and Code is changing, I think there may be a better way to implement a .NET Random.Choice() Method.

```<code>public static int Choice(Vector sequence, int a = 0, int size = 0, bool replace = false)
{
    // F(x)
    var Fx = 1/(b - a)
    var p = (xmax - xmin) * Fx

    return random.Next(0, sequence.Length);
}
</code>```

Vector is only a double[].

How would I go about randomly Choosing a Probability from a Vector like so:

```<code> p = np.array(
 [[ 0.01313731], [ 0.01315883], [ 0.01312814], [ 0.01316345], [ 0.01316839],
 [ 0.01314225], [ 0.01317578], [ 0.01312916], [ 0.01316344], [ 0.01317046],
 [ 0.01314973], [ 0.01314432], [ 0.01317042], [ 0.01314846], [ 0.01315124],
 [ 0.01316694], [ 0.0131816 ], [ 0.01315033], [ 0.0131645 ], [ 0.01314199],
 [ 0.01315199], [ 0.01314431], [ 0.01314458], [ 0.01314999], [ 0.01315409],
 [ 0.01316245], [ 0.01315008], [ 0.01314104], [ 0.01315215], [ 0.01317024],
 [ 0.01315993], [ 0.01318789], [ 0.0131677 ], [ 0.01316761], [ 0.01315658],
 [ 0.01315902], [ 0.01314266], [ 0.0131637 ], [ 0.01315702], [ 0.01315776],
 [ 0.01316194], [ 0.01316246], [ 0.01314769], [ 0.01315608], [ 0.01315487],
 [ 0.01316117], [ 0.01315083], [ 0.01315836], [ 0.0131665 ], [ 0.01314706],
 [ 0.01314923], [ 0.01317971], [ 0.01316373], [ 0.01314863], [ 0.01315498],
 [ 0.01315732], [ 0.01318195], [ 0.01315505], [ 0.01315979], [ 0.01315992],
 [ 0.01316072], [ 0.01314744], [ 0.0131638 ], [ 0.01315642], [ 0.01314933],
 [ 0.01316188], [ 0.01315458], [ 0.01315551], [ 0.01317907], [ 0.01316296],
 [ 0.01317765], [ 0.01316863], [ 0.01316804], [ 0.01314882], [ 0.01316548],
 [ 0.01315487]])
</code>```

The Output in Python is:

```<code>Sum:  array([ 1.])
x: 21 x[x]: 0.01314431
x: 30 x[x]: 0.01315993
x: 54 x[x]: 0.01315498
x: 31 x[x]: 0.01318789
x: 27 x[x]: 0.01314104
</code>```

Sometimes.

EDIT:
After Coffee and sleep, some more insight. The Documentation explains:

Generate a non-uniform random sample from np.arange(5) of size 3 without replacement:

np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
    array([2, 3, 0])

The parameter p introduces a Non-Uniform Distribution to the sequence or Choice.

The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a.

So I guess, if:

```<code>static int[] a = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75};

static double[] p = new double[] { 0.01313731,  0.01315883,  0.01312814,  0.01316345,  0.01316839,  0.01314225,
0.01317578,  0.01312916,  0.01316344,  0.01317046,  0.01314973,  0.01314432,
0.01317042,  0.01314846,  0.01315124,  0.01316694,  0.0131816,   0.01315033,
0.0131645,   0.01314199,  0.01315199,  0.01314431,  0.01314458,  0.01314999,
0.01315409,  0.01316245,  0.01315008,  0.01314104,  0.01315215,  0.01317024,
0.01315993,  0.01318789,  0.0131677,   0.01316761,  0.01315658,  0.01315902,
0.01314266,  0.0131637,   0.01315702,  0.01315776,  0.01316194,  0.01316246,
0.01314769,  0.01315608,  0.01315487,  0.01316117,  0.01315083,  0.01315836,
0.0131665,   0.01314706,  0.01314923,  0.01317971,  0.01316373,  0.01314863,
0.01315498,  0.01315732,  0.01318195,  0.01315505,  0.01315979,  0.01315992,
0.01316072,  0.01314744,  0.0131638,   0.01315642,  0.01314933,  0.01316188,
0.01315458,  0.01315551,  0.01317907,  0.01316296,  0.01317765,  0.01316863,
0.01316804,  0.01314882,  0.01316548,  0.01315487 };
</code>```

How would I efficiently calculate this distribution?

EDIT:

While the above p Parameter may not have a clear distribution:

This p Parameter does:

```<code>p = np.array(
[[  3.09571694e-03], [  6.62372261e-04], [  2.52917874e-04], [  6.93371978e-04],
[  2.22301291e-04], [  3.53796717e-02], [  2.36204398e-04], [  2.41100042e-04],
[  1.59093166e-02], [  5.17099025e-04], [  2.72037896e-04], [  1.29918769e-03],
[  2.68077696e-02], [  5.68696611e-04], [  5.32142704e-04], [  5.88432463e-05],
[  2.53700138e-02], [  2.51216588e-03], [  4.72895541e-04], [  4.20276848e-03],
[  5.65701874e-05], [  1.84972048e-03], [  8.46515331e-03], [  8.02505743e-02],
[  5.34274983e-04], [  5.18868535e-04], [  2.22580377e-04], [  2.50133462e-02],
[  3.70997917e-02], [  5.84941482e-05], [  6.49978323e-04], [  4.18675536e-01],
[  6.16371962e-02], [  3.82260752e-04], [  6.09901544e-04], [  2.54540201e-03],
[  2.46758824e-04], [  4.13621365e-04], [  5.23495532e-04], [  6.40675685e-03],
[  1.14165332e-03], [  1.89148994e-04], [  8.41715724e-04], [  8.65699032e-04],
[  6.71368283e-04], [  2.14908596e-03], [  5.80679210e-02], [  1.11176616e-02],
[  6.58134137e-05], [  2.38992622e-02], [  2.91388753e-04], [  1.93989753e-03],
[  1.82157325e-03], [  3.33691627e-03], [  5.69157244e-03], [  1.11033592e-04],
[  2.42448034e-04], [  8.42765356e-05], [  1.31656056e-02], [  1.68779684e-02],
[  2.72298244e-02], [  8.19056613e-04], [  1.14640462e-02], [  6.21846308e-05],
[  9.24618073e-04], [  3.63659515e-02], [  7.17286486e-05], [  6.24008652e-04],
[  2.59900890e-03], [  1.57848651e-04], [  5.71378707e-05], [  7.62828929e-04],
[  2.91648042e-04], [  1.67612579e-04], [  1.65455262e-04], [  1.01981563e-02]])
</code>```

Some what of a Gaussian Distribution with a Skew to the Left. This Video by PoyserMath is excellent: Stats: Finding Probability Using a Normal Distribution Table  explaining why p must Sum to 1.0

EDIT: 12.04.17 - Finally I found the python file that is associated with this!!!

```<code># Author: Hamzeh Alsalhi <ha258@cornell.edu>
#
# License: BSD 3 clause
from __future__ import division
import numpy as np
import scipy.sparse as sp
import operator
import array

from sklearn.utils import check_random_state
from sklearn.utils.fixes import astype
from ._random import sample_without_replacement

__all__ = ['sample_without_replacement', 'choice']

# This is a backport of np.random.choice from numpy 1.7
# The function can be removed when we bump the requirements to >=1.7
def choice(a, size=None, replace=True, p=None, random_state=None):
    """
    choice(a, size=None, replace=True, p=None)

    Generates a random sample from a given 1-D array

    .. versionadded:: 1.7.0

    Parameters
    -----------
    a : 1-D array-like or int
        If an ndarray, a random sample is generated from its elements.
        If an int, the random sample is generated as if a was np.arange(n)

    size : int or tuple of ints, optional
        Output shape. Default is None, in which case a single value is
        returned.

    replace : boolean, optional
        Whether the sample is with or without replacement.

    p : 1-D array-like, optional
        The probabilities associated with each entry in a.
        If not given the sample assumes a uniform distribution over all
        entries in a.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    Returns
    --------
    samples : 1-D ndarray, shape (size,)
    The generated random samples

    Raises
    -------
    ValueError
    If a is an int and less than zero, if a or p are not 1-dimensional,
    if a is an array-like of size 0, if p is not a vector of
    probabilities, if a and p have different lengths, or if
    replace=False and the sample size is greater than the population
    size

    See Also
    ---------
    randint, shuffle, permutation

    Examples
    ---------
    Generate a uniform random sample from np.arange(5) of size 3:

    >>> np.random.choice(5, 3)  # doctest: +SKIP
    array([0, 3, 4])
    >>> #This is equivalent to np.random.randint(0,5,3)

    Generate a non-uniform random sample from np.arange(5) of size 3:

    >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])  # doctest: +SKIP
    array([3, 3, 0])

    Generate a uniform random sample from np.arange(5) of size 3 without
    replacement:

    >>> np.random.choice(5, 3, replace=False)  # doctest: +SKIP
    array([3,1,0])
    >>> #This is equivalent to np.random.shuffle(np.arange(5))[:3]

    Generate a non-uniform random sample from np.arange(5) of size
    3 without replacement:

    >>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
    ... # doctest: +SKIP
    array([2, 3, 0])

    Any of the above can be repeated with an arbitrary array-like
    instead of just integers. For instance:

    >>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
    >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
    ... # doctest: +SKIP
    array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],
    dtype='|S11')

    """
    random_state = check_random_state(random_state)

    # Format and Verify input
    a = np.array(a, copy=False)
    if a.ndim == 0:
        try:
            # __index__ must return an integer by python rules.
            pop_size = operator.index(a.item())
        except TypeError:
            raise ValueError("a must be 1-dimensional or an integer")
        if pop_size <= 0:
            raise ValueError("a must be greater than 0")
    elif a.ndim != 1:
        raise ValueError("a must be 1-dimensional")
    else:
        pop_size = a.shape[0]
        if pop_size is 0:
            raise ValueError("a must be non-empty")

    if p is not None:
        p = np.array(p, dtype=np.double, ndmin=1, copy=False)
        if p.ndim != 1:
            raise ValueError("p must be 1-dimensional")
        if p.size != pop_size:
            raise ValueError("a and p must have same size")
        if np.any(p < 0):
            raise ValueError("probabilities are not non-negative")
        if not np.allclose(p.sum(), 1):
            raise ValueError("probabilities do not sum to 1")

    shape = size
    if shape is not None:
        size = np.prod(shape, dtype=np.intp)
    else:
        size = 1

    # Actual sampling
    if replace:
        if p is not None:
            cdf = p.cumsum()
            cdf /= cdf[-1]
            uniform_samples = random_state.random_sample(shape)
            idx = cdf.searchsorted(uniform_samples, side='right')
            # searchsorted returns a scalar
            idx = np.array(idx, copy=False)
        else:
            idx = random_state.randint(0, pop_size, size=shape)
    else:
        if size > pop_size:
            raise ValueError("Cannot take a larger sample than "
                             "population when 'replace=False'")

        if p is not None:
            if np.sum(p > 0) < size:
                raise ValueError("Fewer non-zero entries in p than size")
            n_uniq = 0
            p = p.copy()
            found = np.zeros(shape, dtype=np.int)
            flat_found = found.ravel()
            while n_uniq < size:
                x = random_state.rand(size - n_uniq)
                if n_uniq > 0:
                    p[flat_found[0:n_uniq]] = 0
                cdf = np.cumsum(p)
                cdf /= cdf[-1]
                new = cdf.searchsorted(x, side='right')
                _, unique_indices = np.unique(new, return_index=True)
                unique_indices.sort()
                new = new.take(unique_indices)
                flat_found[n_uniq:n_uniq + new.size] = new
                n_uniq += new.size
            idx = found
        else:
            idx = random_state.permutation(pop_size)[:size]
            if shape is not None:
                idx.shape = shape

    if shape is None and isinstance(idx, np.ndarray):
        # In most cases a scalar will have been made an array
        idx = idx.item(0)

    # Use samples as indices for a if a is array-like
    if a.ndim == 0:
        return idx

    if shape is not None and idx.ndim == 0:
        # If size == () then the user requested a 0-d array as opposed to
        # a scalar object when size is None. However a[idx] is always a
        # scalar and not an array. So this makes sure the result is an
        # array, taking into account that np.array(item) may not work
        # for object arrays.
        res = np.empty((), dtype=a.dtype)
        res[()] = a[idx]
        return res

    return a[idx]

def random_choice_csc(n_samples, classes, class_probability=None,
                      random_state=None):
    """Generate a sparse random matrix given column class distributions

    Parameters
    ----------
    n_samples : int,
        Number of samples to draw in each column.

    classes : list of size n_outputs of arrays of size (n_classes,)
        List of classes for each column.

    class_probability : list of size n_outputs of arrays of size (n_classes,)
        Optional (default=None). Class distribution of each column. If None the
        uniform distribution is assumed.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    Returns
    -------
    random_matrix : sparse csc matrix of size (n_samples, n_outputs)

    """
    data = array.array('i')
    indices = array.array('i')
    indptr = array.array('i', [0])

    for j in range(len(classes)):
        classes[j] = np.asarray(classes[j])
        if classes[j].dtype.kind != 'i':
            raise ValueError("class dtype %s is not supported" %
                             classes[j].dtype)
        classes[j] = astype(classes[j], np.int64, copy=False)

        # use uniform distribution if no class_probability is given
        if class_probability is None:
            class_prob_j = np.empty(shape=classes[j].shape[0])
            class_prob_j.fill(1 / classes[j].shape[0])
        else:
            class_prob_j = np.asarray(class_probability[j])

        if np.sum(class_prob_j) != 1.0:
            raise ValueError("Probability array at index {0} does not sum to "
                             "one".format(j))

        if class_prob_j.shape[0] != classes[j].shape[0]:
            raise ValueError("classes[{0}] (length {1}) and "
                             "class_probability[{0}] (length {2}) have "
                             "different length.".format(j,
                                                        classes[j].shape[0],
                                                        class_prob_j.shape[0]))

        # If 0 is not present in the classes insert it with a probability 0.0
        if 0 not in classes[j]:
            classes[j] = np.insert(classes[j], 0, 0)
            class_prob_j = np.insert(class_prob_j, 0, 0.0)

        # If there are nonzero classes choose randomly using class_probability
        rng = check_random_state(random_state)
        if classes[j].shape[0] > 1:
            p_nonzero = 1 - class_prob_j[classes[j] == 0]
            nnz = int(n_samples * p_nonzero)
            ind_sample = sample_without_replacement(n_population=n_samples,
                                                    n_samples=nnz,
                                                    random_state=random_state)
            indices.extend(ind_sample)

            # Normalize probabilites for the nonzero elements
            classes_j_nonzero = classes[j] != 0
            class_probability_nz = class_prob_j[classes_j_nonzero]
            class_probability_nz_norm = (class_probability_nz /
                                         np.sum(class_probability_nz))
            classes_ind = np.searchsorted(class_probability_nz_norm.cumsum(),
                                          rng.rand(nnz))
            data.extend(classes[j][classes_j_nonzero][classes_ind])
        indptr.append(len(indices))

    return sp.csc_matrix((data, indices, indptr),
                         (n_samples, len(classes)),
                         dtype=int)
</code>```

答:
You could try NumSharp, a port of numpy to C#

```<code>double[] distribution = new double[] { 0.1, 0.2, 0.3, 0.4 };

//Simple choice
for (int i = 0; i < 80; i++)
{
    int choice = NumSharp.np.random.choice(distribution.Count(), probabilities:distribution)[0].GetInt32();
    Console.Write(choice.ToString());
}
Console.WriteLine();
</code>```

12222312301223333323323223022211111233123323333133211233333233013312213033030033

NumSharp includes aditionnal parameters (replace,...) but has still, to this date, performance issues:

```<code>EvalTime("NumSharp Single thread",() =>
{
    for (int i = 0; i < 100000; i++)
        NumSharp.np.random.choice(distribution.Count(), probabilities: distribution)[0].GetInt32();
});

EvalTime("NumSharp Multithread", () =>
{
    Parallel.For(0, 100000, i =>
        NumSharp.np.random.choice(distribution.Count(), probabilities: distribution)[0].GetInt32());
});

EvalTime("Evk Single thread", () =>
{
    for (int i = 0; i < 100000; i++)
        Choice(upTo: distribution.Count(), distribution: distribution);
});

EvalTime("Evk Multithread", () =>
{
    Parallel.For(0, 100000, i =>
        Choice(upTo: distribution.Count(), distribution: distribution));
});

public static void EvalTime(string Name,Action a)
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    a();
    sw.Stop();
    Console.WriteLine("{0} : {1}ms", Name,sw.ElapsedMilliseconds);
}
</code>```

Here's the output comparing NumSharp and Evk's implementation above on my PC (24 logical cores)

```<code>NumSharp Single thread : 10701ms
NumSharp Multithread : 19350ms
Evk Single thread : 117ms
Evk Multithread : 61ms
</code>```

Body:
I am trying to put into place some code that will do the same as Python, Numpy.random.Choice

The critical part is: probability

The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a.

Some Test Code:

import numpy as np

n = 5

vocab_size = 3

p = np.array( [[ 0.65278451], [ 0.0868038725], [ 0.2604116175]])

print('Sum: ', repr(sum(p)))

for t in range(n):
    x = np.random.choice(range(vocab_size), p=p.ravel())
    print('x: %s x[x]: %s' % (x, p.ravel()[x]))

print(p.ravel())

This gives an output of:

Sum:  array([ 1.])
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
x: 0 x[x]: 0.65278451
[ 0.65278451  0.08680387  0.26041162]

Sometimes.

There is a Distribution here, and it is a partially Random one, but there is also Structure there.

I want to implement this in C#, and to be honest, I am not sure on an efficient way to do it.

Some 4 Years ago there was a good question asked: Emulate Python's random.choice in .NET

Being this is quite old now and also does not really go into depth on the uniform probability distribution, I thought I would ask for some elaboration?

Now times have changed and Code is changing, I think there may be a better way to implement a .NET Random.Choice() Method.

public static int Choice(Vector sequence, int a = 0, int size = 0, bool replace = false)
{
    // F(x)
    var Fx = 1/(b - a)
    var p = (xmax - xmin) * Fx

    return random.Next(0, sequence.Length);
}

Vector is only a double[].

How would I go about randomly Choosing a Probability from a Vector like so:

 p = np.array(
 [[ 0.01313731], [ 0.01315883], [ 0.01312814], [ 0.01316345], [ 0.01316839],
 [ 0.01314225], [ 0.01317578], [ 0.01312916], [ 0.01316344], [ 0.01317046],
 [ 0.01314973], [ 0.01314432], [ 0.01317042], [ 0.01314846], [ 0.01315124],
 [ 0.01316694], [ 0.0131816 ], [ 0.01315033], [ 0.0131645 ], [ 0.01314199],
 [ 0.01315199], [ 0.01314431], [ 0.01314458], [ 0.01314999], [ 0.01315409],
 [ 0.01316245], [ 0.01315008], [ 0.01314104], [ 0.01315215], [ 0.01317024],
 [ 0.01315993], [ 0.01318789], [ 0.0131677 ], [ 0.01316761], [ 0.01315658],
 [ 0.01315902], [ 0.01314266], [ 0.0131637 ], [ 0.01315702], [ 0.01315776],
 [ 0.01316194], [ 0.01316246], [ 0.01314769], [ 0.01315608], [ 0.01315487],
 [ 0.01316117], [ 0.01315083], [ 0.01315836], [ 0.0131665 ], [ 0.01314706],
 [ 0.01314923], [ 0.01317971], [ 0.01316373], [ 0.01314863], [ 0.01315498],
 [ 0.01315732], [ 0.01318195], [ 0.01315505], [ 0.01315979], [ 0.01315992],
 [ 0.01316072], [ 0.01314744], [ 0.0131638 ], [ 0.01315642], [ 0.01314933],
 [ 0.01316188], [ 0.01315458], [ 0.01315551], [ 0.01317907], [ 0.01316296],
 [ 0.01317765], [ 0.01316863], [ 0.01316804], [ 0.01314882], [ 0.01316548],
 [ 0.01315487]])

The Output in Python is:

Sum:  array([ 1.])
x: 21 x[x]: 0.01314431
x: 30 x[x]: 0.01315993
x: 54 x[x]: 0.01315498
x: 31 x[x]: 0.01318789
x: 27 x[x]: 0.01314104

Sometimes.

EDIT:
After Coffee and sleep, some more insight. The Documentation explains:

Generate a non-uniform random sample from np.arange(5) of size 3 without replacement:

np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
    array([2, 3, 0])

The parameter p introduces a Non-Uniform Distribution to the sequence or Choice.

The probabilities associated with each entry in a. If not given the sample assumes a uniform distribution over all entries in a.

So I guess, if:

static int[] a = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75};

static double[] p = new double[] { 0.01313731,  0.01315883,  0.01312814,  0.01316345,  0.01316839,  0.01314225,
0.01317578,  0.01312916,  0.01316344,  0.01317046,  0.01314973,  0.01314432,
0.01317042,  0.01314846,  0.01315124,  0.01316694,  0.0131816,   0.01315033,
0.0131645,   0.01314199,  0.01315199,  0.01314431,  0.01314458,  0.01314999,
0.01315409,  0.01316245,  0.01315008,  0.01314104,  0.01315215,  0.01317024,
0.01315993,  0.01318789,  0.0131677,   0.01316761,  0.01315658,  0.01315902,
0.01314266,  0.0131637,   0.01315702,  0.01315776,  0.01316194,  0.01316246,
0.01314769,  0.01315608,  0.01315487,  0.01316117,  0.01315083,  0.01315836,
0.0131665,   0.01314706,  0.01314923,  0.01317971,  0.01316373,  0.01314863,
0.01315498,  0.01315732,  0.01318195,  0.01315505,  0.01315979,  0.01315992,
0.01316072,  0.01314744,  0.0131638,   0.01315642,  0.01314933,  0.01316188,
0.01315458,  0.01315551,  0.01317907,  0.01316296,  0.01317765,  0.01316863,
0.01316804,  0.01314882,  0.01316548,  0.01315487 };

How would I efficiently calculate this distribution?

EDIT:

While the above p Parameter may not have a clear distribution:

This p Parameter does:

p = np.array(
[[  3.09571694e-03], [  6.62372261e-04], [  2.52917874e-04], [  6.93371978e-04],
[  2.22301291e-04], [  3.53796717e-02], [  2.36204398e-04], [  2.41100042e-04],
[  1.59093166e-02], [  5.17099025e-04], [  2.72037896e-04], [  1.29918769e-03],
[  2.68077696e-02], [  5.68696611e-04], [  5.32142704e-04], [  5.88432463e-05],
[  2.53700138e-02], [  2.51216588e-03], [  4.72895541e-04], [  4.20276848e-03],
[  5.65701874e-05], [  1.84972048e-03], [  8.46515331e-03], [  8.02505743e-02],
[  5.34274983e-04], [  5.18868535e-04], [  2.22580377e-04], [  2.50133462e-02],
[  3.70997917e-02], [  5.84941482e-05], [  6.49978323e-04], [  4.18675536e-01],
[  6.16371962e-02], [  3.82260752e-04], [  6.09901544e-04], [  2.54540201e-03],
[  2.46758824e-04], [  4.13621365e-04], [  5.23495532e-04], [  6.40675685e-03],
[  1.14165332e-03], [  1.89148994e-04], [  8.41715724e-04], [  8.65699032e-04],
[  6.71368283e-04], [  2.14908596e-03], [  5.80679210e-02], [  1.11176616e-02],
[  6.58134137e-05], [  2.38992622e-02], [  2.91388753e-04], [  1.93989753e-03],
[  1.82157325e-03], [  3.33691627e-03], [  5.69157244e-03], [  1.11033592e-04],
[  2.42448034e-04], [  8.42765356e-05], [  1.31656056e-02], [  1.68779684e-02],
[  2.72298244e-02], [  8.19056613e-04], [  1.14640462e-02], [  6.21846308e-05],
[  9.24618073e-04], [  3.63659515e-02], [  7.17286486e-05], [  6.24008652e-04],
[  2.59900890e-03], [  1.57848651e-04], [  5.71378707e-05], [  7.62828929e-04],
[  2.91648042e-04], [  1.67612579e-04], [  1.65455262e-04], [  1.01981563e-02]])

Some what of a Gaussian Distribution with a Skew to the Left. This Video by PoyserMath is excellent: Stats: Finding Probability Using a Normal Distribution Table  explaining why p must Sum to 1.0

EDIT: 12.04.17 - Finally I found the python file that is associated with this!!!

# Author: Hamzeh Alsalhi <ha258@cornell.edu>
#
# License: BSD 3 clause
from __future__ import division
import numpy as np
import scipy.sparse as sp
import operator
import array

from sklearn.utils import check_random_state
from sklearn.utils.fixes import astype
from ._random import sample_without_replacement

__all__ = ['sample_without_replacement', 'choice']

# This is a backport of np.random.choice from numpy 1.7
# The function can be removed when we bump the requirements to >=1.7
def choice(a, size=None, replace=True, p=None, random_state=None):
    """
    choice(a, size=None, replace=True, p=None)

    Generates a random sample from a given 1-D array

    .. versionadded:: 1.7.0

    Parameters
    -----------
    a : 1-D array-like or int
        If an ndarray, a random sample is generated from its elements.
        If an int, the random sample is generated as if a was np.arange(n)

    size : int or tuple of ints, optional
        Output shape. Default is None, in which case a single value is
        returned.

    replace : boolean, optional
        Whether the sample is with or without replacement.

    p : 1-D array-like, optional
        The probabilities associated with each entry in a.
        If not given the sample assumes a uniform distribution over all
        entries in a.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    Returns
    --------
    samples : 1-D ndarray, shape (size,)
    The generated random samples

    Raises
    -------
    ValueError
    If a is an int and less than zero, if a or p are not 1-dimensional,
    if a is an array-like of size 0, if p is not a vector of
    probabilities, if a and p have different lengths, or if
    replace=False and the sample size is greater than the population
    size

    See Also
    ---------
    randint, shuffle, permutation

    Examples
    ---------
    Generate a uniform random sample from np.arange(5) of size 3:

    >>> np.random.choice(5, 3)  # doctest: +SKIP
    array([0, 3, 4])
    >>> #This is equivalent to np.random.randint(0,5,3)

    Generate a non-uniform random sample from np.arange(5) of size 3:

    >>> np.random.choice(5, 3, p=[0.1, 0, 0.3, 0.6, 0])  # doctest: +SKIP
    array([3, 3, 0])

    Generate a uniform random sample from np.arange(5) of size 3 without
    replacement:

    >>> np.random.choice(5, 3, replace=False)  # doctest: +SKIP
    array([3,1,0])
    >>> #This is equivalent to np.random.shuffle(np.arange(5))[:3]

    Generate a non-uniform random sample from np.arange(5) of size
    3 without replacement:

    >>> np.random.choice(5, 3, replace=False, p=[0.1, 0, 0.3, 0.6, 0])
    ... # doctest: +SKIP
    array([2, 3, 0])

    Any of the above can be repeated with an arbitrary array-like
    instead of just integers. For instance:

    >>> aa_milne_arr = ['pooh', 'rabbit', 'piglet', 'Christopher']
    >>> np.random.choice(aa_milne_arr, 5, p=[0.5, 0.1, 0.1, 0.3])
    ... # doctest: +SKIP
    array(['pooh', 'pooh', 'pooh', 'Christopher', 'piglet'],
    dtype='|S11')

    """
    random_state = check_random_state(random_state)

    # Format and Verify input
    a = np.array(a, copy=False)
    if a.ndim == 0:
        try:
            # __index__ must return an integer by python rules.
            pop_size = operator.index(a.item())
        except TypeError:
            raise ValueError("a must be 1-dimensional or an integer")
        if pop_size <= 0:
            raise ValueError("a must be greater than 0")
    elif a.ndim != 1:
        raise ValueError("a must be 1-dimensional")
    else:
        pop_size = a.shape[0]
        if pop_size is 0:
            raise ValueError("a must be non-empty")

    if p is not None:
        p = np.array(p, dtype=np.double, ndmin=1, copy=False)
        if p.ndim != 1:
            raise ValueError("p must be 1-dimensional")
        if p.size != pop_size:
            raise ValueError("a and p must have same size")
        if np.any(p < 0):
            raise ValueError("probabilities are not non-negative")
        if not np.allclose(p.sum(), 1):
            raise ValueError("probabilities do not sum to 1")

    shape = size
    if shape is not None:
        size = np.prod(shape, dtype=np.intp)
    else:
        size = 1

    # Actual sampling
    if replace:
        if p is not None:
            cdf = p.cumsum()
            cdf /= cdf[-1]
            uniform_samples = random_state.random_sample(shape)
            idx = cdf.searchsorted(uniform_samples, side='right')
            # searchsorted returns a scalar
            idx = np.array(idx, copy=False)
        else:
            idx = random_state.randint(0, pop_size, size=shape)
    else:
        if size > pop_size:
            raise ValueError("Cannot take a larger sample than "
                             "population when 'replace=False'")

        if p is not None:
            if np.sum(p > 0) < size:
                raise ValueError("Fewer non-zero entries in p than size")
            n_uniq = 0
            p = p.copy()
            found = np.zeros(shape, dtype=np.int)
            flat_found = found.ravel()
            while n_uniq < size:
                x = random_state.rand(size - n_uniq)
                if n_uniq > 0:
                    p[flat_found[0:n_uniq]] = 0
                cdf = np.cumsum(p)
                cdf /= cdf[-1]
                new = cdf.searchsorted(x, side='right')
                _, unique_indices = np.unique(new, return_index=True)
                unique_indices.sort()
                new = new.take(unique_indices)
                flat_found[n_uniq:n_uniq + new.size] = new
                n_uniq += new.size
            idx = found
        else:
            idx = random_state.permutation(pop_size)[:size]
            if shape is not None:
                idx.shape = shape

    if shape is None and isinstance(idx, np.ndarray):
        # In most cases a scalar will have been made an array
        idx = idx.item(0)

    # Use samples as indices for a if a is array-like
    if a.ndim == 0:
        return idx

    if shape is not None and idx.ndim == 0:
        # If size == () then the user requested a 0-d array as opposed to
        # a scalar object when size is None. However a[idx] is always a
        # scalar and not an array. So this makes sure the result is an
        # array, taking into account that np.array(item) may not work
        # for object arrays.
        res = np.empty((), dtype=a.dtype)
        res[()] = a[idx]
        return res

    return a[idx]

def random_choice_csc(n_samples, classes, class_probability=None,
                      random_state=None):
    """Generate a sparse random matrix given column class distributions

    Parameters
    ----------
    n_samples : int,
        Number of samples to draw in each column.

    classes : list of size n_outputs of arrays of size (n_classes,)
        List of classes for each column.

    class_probability : list of size n_outputs of arrays of size (n_classes,)
        Optional (default=None). Class distribution of each column. If None the
        uniform distribution is assumed.

    random_state : int, RandomState instance or None, optional (default=None)
        If int, random_state is the seed used by the random number generator;
        If RandomState instance, random_state is the random number generator;
        If None, the random number generator is the RandomState instance used
        by `np.random`.

    Returns
    -------
    random_matrix : sparse csc matrix of size (n_samples, n_outputs)

    """
    data = array.array('i')
    indices = array.array('i')
    indptr = array.array('i', [0])

    for j in range(len(classes)):
        classes[j] = np.asarray(classes[j])
        if classes[j].dtype.kind != 'i':
            raise ValueError("class dtype %s is not supported" %
                             classes[j].dtype)
        classes[j] = astype(classes[j], np.int64, copy=False)

        # use uniform distribution if no class_probability is given
        if class_probability is None:
            class_prob_j = np.empty(shape=classes[j].shape[0])
            class_prob_j.fill(1 / classes[j].shape[0])
        else:
            class_prob_j = np.asarray(class_probability[j])

        if np.sum(class_prob_j) != 1.0:
            raise ValueError("Probability array at index {0} does not sum to "
                             "one".format(j))

        if class_prob_j.shape[0] != classes[j].shape[0]:
            raise ValueError("classes[{0}] (length {1}) and "
                             "class_probability[{0}] (length {2}) have "
                             "different length.".format(j,
                                                        classes[j].shape[0],
                                                        class_prob_j.shape[0]))

        # If 0 is not present in the classes insert it with a probability 0.0
        if 0 not in classes[j]:
            classes[j] = np.insert(classes[j], 0, 0)
            class_prob_j = np.insert(class_prob_j, 0, 0.0)

        # If there are nonzero classes choose randomly using class_probability
        rng = check_random_state(random_state)
        if classes[j].shape[0] > 1:
            p_nonzero = 1 - class_prob_j[classes[j] == 0]
            nnz = int(n_samples * p_nonzero)
            ind_sample = sample_without_replacement(n_population=n_samples,
                                                    n_samples=nnz,
                                                    random_state=random_state)
            indices.extend(ind_sample)

            # Normalize probabilites for the nonzero elements
            classes_j_nonzero = classes[j] != 0
            class_probability_nz = class_prob_j[classes_j_nonzero]
            class_probability_nz_norm = (class_probability_nz /
                                         np.sum(class_probability_nz))
            classes_ind = np.searchsorted(class_probability_nz_norm.cumsum(),
                                          rng.rand(nnz))
            data.extend(classes[j][classes_j_nonzero][classes_ind])
        indptr.append(len(indices))

    return sp.csc_matrix((data, indices, indptr),
                         (n_samples, len(classes)),
                         dtype=int)

Body:
You could try NumSharp, a port of numpy to C#

double[] distribution = new double[] { 0.1, 0.2, 0.3, 0.4 };

//Simple choice
for (int i = 0; i < 80; i++)
{
    int choice = NumSharp.np.random.choice(distribution.Count(), probabilities:distribution)[0].GetInt32();
    Console.Write(choice.ToString());
}
Console.WriteLine();

12222312301223333323323223022211111233123323333133211233333233013312213033030033

NumSharp includes aditionnal parameters (replace,...) but has still, to this date, performance issues:

EvalTime("NumSharp Single thread",() =>
{
    for (int i = 0; i < 100000; i++)
        NumSharp.np.random.choice(distribution.Count(), probabilities: distribution)[0].GetInt32();
});

EvalTime("NumSharp Multithread", () =>
{
    Parallel.For(0, 100000, i =>
        NumSharp.np.random.choice(distribution.Count(), probabilities: distribution)[0].GetInt32());
});

EvalTime("Evk Single thread", () =>
{
    for (int i = 0; i < 100000; i++)
        Choice(upTo: distribution.Count(), distribution: distribution);
});

EvalTime("Evk Multithread", () =>
{
    Parallel.For(0, 100000, i =>
        Choice(upTo: distribution.Count(), distribution: distribution));
});

public static void EvalTime(string Name,Action a)
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    a();
    sw.Stop();
    Console.WriteLine("{0} : {1}ms", Name,sw.ElapsedMilliseconds);
}

Here's the output comparing NumSharp and Evk's implementation above on my PC (24 logical cores)

NumSharp Single thread : 10701ms
NumSharp Multithread : 19350ms
Evk Single thread : 117ms
Evk Multithread : 61ms


问:
Sequelize Where statement with date
I am using Sequelize as my backend ORM. Now I wish to do some WHERE operations on a Date.

More specifically, I want to get all data where a date is between now and 7 days ago.

The problem is that the documentation does not specify which operations you can do on Datatypes.DATE

Can anyone point me in the right direction?

答:
This solution is without the moment.js library.

Between 7 days ago and now

```<code>const sevenDaysAgo = new Date(new Date().setDate(new Date().getDate() - 7));
models.instagram.findAll({
  where: {
    my_date: {
      $gt: sevenDaysAgo,
      $lt: new Date(),
    },
  },
});
</code>```

Between now and 7 days from now

```<code>const sevenDaysFromNow = new Date(new Date().setDate(new Date().getDate() + 7));
models.instagram.findAll({
  where: {
    my_date: {
      $gt: new Date(),
      $lt: sevenDaysFromNow,
    },
  },
});
</code>```

Notes:

$gt stands for "greater than". You could use $gte instead of $gt. $gte stands for "greater than or equal to". Same for $lte of course.

Technically speaking, you need both $lt and $gt to make sure that the date isn't into the future (per the original question).

Other answers show the use of [Sequelize.Op.gt] instead of $gt. Use that if on Sequelize v5.

Title: Sequelize Where statement with date

Body:
This solution is without the moment.js library.

Between 7 days ago and now

const sevenDaysAgo = new Date(new Date().setDate(new Date().getDate() - 7));
models.instagram.findAll({
  where: {
    my_date: {
      $gt: sevenDaysAgo,
      $lt: new Date(),
    },
  },
});

Between now and 7 days from now

const sevenDaysFromNow = new Date(new Date().setDate(new Date().getDate() + 7));
models.instagram.findAll({
  where: {
    my_date: {
      $gt: new Date(),
      $lt: sevenDaysFromNow,
    },
  },
});

Notes:

$gt stands for "greater than". You could use $gte instead of $gt. $gte stands for "greater than or equal to". Same for $lte of course.

Technically speaking, you need both $lt and $gt to make sure that the date isn't into the future (per the original question).

Other answers show the use of [Sequelize.Op.gt] instead of $gt. Use that if on Sequelize v5.


问:
FFMPEG Duration convert To Frames On PowerShell
I am new to FFMPEG

I need to get some duration's of some audio and video files.
my out put comes in seconds and milliseconds i guess

I need to convert this milliseconds into frames
FrameCount should be 30

This is my code

```<code>$audioId = "$id.m4a"
$dur = ffprobe $audioId -show_format 2>&1 | sed -n 's/duration=//p'
echo $dur
</code>```

Output be like, its a loop running

```<code>3.478042
3.455979
3.522021

</code>```

my question is , i need to keep three seconds as it is , on the right side the milliseconds i need it to be divided by 30

that means i need the answers be like

```<code>3.15934
3.15199
3.17400
</code>```

thank you

答:
```<code>$audioId = "$id.m4a"
$dur = ffprobe $audioId -show_format 2>&1 | sed -n 's/duration=//p'
Echo ($dur.Split(".")[0] + "." + [math]::Round($dur.Split(".")[1]/30))
</code>```

Body:
I am new to FFMPEG

I need to get some duration's of some audio and video files.
my out put comes in seconds and milliseconds i guess

I need to convert this milliseconds into frames
FrameCount should be 30

This is my code

$audioId = "$id.m4a"
$dur = ffprobe $audioId -show_format 2>&1 | sed -n 's/duration=//p'
echo $dur

Output be like, its a loop running

3.478042
3.455979
3.522021

my question is , i need to keep three seconds as it is , on the right side the milliseconds i need it to be divided by 30

that means i need the answers be like

3.15934
3.15199
3.17400

thank you


问:
Is there a way to get the element 1 before/after upper indexing limit?
I have a Dataframe with Timeindex and a Timeindex till which I want to slice the dataframe.

```<code>df[:upper_Timeindex_Timevalue]
</code>```

The Question:

How do I get the element before this "limiting-index"?

```<code>df[:upper_Timeindex_Timevalue -1] # this wouldnt work this way bc timevalue +1 is not the next in dataframe
</code>```

And how do I get the element after this "limiting-index"?

```<code>df[:upper_Timeindex_Timevalue +1] # this wouldnt work this way bc timevalue +1 is not the next in dataframe
</code>```

答:
You can use boolean indexing:

```<code>df.loc[df.index < upper_Timeindex_Timevalue].last()
</code>```

or

```<code>df.loc[df.index > lower_Timeindex_TimeValue].first()
</code>```

Body:
I have a Dataframe with Timeindex and a Timeindex till which I want to slice the dataframe.

df[:upper_Timeindex_Timevalue]

The Question:

How do I get the element before this "limiting-index"?

df[:upper_Timeindex_Timevalue -1] # this wouldnt work this way bc timevalue +1 is not the next in dataframe

And how do I get the element after this "limiting-index"?

df[:upper_Timeindex_Timevalue +1] # this wouldnt work this way bc timevalue +1 is not the next in dataframe

Body:
You can use boolean indexing:

df.loc[df.index < upper_Timeindex_Timevalue].last()

or

df.loc[df.index > lower_Timeindex_TimeValue].first()