text:
Q: Program to find all primes in a very large given range of integers i came across this following question on a programming website :
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
I came up with the following solution :
import java.util.*;

public class PRIME1 {
    static int numCases;
    static int left, right;
    static boolean[] initSieve = new boolean[32000];
    static boolean[] answer;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        numCases = sc.nextInt();
        initSieve[0] = true;
        initSieve[1] = true;
        Sieve();
        for (int j = 0; j < numCases; j++) {
            String line = sc.next();
            String line2 = sc.next();
            left = Integer.parseInt(line);
            right = Integer.parseInt(line2);
            answer = new boolean[right - left + 1];
            getAnswer();
            for (int i = 0; i < answer.length; i++) {
                if (!answer[i]) {
                    int ans = i + left;
                    System.out.println(ans);
                }
            }
            System.out.println();
        }
    }

    public static void Sieve() {

        for (int i = 2; i < 32000; i++) {
            if (!initSieve[i]) {
                for (int j = 2 * i; j < 32000; j += i) {
                    initSieve[j] = true;
                }
            }
            if (i * i > 32000)
                break;
        }
    }

    public static void getAnswer() {
        for (int i = 2; i < 32000 && i <= right; i++) {
            if (!initSieve[i]) {
                int num = i;
                if (num * 2 >= left) {
                    num *= 2;
                } else {
                    num = (num * (left / num));
                    if (num < left)
                        num += i;
                }
                for (int j = num; j >= left && j <= right; j += i) {
                    answer[j - left] = true;
                }
            }
        }
    }
}

I have edited my solution after reading some of the suggestions. I am still getting a time limit exceeded kind of error. Any more suggestions as how to further optimize this ? Am calculating all the primes upto 32000 and then using these to find the primes between n to m.
Thanks,
Rohit

A: You are given

1 <= m <= n <= 1000000000, n-m<=100000

these are very small numbers. To sieve a range with an upper bound of n, you need the primes to √n. Here you know n <= 10^9, so √n < 31623, so you need at worst the primes to 31621. There are 3401. You can generate them with a standard sieve in a few microseconds.
Then you can simply sieve the small range from m to n by marking the multiples of the primes you've sieved before, stopping when the prime exceeds √n. Some speedup can be gained by eliminating the multiples of some small primes from the sieve, but the logic becomes more complicated (you need to treat sieves with small m specially).
public int[] chunk(int m, int n) {
    if (n < 2) return null;
    if (m < 2) m = 2;
    if (n < m) throw new IllegalArgumentException("Borked");
    int root = (int)Math.sqrt((double)n);
    boolean[] sieve = new boolean[n-m+1];
    // primes is the global array of primes to 31621 populated earlier
    // primeCount is the number of primes stored in primes, i.e. 3401
    // We ignore even numbers, but keep them in the sieve to avoid index arithmetic.
    // It would be very simple to omit them, though.
    for(int i = 1, p = primes[1]; i < primeCount; ++i) {
        if ((p = primes[i]) > root) break;
        int mult;
        if (p*p < m) {
            mult = (m-1)/p+1;
            if (mult % 2 == 0) ++mult;
            mult = p*mult;
        } else {
            mult = p*p;
        }
        for(; mult <= n; mult += 2*p) {
            sieve[mult-m] = true;
        }
    }
    int count = m == 2 ? 1 : 0;
    for(int i = 1 - m%2; i < n-m; i += 2) {
        if (!sieve[i]) ++count;
    }
    int sievedPrimes[] = new int[count];
    int pi = 0;
    if (m == 2) {
        sievedPrimes[0] = 2;
        pi = 1;
    }
    for(int i = 1 - m%2; i < n-m; i += 2) {
        if (!sieve[i]) {
            sievedPrimes[pi++] = m+i;
        }
    }
    return sievedPrimes;
}

Using a BitSet or any other type of packed flag-array would reduce the memory usage and thus may give a significant speed-up due to better cache-locality.

A: Use a BitSet instead of an Array of Boolean.
public static BitSet primes (final int MAX)
{
     BitSet primes = new BitSet (MAX);
     // make only odd numbers candidates...
     for (int i = 3; i < MAX; i+=2)
     {
        primes.set(i);
     }
     // ... except no. 2
     primes.set (2, true);
     for (int i = 3; i < MAX; i+=2)
     {
        /*
            If a number z is already  eliminated (like 9),
             because it is itself a multiple of a prime
            (example: 3), then all multiples of z (9) are
            already eliminated.
        */
        if (primes.get (i))
        {
            int j = 3 * i;
            while (j < MAX)
            {
                if (primes.get (j))
                    primes.set (j, false);
                j += (2 * i);
            }
        }
    }
    return primes;
}

A: do you HAVE to store the result in the array? how about a method that computes if a given integer is a prime or not and just call it for each number in {left,left+1,...,right} ?

A: You can always use an offset when accessing the isNotPrime array.
Given m, n:
boolean[] isNotPrime = new boolean[n-m+1];

// to now if number x is primer or not
boolean xIsPrime = isNotPrime[x-m];

Here m is the offset.

A: You are not forced to have one large array : you can keep a list of the primes found so far, and test using multiple arrays, having values = array_slot + offset(already tested values). Once you have finished the values from i to j, you add j-i to offset and start a new array starting from J.
You can remove even numbers from your array, that would save you some space (values = array_slot * 2 - 1).

A: Since the distance between m and n is relatively small, you can brute-force and use a fast primality test algorithm in every number between  m and n.
If you allow probabilistic algorithms, you can use Miller-Rabin test. Let M = n-m <= 10^5 and N = n <= 10^9. The complexity of the brute-force algorithm would be O(k M (log N)^3), where k is a constant that controls probabilistic guarantees (for practical applications, k can be set to 10).
For the limits of the problem, this complexity will be around 10^9.


text:
Q: conveting bytes to image using tinytag and PIL I am using tinytags module in python to get the cover art of a mp3 file and want to display or store it. The return type of the variable is showing to be bytes. I have tried fumbling around with PIL using frombytes but to no avail. Is there any method to convert the bytes to image?
from tinytag import TinyTag
tag = TinyTag.get("03. Me, Myself & I.mp3", image=True)

img = tag.get_image()

A: I actually got a PNG image when I called tag.get_image() but I guess you might get a JPEG. Either way, you can wrap it in a BytesIO and open it with PIL/Pillow or display it.  Carrying on from your code:
from PIL import Image
import io

...
im = tag.get_image()

# Make a PIL Image
pi = Image.open(io.BytesIO(im))

# Save as PNG, or JPEG
pi.save('cover.png')

# Display
pi.show()

Note that you don't have to use PIL/Pillow. You could look at the first few bytes and if they are a PNG signature (\x89PNG) save data as binary with PNG extension. If the signature is JPEG (\xff \xd8) save data as binary with JPEG extension.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i get first and last record for all users per day by date range selected I would like to get as the title states, A list of all users first and last swipe time per day, for a selected date range(this can be selected by the user). Right now I am returning every time a user swipes.
Mike Donati  2019-05-29 09:21:01.673    2019-05-29 09:21:01.673
Mike Donati  2019-05-29 09:21:10.207    2019-05-29 09:21:10.207
Mike Donati  2019-05-29 09:23:21.737    2019-05-29 09:23:21.737
Mike Donati  2019-05-29 09:23:30.430    2019-05-29 09:23:30.430
Mike Donati  2019-05-29 09:33:17.640    2019-05-29 09:33:17.640
Mike Donati  2019-05-29 09:33:21.587    2019-05-29 09:33:21.587
Mike Donati  2019-05-29 09:36:16.687    2019-05-29 09:36:16.687
Mike Donati  2019-05-29 09:36:25.083    2019-05-29 09:36:25.083
Mike Donati  2019-05-29 10:00:30.820    2019-05-29 10:00:30.820
Mike Donati  2019-05-29 10:01:07.313    2019-05-29 10:01:07.313
Mike Donati  2019-05-29 10:42:13.057    2019-05-29 10:42:13.057
Mike Donati  2019-05-29 10:42:15.410    2019-05-29 10:42:15.410
Mike Donati  2019-05-29 16:16:51.493    2019-05-29 16:16:51.493
Mike Donati  2019-05-29 16:16:57.637    2019-05-29 16:16:57.637
Mike Donati  2019-05-30 07:49:33.710    2019-05-30 07:49:33.710
Mike Donati  2019-05-30 07:51:56.003    2019-05-30 07:51:56.003
Mike Donati  2019-05-30 08:24:29.797    2019-05-30 08:24:29.797
Mike Donati  2019-05-30 08:24:38.743    2019-05-30 08:24:38.743

SELECT
     u.[FirstName] + ' ' + u.[LastName] AS EmployeeName
    ,min(e.LoggedTime) OVER(PARTITION BY e.LoggedTime) as first
    ,max(e.LoggedTime) OVER(PARTITION BY e.LoggedTime) as last

FROM [ProtegeGX].[dbo].[Users] AS u
LEFT JOIN [ProtegeGXEvents].[dbo].[Events] AS e ON e.RecordIndex1=u.UserID
LEFT JOIN [ProtegeGX].[dbo].[EventTypes] AS et on e.EventTypeID = et.EventTypeID
WHERE  e.LoggedTime Between '2019-05-29'and '2019-05-31' and u.userid = 97
GROUP BY
    u.[FirstName] + ' ' + u.[LastName]
    ,(e.LoggedTime)
ORDER BY
    u.[FirstName] + ' ' + u.[LastName]

I would like the initial swipe in time and last swipe time per day per user

user               first swipe             last swipe
Mike Donati  2019-05-29 09:21:01.673   2019-05-29 16:16:57.637
Mike Donati  2019-05-30 07:49:33.710   2019-05-30 08:24:38.743

A: Why are you using window functions, when you seem to want a simple aggregation?
SELECT u.[FirstName] + ' ' + u.[LastName] AS EmployeeName
       min(e.LoggedTime) as first
       max(e.LoggedTime) as last
FROM [ProtegeGX].[dbo].[Users] u JOIN
     [ProtegeGXEvents].[dbo].[Events] e
     ON e.RecordIndex1 = u.UserID JOIN
     [ProtegeGX].[dbo].[EventTypes] et
     on e.EventTypeID = et.EventTypeID
WHERE e.LoggedTime Between '2019-05-29' AND '2019-05-31' AND
      u.userid = 97
GROUP BY u.[FirstName] + ' ' + u.[LastName];

I changed the JOINs to inner joins, because the WHERE clause is limiting them anyway.
If you want this per day, then:
SELECT u.[FirstName] + ' ' + u.[LastName] AS EmployeeName,
       CONVERT(DATE, e.loggedTime) as theday,
       min(e.LoggedTime) as first
       max(e.LoggedTime) as last
FROM [ProtegeGX].[dbo].[Users] u JOIN
     [ProtegeGXEvents].[dbo].[Events] e
     ON e.RecordIndex1 = u.UserID JOIN
     [ProtegeGX].[dbo].[EventTypes] et
     on e.EventTypeID = et.EventTypeID
WHERE e.LoggedTime Between '2019-05-29' AND '2019-05-31' AND
      u.userid = 97
GROUP BY u.[FirstName] + ' ' + u.[LastName],
         CONVERT(DATE, e.loggedTime);


text:
Q: Kill not killing process if exiting properly I have a simple bash script which I have written to simplify some work I am doing. All it needs to do is start one process, process_1, as a background process then start another, process_2. Once process_2 is finished I then need to terminate process_1.
process_1 starts a program which does not actually stop unless it receives the kill signal, or CTRL+C when I run it myself. The program is output into a file via {program} {args} > output_file
process_2 can take an arbitrary amount of time depending on the arguments it is given.
Code:
#!/bin/bash

#Call this on exit to kill all background processes
function killJobs () {
    #Check process is still running before killing
    if kill -0 "$PID"; then
            kill $PID
    fi
}

...Check given arguments are valid...
#Start process_1
eval "./process_1 ${Arg1} ${Arg2} ${Arg3}" &
PID=$!

#Lay a trap to catch any exits from script
trap killJobs TERM INT

#Start process_2 - sleep for 5 seconds before and after
#Need space between process_1 and process_2 starting and stopping
sleep 5
eval "./process_2 ${Arg1} ${Arg2} ${Arg3} ${Arg4} 2> ${output_file}"
sleep 5

#Make sure background job is killed on exit
killJobs

I check process_1 has been terminated by checking of its output file is still being updated after my script has ended.
If I run the script and then press CTRL+C the script is terminated and process_1 is also killed, the output file is no longer updated.
If I let the script run to its completion without my intervention process_2 and the script both terminate but when I check the output from process_1 it is still being updated.
To check this I put an echo statement just after process_1 is started and another within the if statement of killJobs, so it would only be echoed if kill $PID is called.
Doing this I can see that both ways of exiting start process_1 and then also enter the if statement to kill it. Yet kill does not actually kill the process in the case of normal exit. No error messages are produced either.

A: You're backgrounding the eval instead of process_1, which sets $! to the PID of the script itself, not to process_1. Change to:
#!/bin/bash

#Call this on exit to kill all background processes
function killJobs () {
    #Check process is still running before killing
    if kill -0 "$PID"; then
            kill $PID
    fi
}
...Check given arguments are valid...

#Start process_1
./process_1 ${Arg1} ${Arg2} ${Arg3} &
PID=$!

#Lay a trap to catch any exits from script
trap killJobs TERM INT

#Start process_2 - sleep for 5 seconds before and after
#Need space between process_1 and process_2 starting and stopping
sleep 5
./process_2 ${Arg1} ${Arg2} ${Arg3} ${Arg4} 2> ${output_file}
sleep 5

#Make sure background job is killed on exit
killJobs


text:
Q: How add watermark diagonally limiting height and width according to background image specifications without losing logo quality? Question summary: My expected result is to be able to frame the watermark diagonally and regardless of the width and height of the background image, it always fits within the limits and with dimensions that maintain the quality of the logo.

In order not to lose the quality of the image that I use as a watermark, I had to readjust its size from the width of the image where I am going to paste it, but as you can see in the image that I will publish below the code, when the image has a too small height, the watermark exceeds the limits of the image.
If I need to adjust the watermark according to the width of the other image to maintain the quality, how should I go about adjusting both the height and width so that the watermark fits perfectly inside the other image regardless of its height or width?
from PIL import Image

def watermark_with_transparency(input_image_path,
                                output_image_path,
                                watermark_image_path):

    TRANSPARENCY = 20
    angle = 30

    base_image = Image.open(input_image_path)
    w_img, h_img = base_image.size

    basewidth = w_img
    watermark = Image.open(watermark_image_path)
    wpercent = (basewidth/float(watermark.size[0]))
    hsize = int((float(watermark.size[1])*float(wpercent)))
    watermark = watermark.resize((basewidth,hsize), Image.ANTIALIAS)
    watermark = watermark.rotate( angle, expand=1 )
    w_logo, h_logo = watermark.size

    center_y = int(h_img / 2)
    center_x = int(w_img / 2)
    top_y = center_y - int(h_logo / 2)
    left_x = center_x - int(w_logo / 2)

    if watermark.mode!='RGBA':
        alpha = Image.new('L', (w_img, h_img), 255)
        watermark.putalpha(alpha)

    paste_mask = watermark.split()[3].point(lambda i: i * TRANSPARENCY / 100.)
    base_image.paste(watermark, (left_x,top_y), mask=paste_mask)
    base_image.show()
    base_image.save(output_image_path)

if __name__ == '__main__':
    watermark_with_transparency(
        'jogos_de_hoje_na_tv.png',
        'watermark_create.png',
        'logo_com_transparencia.png'
        )

Current result:

I tried add doing it for the width like this:
    basehight = h_img
    hpercent = (basehight/float(watermark.size[0]))
    wsize = int((float(watermark.size[0])*float(hpercent)))

    watermark = watermark.resize((wsize,hsize), Image.ANTIALIAS)

But the result was a watermark with a lot of height and without any quality in the size adjustment.

A: I change your code like this:
def watermark_with_transparency(input_image_path,
                                output_image_path,
                                watermark_image_path):
    TRANSPARENCY = 20
    angle = 30
    base_image = Image.open(input_image_path)
    base_image.show()
    w_img, h_img = base_image.size
    basewidth = w_img
    watermark = Image.open(watermark_image_path)
    watermark = watermark.rotate(angle, expand=True)
    wpercent = (basewidth / float(watermark.size[0]))
    hpercent = h_img / float(watermark.size[1])
    if wpercent < hpercent:
        hsize = int((float(watermark.size[1]) * float(wpercent)))
        watermark = watermark.resize((basewidth, hsize), Image.ANTIALIAS)
    else:
        wsize = int((float(watermark.size[0]) * float(hpercent)))
        watermark = watermark.resize((wsize, h_img), Image.ANTIALIAS)
    w_logo, h_logo = watermark.size
    center_y = int(h_img / 2)
    center_x = int(w_img / 2)
    top_y = center_y - int(h_logo / 2)
    left_x = center_x - int(w_logo / 2)
    if watermark.mode != 'RGBA':
        alpha = Image.new('L', (w_img, h_img), 255)
        watermark.putalpha(alpha)
    paste_mask = watermark.split()[3].point(lambda i: i * TRANSPARENCY / 100.)
    base_image.paste(watermark, (left_x, top_y), mask=paste_mask)
    base_image.show()
    base_image.save(output_image_path)

The idea is that when your resize your watermark you have to check which factor (height or width) is the smallest and you want to take it. Otherwise, in your first version of the code the resizing did not take into account that the new height could be larger than the input image height.


text:
Q: Let $A \cap B = H$ and suppose that $A=a_1H \cup a_2H \cup …. \cup a_rH$ is a disjoint union. Let $A \cap B = H$ and suppose that  $A=a_1H \cup a_2H \cup …. \cup a_rH$ is a disjoint union. Prove that $AB=a_1B \cup a_2B \cup … \cup a_rB$ is a disjoint union.
The next part of the question is to write down and prove a formula for |AB|, which I can do but I am not sure how to do this part.
Further on in my notes my lecturer mentioned "the general theorem that two cosets of a subgroup either coincide or are disjoint" but doesn't state it anywhere as far as I can see, what is the more formal version of this theorem?
Thanks


text:
Q: Better way to convert string to integer I wrote this code to read a variable in a .txt file, ignore the first character and convert into a integer.It works but looks dumb, is there a better way to do this? I'm using just one string here but it's supposed to work with four.
void read(char a[])
{
    int i;
    char a1[3];
    for (i = 0; i<3; ++i){
        a1[i]= a[i+1];
    }

    int b1 = atoi(a1);
}

int main()
{
    FILE *file;
    file = fopen( "file.txt", "r");

    if (file == NULL) {
        printf( "Arquivo nao encontrado\n");
    }

    char a[4];
    fscanf(file, "%s\n",&a);

    read(a);

    return 0;
}

A: #include <stdio.h>
#include <stdlib.h>

int main(void)
{
    const char filename[] = "file.txt";
    FILE *fp = fopen(filename, "r");
    if (fp == 0)
    {
        fprintf(stderr, "Failed to open file %s for reading\n", filename);
        return(EXIT_FAILURE);
    }

    int value;

    if (fscanf(fp, "%*c%d", &value) != 1)
    {
        fprintf(stderr, "Failed to read integer value from file %s\n", filename);
        fclose(fp);
        return EXIT_FAILURE;
    }

    printf("Read %d\n", value);
    fclose(fp);

    return 0;
}

The %*c reads a single character but does not assign it.  The * to suppress an assignment is a general mechanism in the scanf()
family of functions.
Untested code.


text:
Q: R: Why this doesn't work?, matrix, rounding error? Why this works:
ncota <- 1
nslope <- 29
resul <- matrix(rep(0,ncota*nslope*4),ncota*nslope,4)

But this doesn't?
ncota <- 1
sini <- 0.1; sfin <- 1.5; spaso <- 0.05; nslope <- 1+((sfin-sini)/spaso)
resul <- matrix(rep(0,ncota*nslope*4),ncota*nslope,4)

I guess the problem is that the division gives a noninteger number.
How can I get the second one work?
I need to create a zero matrix with its size calculated from a equation calculation.
cheers

A: If all you have to do is create a matrix of zeroes, you don't need to supply the correct number of zeroes, just supply one and let R recycle it to the required length:
matrix(0, ncota*nslope, 4)

The reason the second one fails is that ncota * nslope * 4 is not exactly 116:
> (ncota * nslope * 4) == 116
[1] FALSE
> all.equal(ncota * nslope * 4, 116)
[1] TRUE

all.equal shows that these are equal if you allow for the floating point error.
?rep includes the following:
 Non-integer values of 'times' will be truncated towards zero.  If
 'times' is a computed quantity it is prudent to add a small fuzz.

and if we do as it says and add a small fuzz, rep does give the desired number of 0s:
> length(rep(0, times = ncota*nslope*4 + 0.00000001))
[1] 116

As noted by Hadley (in the comments), this fuzz can be easily added using the zapsmall function:
> length(rep(0, times = zapsmall(ncota*nslope*4)))
[1] 116

A: You don't need to use rep.  This works just fine:
resul <- matrix(0,ncota*nslope,4)


text:
Q: Arrange data frame reversed order I have a data frame which I want to order (not alphabetically) so I wrote this
z
  Grupos prueba$pendiente
1     TR         12.48182
2 TR2x45         39.87879
3     UT         20.89545
4 UT2x45         36.89015
orden
[1] "UT"     "TR"     "UT2x45" "TR2x45"
z<-arrange(z,orden)
z
  Grupos prueba$pendiente
1 TR2x45         39.87879
2 UT2x45         36.89015
3     TR         12.48182
4     UT         20.89545

dput(z)
  structure(list(Grupos = structure(c(4L, 3L, 2L, 1L), .Label = c("UT",
  "TR", "UT2x45", "TR2x45"), class = "factor"), prueba$pendiente = c(39.8787878787918,
  36.8901515151553, 12.4818181818195, 20.8954545454566)), .Names = c("Grupos",
  "prueba$pendiente"), row.names = c(NA, -4L), class = "data.frame")

Arrange function is working, the only problem is I got the wrong order (reversed) I want UT to be my first value just like in orden vector.
I'm sure it's a quite silly thing but I can't work it out.
Thank you

A: The top accepted answer doesn't work if your haven't applied factors to your data. Instead a much better general approach is to add desc() or - to your data values variable.
So in your case it would look something like:
z = arrange(z, -desc(orden))
or
z = arrange(z, -orden)
Further information and examples can be found in the source documentation

A: Add decreasing = TRUE to arrange
> arrange(z, orden, decreasing = TRUE)
##   Grupos prueba.pendiente
## 1     UT         20.89545
## 2     TR         12.48182
## 3 UT2x45         36.89015
## 4 TR2x45         39.87879

Alternatively, you could re-factor Grupos and use the order function to "subset" the order.
> z$Grupos <- factor(z$Grupos, levels = orden)
> z[order(z$Grupos), ]
##   Grupos prueba.pendiente
## 3     UT         20.89545
## 1     TR         12.48182
## 4 UT2x45         36.89015
## 2 TR2x45         39.87879

A: z[order(orden,decreasing=TRUE),]

A: you could just reverse the order of orden
arrange(z,rev(orden))

A: You can also use the simple base function match
z[match(orden, z$Grupos),]


text:
Q: Mathematical breakthroughs When I read about mathematical history I hear of breakthroughs. For example, Cartesian geometry, Newton/Leibniz Calculus, and so on. My question is this: What are some recent epoch-making breakthroughs in maths? I'm more interested in theories/new branches of maths such as cartesian geometry and calculus, rather than theorems such as Fermat's Last Theorem and the Riemann Hypothesis.
Thanks.
EDIT: By recent breakthrough's I mean anything after the complete solution to "the riddle of the quintics" by Galois.
EDIT: Examples: Use of computers in mathematics (thanks to Kieren MacMillan), combinatorics, graph theory, etc. I would also appreciate it if you could use your intuition to guess at which new branches of mathematics might appear. For example, imagine you were placed in the mathematical world pre-Newton and knew about everything that was going on at the time, I'm sure it would be possible to anticipate Calculus. Is something like that possible today?

A: I suggest category theory, not because of the investigations of more or less exotic categories, but because of how different theories are coupled together through functors and become comparable.

A: Despite knowing little about it myself, I would say the use of computer applications to develop and/or verify mathematical proofs would count.

A: Two things that happened after Galois and created new branches of mathematics:

*

*Cantor's foundations of set theory.

*The creation of functional analysis by the Polish school around Banach.

A: A lot of theory of computation (started with Turing, Von Neumann and others) brought areas of study for mathematics. An important one is Complexity Theory, which made possible to classify problems in terms of their computational difficulty.
This kind of thinking wasn't too much important before the computers arise, but today is very important and has a whole theory behind.
One of the greatest open problems in Complexity theory is the famous P versus NP.

A: Far away from my expertise but I heard that Homotopy Type Theory  may lay a new foundation to the way we analyze proofs.
(Google "The HoTT Book")

A: I suggest the rapid development in the early 20th century of game theory, largely through the work of von Neumann.  Game theory now has important applications in various fields, especially biology and economics.

A: Linear algebra applications were theoretically doable, but often completely impractical before computers could be used to speed up computation. There are probably other topics that had a good theoretical base, but the "breakthrough" of fast computation made them finally a lot more actionable.

A: I will say convex optimization. Yes, convexity has been studied for a long time, but convex optimization as a separate branch is recent. there is a lot of development in last thirty years, especially in the methods related to numerical solutions.


text:
Q: How to make form model update on blur in angular 2 Is there an equivalent to this in angular 2?
ng-model-options="{ updateOn: 'blur' }"

Thanks

A: In Angular 2 you can use the native DOM events
<input (blur)="someMethod()" />

Now, just define a method that does what you need when the field is blurred

A: Even though this is a very old thread, there is now a very neat solution which comes with Angular5.
You trigger the update on blur like this:
Tempalte driven forms:
<input [(ngModel)]="lastname" [ngModelOptions]="{ updateOn: 'blur' }">

Reactive forms:
this.nameForm = new FormGroup ({
  firstname: new FormControl('', {
    validators: Validators.required,
    updateOn: 'submit'
  }),
  lastname: new FormControl('', {
    validators: Validators.required,
    updateOn: 'submit'
  })
});

(you can select submit or blur as values)
Reference:
https://medium.com/codingthesmartway-com-blog/angular-5-forms-update-9587c3735cd3


text:
Q: Why does the attribute Height has a value * in the following context? I am learning Windows Phone 8.1 on my own. While designing I saw a piece of code somewhat like this in a website.
Can anyone explain to me why the attribute Height is given a value * instead of any numeric value in the following line??
<RowDefinition Height="*"></RowDefinition>

Full code is specified below:
<Grid x:Name="myGrid">
      <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
      </Grid.RowDefinitions>
</Grid>

A: It's called star sizing (see docs). It will distribute available space by weighted proportions.
For example:
<Grid>
    <Grid.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="FontSize" Value="20" />
            <Setter Property="Foreground" Value="Black" />
            <Setter Property="HorizontalAlignment" Value="Center" />
            <Setter Property="VerticalAlignment" Value="Center" />
        </Style>
    </Grid.Resources>

    <Grid.RowDefinitions>
        <RowDefinition Height="50" />
        <RowDefinition Height="*" />
        <RowDefinition Height="2*" />
        <RowDefinition Height="2*" />
    </Grid.RowDefinitions>

    <Border Grid.Row="0" Background="Red">
        <TextBlock>I'm 50px tall</TextBlock>
    </Border>
    <Border Grid.Row="1" Background="Lime">
        <TextBlock>I get 20% of the remaining space</TextBlock>
    </Border>
    <Border Grid.Row="2" Background="Cyan">
        <TextBlock>I get 40% of the remaining space</TextBlock>
    </Border>
    <Border Grid.Row="3" Background="Yellow">
        <TextBlock>I get 40% of the remaining space</TextBlock>
    </Border>
</Grid>


text:
Q: Задать границы окон в Windows 10 Есть желание изменить границы открытых окон в Windows 10, а именно - имеется развернутое на весь экран окно. По умолчанию в проводнике системы окно разворачивается максимально по высоте от верхней границы экрана до панели "Пуск" и максимально по ширине от левого до правого края монитора. Если панель "Пуск" переместить на левый, правый, верхний край, то, соответственно, окно подгоняется по размерам под новое расположение панели.
Есть ли возможность как-то искусственно ограничить размеры окна так, чтобы снизу экрана помещалась панель быстрого доступа типа RocketDock и, таким образом, создавалась стилистика систем MacOS, как на скриншоте
Догадываюсь, что это можно реализовать с помощью самописной программы. Тогда нужны подсказки по, если не ошибаюсь, WinApi.

A: Чтобы изменить рабочую область экрана (Working Area), вам нужно создать так называемый AppBar.
Это делается с помощью WinAPI-функции SHAppBarMessage.
Более подробно написано здесь.
Вот пример приложения на C#.
Если само окно AppBar-а вам не нужно, можно его сделать полностью прозрачным (в т.ч. для кликов мышью) с помощью расширенных стилей WS_EX_TRANSPARENT и WS_EX_LAYERED.


text:
Q: OWL Inferences With Jena (Turtle format) I'm trying to make OWL inferences with Jena. As a start, my goal is merely to infer that if an educational institution is of type dbo:EducationalInstitution, then it is also dbo:institution
Here's the java code (adapted from the jena doc) :
package test;

import org.apache.jena.util.FileManager;
import org.apache.jena.util.PrintUtil;
import org.apache.jena.rdf.model.*;
import org.apache.jena.reasoner.Reasoner;
import org.apache.jena.reasoner.ReasonerRegistry;

public class Test {
    public static void main(String[] args){
        Model schema = FileManager.get().loadModel("file:/home/mica/Downloads/sparql/ontology.ttl");
        Model data = FileManager.get().loadModel("file:/home/mica/Downloads/sparql/result.ttl");
        Reasoner reasoner = ReasonerRegistry.getOWLReasoner();
        reasoner = reasoner.bindSchema(schema);
        InfModel infmodel = ModelFactory.createInfModel(reasoner, data);

        Resource nForce = infmodel.getResource("<0762762P>");
        System.out.println(nForce);
        System.out.println("nForce *:");
        printStatements(infmodel, nForce, null, null);
}
    public static void printStatements(Model m, Resource s, Property p, Resource o) {
        for (StmtIterator i = m.listStatements(s,p,o); i.hasNext(); ) {
            Statement stmt = i.nextStatement();
            System.out.println(" - " + PrintUtil.print(stmt));
        }
    }

}

An example of my data :
@prefix dbo:  <http://dbpedia.org/ontology/> .
@prefix ex:  <http://ex.org/a#> .
@prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix xsd:  <http://www.w3.org/2001/XMLSchema#> .
@prefix dbf:  <http://fr.dbpedia.org/resource/> .
@prefix foaf:  <http://xmlns.com/foaf/0.1/> .

<0762762P>  rdf:type  dbo:Event ;
        dbo:status  "En cours" ;
        dbo:Place   _:b0 .

_:b0    dbf:Ville                   "Rouen" ;
    rdf:type dbo:EducationalInstitution ;
        foaf:name                   "Université du Havre" .

And the following ontology:
@prefix dbo:  <http://dbpedia.org/ontology/> .
@prefix ex:  <http://ex.org/a#> .
@prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#'> .
@prefix xsd:  <http://www.w3.org/2001/XMLSchema#> .
@prefix dbf:  <http://fr.dbpedia.org/resource/> .
@prefix foaf:  <http://xmlns.com/foaf/0.1/> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .

dbo:Event rdf:type owl:Class .
dbo:Place rdf:type owl:ObjectProperty ;
          rdfs:domain dbo:Event ;
          rdfs:range dbo:Event .
dbo:institution rdf:type owl:Class .
dbo:EducationalInstitution rdf:type owl:Class ;
                           rdfs:subClassOf dbo:institution .
dbo:Place rdf:type dbo:EducationalInstitution .

I'm not getting the expected results:
nForce *:

A: Your whole ontology is strange:

*

*You're reusing the DBpedia ontology in which dbo:Place is already defined as a class, but you're using it as an object property.

*Next, you declared the range of this object property to be an dbo:Event. Semantically, this also sound strange.

*You have a triple which assigns dbo:Place to be an instance of class
dbo:EducationalInstitution. That means, in the end dbo:Place is a class, a property and an individual. This is really bad modelling.

Other conventions:

*

*reusing ontologies is good, but you should not reuse the namespace but use your own namespace

*naming convention:

*

*for classes CamelCase style

*for properties lowerCamelCase style

Why don't you use a more appropriate modelling like this:
@prefix dbo:  <http://dbpedia.org/ontology/> .
@prefix ex:  <http://ex.org/a#> .
@prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#'> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .

dbo:Event rdf:type owl:Class .
ex:takesPlaceAt rdf:type owl:ObjectProperty ;
          rdfs:domain dbo:Event ;
          rdfs:range dbo:Place .
ex:Institution rdf:type owl:Class .
ex:EducationalInstitution rdf:type owl:Class ;
                           rdfs:subClassOf ex:Institution .
dbo:EducationalInstitution rdfs:subClassOf dbo:Place .

Regarding the data:
_:b0    dbf:Ville                   "Rouen" ;
    rdf:type ex:EducationalInstitution ;
        foaf:name                   "Université du Havre" .

DBpedia ontology has propertiesThat's for sure wrong.

*

*dbf:Ville is not a property but an individual. Why do you use it as a property? The Dbpedia ontology has a property dbo:city. And the resource for Rouen exists already.

Maybe you could do it like this:
@prefix dbo:  <http://dbpedia.org/ontology/> .
@prefix ex:  <http://ex.org/a#> .
@prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix xsd:  <http://www.w3.org/2001/XMLSchema#> .
@prefix dbr:  <http://dbpedia.org/resource/> .
@prefix foaf:  <http://xmlns.com/foaf/0.1/> .

<0762762P>  rdf:type  dbo:Event ;
        dbo:status  "En cours" ;
        dbo:Place   _:b0 .

_:b0    dbo:city                 http://dbpedia.org/resource/Rouen ;
    rdf:type ex:EducationalInstitution ;
        foaf:name                   "Université du Havre" .


text:
Q: Audio Code (very simple code) does not work for me

<audio id="myAudio" src="Avengers.mp3" type="audio/mpeg"></audio>
<script>
window.onload = function(){
  document.getElementById('myAudio').play()
}
</script>

Currently testing on NotePad, worked for my friend within a game, I copied just the audio code out, did not work for me..I have the mp3 file on my file, aswell as uploaded on github. Heres the link just in case.
https://raw.githubusercontent.com/JosephShin7/game-dev-2018-Joseph/master/avengers-theme.mp3
--edit I already tried with the .mp3 and on my folder I renamed it to "Avengers"--
I wouldn't have posted for such a small mistake like that..I hope..

A: <audio id="myAudio" src="Avengers.mp3" type="audio/mpeg"></audio>
<script>
window.onload = function(){
  document.getElementById('myAudio').play()
}
</script>

You have to add the file's extension in the source.


text:
Q: Using R, how to regroup multiple dataframe columns into a smaller number of new columns I am carrying out some exercises from a very good online R/bioinformatics course. To this end I am wrangling with data in the form of a 'SummarizedExperiment' object from a Bioconductor package of the same name. The rows consist of gene names and gene expression values; the columns consist of 9 ctrl (control) samples, 9 'drug1' treated samples and 9 'drug5' treated samples. Here is what the table looks like:
 The task is to regroup data in this dataframe so that CTRL0_1 - CTRL0_9 are placed in a single column, named 'CTRL0'. In the same fashion, new 'DRUG1' and 'DRUG5' named columns are needed consisting of gene expression for each gene in the columns DRUG1_1 - DRUG1_9 and DRUG5_1 - DRUG5_9, respectively. Data are derived from the final question on this webpage: https://uclouvain-cbio.github.io/WSBIM1207/sec-bioinfo.html The task is to generate a ggplot like this: Instead, with my inelegant code I get this: To generate MY plot, I used this code:
table_gene_gp_expr <- geneCol_filter_assaySeDf %>%
  pivot_longer(cols = CTRL0_1:CTRL0_9,
               names_to = "ctrl0",
               values_to = "ctrl0_expr") %>%
  pivot_longer(cols = DRUG1_1:DRUG1_9,
               names_to = "drug1",
               values_to = "drug1_expr") %>%
  pivot_longer(cols = DRUG5_1:DRUG5_9,
               names_to = "drug5",
               values_to = "drug5_expr") %>%
  pivot_longer(cols = c(ctrl0_expr, drug1_expr, drug5_expr),
               names_to = "group",
               values_to = "gene_expression") %>%
  select(gene, group, gene_expression)

I have used consecutive pivot_longer() commands, but I wonder if there is a more efficient way to generate the table below that I used for MY ggplot. Note the data in MY gggplot and the correct ggplot are different, which I can't explain. The head() of the table I used looks like this: I can post the code I wrote to generate the 'wide' dataframe of the 1st table shown if it's really needed.

A: Given sample data like this:
tibble(gene = c("gene1", "gene2"),
   CTRL0_1 = 1:2,
   CTRL0_2 = 3:4,
   DRUG1_1 = 5:6,
   DRUG1_2 = 7:8,
   DRUG5_1 = 9:10) -> test

Here are two variations of syntax for pivoting all your data columns and then splitting them up by group. You'd need a different approach if the data in those columns had different types.
test %>%
  pivot_longer(cols = -gene) %>%
  separate(name, c("group", "obs"), convert = TRUE) %>%
  pivot_wider(names_from = group, values_from = value)

test %>%
  pivot_longer(cols = -gene, names_to = c("group", "obs"), names_sep = "_") %>%
  pivot_wider(names_from = group, values_from = value)


text:
Q: How to fetch claims from the request in the .net core web api if the authentication/authorization is at API gateway level (KONG) We have:

*

*Identity server which generates JWT tokens along with custom claims based on the username and password.

*Order microservice with the endpoint "/orders" which returns the list of orders based on the claims present in the present JWT token.

*Kong gateway to handle all the requests and forward to appropriate service based on configuration.

*We have enabled JWT plugin in Kong to authorized requests (i.e validate the JWT token generated by the Identity server).

What is the best way to get the claims in the Order microservice if we have not written any logic related to authentication and authorization in the Startup class?
Thanks, Saurabh


text:
Q: Image Data Generator for images in Numpy array So I have my images in a numpy array but not in a directory. I have a final numpy array which is a 4d tensor of shape (sample, 48, 48, 1). My goal is to use keras's image data generator to convert them to (sample, 224, 224, 1). Please guide me on how to do it as so far I have seen examples of people using image data generators from the directory where they load actuall images.
I have 4 numpy arrays stored localy train_images.npy, train_labels.npy, test_images.npy and test_labels.npy.
The shape for images in these numpy is (sample, 48, 48, 1)
The shape for labels in these numpy is (sample, number of classes) as i have already converted them to keras.utils.np_utils.to_categorical method.

A: For this you should use ImageDataGenerator.flow, which takes numpy arrays directly. This replaces the flow_from_directory call, all other code using the generator should be the same.


text:
Q: Want to validate the width and height of each image in an multi-dimensional array Hello I want to validate the width and height of each image that I upload as an array. Here is my code:
$photo_temp = array();
$photo_temp = $_FILES['photo']["tmp_name"];
$photo_temp = array_values(array_filter($photo_temp));
$other_temp = $_FILES['photo']["tmp_name"];

for($i=0;$i<count($photo);$i++)
{
 foreach ($other_temp as $single_file) {
 if(!empty($single_file)) {
 $photo_temp[$single_file] = getimagesize($single_file);
 $width2 = $photo_temp[$single_file][0];
 $height2 = $photo_temp[$single_file][1];
 }
}
print_r($photo_temp);
$my_ext1 = pathinfo( $photo[$i], PATHINFO_EXTENSION );
if( $my_ext1=='jpg' || $my_ext1=='png' || $my_ext1=='jpeg' || $my_ext1=='gif' ) {
$final_name1[$m] = $z.'.'.$my_ext1;
                    move_uploaded_file($photo_temp[$i],"../assets/uploads/product_photos/".$final_name1[$m]);
$m++;
$z++;
}else if ($width2 > "300" || $height2 > "200") {
$valid = 0;
$error_message .= 'Image dimension should be within 300X200<br>';
 }
}

Here is the UI of how I'm aiming to do:
enter image description here
I want the error message to be sent if the image dimension is above 300 x 200 but the image kept on saving in the database even tho I had checked the error.


text:
Q: anova with unbalanced sample size (small sample size in one group) I'm doing an ANOVA with a 3-level categorical variable to identify covariate for later regression. The sample size of one of the group is n= 2 to 3, and the sample size for the largest group is around 100. The results suggested that there are significant difference among groups, but I just wonder if I can trust the results when one group has such small sample size?
Also, if I would like to include this categorical group variable (with 3 level) as a covariate in a regression. With one of the category has only 2 person, should I still keep this category as a separate group (when dummy coding)
Thank you!


text:
Q: Error handling when tab doesn't exist in Excel VBA `Range("P" & Sheetfind).NumberFormat = "dd mmmm yyyy"tb = Range("P" & Sheetfind).Text
Workbooks.Open Filename:="\\data\Hq\Work Returns\QC\" & Selection.Value & ".xlsx", ReadOnly:=True
Sheets(tb).Select
Workbooks(usersname & ".xlsx").Activate
Set WB2 = ActiveWorkbook
' Put stuff
Range("B2:d2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ThisWorkbook.Activate
Sheets("Prep sheet").Select
Range("B" & movedown).Select
     Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Sheetfind = Sheetfind + 1`

Hello Excel gurus
As above, I have provided code which essentially opens up a document with a name specified from a cell in Excel, and finds the tab which has the same name as the value in cell P1 (As Sheetfind is 1, defined earlier in the code) and grabs data from it. No issues here, works fine.
My issue is, I get an error if that particular sheet doesn't exist, for example if the code is looking for '14 July 2018' and that sheet wasn't created by the searched person. I can't figure out a way of cycling through date ranges in column P until it hits a match.
I thought sheetfind +1 might work, as it would go from "p1" to "p2", but I can't figure out how to do this. P2 in this instance, would be the '13 July 2018'.
Any advice is massively appreciated - thanks in advance all.

A:
While I generally advise against using this whenever possible, as it
  leads to bad coding habits of "when something doesn't work, simply
  supress it", there are some cases (usually with opening/checking
  availability of Workbooks, Worksheets, etc when it can prove
  actually useful)

On Error Resume Next 'or you can refer to a block: instead of Next

suppresses errors all together, until it receives a callback
On Error GoTo 0

which switches VBA to default Error handling.
So wrapping your entire could inside it will suppress any potential errors.

But as I mentioned, people often tend to (over)rely on the Error suppression instead of actually doing proper coding themselves.
The right mentality and question you should be asking yourself is, how can I solve this problem without needing to rely on Error handling altogther?
In many cases (this one included), we could take the easy way out and suppress any potential errors, or we can actually do some proper coding and solve the issue the proper way!

Now I found it unclear, what exactly you're trying to do from your original code snippet. I presumed that you're trying to copy-paste range B2:D2 if found, but if not, just edit the code inside the if condition

Function inArray(ByVal what As String, ByVal in_array As Variant) As Boolean
    inArray = (UBound(Filter(in_array, what)) > -1)
    ' returns true if found, otherwise false
End Function

Private Sub check_sheets()

    Dim lr As Long ' last (active) row
    lr = Sheets("default").Cells(Rows.Count, "P").End(xlUp).Row

    Dim sheetnames() As String ' create array for our sheets
    ReDim sheetnames(1 To ThisWorkbook.Sheets.Count) ' size allocation

    Dim i As Long
    For i = 1 To ThisWorkbook.Sheets.Count
        sheetnames(i) = Sheets(i).Name ' store sheetname inside array
    Next i

    Dim cell As Range ' looping through column P
    For Each cell In Sheets("default").Range("P1:P" & lr)
        If (inArray(cell.Value2, sheetnames) = True) Then
            ' worksheet found, do something...
            Sheets("default").Range("B2:D2").Copy
            Sheets(cell.Value2).Range("B2").PasteSpecial xlPasteValues
        Else
            ' worksheet not found, maybe do something...?
            MsgBox ("Sheet " & cell.Value2 & " not found!")
        End If
    Next cell

End Sub

This answer also presumes that the column P with sheetnames is in a Worksheet called "default"

In general you can see my answer has a lot of variables, but that's what happens when the question is not clearly specified, unfortunately.
 Either way, this answer should be more than sufficient with whatever you're trying to achieve :)


text:
Q: Ajax based username availability check Anyone have examples for creating a new user registration form where the web application checks for username availability via making an ajax call on the form and returning available or not on the same page without a full page post? Something similar to new user registration on Hotmail.

A: This seems to be a pretty straight forward tutorial.  There really isn't that much to it.

A: This article I wrote has a sample project. That can get you started: Membership Using ASP.NET AJAX


text:
Q: errors with an array to store random variables' values for a program of numbers sorting algorithm I'm trying to code an algorithm in c++ to sort random numbers. I've coded a function to generate the random numbers that take as parameters a variable for the number of integers and an array to store the random numbers but when I declare the array there's an error telling me that structured binding declaration cannot have a type long int and that there's an empty structured binding declaration and also that expected initializer before 'Nb_alea' that is the name of the function. I don't understand quite well the meaning of those errors.
Could you explain, please!
Here is the code :
int main()
{
cout << "Hello world!"<< endl;
long x;
cout<<"Veuillez saisir le nombre d'entiers vous souhaitez trier par ordre décroissant : "<<endl;
cin>>x;
long tab_nb_alea[x];
int y;
cout<<"1-tri rapide, 2-tri fusion, 3-tri par tas"<<endl;
cin>>y;
string chemin_acces;
cout<<"Veuillez rentrer le chemin d'accès du dossier vers lequel vous souhaitez creer et enregistrer le ficher texte : "<<endl;
cin>>chemin_acces;
Nb_alea(x, tab_nb_alea);
}

long[] Nb_alea(long x, long tab_nb_alea[])
{
int max;
max=100;
if(x==0)
{
    cout<<"Probleme, vous devez selectionner un nb superieur a 0!"<<endl;
}else if(x==1)
{
    tab_nb_alea[x]=rand()%max;
    return tab_nb_alea;
}else if(x>1)
{
    srand(time(0));
    tab_nb_alea[x]=rand()%max;
    return Nb_alea(x-1, tab_nb_alea);
    }
}

||=== Build: Release in ProjetC++037_REVEILLAUD_Elie_Juin_2021 (compiler: GNU GCC Compiler) ===|
C:\Users\elie\Documents\c\exo_listes_chainee\ProjetC++037_REVEILLAUD_Elie_Juin_2021\main.cpp|23|warning: structured bindings only available with -std=c++17 or -std=gnu++17|
C:\Users\elie\Documents\c\exo_listes_chainee\ProjetC++037_REVEILLAUD_Elie_Juin_2021\main.cpp|23|error: structured binding declaration cannot have type 'long int'|
C:\Users\elie\Documents\c\exo_listes_chainee\ProjetC++037_REVEILLAUD_Elie_Juin_2021\main.cpp|23|note: type must be cv-qualified 'auto' or reference to cv-qualified 'auto'|
C:\Users\elie\Documents\c\exo_listes_chainee\ProjetC++037_REVEILLAUD_Elie_Juin_2021\main.cpp|23|error: empty structured binding declaration|
C:\Users\elie\Documents\c\exo_listes_chainee\ProjetC++037_REVEILLAUD_Elie_Juin_2021\main.cpp|23|error: expected initializer before 'Nb_alea'|
||=== Build failed: 3 error(s), 1 warning(s) (0 minute(s), 0 second(s)) ===|

A: Like my comment says, you cannot return a C-array from a function. You have a ton of options here, and the best choice is to use std::vector. The other choices are std::array and a dynamic C-array.
Here's your code touched up to use a std::vector. I also use <random> and C++ PRNGs. They should be preferred over rand().
#include <iostream>
#include <random>  // CHANGED: Use C++ prngs over rand()
#include <string>
#include <vector>  // CHANGED: Use vector over C-array

// CHANGED: Moved function ahead of main() so code will compile
std::vector<long> Nb_alea(long size) {
  constexpr int max = 100;  // CHANGED: Condense declaration/initialization
  std::vector<long> tab_nb_alea;

  // CHANGED: Declaration of C++ prng and distribution
  static std::mt19937 prng(std::random_device{}());
  static std::uniform_int_distribution<long> range(0, max - 1);

  if (size == 0) {
    std::cout << "Probleme, vous devez selectionner un nb superieur a 0!"
              << std::endl;
  } else {
    // CHANGED: Loop to push back 'size' numbers into vector
    for (int i = 0; i < size; ++i) {
      tab_nb_alea.push_back(range(prng));
    }
  }
  return tab_nb_alea;
}

int main() {
  std::cout << "Hello world!" << std::endl;
  long x;
  std::cout << "Veuillez saisir le nombre d'entiers vous souhaitez trier par "
               "ordre décroissant : "
            << std::endl;
  std::cin >> x;
  // long tab_nb_alea[x];  // CHANGED: Not needed

  /*  CHANGED:: Commented out as it has no bearing on your question
  int y;
  std::cout << "1-tri rapide, 2-tri fusion, 3-tri par tas" << std::endl;
  std::cin >> y;
  std::string chemin_acces;
  std::cout << "Veuillez rentrer le chemin d'accès du dossier vers lequel vous "
               "souhaitez creer et enregistrer le ficher texte : "
            << std::endl;
  std::cin >> chemin_acces;
  */

  auto vec = Nb_alea(x);  // CHANGED: Because function returns vector,
                          // initialize here. Also adjusted function call to
                          // match the changed function

  // ADDED: Print vector to demonstrate it is working properly
  for (auto i : vec) {
    std::cout << i << ' ';
  }
  std::cout << '\n';
}


text:
Q: Complexification of real linear map and Hermitian metric Consider

*

*$V$ a finite dimensional real vector space with Euclidean metric $\langle|\rangle$

*$\langle|\rangle_{\mathbb{C}}$ the induced Hermitian metric on the complexification $V_{\mathbb{C}}=V\otimes\mathbb{C}$

*$f(A)$ the complex-linear extension of any real-linear map $A:V\longrightarrow V$

*$A'$ such that $\langle Av_1|v_2\rangle=\langle v_1|A'v_2\rangle$ for all $v_1,v_2\in V$

*$f(A)'$ such that $\langle f(A)w_1|w_2\rangle_{\mathbb{C}}=\langle w_1|f(A)'w_2\rangle_{\mathbb{C}}$ for $w_1,w_2\in V_{\mathbb{C}}$
I need to show that $f(A')=f(A)'$. Is it enough to show that $\langle f(A)w_1|w_2\rangle_{\mathbb{C}}=\langle w_1|f(A')w_2\rangle_{\mathbb{C}}$? How can I do that? Thanks for your help !


text:
Q: Why should I avoid this sentence "This year I am going to finish writing my book? This year, I will finish writing my book.
Avoid
This year, I am going to finish writing my book.
https://languagetool.org/insights/post/will-vs-going-to/#:~:text=In%20casual%20speech%20and%20writing,that%20have%20been%20previously%20planned
From this website you should avoid the second version
Why should I avoid the second one? Both are intentions, so both should be correct . "Going to" should even be better as it is a very near  future even more as the decision has now been made and the action  has been already planned. You can't finish a book without thinking of the end  before.


text:
Q: sed replace only lines with matching groups Currently, I have this command:
sed 's/\([^C]*\)/\1AB/'

It inserts "AB" before the first instance of "C" on a line. But it is also adding "AB" at the end of every line without a "C".
How can I have it only edit when it finds "C"?

A: What's wrong with simply replacing the C?
sed 's/C/ABC/'

This will only replace the first instance (if you wanted to replace them all, you would add g at the end).

A: You need an address filter:
sed '/C/s/\([^C]*\)/\1AB/'


text:
Q: Jquery .keyup on a dynamically added textfield How to add keyup event for dynamically added textfield.i am developing web application in drupal.when i tried to use "live",Menu's are not working
$('input[id$="-code"], input[id$="-case"], input[id$="-vehicle-no"]')
.live('keyup', function(e){
   $(this).val($(this).val().toUpperCase());
});

A: To save the mess in the code add a class to the input field you are adding dynamically so that it will be easy for you. Anyways using live will work. Check out this fiddle
http://jsfiddle.net/QugQw/1/

A: "@swordfish..in my case after "AddRow" button click,itcreates a row with four textfields.Among that "vehicle no" textfield is there.For only that particular textfield i want to add this event.How can i customize ur code according to that.."
Sounds like you are creating new rows containing the fields you are wanting to attach the keyup event to. If so, then you may have more than one element on the same page with the same ID. A big no-no.
Instead, as swordfish has suggested, add a class to the fields you wish to attach the keyup event to (using that class in the jQuery selector), and drop the id attribute, using just the name attribute instead (but not using the name attribute for the jQuery selector - you won't need it).

A: You can do it in another way also. Though it will violate "Don't Repeat Yourself". Refer to this section in jquery FAQs, problem with dynamically created elements. Instead of using live, just use .keyup() with the selector. You declare these binding again below the code where the elements are dynamically created. Use the below somewhere in the code inside $(document).ready() method.
$('input[id$="-code"], input[id$="-case"], input[id$="-vehicle-no"]')
.keyup(function(e){
$(this).val($(this).val().toUpperCase());
});

And below the code where you dynamically create those elements put the below.
$('input[id$="-code"], input[id$="-case"], input[id$="-vehicle-no"]')
.unbind('keyup').keyup(function(e){
$(this).val($(this).val().toUpperCase());
});

If other things are fine, it should work. Give it a try.

A: For new elements on JQuery you use live function. But if you are using Drupal you must use behaviors.
I really don't understand exactly your problem, but I read that you try to use live, so I think this could help http://drupal.org/node/756722#behaviors


text:
Q: how to stop components in android GUI not to overlap I am trying to make the image button fix completely on the screen and the spinner. It seems to have a problem with the weight sum and weight layout. I have tried to fix it, but haven't gotten anywhere. This is my code:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".ElderActivity"
    android:orientation="vertical"
    android:weightSum="1">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/first"
        android:background="#ffab7c74"
        android:layout_weight="1">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Smart House"
            android:id="@+id/textView"
            android:gravity="center"
            android:autoText="true"
            android:textColor="#fffff7f4" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/environment"
            android:layout_weight="1"
            android:id="@+id/imageButton" />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/law"
            android:layout_weight="1" />

    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/spinner"
            android:layout_weight="1" />
        <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/spinner1"
            android:layout_weight="1" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/consumer"
            android:layout_weight="1"/>
        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/educations"
            android:layout_weight="1"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/spinner2"
            android:layout_weight="1" />
        <Spinner
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/spinner3"
            android:layout_weight="1" />

    </LinearLayout>

</LinearLayout>

[screem shot of screen][1]: https://i.stack.imgur.com/tPFDi.jpg

A: It is very bad practice to use the weight option, especially if you have weight options in deep hierarchy of layout. For your example you need to use RelativeLayout or even TableLayout.
But if you want a mess up for your bottom part you can use tricky thing like:
    <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <View android:id="@+id/strut"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"/>

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text1"
        android:layout_alignEnd="@id/strut"
        android:layout_alignParentStart="true"
        />

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/strut"
        android:layout_alignParentEnd="true"
        android:text="@string/text2"
        />

</RelativeLayout>


text:
Q: How to ensure bootloader is started I am working with openmote-cc2538 for the project: https://github.com/cetic/6lbr/wiki
Here when I was trying to flash  openmote with this command
sudo make TARGET=cc2538dk BOARD=openmote-CC2538 bootload0/dev/ttyUSB0 slip-radio.upload

This error message is displayed
ERROR:Cant CONNECT TO TARGET:Ensure bootloader is started(no answer on sync sequence)

cc2538 bsl.py script is available for uploading binary to openmote. But I don't have much experience about this. Can anybody give me some suggestions regarding how to proceed??

A: Grab a scope and probe different digital I/O pins on the CC2538. Typically a bootloader will initialize all the ports on the chip and you will see them change state, which is an indication that the bootloader is indeed running. I would guess one of the LEDs would change state as well (which doesn't require a scope).


text:
Q: How to determine if AVCaptureDevice has focus I have successfully turned on the setSubjectAreaChangeMonitoringEnabled:
self.videoDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
[self.videoDevice lockForConfiguration:nil]; //you must lock before setting torch mode
[self.videoDevice setSubjectAreaChangeMonitoringEnabled:YES];
[self.videoDevice unlockForConfiguration];

in start method I have included the following notification:
[[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(areWeFocused:)
                                             name: AVCaptureDeviceSubjectAreaDidChangeNotification
                                           object: nil];

Then I have the areWeFocused method (which I know is wrong but I need help with it):
- (void)areWeFocused:(NSNotification *) notification {
    BOOL adjusting = [self.videoDevice isAdjustingFocus];
    if (!adjusting) {
        //NSLog(@"I have focus");
    } else {
        NSLog(@"NOT");
    }
}

If uncommented my NSLog always prints I have focus, but commenting that line I never get NOT.  How can I detect if we are in focus?  BTW:  Focus mode is AutoFocus and ContinuousAutoFocus
Thank you for your help.


text:
Q: Find the $1717$th term of the sequence of positive integers whose binary representation reads the same left to right as right to left. The question is to find the number of $1$'s in the $1717$th term.
I solved it but my method is not elegant IMO and it goes like this.
Let the number of digits in one binary representation in this pattern be $x$. Let $f(x)$ be the amount of representations having $x$ digits.
Then $f(1)=f(2)=1$, $f(3)=f(4)=2$, $f(5)=f(6)=4=2^2, f(7)=f(8)=8=2^3 \cdots \cdots$
So, $2^n$ gives the amount of the binary representations with $2n+2$ and $2n+1$ digits.
And $1+1+2+2+\cdots 2^n+2^n=2(2^{n+1}-1)$ gives the total number of the binary representations from $1$-digit representation to $2n$-digit representations.
Hence, $2(2^{n+1}-1)=1717$, so $512\le 2^{n+1}=859.5\le 1024$. That means $8\le n\le 9$.
Until $n=8$, there are altogether $2(2^9-1)=1022$ numbers, and until $n=9$ there are altogether $2046$ numbers.
So, for the $1717$th term, it corresponds to $n=9$. Since there are $1024$ terms in the case where $n=9$, which is corresponding to $512$ representations with $19$ and another $512$ representations with $20$ digits, the $1717$th term should have $20$ digits, and it is in fact the $1717-512-1022=183$th term starting from the first $20$-digit representation.
Then since every representation is symmetric, we only need to consider what is going on in the first 10 digits.
Since it must start with $1$, and for each digit, it can be either $0$ or $1$, the $k$ in $2^k<183, k\in \mathbb Z$ implies where the "highest" $1$ is other than the starting $1$.
Since $k=8$, it is 1 _ 1 _ _ _ _ _ _ _.
Then since $2^{k_1}<183-128$ that means $k_1=5$, the representation is 1 _ 1 _ _ 1 _ _ _ _.
Similarly, I finally got 1 _ 1 _ _ 1 1 _ 1 1. That means the $1717$th term will have $12$ $1$'s.
Ok now could anyone offer a more elegant method?

A: You need to find a way of calculating exactly the first half of the binary representation knowing the place, in this case $1717$. If you create the sequence of numbers that give you only the first half you find this one: A162751. There are some good properties about it, the most important one is that for $i \geq 2$ we have $a(2^i-1) = 2^{i-1}$. You could prove this by induction, having in mind that each "cycle" that we see in the sequence is just writing numbers with odd $0$ and $1$s in its binary representation first (which we know there is a particular power of $2$ of them) and after that the same repeated sequence but for ones with even number of $0$ and $1$. So you end up ending each cycle after a power of $2$, so it's natural to have a formula like the one before.
Now you can use this to obtain $a(1023) = 512$. We know the sequence of $512$ numbers after this one repeats, and we notice $1717$ is in the second half. We need to know where exactly it ends. You can see that the cycle repeats exactly in $2^i - 1 + 2^{i-1}$, in this case $i=10$ and it repeats in $1535 = 1023+512$, so $a(1535) = 512$. Until $1717$ the sequence just adds one, so $a(1717) = a(1535) + 1717-1535 = 512+182 = 694$. If you count the number of this number in binary ($1010110110$) you're counting the number of $1$ in the first half, so take that number, in this case six $1$, and double it to obtain $12$ ones.


text:
Q: How to securely upload files in Node with Express? There are many articles, tutorials, and questions about file uploads in node but mostly they are for beginners and none of them fully explains how to secure file uploads for production.
I have tried very hard to find a complete answer on how to do it, but it was not successful.
Below is an explanation of my findings.

*

*Limit file size on uploads:
app.use(express.limit('4mb'));

*Limit file uploads to only certain routes:
I can't get this to actually work but here is what I have tried:
Replace:
app.use(express.bodyParser());

with
app.use(express.json());
app.use(express.urlencoded());

and add the multipart middleware to every upload route:
app.post('/upload', express.multipart(), uploadController.uploadPhoto);

This part doesn't work, but the upload works fine if I leave express.bodyParser(). So what am I doing wrong?

*Checking uploaded file type before saving upload to disk:
I couldn't figure this part out, but a suggestion was to write a custom middleware that uses formidable to parse file uploads and trying to resize the file before it is saved (assuming that it is an image) using a library like image magic. The suggestion was that this would make the image safe and ensure that it is actually an image (because the process would fail if it is not an image).
This would only work with images though, so it is not a complete solution.
How can I implement this? Any example code?
Is there anything else that I am missing for uploads to be safe?

A: Approach 2 actually works. The problem I had was that
app.use(passport.session());

was stopping it from working. So, if you are using passport.js for authentication this might be the issue. If you use this approach just make sure to add the security on the actual route.

I ended up using this plugin

https://github.com/tih-ra/alleup

which works great with image uploads and automatically resizes the files to multiple versions and uploads them to amazon s3. Using this plugin would be inline with using approach 3, but the files are uploaded to the tmp folder first and then deleted.

A: I am using multiparty for uploading (and streaming) files.
var form = new multiparty.Form();
To 1:
form.on('progress', function (bytesReceived) {
  if (262144000 < bytesReceived) {
   abortConnection('filesizeexeeded');
  }
});

implement your own abort Connection function; e.g.:
function abortConnection(reason) {
  res.writeHead(413, { 'Connection': 'close' });
  return res.end(reason);
}

warning: the browser will most probably retry the upload (up to 4 times). I am using a websocket connection to cancel the upload on the client side.
To 2: (use multiparty)
To 3: I created a gist that shows how to check the mime-type on the fly using mmmagic.
If you are using passport in combination with multiparty you might find this useful:
https://github.com/jaredhanson/passport/pull/106#issuecomment-14188999


text:
Q: Disabled root login and no root users.. What to do? CentOs 6 So I was undoing some changes here on CentOs 6, and I ended up removing all users who had root access, accept for the root user. But then I realized the root login is disabled, and I just disabled root access for the user I am logged into.
Now I can't modify/access really any file.
What can I do from here? Through FTP it just blocks uploading.

A: You may login as root by editing Grub configuration on system boot, manual @ centos.org and login in single user mode, then you simply change what you need.
OR
Use KVM (solution in this case) :)


text:
Q: How to set an image for Cell Separator in iOS In my table view, I need to set the cell separator as an image that I have with me. How can I do this?

A: A simple solution is you can set a pattern image as cell seperator.
[tableView setSeparatorColor:[UIColor colorWithPatternImage:[UIImage imageNamed:...]]];

Or you can simply add a UIImageView in the cell content view
UIImageView *imagView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"seprater.png"]];
imgView.frame = CGRectMake(0,cell.contentView.frame.size.height - 1.0, cell.contentView.frame.size.width, 1);
[customCell.contentView addSubview:imageView];

A: Your best bet is probably to set the table's separatorStyle to UITableViewCellSeparatorStyleNone.
And manually adding/drawing a line (perhaps in tableView:cellForRowAtIndexPath:) when you want it.
In tableView:cellForRowAtIndexPath:
...
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];

    // Drawing our own separatorLine here because I need to turn it off for the
    // last row. I can only do that on the tableView and on on specific cells.
    // The y position below has to be 1 less than the cell height to keep it from
    // disappearing when the tableView is scrolled.
    UIImageView *separatorLine = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, cell.frame.size.height - 1.0f, cell.frame.size.width, 1.0f)];
    separatorLine.image = [[UIImage imageNamed:@"grayDot"] stretchableImageWithLeftCapWidth:1 topCapHeight:0];
    separatorLine.tag = 4;

    [cell.contentView addSubview:separatorLine];

    [separatorLine release];
}

// Setup default cell settings.
...
UIImageView *separatorLine = (UIImageView *)[cell viewWithTag:4];
separatorLine.hidden = NO;
...
// In the cell I want to hide the line, I just hide it.
seperatorLine.hidden = YES;

...
In viewDidLoad:
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

A: to active this put an image view at the bottom of your cell and assign an image to it .also please make sure you have set cellSeperatorStyle as None
That should work

A: {    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];}

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath
    {
         UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"<image name>"]];
        imgView.frame = CGRectMake(0, cellHeight, cellWidth, 1);
        [customCell.contentView addSubview:imgView];
         return  customCell;

     }
}

A: First of all you have to make SeparatorStyle to none by following code
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];

after that add image too the end of every cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  *)indexPath
{
     .....

     UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"seprater.png"]];
     [imgView sizeToFit];
     [Cell.contentView addSubview:imgView];

     .....

 }


text:
Q: How to Handle multiple checkbox with default value checked using state with some array of object [React-JS Typescript] i'm using multiple input checkbox for my form input in react. like image bellow:

this is some part of my code:
interface CheckType {
  id: any;
  desc: string;
  checked: boolean;
}

interface CheckListInputProps {
  options: Array<CheckType>;
  onChange: (e: React.ChangeEvent<HTMLInputElement>, data: Array<CheckType>) => void
}

const CheckListInput: React.FC<CheckListInputProps> = ({options, onChange}) => {
  const [initOpt, setInitOpt] = useState<Array<CheckType>([])

  useEffect(()=>{
    setInitOpt(options);
  },[options])

const changeHandler = (e: React.ChangeEvent<HTMLInputElement>) => {
  let {value, checked} = e.currentTarget
  let index = initOpt.findIndex(item => item.id===value);
  initOpt[index].checked = checked
  setInitOpt(initOpt)
  onChange(e, initOpt);
}

  return (

      {
        initOpt.map((item, index) => (

            <input value={item.id} checked={item.checked} onChange={changeHandler}/>
            {item.desc}

       )}

)
}

when i called this function in other file:
const ChangeHandler = (e: React.ChangeEvent<HTMLInputElement>, data: Array<any>) => {
  console.log(data);
}

const options = [
  {id: 0, desc: "GET", checked: false},
  {id: 1, desc: "POST", checked: false},
  {id: 2, desc: "DELETE", checked: false}
]

return <CheckListInput options={options} onChange={ChangeHandler}/

everything works fine. the log show what i want. but the problem is in interface the checkbox won't change into checked or unchecked. how do i fix this? is it any wrong with this checked={item.checked}


text:
Q: How to introduce multi-column constraint with JPA annotations? I am trying to introduce a multi-key constraint on a JPA-mapped entity:
public class InventoryItem {
    @Id
    private Long id;

    @Version
    private Long version;

    @ManyToOne
    @JoinColumn("productId")
    private Product product;

    @Column(nullable=false);
    private long serial;
}

Basically (product, serial) pair should be unique, but I only found a way to say that serial should be unique.  This obviously isn't a good idea since different products might have same serial numbers.
Is there a way to generate this constraint via JPA or am I forced to manually create it to DB?

A: As already answered, multi-column index can be added using @Table annotation. However, columnNames needs to be the name of actual DB columns, not the class attribute. So, if the column is like the following:
@Column(name="product_id")
Long productId;

Then the @Table annotation should be like the following
@Table(uniqueConstraints=
       @UniqueConstraint(columnNames = {"product_id", "serial"}))

A: You can declare unique constraints using the @Table(uniqueConstraints = ...) annotation in your entity class, i.e.
@Entity
@Table(uniqueConstraints={
    @UniqueConstraint(columnNames = {"productId", "serial"})
})
public class InventoryItem {
    ...
}

Note that this does not magically create the unique constraint in the database, you still need  a DDL for it to be created. But seems like you are using some sort of automated tool for creating the database based on JPA entity definitions.


text:
Q: Synchronous ADO.NET dataservices calls in Silverlight I'm using ADO.NET dataservices in a Silverlight application and since the silverlight libraries don't support the ToList() call on the IQueryable I thought it might be possible to create an extension method around this called SilverlightToList(). So in this method I'm calling the BeginExecute method on my context as shown below:
            var result = context.BeginExecute<T>(currentRequestUri,null,context);
            result.AsyncWaitHandle.WaitOne();
            return context.EndExecute<T>(result).ToList();

The problem is that when I call the WaitOne() method this results in a deadlock. Is this a limitation of ADO.NET dataservices in Silverlight? Is there perhaps a workaround for this?

A: I have managed to defeat ( :P ) the async monster in silverlight like so:
var ctx = new ModelEntities(new Uri("http://localhost:2115/Data.svc"));

ManualResetEvent m1 = new ManualResetEvent(false);
ManualResetEvent m2 = new ManualResetEvent(false);

var q1 = (DataServiceQuery<Department>)(from e in ctx.Department select e);
var q2 = (DataServiceQuery<Person>)(from e in ctx.Person select e);

Department[] r1 = null;
Person[] r2 = null;

q1.BeginExecute(r =>
{
    try { r1 = q1.EndExecute(r).ToArray(); }
    finally { m1.Set(); }
}, null);
q2.BeginExecute(r =>
{
    try { r2 = q2.EndExecute(r).ToArray(); }
    finally { m2.Set(); }
}, null);

ThreadPool.QueueUserWorkItem((o) =>
{
    WaitHandle.WaitAll(new WaitHandle[] { m1, m2 });
    // do your thing..
});

The basic ideea is to spawn a waiter thread (the last block) which would have references to the wait objects. DON'T put your WaitAll call in the caller method / thread because this will result in a deadlock as others mentioned earlier on this site or other sites.
The deadlock occurs because the threads are not starting until the method ends and the method does not end because the WaitAll call waits for the child threads to end.
Not in my case above however because the WaitAll is on ANOTHER thread.
PS : Instead of the // do your thing line place code that uses the r1 and r2 captured references which will hold the data or null if that result failed.

A: Silverlight probably isn't going to like synchronous anything, because it's intended to run in the browser, and it only can have one thread to play with - and it has to share that. And the only thread available for the host is the one provided by the browser.

A: I've since found this post on the MSDN forum which says that any managed->UnManaged->Managed marshalling happens on the UI thread which explains why the WaitOne method call is hanging...

A: All service calls in Silverlight must be asynchronous. So you have to define a callback to get the result - like this:
context.BeginExecute<T>(currentRequestUri, resultCallback, context);

private void resultCallback(IAsyncResult asyncResult)
{
    DataServiceContext context = asyncResult.AsyncState as DataServiceContext;
    var result = context.EndExecute<T>(asyncResult);
    // Do whatever you need with the result here
}

Here's a good reference at MSDN: http://msdn.microsoft.com/en-us/library/cc838191(VS.95).aspx


text:
Q: Does Angularjs really require two requests per resource? I am experimenting with Angularjs and I really like what I have seen so far. However, one thing looks strange to me: As far as I can tell, Angular requires at least 2 requests for every dynamic view created: The first for the document and the second for data using $http service.
That seems to be an incredible disadvantage for the following reasons:

*

*network latency is doubled

*the user can't see anything useful until the response to second request is preocessed

Imagine a page with a dynamicly created list of items. The first request pulls the document, the second gets the data to be dsiplayed. The user will end up with an empty list for a short period of time until the response to the second request is processed.
While it is possible to not show the list until the data is complete it is clear that the user experience will suffer from the doubled network latency. I see this as a major disadvantage over server side frameworks that deliver a document that initially contains the data.
Do I miss something here or is this a limitation 'by design'?


text:
Q: Dart, Flutter List onTap to get index of taped item i created a search delegate class and what i want sounds logically simple but i cant wrap my head around it as i am new programming
i want to get the text or maybe i should say string of the text in the listTile i tap on ,
then pass that text to the showResult of search delegate and view it in a text widget
... here is my code
import 'package:flutter/material.dart';
import 'package:schooler/style/const.dart';
//follow steps 1 - 3
class DataSearch extends SearchDelegate<String> {
  final List<String> languages = [//3.here is my list
    'dart',
    'Csharp',
    'Java',
    'JavaScript',
    'C++',
    'go ',
    'python',
    'php'
  ];

  final List<String> recentSearch = [
    'go ',
    'python',
    'php',
  ];
  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () {
          query = '';
        },
      )
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: AnimatedIcon(
        icon: AnimatedIcons.menu_arrow,
        progress: transitionAnimation,
      ),
      onPressed: () {
        close(context, null);
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return Scaffold(
      body: ListView(
        physics: BouncingScrollPhysics(),
        children: <Widget>[
          Row(
            children: <Widget>[
              CircleAvatar(),
              Text(languages[0].substring(query.length)),//2.i want to return the gotten index here
            ],
          ),
        ],
      ),
    );
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    final suggestionList = query.isEmpty
        ? recentSearch
        : languages.where((element) => element.startsWith(query)).toList();
    return ListView.builder(
      physics: BouncingScrollPhysics(),
      itemBuilder: (context, index) => ListTile(
        onTap: () {
          showResults(context); //1.when i tap the item on the listTile i want it to get the index of the taped item
        },
        leading: query.isEmpty
            ? Icon(
                Icons.history,
              )
            : Icon(Icons.search),
        title: RichText(
          text: TextSpan(
            text: suggestionList[index].substring(
              0,
              query.length,
            ),
            style: TextStyle(
              color: kBlackColor,
              fontWeight: kBold,
            ),
            children: [
              TextSpan(
                text: suggestionList[index].substring(query.length),
                style: TextStyle(color: kGreyColor),
              ),
            ],
          ),
        ),
      ),
      itemCount: suggestionList.length,
    );
  }
}

here if i tap on 'go' it should get get the text and pass it to the showResult
here is my show result ..but i just hard coded my 'list[0]index in there' i guess what i am trying to say is get the text from the item i taped and show it here

A: First lets fix your itemBuilder in your ListView so it indexes each element and then add that index into your showResults() function call so you have access to it:
ListView.builder(
      physics: BouncingScrollPhysics(),
      itemBuilder: (context, index) => ListTile( // Add index here to pass the index to the builder.
        onTap: () {
          showResults(context, index); // Add the index to function call
        },

Just be sure your showResults() function is modified to accept an int index parameter, and while I dont see that function, I am assuming it calls buildResults() at some point which needs to be modified to accept an index:
@override
  Widget buildResults(BuildContext context, int index) {
    return Scaffold(
      body: ListView(
        physics: BouncingScrollPhysics(),
        children: <Widget>[
          Row(
            children: <Widget>[
              CircleAvatar(),
              Text(languages[index].substring(query.length)),// Use the index here to return the desired text
            ],
          ),
        ],
      ),
    );
  }


text:
Q: Accessing annotation of an enum referenced by an implemented interface I am trying to access parameters of an annotation of an enum field that is referenced by an interface that is implemented by many enum classes. Something like this:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface MyAnnotation {
    String someValue();
}

interface CommonInterface {}

enum FirstEnum implements CommonInterface{
    @MyAnnotation(someValue = "abc")
    A;
}

enum SecondEnum implements CommonInterface{
    @MyAnnotation(someValue = "cde")
    B;
}

void foo(CommonInterface enumValue){
   String someValue; // get the parameter value
}

I found a way around this by adding methods to the common interface that return reflection information of the enum class, like this:
interface CommonInterface{
    Class<? extends CommonInterface> getEnumClass();
    String getName();
}

enum FirstEnum implements CommonInteface{
    @MyAnnotation(someValue = "abc")
    A;

    public Class<? extends CommonInteface> getEnumClass() {
        return getClass();
    }

    public String getName() {
        return name();
    }
}

void foo(CommonInterface enumValue){
    MyAnnotation myAnnotation = enumValue.getEnumClass().getField(enumValue.getName()).getAnnotation(MyAnnotation.class);
}

Is there a nicer way of doing the same thing? I saw some solutions where they recommend a wrapper enum class which takes the enum values referenced by the interface as constructor args. In my case that is not very feasible, because there will be many of these enums implementing the common interface and each will have many values, so maintaining it wouldn't be nice.
Thanks

A: You don't need to expose getEnumClass() via your CommonInterface, calling getClass() on the instance will always suffice. Likewise why call your method getName() why not just call it name() so it's implicitly implementation by Enum?
You can just do something like this without any methods added to CommonInterface:
void foo(CommonInterface enumValue) throws Exception {
    String name = enumValue.getClass().getMethod("name").invoke(enumValue).toString();
    MyAnnotation myAnnotation = enumValue.getClass().getField(name).getAnnotation(MyAnnotation.class);
    System.out.println(myAnnotation.someValue());
}

That's dangerous though because it assumes all implementations of CommonInterface are enums and therefore have a name() method. To make thinks "safer" in case you have a CommonInterface implementation which isn't an enum add the "name" method to CommonInterface:
interface CommonInterface {
    String name();
}

And then your "foo" method becomes:
void foo(CommonInterface enumValue) throws Exception {
    MyAnnotation myAnnotation = enumValue.getClass().getField(enumValue.name()).getAnnotation(MyAnnotation.class);
    System.out.println(myAnnotation.someValue());
}


text:
Q: iOS AVPlayer replaceCurrentItemWithPlayerItem:nil block UI Thread It seems that the api replaceCurrentItemWithPlayerItem: will stuck the main thread for some seconds, I understand that replacing the item need the information of the new item which might take some time to preload. But questions come up that why replaceCurrentItemWithPlayerItem: with a nil item object would also stuck the main thread?? It happens to me that sometimes it take more than 5 seconds to replace a nil playerItem.
I wonder what can I do to avoid the issue. Thanks for any advices!

A: I came across a similar blocking UI thread issue when I used UICollectionView to display and preview video in local photo library via ALAssetLibrary.
The scroll on switching videos is not smoothly,so I guess some method block UI thread.Then I use Core Animation of Instruments to analyze what exactly occupy the UI thread.In Time Profiler I found out that replaceCurrentItemWithPlayerItem need about 30ms to execute in main thread,which is more than 16ms (1000/60(fps)) result in choppy scrolling.
To solve the problem,first I tried that put replaceCurrentItemWithPlayerItem in to background thread using GCD,but It not work.I'm not sure if it is because the Cocoa itself need update UI when call replaceCurrentItemWithPlayerItem,which means the UI thread is still block.Finally I made it work by putting replaceCurrentItemWithPlayerItem at the scrolling end (the delegate func scrollViewDidEndDecelerating(scrollView: UIScrollView)).Now the scrolling is smoothly,yep!
Therefore,my advice is obvious : Using Instruments to analyse what exactly occupy the UI thread


text:
Q: PHP incoming webhook handling I have a 3rd party website that has webhooks that send to a specific url. I set it up to send to a blank page on my site (example: www.mysite.com/webhook.php)
I have a var_dump set up in the webhook.php that should display any information in the post or get.. I am new to webhooks and might just not understand how they work. I assume that i can have var_dump($_POST) in my php file to display an array of the HTTP request that is coming to my site.
I cannot see any requests on my site from the hook after sending test data.. any ideas?

A: I would do this to test the webhook.
<?php
$fWrite = fopen("log.txt","a");
$wrote = fwrite($fWrite, var_dump($_POST));
fclose($fWrite);
?>

This will return var_dump data in log.txt file, since as rickdenhaan said 36 mins ago, your current webhook.php return data to the webhook not your view.
You may need to create log.txt manually if you don't have right on directory (755)
I'm currently working with a payment API that use webhook. Webhook send data to X url then do action and return code to webhook. so webhook.php is the place where my order if ispaid or not is proceed or not... here what I did:
if ($payment->isPaid() == TRUE)
{
    /*
     * At this point you'd probably want to start the process of delivering the product to the customer.
     */
    $con->query("UPDATE orders SET bankno = '$bankno', status = 'paid' WHERE ordertr = '$ids'");

}
elseif ($payment->isOpen() == FALSE)
{
    /*
     * The payment isn't paid and isn't open anymore. We can assume it was aborted.
     */
    $con->query("UPDATE orders SET bankno = '$bankno', status = 'closed' WHERE ordertr = '$ids'");

}

So if order paid mark as paid in database if not mark as closed. This show webhook usage. Doing action according to what the webhook data send.

A: here is how i get content sent to my app:
$varname = json_decode(file_get_contents('php://input'));
well my content are JSON encoded, but I think this would be fine:
$varname = file_get_contents('php://input');


text:
Q: How to apply different corner radius to different corners of UIView in iOS Swift? I want to apply different corner radius value to different corners of UIView in iOS using swift. It means topLeft, topRight, bottomLeft, bottomRight corners of UIView should have different corner radiuous(i.e 1, 5, 10, 15). How can be implement it?
I tried applying cornerRadius in same way but It overrides the previous cornerRadius values.

A: If your deployment target is abouve iOS 10 then you should use maskedCorners
if #available(iOS 11.0, *) {
    customeView.clipsToBounds = true
    customeView.layer.cornerRadius = 5
    customeView.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner, .layerMaxXMinYCorner, .layerMinXMinYCorner]
}

else try this
let path = UIBezierPath(roundedRect: customeView.bounds, byRoundingCorners:[.bottomLeft, .bottomRight], cornerRadii: CGSize(width: 5, height: 5))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            customeView.layer.mask = mask


text:
Q: C# API always return Error 400 Bad Request Angular/Electron app This is my first time asking a question here.
I have a problem with my Web API server in C#.
I explain, I have an application in Angular, under Electron (not developed by me) which makes API calls.
When I start my API server, all requests return 400 error (Bad request). APIs call don't reach the code, nor the Middleware that I tried to develop. I also set the CORS to allow access to all origins or all methods. APIs run fine in a browser or with Postman.

Here it's my API server configuration. I tried a lot of different things and I don't think that's the problem.

services.AddCors(options => {
     options.AddDefaultPolicy(policy => {
           policy.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
     }
}

//...
//further in code
//...

app.UseRouting();
app.UseCors();
app.UseMiddleware(typeof(CorsMiddleware));

After several tries, I found that queries run correctly when in Chrome dev tools when I disable manual user-agent selection. In Chrome Dev', when you go to Settings -> More tools -> Network conditions. The "Select automatically" condition of the User-Agent is activated and all request return 400 (Bad Request), when I desactivate it, all requests return 200 OK.
automatic user agent selection
This is the only way for queries to run correctly. Is there a solution knowing that I don't have a hand on the Angular code. Is this blocked by Electron?
Do I need to add something in the configuration of my API server ? Maybe to open to all User-Agent ?
Thanks


text:
Q: How can I get value of char to convert to int? I want to convert binary count to decimal. My code snippet :
int main(){
    string count;
    char number;
    int counter;
    int score = 0;

    cout << "Wpisz liczbę w systemie binarnym" << endl;
    cin >> count;
    count << endl;

    counter = count.length();

    for (int i = 0; i < counter; i++)
    {
        number = count[i];
        int aaa = (int) number - '0' // is that correct ? I think not.
        score = aaa * pow(2,i) + score;
    }

    count <<wynik;
    return 0;
}

But my programm gives very strange scores, for example :
input : 100 (decimal 8)
output : 1
input 1000 (decimal 16)
output : 1
I don't know why. Can you help me ? I think, that that is the problem with char ? Am I true ?
Thanks,
Sorry for my Englosh

A: Give this a try:
int main(){
    string liczba;
    int licznik;
    int wynik = 0;

    cout << "Wpisz liczb w systemie binarnym" << endl;
    cin >> liczba;

    licznik = liczba.length();

    for (int i = 0; i < licznik; i++)
    {
        int aaa = liczba[i] -'0'; // A bit hacky way to convert char to int
        wynik += aaa * pow(2.0,licznik - i - 1); // Minus 1 to get the correct power
    }
    cout << wynik;
    return 0;
}

Not sure where you got count from in your code, but I assume you actually meant cout.
See this question for more on char conversion.
Also, as others have pointed out, when reading the chars out of a string starting with a 0 index, you'll be pulling out binary digits of decreasing significance. That means your exponent should be decreasing, not increasing.
Edit: I also noticed in your question you are reading binary incorrectly:

input : 100 (decimal 8) output : 1
  input 1000 (decimal 16) output : 1

100 is 4, not 8. Likewise, 1000 is 8, not 16. Perhaps you're forgetting 2^0, or the 1's digit?

A: Another way is to get rid of the pow which involves cast to the from double.
int main(){
    string liczba;
    int licznik;
    int wynik = 0;

    cout << "Wpisz liczb w systemie binarnym" << endl;
    cin >> liczba;

    licznik = liczba.length();

    for (int i = 0; i < licznik; i++)
    {
        int aaa = liczba[i] -'0'; // A bit hacky way to convert char to int
        wynik *= 2;   // shift existing total up a power of 2 (could use << 1)
        wynik += aaa; // Add the next digit
    }
    cout << wynik;
    return 0;
}


text:
Q: Why can I call function which is not exported in sub-shell? I am learning bash. In my current understanding, I need to export function to use it in sub-shell. However, I can call a function which is not exported in sub-shell. I would like to know why or how non-exported function works in sub-shell. The test code is following,
file name : level1.sh
#!/bin/bash
function level_1_func {
  echo "function 1: $1, PID=${BASHPID}"
}

file name : level0.sh
#!/bin/bash
# *** If you don't load level1.sh before this function or script,
# *** level_1_func in this function causes an error of "command not found"
function level0_func {
  echo "function 0: $1, PID=${BASHPID}"
  level_1_func "inside level0_func"
}

top.sh
source "./level0.sh"

# *** Error in level0_func : "level_1_func: command not found."
# *** It is because level1.sh has not been loaded.
level0_func "in the current shell"

# *** Here it loads level1.sh. After this lines,
# *** it can call level_1_func even in sub-shell.
# *** (definition of function is exported automatically?)
source "./level1.sh"

out_puts="$(level0_func "in the sub shell")"
echo "${out_puts}"

Output of "bash top.sh" is following
function 0: in the current shell, PID=7575
./level0.sh: line 7: level_1_func: command not found
function 0: in the sub shell, PID=7577
function 1: inside level0_func, PID=7577

A: A subshell was invoked by the command substitution, but this subshell has the same context as the current shell. You need to invoke bash explicitly to create a new context.
out_puts="$(bash -c level0_func level0_func "in the sub shell")"

A: This is not just the case with functions, but with everything else in the environment, including shell options, and even local variables.
For example:
 3.2: ~$ foo=42
 3.2: ~$ set|grep foo
 foo=42
 3.2: ~$ echo $(set|grep foo)
 foo=42
 3.2: ~$ bash -c set|grep foo
 3.2: ~$

Here is an example using a shell option:
3.2: ~$ set -o nounset
3.2: ~$ echo $(set -o|grep nounset)
nounset on
3.2: ~$ bash -c 'set -o|grep nounset'
nounset         off

The term "sub-shell" is overused, often inaccurately.  When you create a "true" sub-shell then bash makes a copy of the current process, so everything is copied (a fork action).  When you create a new process it basically destroys (an exec type action) anything that is not in the environment block, i.e. exported (other things are also retained from the original process, such as the user and group id, current directory, etc.).