问:
Summation of series 1 + (1+2+1) + (1+2+1+3+1+2+1)
The function is : F(n-1) n F(n-1)

Its a type of palindrome function called Zimmer Series.

The values would be : 1, 121, 1213121, ...

I want to figure the summation of the individual digits.

1 + (1+2+1) + (1+2+1+3+1+2+1) + ...

Any help is welcome.

答:
Breaking this down into steps, we first find out a formula for the summation of a single value of the series and then we can find out the summation of said formula.

Expanding the definition you gave and manipulating it:

```<code>F(n) = n + 2F(n-1)
F(n) = n + 2(n-1) + 2<sup>2</sup>(n-2) + 2<sup>3</sup>(n-3) + ... + 2<sup>n-1</sup>
2F(n) =    2n     + 2<sup>2</sup>(n-1) + 2<sup>3</sup>(n-2) + ... + 2<sup>n-1</sup>(2) + 2<sup>n</sup>

F(n) - 2F(n) = -F(n) = n - 2 - 2<sup>2</sup> - 2<sup>3</sup> - ... - 2<sup>n</sup>
</code>```

From this and using the formula for Geometric Progression we can then get an expression for a single term of the series.

```<code>F(n) = (2<sup>n</sup> + 2<sup>n-1</sup> + ... + 2) - n
     = (2<sup>n+1</sup> - 2) - n</code>```

Now we just have to work out the summation of this expression.

```<code>G(n) = Σ F(n) = Σ (2<sup>n+1</sup> - 2 - n)
G(n) = (2<sup>n+2</sup> - 2<sup>2</sup>) - (2n) - (n(n+1)/2)</code>```

Simplifying this should hopefully give you the answer you seek!

```<code>G(n) = (2<sup>n+2</sup>  - (n(n+5)/2) - 2<sup>2</sup>)
</code>```

Trying this out on a few of the terms just to double check.

```<code>G(1) = (2<sup>1+2</sup> - (1(1+5)/2) - 2<sup>2</sup>)
G(1) = 1</code>```

```<code>G(2) = (2<sup>2+2</sup>  - (2(2+5)/2) - 2<sup>2</sup>)
G(2) = 5 = 1 + (1 + 2 + 1)</code>```

```<code>G(3) = (2<sup>3+2</sup>  - (3(3+5)/2) - 2<sup>2</sup>)
G(3) = 16 = 1 + (1 + 2 + 1) + (1 + 2 + 1 + 3 + 1 + 2 + 1)</code>```

Body:
Breaking this down into steps, we first find out a formula for the summation of a single value of the series and then we can find out the summation of said formula.

Expanding the definition you gave and manipulating it:

F(n) = n + 2F(n-1)
F(n) = n + 2(n-1) + 22(n-2) + 23(n-3) + ... + 2n-1
2F(n) =    2n     + 22(n-1) + 23(n-2) + ... + 2n-1(2) + 2n

F(n) - 2F(n) = -F(n) = n - 2 - 22 - 23 - ... - 2n

From this and using the formula for Geometric Progression we can then get an expression for a single term of the series.

F(n) = (2n + 2n-1 + ... + 2) - n
     = (2n+1 - 2) - n

Now we just have to work out the summation of this expression.

G(n) = Σ F(n) = Σ (2n+1 - 2 - n)
G(n) = (2n+2 - 22) - (2n) - (n(n+1)/2)

Simplifying this should hopefully give you the answer you seek!

G(n) = (2n+2  - (n(n+5)/2) - 22)

Trying this out on a few of the terms just to double check.

G(1) = (21+2 - (1(1+5)/2) - 22)
G(1) = 1

G(2) = (22+2  - (2(2+5)/2) - 22)
G(2) = 5 = 1 + (1 + 2 + 1)

G(3) = (23+2  - (3(3+5)/2) - 22)
G(3) = 16 = 1 + (1 + 2 + 1) + (1 + 2 + 1 + 3 + 1 + 2 + 1)


来源: stackexchange

问:
What is the struct (binary format) of float datatype in C?
How can I find information about float datatype in C? I mean the bit struct for this type (decimal, signal indicator, etc...)?
Let me explain what I'm trying to do:

I am implementing an network protocol and I need to send 6 octects with Latitude and Longitude (according to protocol documentation). First 3 octects must have LAT information and last 3 must have LON information.
I can't use bitwise operators in float datatype, so for debug, I'm copying memory of float variable to a new uint32_t variable (both 4-bytes wide) and then, trying to shift bit's to get the correct value, but it's not working.

This is the code that I'm using to test/debug conversion:

```<code>    int32_t b = 0;
    memcpy(&b,&a,4);
    int32_t c = (b >> 23);
    printf("Valor de C: 0x%X, Decimal: %d\n",c,c);
// Should print only '23', but it's printing
// Valor de C: 0x41B, Decimal: 1051
</code>```

After 'knowing' the correct bit-position of float, I'll copy those bit's to my protocol data, which is an array of unsigned char[6] (this I can't change the type, only values).

Any tip's about how to accomplish this?

答:
The interpretation of data is something separate from the data. The unit of the data is something separate from the data itself. So I can say 123 milliseconds or 0.123 seconds or 234 half-milliseconds or 1.23 * 10^-2 seconds and all these forms represent the same "value".

The data you posted I guess is composed of two numbers encoded in twos-complement numbers represented in big endian with most significant bit first.

```<code>unsigned char data[6]; // assuming indexes reference octet numbers
// big endian - first byte is the most significant
// I assume the hardware uses twos complement internally
// the method as described in https://stackoverflow.com/questions/35876000/converting-24-bit-integer-2s-complement-to-32-bit-integer-in-c
int32_t latitude_value = (int32_t)( data[0] << 24 | data[1] << 16 | data[2] << 8 ) / 256;
// latitude_value represents latitude in units of 180/2^23 degrees
</code>```

Now you can "transform" the latitute from units of 180/2^23 degrees to units of plain degrees if you want to represent it that way:

```<code>double latitue_in_degrees = (double)latitude * 180.0 / exp2(23);
</code>```

Note that there are problems with floating point types.

What is the struct (binary format) of float datatype in C?

  How can I find information about float datatype in C?

  I mean the bit struct for this type (decimal, signal indicator, etc...)?

The exact format of float type depends on your compiler - it can be anything. Well, an overwhelming majority of systems/compilers today use binary32 format from IEC 754 standard for float datatype. Refer to the standard and endless net resources for the exact format of the datatype. For example this converter is just fun to use.

ContentLicense: CC BY-SA 4.0

Body:
How can I find information about float datatype in C? I mean the bit struct for this type (decimal, signal indicator, etc...)?
Let me explain what I'm trying to do:

I am implementing an network protocol and I need to send 6 octects with Latitude and Longitude (according to protocol documentation). First 3 octects must have LAT information and last 3 must have LON information.
I can't use bitwise operators in float datatype, so for debug, I'm copying memory of float variable to a new uint32_t variable (both 4-bytes wide) and then, trying to shift bit's to get the correct value, but it's not working.

This is the code that I'm using to test/debug conversion:

    int32_t b = 0;
    memcpy(&b,&a,4);
    int32_t c = (b >> 23);
    printf("Valor de C: 0x%X, Decimal: %d\n",c,c);
// Should print only '23', but it's printing
// Valor de C: 0x41B, Decimal: 1051

After 'knowing' the correct bit-position of float, I'll copy those bit's to my protocol data, which is an array of unsigned char[6] (this I can't change the type, only values).

Any tip's about how to accomplish this?

Body:
The interpretation of data is something separate from the data. The unit of the data is something separate from the data itself. So I can say 123 milliseconds or 0.123 seconds or 234 half-milliseconds or 1.23 * 10^-2 seconds and all these forms represent the same "value".

The data you posted I guess is composed of two numbers encoded in twos-complement numbers represented in big endian with most significant bit first.

unsigned char data[6]; // assuming indexes reference octet numbers
// big endian - first byte is the most significant
// I assume the hardware uses twos complement internally
// the method as described in https://stackoverflow.com/questions/35876000/converting-24-bit-integer-2s-complement-to-32-bit-integer-in-c
int32_t latitude_value = (int32_t)( data[0] << 24 | data[1] << 16 | data[2] << 8 ) / 256;
// latitude_value represents latitude in units of 180/2^23 degrees

Now you can "transform" the latitute from units of 180/2^23 degrees to units of plain degrees if you want to represent it that way:

double latitue_in_degrees = (double)latitude * 180.0 / exp2(23);

Note that there are problems with floating point types.

What is the struct (binary format) of float datatype in C?

  How can I find information about float datatype in C?

  I mean the bit struct for this type (decimal, signal indicator, etc...)?

The exact format of float type depends on your compiler - it can be anything. Well, an overwhelming majority of systems/compilers today use binary32 format from IEC 754 standard for float datatype. Refer to the standard and endless net resources for the exact format of the datatype. For example this converter is just fun to use.


问:
Jenkins: java.lang.IllegalStateException: Jenkins.instance is missing
While using Jenkins, I've got an error like this:

A problem occurred while processing the request. Please check our bug tracker to see if a similar problem has already been reported. If it is already reported, please vote and put a comment on it to let us gauge the impact of the problem. If you think this is a new issue, please file a new issue. When you file an issue, make sure to add the entire stack trace, along with the version of Jenkins and relevant plugins. The users list might be also useful in understanding what has happened.

Stack trace:

```<code>java.lang.IllegalStateException: Jenkins.instance is missing. Read the documentation of Jenkins.getInstanceOrNull to see what you are doing wrong.
    at jenkins.model.Jenkins.get(Jenkins.java:778)
    at hudson.security.TokenBasedRememberMeServices2.autoLogin(TokenBasedRememberMeServices2.java:164)
    at org.acegisecurity.ui.rememberme.RememberMeProcessingFilter.doFilter(RememberMeProcessingFilter.java:104)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at jenkins.security.BasicHeaderProcessor.doFilter(BasicHeaderProcessor.java:93)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
    at hudson.security.HttpSessionContextIntegrationFilter2.doFilter(HttpSessionContextIntegrationFilter2.java:67)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:90)
    at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1604)
    at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1604)
    at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:82)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1604)
    at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1604)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:545)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:512)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:235)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1592)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:233)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1296)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:188)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:485)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1562)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:186)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1211)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127)
    at org.eclipse.jetty.server.Server.handle(Server.java:500)
    at org.eclipse.jetty.server.HttpChannel.lambda$handle$1(HttpChannel.java:386)
    at org.eclipse.jetty.server.HttpChannel.dispatch(HttpChannel.java:562)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:378)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:270)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:311)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:103)
    at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:117)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:806)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.run(QueuedThreadPool.java:938)
    at java.lang.Thread.run(Unknown Source)
</code>```

How to solve this problem?

答:
Please try this :

```<code>sudo chown jenkins:jenkins -R /var/lib/jenkins/
sudo service jenkins restart
</code>```

Body:
While using Jenkins, I've got an error like this:

A problem occurred while processing the request. Please check our bug tracker to see if a similar problem has already been reported. If it is already reported, please vote and put a comment on it to let us gauge the impact of the problem. If you think this is a new issue, please file a new issue. When you file an issue, make sure to add the entire stack trace, along with the version of Jenkins and relevant plugins. The users list might be also useful in understanding what has happened.

Stack trace:

java.lang.IllegalStateException: Jenkins.instance is missing. Read the documentation of Jenkins.getInstanceOrNull to see what you are doing wrong.
    at jenkins.model.Jenkins.get(Jenkins.java:778)
    at hudson.security.TokenBasedRememberMeServices2.autoLogin(TokenBasedRememberMeServices2.java:164)
    at org.acegisecurity.ui.rememberme.RememberMeProcessingFilter.doFilter(RememberMeProcessingFilter.java:104)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.ui.AbstractProcessingFilter.doFilter(AbstractProcessingFilter.java:271)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at jenkins.security.BasicHeaderProcessor.doFilter(BasicHeaderProcessor.java:93)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at org.acegisecurity.context.HttpSessionContextIntegrationFilter.doFilter(HttpSessionContextIntegrationFilter.java:249)
    at hudson.security.HttpSessionContextIntegrationFilter2.doFilter(HttpSessionContextIntegrationFilter2.java:67)
    at hudson.security.ChainedServletFilter$1.doFilter(ChainedServletFilter.java:87)
    at hudson.security.ChainedServletFilter.doFilter(ChainedServletFilter.java:90)
    at hudson.security.HudsonFilter.doFilter(HudsonFilter.java:171)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1604)
    at org.kohsuke.stapler.compression.CompressionFilter.doFilter(CompressionFilter.java:49)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1604)
    at hudson.util.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:82)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1604)
    at org.kohsuke.stapler.DiagnosticThreadNameFilter.doFilter(DiagnosticThreadNameFilter.java:30)
    at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1604)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:545)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:512)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:235)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1592)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:233)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1296)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:188)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:485)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:1562)
    at org.eclipse.jetty.server.handler.ScopedHandler.nextScope(ScopedHandler.java:186)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1211)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127)
    at org.eclipse.jetty.server.Server.handle(Server.java:500)
    at org.eclipse.jetty.server.HttpChannel.lambda$handle$1(HttpChannel.java:386)
    at org.eclipse.jetty.server.HttpChannel.dispatch(HttpChannel.java:562)
    at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:378)
    at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:270)
    at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:311)
    at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:103)
    at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:117)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:806)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.run(QueuedThreadPool.java:938)
    at java.lang.Thread.run(Unknown Source)

How to solve this problem?

Body:
Please try this :

sudo chown jenkins:jenkins -R /var/lib/jenkins/
sudo service jenkins restart


问:
Bounded Types in generics
Given an example below, why do I need to use doubleValue()(for which it's needed to extend Number class) in reciprocal(), Since there is auto unboxing feature in java which unboxes the numeric object stored in num and can calculate the reciprocal of num and return a double value?

```<code>class gen<T extends Number>{
     T num ;

     gen(T n ){
         num = n ;
     }

     double reciprocal() {
         return (1 / num.doubleValue()) ;
     }
 }

public class demo  {

    public static void main(String[] args) {
        gen<Integer> ob = new gen<Integer>(5) ;
        System.out.println(ob.reciprocal()) ;
    }

}
</code>```

Also, why can't I write the same code as shown below?
 P.S. : The following code shows error in reciprocal() method:

```<code>class gen<T>{
     T num ;

     gen(T n ){
         num = n ;
     }

     double reciprocal() {
         return (1 / num) ;
         // it shows error in the above step. it says "operator / is undefined
     }
 }

public class demo  {

    public static void main(String[] args) {
        gen<Integer> ob = new gen<Integer>(5) ;
        System.out.println(ob.reciprocal()) ;
    }

}
</code>```

答:
Auto-unboxing is not a feature of the Number class, it's a feature of some of its sub-classes (Integer, Double, Float, etc...). There are many sub-classes of Number that don't have this feature (for example, BigInteger, BigDecimal, etc...).

Since the generic type parameter in your first snippet can be of any type that extends Number, it doesn't necessarily have auto-unboxing, so you have to tell the compiler how to convert T to a numeric primitive type that can be an operand of the division operator.

In your second snippet, T has no bound, so it can be anything. The / operator it not defined for any arbitrary type. It is defined for numeric operands. Hence the compiler cannot apply / to 1 and num when num is of some arbitrary reference type.

Title: Bounded Types in generics

Body:
Given an example below, why do I need to use doubleValue()(for which it's needed to extend Number class) in reciprocal(), Since there is auto unboxing feature in java which unboxes the numeric object stored in num and can calculate the reciprocal of num and return a double value?

class gen<T extends Number>{
     T num ;

     gen(T n ){
         num = n ;
     }

     double reciprocal() {
         return (1 / num.doubleValue()) ;
     }
 }

public class demo  {

    public static void main(String[] args) {
        gen<Integer> ob = new gen<Integer>(5) ;
        System.out.println(ob.reciprocal()) ;
    }

}

Also, why can't I write the same code as shown below?
 P.S. : The following code shows error in reciprocal() method:

class gen<T>{
     T num ;

     gen(T n ){
         num = n ;
     }

     double reciprocal() {
         return (1 / num) ;
         // it shows error in the above step. it says "operator / is undefined
     }
 }

public class demo  {

    public static void main(String[] args) {
        gen<Integer> ob = new gen<Integer>(5) ;
        System.out.println(ob.reciprocal()) ;
    }

}


问:
how to compute the sum of minimum value in python
i'm trying to build k-medoids algorithm in python. i have difficulties in computing the cost. I'm using 3 cluster. For example i have S (the distance matrix for every point to each cluster).

```<code>S = array([[3.1398624 , 3.04813418, 4.99560254],
       [3.46696607, 2.94348558, 5.47449423],
       [2.68335282, 4.12807209, 4.43433005],
       [2.64792413, 3.48070146, 4.93280055],
       [1.97348315, 3.46405704, 4.20034798],
       [2.62944855, 3.4593389 , 4.9092722 ]])
</code>```

and the assigned label for each point(using the minimum S to assign label), for example:

```<code>labels = array([1, 1, 0, 0, 0, 0], dtype=int32)
</code>```

so i try to compute the cost, which is the sum of the minimum distance for each point.

```<code>def calculate_cost(S):
    cost = 0
    min_cost_idx = np.argmin(S, axis=1)
    for i in range(len(min_cost_idx)):
        cost += np.sum(S[i])
    return cost
</code>```

but it gives me the sum of all  S , not the sum of the minimum  S for each data point.

答:
It is because i takes value for each row, but not the required index within that row.
You should change your for loop to:

```<code>for i,val in enumerate(min_cost_idx):
    cost += np.sum(S[i][val])
</code>```

Having said that, you can also get rid of the for loop altogether, and take the sum using the np.min function.

```<code>%timeit (calculate_cost(S))
26.9 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit sum(np.min(S, axis=1))
4.79 µs ± 90.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
</code>```

Body:
i'm trying to build k-medoids algorithm in python. i have difficulties in computing the cost. I'm using 3 cluster. For example i have S (the distance matrix for every point to each cluster).

S = array([[3.1398624 , 3.04813418, 4.99560254],
       [3.46696607, 2.94348558, 5.47449423],
       [2.68335282, 4.12807209, 4.43433005],
       [2.64792413, 3.48070146, 4.93280055],
       [1.97348315, 3.46405704, 4.20034798],
       [2.62944855, 3.4593389 , 4.9092722 ]])

and the assigned label for each point(using the minimum S to assign label), for example:

labels = array([1, 1, 0, 0, 0, 0], dtype=int32)

so i try to compute the cost, which is the sum of the minimum distance for each point.

def calculate_cost(S):
    cost = 0
    min_cost_idx = np.argmin(S, axis=1)
    for i in range(len(min_cost_idx)):
        cost += np.sum(S[i])
    return cost

but it gives me the sum of all  S , not the sum of the minimum  S for each data point.

Body:
It is because i takes value for each row, but not the required index within that row.
You should change your for loop to:

for i,val in enumerate(min_cost_idx):
    cost += np.sum(S[i][val])

Having said that, you can also get rid of the for loop altogether, and take the sum using the np.min function.

%timeit (calculate_cost(S))
26.9 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

%timeit sum(np.min(S, axis=1))
4.79 µs ± 90.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)


问:
How to move the file pointer to next character through "ifstream" without "getting" any character, just like "fseek" does?
seekg uses ios as the second argument, and ios can be set to end or beg or some other values as shown here: http://www.cplusplus.com/reference/iostream/ios/

I just want the pointer to move to the next character, how is that to be accomplished through ifstream?

EDIT
Well, the problem is that I want a function in ifstream similar to fseek, which moves the pointer without reading anything.

答: Read the docs for seekg and use ios_base::cur as indicated there.

ContentLicense: CC BY-SA 3.0


问:
Using R to extract sums from a raster layer, in areas outside potentially overlapping buffers
I am very new to raster data and the use of R for spatial data analysis, so apologies if there's an obvious solution or process for this I've missed.

I have a raster file of population data from WorldPop, and a set of latitude / longitude location points that overlay onto that. I am trying to determine what portion of the population is (according to the WorldPop estimates) within a given distance of these points of interest, and also what portion is not.

I understand that using raster::extract, I should be able to get the sum of population values from (for example) a 1-kilometer buffer around each of these points. (Although my points and raster data are both in lat/lon projection, so I gather I need to first correct for this by changing the projection to utm as done here.)

However, because some number of these points will be less than 1 km apart, I am concerned that this total sum is double-counting the population of some cells where buffers overlap. Does buffering automatically correct for this, or is there an efficient way to ensure that this is not the case, and also to get the values from the inverse of the buffered point area selection?

答:
Well, thanks to a suggestion via Twitter and this guide to creating SpatialPolygons around points, I've been able to find an answer for this. This is probably not the most efficient means of doing so — it's proving to be very slow on large polygons - but it's workable for my purposes.

Here's sample code:

```<code>library(tabularaster)
library(raster)
library(tidyverse)
library(geos)

# -----------------------

# load point data ---

p <- read_csv("points_of_interest.csv")
p_df <- p %>% rename(x = lat, y = lon)
p_coords <- p_df[, c("y","x")]

p_spdf <- SpatialPointsDataFrame(
   coords = pc_coords,
   data = p_df,
   proj4string = CRS("+init=epsg:4326"))

# convert projection to metric units

p_mrc <- spTransform(
   p_spdf,
   CRS("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0
       +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs")
   )

# buffer to 1000 meters

p_mrc_1k_mrc <- gBuffer(
   p_mrc, byid = TRUE, width = 1000)

# switch back to lat/lon
p_mrc_1k <- spTransform(p_mrc_1k_mrc, CRS("+init=epsg:4326"))

# load raster data -------

r <- raster("pop.tif")
r_tib <- tabularaster::as_tibble(r)

# get intersection of cells and polygons
cell_df_1k <- cellnumbers(r, p_mrc_1k)

# get list of cells where there is intersection
target_cell_1k <- cell_df_1k$cell_

# add cell values to df listing all cells covered by polys
target_cells_extract_1k <- cell_df_1k %>%
  rename(cellindex = cell_) %>%
  left_join(r_tib)

# calculate the sum of population within 1k radius for each object
# (this includes overlapping population cells shared between polys)
cell_sum_1k <- target_cells_extract_1k %>%
  group_by(object_) %>%
  summarize(pop_1k = sum(cellvalue, na.rm = T))

# get only unique cell values for total overlapping coverage of all polys
target_cells_unique_1k <- r_tib %>% filter(cellindex %in% target_cell_1k)

total_coverage_pop <- sum(target_cells_unique_1k$cellvalue, na.rm = T)
outside_coverage_pop <- sum(r_tib$cellvalue) - total_coverage_pop

</code>```

Body:
Well, thanks to a suggestion via Twitter and this guide to creating SpatialPolygons around points, I've been able to find an answer for this. This is probably not the most efficient means of doing so — it's proving to be very slow on large polygons - but it's workable for my purposes.

Here's sample code:

library(tabularaster)
library(raster)
library(tidyverse)
library(geos)

# -----------------------

# load point data ---

p <- read_csv("points_of_interest.csv")
p_df <- p %>% rename(x = lat, y = lon)
p_coords <- p_df[, c("y","x")]

p_spdf <- SpatialPointsDataFrame(
   coords = pc_coords,
   data = p_df,
   proj4string = CRS("+init=epsg:4326"))

# convert projection to metric units

p_mrc <- spTransform(
   p_spdf,
   CRS("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0
       +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs")
   )

# buffer to 1000 meters

p_mrc_1k_mrc <- gBuffer(
   p_mrc, byid = TRUE, width = 1000)

# switch back to lat/lon
p_mrc_1k <- spTransform(p_mrc_1k_mrc, CRS("+init=epsg:4326"))

# load raster data -------

r <- raster("pop.tif")
r_tib <- tabularaster::as_tibble(r)

# get intersection of cells and polygons
cell_df_1k <- cellnumbers(r, p_mrc_1k)

# get list of cells where there is intersection
target_cell_1k <- cell_df_1k$cell_

# add cell values to df listing all cells covered by polys
target_cells_extract_1k <- cell_df_1k %>%
  rename(cellindex = cell_) %>%
  left_join(r_tib)

# calculate the sum of population within 1k radius for each object
# (this includes overlapping population cells shared between polys)
cell_sum_1k <- target_cells_extract_1k %>%
  group_by(object_) %>%
  summarize(pop_1k = sum(cellvalue, na.rm = T))

# get only unique cell values for total overlapping coverage of all polys
target_cells_unique_1k <- r_tib %>% filter(cellindex %in% target_cell_1k)

total_coverage_pop <- sum(target_cells_unique_1k$cellvalue, na.rm = T)
outside_coverage_pop <- sum(r_tib$cellvalue) - total_coverage_pop


问:
CoreLocation - Continuous location update in background with authorizedWhenInUse authorization
I need to track the user location in background, like the navigation feature in waze and apple maps.

However, I want to use it with authorizedWhenInUse  permission.

As I understand, application can keep track of user location even with authorizedWhenInUse permission, as in this state, application considered foreground (Blue line appears on top of the status bar - means that the user knows that the application doing location work)

It all works fine when I grant authorizedAlways permission.

However, when the permission is authorizedWhenInUse, and I send the application to background, the blue line appears, but application gets terminated after about one minute, and the following message appears in the log:

Message from debugger: Terminated due to signal 9

Here is how I track location updates before going to background:

```<code>locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.delegate = self
locationManager.startUpdatingLocation()
</code>```

And my plist contains the background mode:

```<code><key>UIBackgroundModes</key>
<array>
    <string>location</string>
</array>
</code>```

答:
Try to set showsBackgroundLocationIndicator property to true

https://developer.apple.com/documentation/corelocation/choosing_the_location_services_authorization_to_request says:

Location services are available to apps with
  CLAuthorizationStatus.authorizedWhenInUse only while the app is “in
  use”. On all platforms that support When In Use authorization, an app
  is considered in use:

When the app runs in the foreground.

In the few seconds after an app leaves the foreground, a short grace
  period for your app to finish any current location tasks the user
  initiated.

When the app shows the background location usage indicator
  (showsBackgroundLocationIndicator). On iOS, the indicator is a blue
  bar or pill at the top of the screen; on watchOS it’s a small icon.

It would be nice to read the whole article :)

If you don't want to see blue bar at top, use authorizedAlways auth type.

Body:
I need to track the user location in background, like the navigation feature in waze and apple maps.

However, I want to use it with authorizedWhenInUse  permission.

As I understand, application can keep track of user location even with authorizedWhenInUse permission, as in this state, application considered foreground (Blue line appears on top of the status bar - means that the user knows that the application doing location work)

It all works fine when I grant authorizedAlways permission.

However, when the permission is authorizedWhenInUse, and I send the application to background, the blue line appears, but application gets terminated after about one minute, and the following message appears in the log:

Message from debugger: Terminated due to signal 9

Here is how I track location updates before going to background:

locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.delegate = self
locationManager.startUpdatingLocation()

And my plist contains the background mode:

<key>UIBackgroundModes</key>
<array>
    <string>location</string>
</array>


问:
Git on ubuntu server: other users cannot push
I have setup a git server on an ubuntu server machine.

Everything seems to work OK, and I am able to pull/push from other machines via ssh.

What is the problem is when I try to add other users to the server.

I create their accounts and they are able to pull, but when they try to push they get a message:

```<code>error: remote unpack failed: unable to create temporary object directory
</code>```

I read online that this usually has to do with disk space on the remonte machine, but it's not the case here.

I suspect something with permissions, but i cannot find anything!

答:
Make sure to create your repository with:

the core.sharedRepository set to group (or true)

a group which will be common to all your users.

You can see a full example in "Git: Sharing a single git controlled folder among a group under Linux".

You cal also change the permissions of your existing repository to make sure it is accessible by that one common group.

Body:
I have setup a git server on an ubuntu server machine.

Everything seems to work OK, and I am able to pull/push from other machines via ssh.

What is the problem is when I try to add other users to the server.

I create their accounts and they are able to pull, but when they try to push they get a message:

error: remote unpack failed: unable to create temporary object directory

I read online that this usually has to do with disk space on the remonte machine, but it's not the case here.

I suspect something with permissions, but i cannot find anything!


问:
Docker: Passing Env variables for Cloud Code to Parse-Server and Parse-Dashboard
I am trying to use following parseplatform images from docker hub instead of creating my own and wondering how to go about passing additional variables for -

S3 Adapter for AWS S3

Mailgun Adapter for Email

Twilio for Send SMS

Add custom location for Cloud Code config as ENV var

```<code>     version: '3'
        services:
            parse:
                image: parseplatform/parse-server
                ports:
                    - 1337:1337
                environment:
                    - PARSE_SERVER_APPLICATION_ID=
                    - PARSE_SERVER_MASTER_KEY=
                    - PARSE_SERVER_FILE_KEY=
                    - PARSE_SERVER_DATABASE_URI=""
            dashboard:
                image: parseplatform/parse-dashboard
                ports:
                    - 4040:4040
                environment:
                    - PARSE_DASHBOARD_SERVER_URL=http://localhost:1337/parse
                    - PARSE_DASHBOARD_APP_ID=
                    - PARSE_DASHBOARD_MASTER_KEY=
                    - PARSE_DASHBOARD_APP_NAME=
                    - PARSE_DASHBOARD_ALLOW_INSECURE_HTTP=1
                    - PARSE_DASHBOARD_USER_ID=user
                    - PARSE_DASHBOARD_USER_PASSWORD=
</code>```

答:
Figured out how to pass in the cloud code but now trying to understand how to tackle 3rd party libraries like Twilio -</p>

```<code>            - PARSE_SERVER_CLOUD=/parse-server/cloud/main.js
        volumes:
            - ./parse-server/cloud:/parse-server/cloud
</code>```

Body:
I am trying to use following parseplatform images from docker hub instead of creating my own and wondering how to go about passing additional variables for -

S3 Adapter for AWS S3

Mailgun Adapter for Email

Twilio for Send SMS

Add custom location for Cloud Code config as ENV var

     version: '3'
        services:
            parse:
                image: parseplatform/parse-server
                ports:
                    - 1337:1337
                environment:
                    - PARSE_SERVER_APPLICATION_ID=
                    - PARSE_SERVER_MASTER_KEY=
                    - PARSE_SERVER_FILE_KEY=
                    - PARSE_SERVER_DATABASE_URI=""
            dashboard:
                image: parseplatform/parse-dashboard
                ports:
                    - 4040:4040
                environment:
                    - PARSE_DASHBOARD_SERVER_URL=http://localhost:1337/parse
                    - PARSE_DASHBOARD_APP_ID=
                    - PARSE_DASHBOARD_MASTER_KEY=
                    - PARSE_DASHBOARD_APP_NAME=
                    - PARSE_DASHBOARD_ALLOW_INSECURE_HTTP=1
                    - PARSE_DASHBOARD_USER_ID=user
                    - PARSE_DASHBOARD_USER_PASSWORD=

Body:
Figured out how to pass in the cloud code but now trying to understand how to tackle 3rd party libraries like Twilio -

            - PARSE_SERVER_CLOUD=/parse-server/cloud/main.js
        volumes:
            - ./parse-server/cloud:/parse-server/cloud


问:
How to append new values from master Google sheet onto multiple sheet with conditions
I have a Master Google Sheet with five columns that automatically gets updated daily.

```<code>Date    Event   Value1  Value2  Value3
May 1   ABC     A       Yes     Yes
May 1   ABC     B       Yes     Yes
May 1   ABC     C       Yes     Yes
May 1   DEF     A       Yes     Yes
May 1   DEF     B       Yes     Yes
May 1   GHI     A       Yes     Yes
May 1   GHI     C       Yes     Yes
May 2   ABC     A       Yes     Yes
May 2   DEF     D       Yes     Yes
May 2   GHI     C       Yes     Yes
</code>```

The same document has a corresponding sheet for the three types of events in the Master Sheet: ABC, DEF and GHI. These sheets have existing values in it.

I would like a Google Apps Script to only append unique and new values from Value1 to corresponding Event sheets on edit of the Master sheet. Example:

Sheet ABC

```<code>Value
A
B
C
</code>```

Sheet DEF

```<code>Value
A
B
D
</code>```

Sheet GHI

```<code>Value
A
C
</code>```

It's not really dependent on the date, but rather looking through what already exists in the corresponding sheets.

I'm a complete beginner in Google Apps Scripts. I've looked into other solutions and the furthest I've gone is to find how to dynamically create the different sheets based off of the Event value from here.

The only issue is that this copies over all rows which means I get duplicates in my other sheets.

```<code>function createNewSheets() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var masterSheet = spreadsheet.getSheetByName('Raw');
  var data_range = masterSheet.getRange('B:C').getValues();
  // Get headers row (to be appended on top when new sheet is created):
  var headers = data_range[0];
  // Iterate through all rows of data from Raw:
  for (var i = 1; i < data_range.length; i++) {
    var row = data_range[i]; // Current row
    var eventName = row[0]; // Event name
    // Get sheet with current event name:
    var sheet = spreadsheet.getSheetByName(eventName);
    // Check if sheet with current event name exists. If it doesn't it creates it:
    if (!sheet) {
      sheet = spreadsheet.insertSheet(eventName);
      sheet.appendRow(headers);
    }
    // Appends current row of data to the new sheet:
    sheet.appendRow(row);

  }
}
</code>```

I just need help changing the sheet.appendRow(row); line to only pull unique values.

答:
You need to implement a conditional statement verifying either an entry with the same value in row[1] exists already

For this you have to loop through the rows of the destination sheet in the same way already do for the master sheet

Transform the value range to a simple array with flat()

Compare the entries in column B (?) against row[1] with indexOf()

Sample:

```<code>function createNewSheets() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var masterSheet = spreadsheet.getSheetByName('Raw');
  var data_range = masterSheet.getRange(1,2,masterSheet.getLastRow(),2).getValues();
  // Get headers row (to be appended on top when new sheet is created):
  var headers = data_range[0];
  // Iterate through all rows of data from Raw:
  for (var i = 1; i < data_range.length; i++) {
    var row = data_range[i]; // Current row
    var eventName = row[0]; // Event name
    // Get sheet with current event name:
    var sheet = spreadsheet.getSheetByName(eventName);
    // Check if sheet with current event name exists. If it doesn't it creates it:
    if (!sheet) {
      sheet = spreadsheet.insertSheet(eventName);
      sheet.appendRow(headers);
    }
    //retrieves values in column A of the destination sheet
    var sheetValuesB = sheet.getRange(1,2,masterSheet.getLastRow(),1).getValues();
    //transforms the values into a 1-D array
    sheetValuesB = sheetValuesB.flat();
    //check if row[1] already exists in sheet
    if(sheetValuesB.indexOf(row[1]) == -1){
      // Appends current row of data to the new sheet:
      sheet.appendRow(row);
    }
  }
}
</code>```

Annotation:

I encourage you define the range setting as the limit getLastRow() which retrieves the last row containing data, whilst the notation B:C would also iterate through all the empty rows and make your script unnecessary slow.

Body:
I have a Master Google Sheet with five columns that automatically gets updated daily.

Date    Event   Value1  Value2  Value3
May 1   ABC     A       Yes     Yes
May 1   ABC     B       Yes     Yes
May 1   ABC     C       Yes     Yes
May 1   DEF     A       Yes     Yes
May 1   DEF     B       Yes     Yes
May 1   GHI     A       Yes     Yes
May 1   GHI     C       Yes     Yes
May 2   ABC     A       Yes     Yes
May 2   DEF     D       Yes     Yes
May 2   GHI     C       Yes     Yes

The same document has a corresponding sheet for the three types of events in the Master Sheet: ABC, DEF and GHI. These sheets have existing values in it.

I would like a Google Apps Script to only append unique and new values from Value1 to corresponding Event sheets on edit of the Master sheet. Example:

Sheet ABC

Value
A
B
C

Sheet DEF

Value
A
B
D

Sheet GHI

Value
A
C

It's not really dependent on the date, but rather looking through what already exists in the corresponding sheets.

I'm a complete beginner in Google Apps Scripts. I've looked into other solutions and the furthest I've gone is to find how to dynamically create the different sheets based off of the Event value from here.

The only issue is that this copies over all rows which means I get duplicates in my other sheets.

function createNewSheets() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var masterSheet = spreadsheet.getSheetByName('Raw');
  var data_range = masterSheet.getRange('B:C').getValues();
  // Get headers row (to be appended on top when new sheet is created):
  var headers = data_range[0];
  // Iterate through all rows of data from Raw:
  for (var i = 1; i < data_range.length; i++) {
    var row = data_range[i]; // Current row
    var eventName = row[0]; // Event name
    // Get sheet with current event name:
    var sheet = spreadsheet.getSheetByName(eventName);
    // Check if sheet with current event name exists. If it doesn't it creates it:
    if (!sheet) {
      sheet = spreadsheet.insertSheet(eventName);
      sheet.appendRow(headers);
    }
    // Appends current row of data to the new sheet:
    sheet.appendRow(row);

  }
}

I just need help changing the sheet.appendRow(row); line to only pull unique values.

Body:
You need to implement a conditional statement verifying either an entry with the same value in row[1] exists already

For this you have to loop through the rows of the destination sheet in the same way already do for the master sheet

Transform the value range to a simple array with flat()

Compare the entries in column B (?) against row[1] with indexOf()

Sample:

function createNewSheets() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var masterSheet = spreadsheet.getSheetByName('Raw');
  var data_range = masterSheet.getRange(1,2,masterSheet.getLastRow(),2).getValues();
  // Get headers row (to be appended on top when new sheet is created):
  var headers = data_range[0];
  // Iterate through all rows of data from Raw:
  for (var i = 1; i < data_range.length; i++) {
    var row = data_range[i]; // Current row
    var eventName = row[0]; // Event name
    // Get sheet with current event name:
    var sheet = spreadsheet.getSheetByName(eventName);
    // Check if sheet with current event name exists. If it doesn't it creates it:
    if (!sheet) {
      sheet = spreadsheet.insertSheet(eventName);
      sheet.appendRow(headers);
    }
    //retrieves values in column A of the destination sheet
    var sheetValuesB = sheet.getRange(1,2,masterSheet.getLastRow(),1).getValues();
    //transforms the values into a 1-D array
    sheetValuesB = sheetValuesB.flat();
    //check if row[1] already exists in sheet
    if(sheetValuesB.indexOf(row[1]) == -1){
      // Appends current row of data to the new sheet:
      sheet.appendRow(row);
    }
  }
}

Annotation:

I encourage you define the range setting as the limit getLastRow() which retrieves the last row containing data, whilst the notation B:C would also iterate through all the empty rows and make your script unnecessary slow.


问:
Dynamically display photos of same item and hide carousel if there is only one photo
In a react app, I display 1-5 photos of each item. All the photos are in a folder under Node, so the way I display them is using their url, i.e. http://10.1.1.1:3000/01-0001.JPG
So, I don't make an http request to get them.

Problem is:

It is not possible to know how many photos each item has. For example, one item could have 5 photos and another one only one photo. The format of the filename is this: 01-0001.JPG, 01-0001.1.JPG, 01-0001.2.JPG

So, what I currently do is this:

```<code>    const Item1 = () => {
      return (
        <img src={`${process.env.REACT_APP_NODE_SERVER}/${item.No}.JPG`} onError={this.addDefaultSrc} alt='1'></img>
      )
    }

    const Item2 = () => {
      return (
        <img src={`${process.env.REACT_APP_NODE_SERVER}/${item.No}.1.JPG`} onError={this.addDefaultSrc} alt='2'></img>
      )
    }

    const Item3 = () => {
      return (
        <img src={`${process.env.REACT_APP_NODE_SERVER}/${item.No}.2.JPG`} onError={this.addDefaultSrc} alt='3'></img>
      )
    }
</code>```

and I use this function to display a dummy photo when there is no photo

```<code>  addDefaultSrc(ev) {
    ev.target.src = `${process.env.REACT_APP_NODE_SERVER}/notfound.png`;
    ev.target.onerror = null;
  }
</code>```

This is bad solution because I don't want the client to see a dummy picture, instead client should see only the true number of photos for each item.

I am using react-multi-carousel

```<code>          <Carousel
          responsive={responsive}
          swipeable={false}
          draggable={false}
          showDots={true}
          ssr={false} // means to render carousel on server-side.
          infinite={false}
          autoPlay={false}
          autoPlaySpeed={1000}
          keyBoardControl={true}
          customTransition="all .5"
          transitionDuration={500}
          containerClass="carousel-container"
          removeArrowOnDeviceType={["tablet", "mobile"]}
          deviceType={this.props.deviceType}
          dotListClass="custom-dot-list-style"
          itemClass="carousel-item-padding-40-px">
            <div><Item1 /></div>
            <div><Item2 /></div>
            <div><Item3 /></div>
          </Carousel>
</code>```

Any help would be much appreciated.

答:
I think you should loop over images, set initial style to display: none, wait for all callbacks and calculate appropriate state when everything is complete.

Example

const { useState, useEffect } = React;

const random = () => Math.floor(Math.random() * 5 + 5);
const getImages = () => Promise.resolve(Array(random()).fill(0).map((pr, index) => {

  const id = index + 750;

  return {
    id,
    url: `https://i.picsum.photos/id/${id}/100/100.jpg`,
    loaded: false,
    error: false,
    alt: id
  }
}))

const Images = ({onComplete}) => {
  const [images, setImages] = useState([]);
  const [allLoaded, setLoaded] = useState(false);

  useEffect(() => {
    let isUnmounted = false;

    getImages()
      .then(images => {
        if(isUnmounted) {
          return;
        }

        setImages(images);
      })

    return () => {
      isUnmounted = true;
    }
  }, [])

  useEffect(() => {
    let isUnmounted = false;

    const loadedImagesCount = images.reduce((acc, image) => acc + Number(image.error) + Number(image.loaded), 0);

    if(images.length === loadedImagesCount) {
      setTimeout(() => {
        if(isUnmounted) {
          return;
        }

        setLoaded(true);
        onComplete();
      }, 500);
    }

    return () => {
      isUnmounted = true;
    }
  }, [images])

  const onError = id => {
    setImages(images => {
      const imageIndex = images.findIndex(image => image.id ===id)
      const image = images[imageIndex];

      return [
        ...images.slice(0, imageIndex),
        {
          ...image,
          error: true
        },
        ...images.slice(imageIndex + 1)
      ]
    })
  }

  const onLoad = id => {
    setImages(images => {

      const imageIndex = images.findIndex(image => image.id ===id)
      const image = images[imageIndex];

      return [
        ...images.slice(0, imageIndex),
        {
          ...image,
          loaded: true
        },
        ...images.slice(imageIndex + 1)
      ]
    })
  }

  const loadedImagesCount = images.reduce((acc, image) => acc + Number(image.loaded), 0)

  if(allLoaded && [0, 1].includes(loadedImagesCount)) {
    return 'No images or only one image - hidden'
  }

  return <React.Fragment>
    {images.map(({id, loaded, error, url, alt}) => <img key={id} src={url} className={`image ${error ? 'image--error' : null} ${allLoaded && loaded ? 'image--loaded' : null}`} onLoad={() => onLoad(id)} onError={() => onError(id)} alt={alt}/>)}
  </React.Fragment>
}

const App = () => {
  const [loading, setLoading] = useState(true);

  const onComplete = () => {
    setLoading(false);
  }

  return

    {loading ? 'Loading...' : null}
    <Images onComplete={onComplete}/>

}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.image {
  display: none;
}

.image--error {
  display: none;
}

.image--loaded {
  display: inline;
}</code>```

```

Body:
In a react app, I display 1-5 photos of each item. All the photos are in a folder under Node, so the way I display them is using their url, i.e. http://10.1.1.1:3000/01-0001.JPG
So, I don't make an http request to get them.

Problem is:

It is not possible to know how many photos each item has. For example, one item could have 5 photos and another one only one photo. The format of the filename is this: 01-0001.JPG, 01-0001.1.JPG, 01-0001.2.JPG

So, what I currently do is this:

    const Item1 = () => {
      return (
        <img src={`${process.env.REACT_APP_NODE_SERVER}/${item.No}.JPG`} onError={this.addDefaultSrc} alt='1'>
      )
    }

    const Item2 = () => {
      return (
        <img src={`${process.env.REACT_APP_NODE_SERVER}/${item.No}.1.JPG`} onError={this.addDefaultSrc} alt='2'>
      )
    }

    const Item3 = () => {
      return (
        <img src={`${process.env.REACT_APP_NODE_SERVER}/${item.No}.2.JPG`} onError={this.addDefaultSrc} alt='3'>
      )
    }

and I use this function to display a dummy photo when there is no photo

  addDefaultSrc(ev) {
    ev.target.src = `${process.env.REACT_APP_NODE_SERVER}/notfound.png`;
    ev.target.onerror = null;
  }

This is bad solution because I don't want the client to see a dummy picture, instead client should see only the true number of photos for each item.

I am using react-multi-carousel

          <Carousel
          responsive={responsive}
          swipeable={false}
          draggable={false}
          showDots={true}
          ssr={false} // means to render carousel on server-side.
          infinite={false}
          autoPlay={false}
          autoPlaySpeed={1000}
          keyBoardControl={true}
          customTransition="all .5"
          transitionDuration={500}
          containerClass="carousel-container"
          removeArrowOnDeviceType={["tablet", "mobile"]}
          deviceType={this.props.deviceType}
          dotListClass="custom-dot-list-style"
          itemClass="carousel-item-padding-40-px">

<Item1 />

<Item2 />

<Item3 />

          </Carousel>

Any help would be much appreciated.

Body:
I think you should loop over images, set initial style to display: none, wait for all callbacks and calculate appropriate state when everything is complete.

Example

const { useState, useEffect } = React;

const random = () => Math.floor(Math.random() * 5 + 5);
const getImages = () => Promise.resolve(Array(random()).fill(0).map((pr, index) => {

  const id = index + 750;

  return {
    id,
    url: `https://i.picsum.photos/id/${id}/100/100.jpg`,
    loaded: false,
    error: false,
    alt: id
  }
}))

const Images = ({onComplete}) => {
  const [images, setImages] = useState([]);
  const [allLoaded, setLoaded] = useState(false);

  useEffect(() => {
    let isUnmounted = false;

    getImages()
      .then(images => {
        if(isUnmounted) {
          return;
        }

        setImages(images);
      })

    return () => {
      isUnmounted = true;
    }
  }, [])

  useEffect(() => {
    let isUnmounted = false;

    const loadedImagesCount = images.reduce((acc, image) => acc + Number(image.error) + Number(image.loaded), 0);

    if(images.length === loadedImagesCount) {
      setTimeout(() => {
        if(isUnmounted) {
          return;
        }

        setLoaded(true);
        onComplete();
      }, 500);
    }

    return () => {
      isUnmounted = true;
    }
  }, [images])

  const onError = id => {
    setImages(images => {
      const imageIndex = images.findIndex(image => image.id ===id)
      const image = images[imageIndex];

      return [
        ...images.slice(0, imageIndex),
        {
          ...image,
          error: true
        },
        ...images.slice(imageIndex + 1)
      ]
    })
  }

  const onLoad = id => {
    setImages(images => {

      const imageIndex = images.findIndex(image => image.id ===id)
      const image = images[imageIndex];

      return [
        ...images.slice(0, imageIndex),
        {
          ...image,
          loaded: true
        },
        ...images.slice(imageIndex + 1)
      ]
    })
  }

  const loadedImagesCount = images.reduce((acc, image) => acc + Number(image.loaded), 0)

  if(allLoaded && [0, 1].includes(loadedImagesCount)) {
    return 'No images or only one image - hidden'
  }

  return <React.Fragment>
    {images.map(({id, loaded, error, url, alt}) => <img key={id} src={url} className={`image ${error ? 'image--error' : null} ${allLoaded && loaded ? 'image--loaded' : null}`} onLoad={() => onLoad(id)} onError={() => onError(id)} alt={alt}/>)}
  </React.Fragment>
}

const App = () => {
  const [loading, setLoading] = useState(true);

  const onComplete = () => {
    setLoading(false);
  }

  return <div>
    {loading ? 'Loading...' : null}
    <Images onComplete={onComplete}/>
  </div>
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
  );

.image {
  display: none;
}

.image--error {
  display: none;
}

.image--loaded {
  display: inline;
}

<script src="https://unpkg.com/react/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<div id="root"></div>


问:
How to set focus to an antd Input.Password component?
I am trying to set focus an input.password field. Is it possible?

I didnt see any information on antd docs. I wonder if its possible

Input(Input.TextArea) has a Input(textAreaRef) property through ref. but in Input.Password, I can't find anything about this. Is there a way to accomplish my question?

答:
Sometimes you point with ref to Component instead of DOM-element, so, try this:

In case of Input component from antd library:

```<code>import React, { useRef, useEffect } from "react";
import { Input, Form } from "antd";
import "antd/dist/antd.css";

const MyComponent = () => {
  // Same as React.createRef()
  const passwordInput = useRef(null);

  useEffect(() => {
    if (passwordInput.current) {
      // or, if Input component in your ref, then use input property like:
      // passwordInput.current.input.focus();
      passwordInput.current.focus();
    }
  }, [passwordInput]);

  return (
    <Form>
      <Form.Item name="login">
        <Input type="text" placeholder="Login" />
      </Form.Item>
      <Form.Item name="password">
        <Input type="password" placeholder="Password" ref={passwordInput} />
      </Form.Item>
    </Form>
  );
};

export default MyComponent;
</code>```

In case of DOM Element

```<code>import React, { useRef, useEffect } from "react";

const MyComponent2 = () => {
  const passwordInput = useRef(null);

  useEffect(() => {
    if (passwordInput.current) {
      passwordInput.current.focus();
    }
  }, [passwordInput]);

  return (
    <form>
      <input type="text" placeholder="Login" />
      <input type="password" placeholder="Password" ref={passwordInput} />
    </form>
  );
};

export default MyComponent2;
</code>```

This is example on codesandbox

P.S. useEffect hook works almost same as componentDidMount in Class component

Body:
Sometimes you point with ref to Component instead of DOM-element, so, try this:

In case of Input component from antd library:

import React, { useRef, useEffect } from "react";
import { Input, Form } from "antd";
import "antd/dist/antd.css";

const MyComponent = () => {
  // Same as React.createRef()
  const passwordInput = useRef(null);

  useEffect(() => {
    if (passwordInput.current) {
      // or, if Input component in your ref, then use input property like:
      // passwordInput.current.input.focus();
      passwordInput.current.focus();
    }
  }, [passwordInput]);

  return (
    <Form>
      <Form.Item name="login">
        <Input type="text" placeholder="Login" />
      </Form.Item>
      <Form.Item name="password">
        <Input type="password" placeholder="Password" ref={passwordInput} />
      </Form.Item>
    </Form>
  );
};

export default MyComponent;

In case of DOM Element

import React, { useRef, useEffect } from "react";

const MyComponent2 = () => {
  const passwordInput = useRef(null);

  useEffect(() => {
    if (passwordInput.current) {
      passwordInput.current.focus();
    }
  }, [passwordInput]);

  return (
    <form>
      <input type="text" placeholder="Login" />
      <input type="password" placeholder="Password" ref={passwordInput} />
    </form>
  );
};

export default MyComponent2;

This is example on codesandbox

P.S. useEffect hook works almost same as componentDidMount in Class component


问:
Laravel Parameter Grouping (and/or where)
I upgraded Laravel to version 7, and when I do a query like this:

```<code>$users = User::where('name', '=', 'John')
           ->where(function ($query) {
               $query->where('votes', '>', 100)
                     ->orWhereNull('title');
           })
           ->get();
</code>```

it doesn't work as expected, and I got this error  [SQL Server] Must specify table to select from

because the SQL should be like this:

```<code>select * from users where name = 'John' and (votes > 100 or title is null)
</code>```

but when I debug the returned query it shows like this:

```<code>select * from users where name = 'John' and (select * votes > 100 or title is null) is null
</code>```

The above query it just an example of my complex query, and I have a lot like this query in all of my project so I don't need a replacement, I just need to know how to fix it as it worked fine before upgrading

答:
You can use whereRaw for the alternative method, for example

```<code>$users = Table::whereRaw(" name=? AND (votes=? OR title=?)", array(?,?,?))
</code>```

Body:
I upgraded Laravel to version 7, and when I do a query like this:

$users = User::where('name', '=', 'John')
           ->where(function ($query) {
               $query->where('votes', '>', 100)
                     ->orWhereNull('title');
           })
           ->get();

it doesn't work as expected, and I got this error  [SQL Server] Must specify table to select from

because the SQL should be like this:

select * from users where name = 'John' and (votes > 100 or title is null)

but when I debug the returned query it shows like this:

select * from users where name = 'John' and (select * votes > 100 or title is null) is null

The above query it just an example of my complex query, and I have a lot like this query in all of my project so I don't need a replacement, I just need to know how to fix it as it worked fine before upgrading

Body:
You can use whereRaw for the alternative method, for example

$users = Table::whereRaw(" name=? AND (votes=? OR title=?)", array(?,?,?))


问:
How to get the value of a particular textView inside ListView in Android?
In my application I need to move from one activity to another depending on the list clicked. In each listview there will be three textview namely: Emp_id, Emp_name,Emp_address, so whenever I click on a particular list that should move to next activity of the corresponding Emp_id. So here I want to catch the Emp_id, which I am unable. I have tried a lot but got only the first Emp_id not the list that I have clicked.

CODE:

```<code>ArrayList<HashMap<String, String>> mylist2 = new ArrayList<HashMap<String, String>>();

        try{
            JSONObject jObj = new JSONObject(Mydetail);
            JSONArray data = jObj.getJSONArray("mydata");

            for(int i=0;i<data.length();i++){
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject e = data.getJSONObject(i);

                map.put("id", String.valueOf(i));
                map.put("Eid", "" + e.getString("E_id"));
                map.put("Ename", "" + e.getString("E_name"));
                map.put("Eaddress", "" + e.getString("E_address"));
                mylist2.add(map);
            }
        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }

         ListAdapter adapter = new SimpleAdapter(this, mylist2 , R.layout.datalist,
                                  new String[] { "Eid", "Ename", "Eaddress" },
                                  new int[] {  R.id.TextView1,R.id.TextView2e,R.id.TextView3 });
                                  setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
                //String val = o.get("id");

                Pnm = (TextView)findViewById(R.id.TextView1);
                 String str = ((TextView)Pnm).getText().toString();

                Toast.makeText(projects.this, str,Toast.LENGTH_LONG).show();

                Intent newActivitySecond = new Intent(projects.this, modules.class);
                projects.this.startActivity(newActivitySecond);

            }
        });
</code>```

Thanks

答:
Try like this:</p>

```<code> ListView lv_ArchivePartylist;

    lv_ArchivePartylist = (ListView)findViewById(R.id.archive_ListView01);
            lv_ArchivePartylist.setOnItemClickListener(new OnItemClickListener()
                {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
                    // TODO Auto-generated method stub
                    String message = view.findViewById(R.id.txt_box1).getText().toString;
                    Toast.makeText(Activityname.this, message, Toast.LENGTH_SHORT).show();

    }
    }

    });
</code>```

Body:
In my application I need to move from one activity to another depending on the list clicked. In each listview there will be three textview namely: Emp_id, Emp_name,Emp_address, so whenever I click on a particular list that should move to next activity of the corresponding Emp_id. So here I want to catch the Emp_id, which I am unable. I have tried a lot but got only the first Emp_id not the list that I have clicked.

CODE:

ArrayList<HashMap<String, String>> mylist2 = new ArrayList<HashMap<String, String>>();

        try{
            JSONObject jObj = new JSONObject(Mydetail);
            JSONArray data = jObj.getJSONArray("mydata");

            for(int i=0;i<data.length();i++){
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject e = data.getJSONObject(i);

                map.put("id", String.valueOf(i));
                map.put("Eid", "" + e.getString("E_id"));
                map.put("Ename", "" + e.getString("E_name"));
                map.put("Eaddress", "" + e.getString("E_address"));
                mylist2.add(map);
            }
        }catch(JSONException e)        {
             Log.e("log_tag", "Error parsing data "+e.toString());
        }

         ListAdapter adapter = new SimpleAdapter(this, mylist2 , R.layout.datalist,
                                  new String[] { "Eid", "Ename", "Eaddress" },
                                  new int[] {  R.id.TextView1,R.id.TextView2e,R.id.TextView3 });
                                  setListAdapter(adapter);

        final ListView lv = getListView();
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                @SuppressWarnings("unchecked")
                HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
                //String val = o.get("id");

                Pnm = (TextView)findViewById(R.id.TextView1);
                 String str = ((TextView)Pnm).getText().toString();

                Toast.makeText(projects.this, str,Toast.LENGTH_LONG).show();

                Intent newActivitySecond = new Intent(projects.this, modules.class);
                projects.this.startActivity(newActivitySecond);

            }
        });

Thanks

Body:
Try like this:

 ListView lv_ArchivePartylist;

    lv_ArchivePartylist = (ListView)findViewById(R.id.archive_ListView01);
            lv_ArchivePartylist.setOnItemClickListener(new OnItemClickListener()
                {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
                    // TODO Auto-generated method stub
                    String message = view.findViewById(R.id.txt_box1).getText().toString;
                    Toast.makeText(Activityname.this, message, Toast.LENGTH_SHORT).show();

    }
    }

    });


问:
How can I pass data from child component to parent component in Reactjs?
I have two components one child and another is parent component. I am conditionally rendring my child component. Function of this code is just when you click on button a timer will display and when you click stop timer will stop. Here "Timer" is child componenet and I have used state property in "timer" componenet and I want to display the value of Timer when a just before clicking on "stop timer button". So how do I pass the "timer" state variable value from child to parent component.

```<code> const[time,setTime]=useState(0);
 const handleStart=()=>{
    setTime(true);
 }
const handleStop=()=>{
    setTime(false);
 }
 .....
<button onClick={handleStart}>Start StopWatch</button>
<button onClick={handleStop}>Stop StopWatch</button>
{time?<Timer/>:null}
</code>```

This was the parent component and the following code is for "timer" component.

```<code>import React,{useEffect,useState} from 'react';
const Timer = () => {
    const[timer,setTimer]=useState(0);
    useEffect(()=>{
        setTimeout(()=>{
            setTimer(prevTime=>prevTime+1);
        },100)
    },[timer])
    let style={
        position:"absolute",
        height:"100px",
        weight:"200px",
        backgroundColor:"red",
        zIndex:"1"
    }
    const handleStopTime=()=>{
        console.log(timer);
        setTimer(0);
    }
    return (
        <div style={style}>
            <h1>{timer}</h1>
        </div>
      );
}

export default Timer;
</code>```

答:
You can pass a function to a child component which update a value in the the parent component.

Example :

my parent have a variable : name;
So i set a function in a parent component as :

```<code>updateName = (newValue) => {
    this.setState({
                name: newValue,
            });
    }
</code>```

and then i call my child component and give him the function in props, so he can modify this value :

```<code><ChildComponent updateName={this.updateName} />
</code>```

Body:
I have two components one child and another is parent component. I am conditionally rendring my child component. Function of this code is just when you click on button a timer will display and when you click stop timer will stop. Here "Timer" is child componenet and I have used state property in "timer" componenet and I want to display the value of Timer when a just before clicking on "stop timer button". So how do I pass the "timer" state variable value from child to parent component.

 const[time,setTime]=useState(0);
 const handleStart=()=>{
    setTime(true);
 }
const handleStop=()=>{
    setTime(false);
 }
 .....
<button onClick={handleStart}>Start StopWatch</button>
<button onClick={handleStop}>Stop StopWatch</button>
{time?<Timer/>:null}

This was the parent component and the following code is for "timer" component.

import React,{useEffect,useState} from 'react';
const Timer = () => {
    const[timer,setTimer]=useState(0);
    useEffect(()=>{
        setTimeout(()=>{
            setTimer(prevTime=>prevTime+1);
        },100)
    },[timer])
    let style={
        position:"absolute",
        height:"100px",
        weight:"200px",
        backgroundColor:"red",
        zIndex:"1"
    }
    const handleStopTime=()=>{
        console.log(timer);
        setTimer(0);
    }
    return (

{timer}

      );
}

export default Timer;

Body:
You can pass a function to a child component which update a value in the the parent component.

Example :

my parent have a variable : name;
So i set a function in a parent component as :

updateName = (newValue) => {
    this.setState({
                name: newValue,
            });
    }

and then i call my child component and give him the function in props, so he can modify this value :

<ChildComponent updateName={this.updateName} />


问:
What can a hacker do with your .ENV file?
I understand most of mysql deny external connections. So, let's say my .env file is exposed and a hacker manages to get it. What can they do with its information?</p>

答:
Database: the hacker can use the DB credentials and read/write/remove data from your database.

Client's Credentails: after the DB login, with the ENV_KEY they can decrpt password of all the users. Basically login in and violate the privacy.

Payment Gateway: If using any payment gateway then those key + secret is also exposed. Not sure what they would use this for. I mean, they would rather receive payments on their payment account.

Clone: All those years of hard work will be copied in seconds. (Saw it on Silicon Valley)

Even worse, your clients information is in their hands now. They can sell/share that & because of that you are liable for that breach.

Basically whatever good or bad you can do with your project, the hacker can do much more damage because he/she will not be responsible for his/her actions. You will be.


问:
CountNonDivisible - Codility training task
I'm training on codility now. Some tasks I can solve by myself, but with some tasks have problems.

Difficulty of this task is <**>. It's medium, but I stalled.

Problem:

You are given a non-empty zero-indexed array A consisting of N integers.
For each number A[i] such that 0 ≤ i < N, we want to count the number of elements of the array that are not the divisors of A[i]. We say that these elements are non-divisors.
For example, consider integer N = 5 and array A such that:

```<code>A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 3
A[4] = 6
</code>```

For the following elements:

```<code>A[0] = 3, the non-divisors are: 2, 6,
A[1] = 1, the non-divisors are: 3, 2, 3, 6,
A[2] = 2, the non-divisors are: 3, 3, 6,
A[3] = 3, the non-divisors are: 2, 6,
A[6] = 6, there aren't any non-divisors.
</code>```

Write a function:

```<code>class Solution { public int[] solution(int[] A); }
</code>```

that, given a non-empty zero-indexed array A consisting of N integers, returns a sequence of integers representing the numbers of non-divisors.
The sequence should be returned as:

a structure Results (in C),

or a vector of integers (in C++),

or a    record Results (in Pascal),

or an array of integers (in any other programming language).

For example, given:

```<code>A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 3
A[4] = 6
</code>```

the function should return [2, 4, 3, 2, 0], as explained above.
Assume that:

N is an integer within the range [1..50,000];

each element of array A is an integer within the range [1..2 * N].

Complexity:

expected worst-case time complexity is O(N*log(N));

expected worst-case space complexity is O(N), beyond input storage
(not counting the storage required for input arguments).

Elements of input arrays can be modified.

I have written some solutions. But my solutions bulky and still have O(n^2) complexity.

Can you help me with some ideas or algorithms how to do it optimally? It's not an interview task or something else. I'm just training and try to solve all tasks.

You can find this task here: http://codility.com/demo/train/ Lesson 9, first task in lesson.

答:
JavaScript solution with 100% score.
Codility detected the complexity to be O(nlogn), but it's actually O(n * sqrt(n))</p>

```<code>function solution(A) {
  const createCounts = A => {
    const counts = Array(A.length * 2 + 1).fill(0)
    for (let i = 0; i < A.length; i++) {
      counts[A[i]] += 1
    }
    return counts
  }
  const counts = createCounts(A)
  const results = []
  for (let i = 0; i < A.length; i++) {
    let nonDivisiblesCount = A.length
    let j = 1
    while (j * j < A[i]) {
      if (A[i] % j === 0) {
        nonDivisiblesCount -= counts[j]
        nonDivisiblesCount -= counts[A[i] / j]
      }
      j++
    }
    if (j * j === A[i]) {
      nonDivisiblesCount -= counts[j]
    }
    results.push(nonDivisiblesCount)
  }
  return results
}

const A = [3, 1, 2, 3, 6]
console.log(A)
const s = solution(A)
console.log(s)
</code>```

Body:
I'm training on codility now. Some tasks I can solve by myself, but with some tasks have problems.

Difficulty of this task is <**>. It's medium, but I stalled.

Problem:

You are given a non-empty zero-indexed array A consisting of N integers.
For each number A[i] such that 0 ≤ i < N, we want to count the number of elements of the array that are not the divisors of A[i]. We say that these elements are non-divisors.
For example, consider integer N = 5 and array A such that:

A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 3
A[4] = 6

For the following elements:

A[0] = 3, the non-divisors are: 2, 6,
A[1] = 1, the non-divisors are: 3, 2, 3, 6,
A[2] = 2, the non-divisors are: 3, 3, 6,
A[3] = 3, the non-divisors are: 2, 6,
A[6] = 6, there aren't any non-divisors.

Write a function:

class Solution { public int[] solution(int[] A); }

that, given a non-empty zero-indexed array A consisting of N integers, returns a sequence of integers representing the numbers of non-divisors.
The sequence should be returned as:

a structure Results (in C),

or a vector of integers (in C++),

or a    record Results (in Pascal),

or an array of integers (in any other programming language).

For example, given:

A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 3
A[4] = 6

the function should return [2, 4, 3, 2, 0], as explained above.
Assume that:

N is an integer within the range [1..50,000];

each element of array A is an integer within the range [1..2 * N].

Complexity:

expected worst-case time complexity is O(N*log(N));

expected worst-case space complexity is O(N), beyond input storage
(not counting the storage required for input arguments).

Elements of input arrays can be modified.

I have written some solutions. But my solutions bulky and still have O(n^2) complexity.

Can you help me with some ideas or algorithms how to do it optimally? It's not an interview task or something else. I'm just training and try to solve all tasks.

You can find this task here: http://codility.com/demo/train/ Lesson 9, first task in lesson.

Body:
JavaScript solution with 100% score.
Codility detected the complexity to be O(nlogn), but it's actually O(n * sqrt(n))

function solution(A) {
  const createCounts = A => {
    const counts = Array(A.length * 2 + 1).fill(0)
    for (let i = 0; i < A.length; i++) {
      counts[A[i]] += 1
    }
    return counts
  }
  const counts = createCounts(A)
  const results = []
  for (let i = 0; i < A.length; i++) {
    let nonDivisiblesCount = A.length
    let j = 1
    while (j * j < A[i]) {
      if (A[i] % j === 0) {
        nonDivisiblesCount -= counts[j]
        nonDivisiblesCount -= counts[A[i] / j]
      }
      j++
    }
    if (j * j === A[i]) {
      nonDivisiblesCount -= counts[j]
    }
    results.push(nonDivisiblesCount)
  }
  return results
}

const A = [3, 1, 2, 3, 6]
console.log(A)
const s = solution(A)
console.log(s)


问:
Problem in code to divide N conditionally
So, I'm trying to solve the following Problem Statement

For an integer N, find the number of times the following operation can be performed:

```<code>Select an integer z which satisfies the 3 conditions:

1. Z can be expressed as p^e where p is prime and e > 0
2. z is a factor of N
3. z is different from all previous zs

Now replace N with N / z
</code>```

This is the code that I tried:

```<code>#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

const bool isPrime(long long num) {
    for (long long div = 2; div <= sqrt(num); div++) {
        if (num % div == 0) {
            return false;
        }
    }
    return true;
}

std::vector<long long> getFactors(const long long number) {
    std::vector<long long> vec_of_divisors;
    for (long long i = 1; i <= number / 2; i++) {
        if (number % i == 0) {
            vec_of_divisors.push_back(i);
        }
    }
    vec_of_divisors.push_back(number);
    return vec_of_divisors;
}

bool hasPrimeFactors(long long num) {
    std::vector<long long> divisors = getFactors(num);
    std::vector<long long> prime_vec;
    for (const auto& divisor : divisors) {
        if (isPrime(divisor)) {
            return true;
        }
    }
    return false;
}

int main() {
    long long N = 997764507000;
    //std::cin >> N;
    long count = 0;
    std::vector<long long> usedFactors;

    auto notUsed = [&](long long num) {
        for (auto& elem : usedFactors) {
            if (elem == num) {
                return false;
            }
        }
        return true;
    };
    long long temp;
    do {
        temp = N;
        std::vector<long long> factors = getFactors(N);
        for (auto& factor : factors) {
            if ((factor != 1) && hasPrimeFactors(factor) && notUsed(factor)) {
                usedFactors.push_back(factor);
                N = N / factor;
                count++;
                break;
            }
        }
    } while (temp != N);
    std::cout << count << std::endl;
    return 0;
}
</code>```

It exceeds the time limit of 2secs

It seems the code is really inefficient.
What am I missing?

I have tried debugging, but it takes a really long time after it reaches 10^11

答:
The number N can be factored into (p1 ^ e1)(p2 ^ e2) .... For each of these factors p^e, the most that you can divide N by is (p)(p ^ 2)(p ^ 3).... Of course, all those powers need to sum to less than or equal to e.

So you only need to compute all the factors once, and then for each e, find the largest triangular number that is less than or equal to e. The repeated factor calculations are wasted work, and is unnecessary.

Body:
So, I'm trying to solve the following Problem Statement

For an integer N, find the number of times the following operation can be performed:

Select an integer z which satisfies the 3 conditions:

1. Z can be expressed as p^e where p is prime and e > 0
2. z is a factor of N
3. z is different from all previous zs

Now replace N with N / z

This is the code that I tried:

#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

const bool isPrime(long long num) {
    for (long long div = 2; div <= sqrt(num); div++) {
        if (num % div == 0) {
            return false;
        }
    }
    return true;
}

std::vector<long long> getFactors(const long long number) {
    std::vector<long long> vec_of_divisors;
    for (long long i = 1; i <= number / 2; i++) {
        if (number % i == 0) {
            vec_of_divisors.push_back(i);
        }
    }
    vec_of_divisors.push_back(number);
    return vec_of_divisors;
}

bool hasPrimeFactors(long long num) {
    std::vector<long long> divisors = getFactors(num);
    std::vector<long long> prime_vec;
    for (const auto& divisor : divisors) {
        if (isPrime(divisor)) {
            return true;
        }
    }
    return false;
}

int main() {
    long long N = 997764507000;
    //std::cin >> N;
    long count = 0;
    std::vector<long long> usedFactors;

    auto notUsed = [&](long long num) {
        for (auto& elem : usedFactors) {
            if (elem == num) {
                return false;
            }
        }
        return true;
    };
    long long temp;
    do {
        temp = N;
        std::vector<long long> factors = getFactors(N);
        for (auto& factor : factors) {
            if ((factor != 1) && hasPrimeFactors(factor) && notUsed(factor)) {
                usedFactors.push_back(factor);
                N = N / factor;
                count++;
                break;
            }
        }
    } while (temp != N);
    std::cout << count << std::endl;
    return 0;
}

It exceeds the time limit of 2secs

It seems the code is really inefficient.
What am I missing?

I have tried debugging, but it takes a really long time after it reaches 10^11


问:
How to insert programmatically apostrophes into Cell object (Visio Addin)
When i tried to insert aposttrophes into Cell like this:

```<code>newName = "name with aposttrophes \"";
myShape.Cells[myCell].FormulaU = '"' + newName  + '"';
</code>```

I got the following exception: "\n\nMissing quote."

Whether there is way to insert apostrophes to Cell.Formula Visio object?

答:
TLDR; use double-quote:

```<code>newName = "name with aposttrophes \"\"";
</code>```

Explanation: when you use .FormulaU you actually setting a formula value. Means, the expression you specify is interpreted by Visio as formula and evaluated. A constant string is a valid expression. Single quote in the string "ends" your formula and you get odd number of quotes in it (unclosed quotes) thus this error message. So before assigning, just duplicate all quotes in the string, like this:

```<code>myShape.Cells[myCell].FormulaU = '"' + newName.Replace("\"", "\"\"") + '"';
</code>```

On reading back (if you use the same .FormulaU to read it back, and not .Characters.Text, which is preferable, because it calculates fields), do the reverse and de-deuplicate all quotes.

Body:
When i tried to insert aposttrophes into Cell like this:

newName = "name with aposttrophes \"";
myShape.Cells[myCell].FormulaU = '"' + newName  + '"';

I got the following exception: "\n\nMissing quote."

Whether there is way to insert apostrophes to Cell.Formula Visio object?

Body:
TLDR; use double-quote:

newName = "name with aposttrophes \"\"";

Explanation: when you use .FormulaU you actually setting a formula value. Means, the expression you specify is interpreted by Visio as formula and evaluated. A constant string is a valid expression. Single quote in the string "ends" your formula and you get odd number of quotes in it (unclosed quotes) thus this error message. So before assigning, just duplicate all quotes in the string, like this:

myShape.Cells[myCell].FormulaU = '"' + newName.Replace("\"", "\"\"") + '"';

On reading back (if you use the same .FormulaU to read it back, and not .Characters.Text, which is preferable, because it calculates fields), do the reverse and de-deuplicate all quotes.


问:
Use custom font with nodeJs and svgToPng
I'm trying to convert an SGV to PNG using the library svgToPng

This works great, other than the custom Google font I am using does not display properly.

What should look like this

Instead instead looks like this

Here is the complete code which includes the font as a base64 string, this renders fine in a browser, but when ran on nodeJS does not work.  I've also tried having the font files with relative and absolute paths to the Google CDN, both of which do the same result.

I am wanting to run this as an Azure Function, so the option to install the font on my machine isn't an option which I have seen before in others answers.

```<code>var svgString = `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="800" height="800"><defs></defs><style>@font-face { font-family: 'Dokdo'; src: url(data:application/font-woff2;charset=utf-8;base64,[encoded data, 9440 characters]) format('woff2');    font-weight: normal;    font-style: normal;}</style><g><rect fill="rgb(80,80,80)" stroke="none" x="0" y="0" width="150" height="70"></rect><text fill="rgb(255,255,255)" font-family="Dokdo" font-size="50px" x="10" y="50">TEST</text></g></svg>`;

var buffer = await svg2png(Buffer.from(svgString));
var result = await buffer.toString("base64");
console.log(result);
</code>```

答:
If your SVG contains text and used on an  tag, web fonts will not render on all browsers due to security reasons, and will be displayed using system fonts (mostly Times New Roman).

You must embed the fonts first. Try https://vecta.io/nano to compress your SVG and download it as PNG. If it doesn't embed your fonts, use Sketch, Photoshop, ... to vectorize the font first.

Body:
I'm trying to convert an SGV to PNG using the library svgToPng

This works great, other than the custom Google font I am using does not display properly.

What should look like this

Instead instead looks like this

Here is the complete code which includes the font as a base64 string, this renders fine in a browser, but when ran on nodeJS does not work.  I've also tried having the font files with relative and absolute paths to the Google CDN, both of which do the same result.

I am wanting to run this as an Azure Function, so the option to install the font on my machine isn't an option which I have seen before in others answers.

var svgString = `<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="800" height="800"><defs></defs><g><rect fill="rgb(80,80,80)" stroke="none" x="0" y="0" width="150" height="70"></rect><text fill="rgb(255,255,255)" font-family="Dokdo" font-size="50px" x="10" y="50">TEST</text></g></svg>`;

var buffer = await svg2png(Buffer.from(svgString));
var result = await buffer.toString("base64");
console.log(result);

Body:
If your SVG contains text and used on an <img> tag, web fonts will not render on all browsers due to security reasons, and will be displayed using system fonts (mostly Times New Roman).

You must embed the fonts first. Try https://vecta.io/nano to compress your SVG and download it as PNG. If it doesn't embed your fonts, use Sketch, Photoshop, ... to vectorize the font first.


问:
How to navigate through pages within the website using Selenium and Python
I'm scraping this website( http://rera.rajasthan.gov.in/ProjectSearch) using Python and Selenium. I have the code working but it currently only scrapes the first page, I would like to iterate through all the pages and scrape all the VIEW present in them, but they handle pagination in a weird way how would I go through the pages and scrape them one by one?

My source code:

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, WebDriverException
import time

opt = webdriver.ChromeOptions()
opt.add_argument("--ignore-certificate-errors")
opt.add_argument("--start-maximized")

driver = webdriver.Chrome(executable_path=r"C:\Users\fit foodie\PycharmProjects\Selenium\Browser\chromedriver.exe", options=opt)

driver.get(url="http://rera.rajasthan.gov.in/")
search= driver.find_element_by_xpath("//*[@id='liSearch']/a").click()
proj_src=driver.find_element_by_xpath("//*[@id='liSearch']/ul/li[1]/a").click()

search_btn = driver.find_element_by_xpath('//*[@id="btn_SearchProjectSubmit"]').click()

def page():
    while True:
        try:
            driver.execute_script("return arguments[0].scrollIntoView(true);", WebDriverWait(driver, 20).until(
                EC.element_to_be_clickable((By.XPATH, "//*[@id='OuterProjectGrid']/div[4]/div[4]/a"))))
            driver.find_element_by_xpath("//*[@id='OuterProjectGrid']/div[4]/div[4]/a").click()
            print("Navigating to Next Page")
        except (TimeoutException, WebDriverException) as e:
            print("Last page reached")
            break
</code>```

unable to paginate through this

img:

this is the

答:
try this ,</p>

```<code>def page():
    count = 0
    while True:
        try:
            count += 1
            driver.execute_script("return arguments[0].scrollIntoView(true);", WebDriverWait(driver, 20).until(
                EC.element_to_be_clickable((By.XPATH, "//*[@id='OuterProjectGrid']/div[4]/div[4]/a[1]"))))
            driver.find_element_by_xpath("//*[@id='OuterProjectGrid']/div[4]/div[4]/a["+str(count)+"]").click()
            print("Navigating to Next Page")
            time.sleep(5)
        except (TimeoutException, WebDriverException) as e:
            print("Last page reached")
            break

page()
</code>```

Body:
I'm scraping this website( http://rera.rajasthan.gov.in/ProjectSearch) using Python and Selenium. I have the code working but it currently only scrapes the first page, I would like to iterate through all the pages and scrape all the VIEW present in them, but they handle pagination in a weird way how would I go through the pages and scrape them one by one?

My source code:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, WebDriverException
import time

opt = webdriver.ChromeOptions()
opt.add_argument("--ignore-certificate-errors")
opt.add_argument("--start-maximized")

driver = webdriver.Chrome(executable_path=r"C:\Users\fit foodie\PycharmProjects\Selenium\Browser\chromedriver.exe", options=opt)

driver.get(url="http://rera.rajasthan.gov.in/")
search= driver.find_element_by_xpath("//*[@id='liSearch']/a").click()
proj_src=driver.find_element_by_xpath("//*[@id='liSearch']/ul/li[1]/a").click()

search_btn = driver.find_element_by_xpath('//*[@id="btn_SearchProjectSubmit"]').click()

def page():
    while True:
        try:
            driver.execute_script("return arguments[0].scrollIntoView(true);", WebDriverWait(driver, 20).until(
                EC.element_to_be_clickable((By.XPATH, "//*[@id='OuterProjectGrid']/div[4]/div[4]/a"))))
            driver.find_element_by_xpath("//*[@id='OuterProjectGrid']/div[4]/div[4]/a").click()
            print("Navigating to Next Page")
        except (TimeoutException, WebDriverException) as e:
            print("Last page reached")
            break

unable to paginate through this

img:

this is the

Body:
try this ,

def page():
    count = 0
    while True:
        try:
            count += 1
            driver.execute_script("return arguments[0].scrollIntoView(true);", WebDriverWait(driver, 20).until(
                EC.element_to_be_clickable((By.XPATH, "//*[@id='OuterProjectGrid']/div[4]/div[4]/a[1]"))))
            driver.find_element_by_xpath("//*[@id='OuterProjectGrid']/div[4]/div[4]/a["+str(count)+"]").click()
            print("Navigating to Next Page")
            time.sleep(5)
        except (TimeoutException, WebDriverException) as e:
            print("Last page reached")
            break

page()


问:
All my personal files are listed as untracked files
I don´t remember but I must have done git init in my personal file (C:\Users\lucas).

I want to upload a project to github. That project is in C:\Users\lucas\Desktop\project but for some reason VSCode tells me that every file in C:\Users\lucas are listed as untracked files.

I couldn't find the .git file in C:\Users\lucas but through PowerShell using cd .git I could access it. I tried to delete it but there are some files in there.

Should I delete this folder or does it contain important information? Is it supposed to exist a .git file in there?

Thanks!

答:
You initiated repository in your C:\Users\lucas.

Go to settings, set invisible files and folders to visible, delete .git folder

navigate to C:\Users\lucas\Desktop\project in terminal and run git init from there


问:
How to delete Telegram Group
How to delete a Telegram Group that I just created?

Note, it about deleting a Telegram Group, not

Delete Message from Telegram Group

Delete Telegram None Admin Super Group

Remove image/message from a telegram group

etc. thx.

答: In the latest version of Telegram X on Android, as of June 1st 2020, you can go to Manage Group (the pencil icon) -> 3 Dots -> Destroy Group

Title: How to delete Telegram Group