问:
How to push all git repo's from a directory to git in a shellscript
I am trying to write a bash script that finds new repo's and files and commit & push them all, and future git repo's that i add to my projects folder.

All my git projects are stored in a folder i have on my system for simplicity.

The problem i am facing is that whenever i try and use a 1 liner to find all .git folders and run commands on them it fails to do all the 3 git commands on the folders that need it(add, commit, push)

I have tried to run different versions of the script, some with & at git push and some with && but it still only adds and commits the repo's with changes but it dont push them.

I also tried making it into a function to make it run on as an individual command but i still get error messages all over the place.

My script looks like this:

```<code># Location of all my github projects
mygit=$HOME/github/myrepos

addcompush="git add . && git commit -a -m "Uploaded by script, no commit msg" & git push"

# Find all git repo folders and run git add + git commit + git push on them
find "$mygit" -name ".git" -type d -exec bash -c "echo '{}' && cd '{}'/.. && $(addcompush)" \;
</code>```

I also tried diffrent versions of this as explained above:

```<code>find "$mygit" -name ".git" -type d -exec bash -c "echo '{}' && cd '{}'/.. && git add . && git commit -a -m "uploaded by script" && git push" \;
</code>```

This does the git add and commit but it does not push them, my suspicion is that it is due to the &&. But i am totaly lost as of how to fix this.

Do i need to restructure my entire way of approaching this or can i make this work as is?

答:
Posting my own solution here, not the most elegant solution but it works. The way i see it atm the find command breaks if there is nothing to commit in 1 folder.

Hence i found it to be better to make a script that deals with execution in a much more straight forward way that a 1 liner.

```<code># Location of the git folder collection
mygitfolder=$HOME/github/myrepos

# Loop through all folders and place the names in an array
git_folders=()
while IFS= read -r line; do
    git_folders+=( "$line" )
  done< <(ls ~/github/myrepos/)

# Loop through the array and run the commands needed to automaticly push a repo to github,
# git add, commit, push(IF commit executed sucsessfully meaning it was something to commit in that folder)
for folder in "${git_folders[@]}"
do
   cd "$mygitfolder/$folder"; printf "\n\nChecking the $folder repo "
   git add .
   git commit -a -m "Uploaded by script, no commit msg added"
   if [[ $? -eq 0 ]]; then
     git push
   fi
done
</code>```

Body:
I am trying to write a bash script that finds new repo's and files and commit & push them all, and future git repo's that i add to my projects folder.

All my git projects are stored in a folder i have on my system for simplicity.

The problem i am facing is that whenever i try and use a 1 liner to find all .git folders and run commands on them it fails to do all the 3 git commands on the folders that need it(add, commit, push)

I have tried to run different versions of the script, some with & at git push and some with && but it still only adds and commits the repo's with changes but it dont push them.

I also tried making it into a function to make it run on as an individual command but i still get error messages all over the place.

My script looks like this:

# Location of all my github projects
mygit=$HOME/github/myrepos

addcompush="git add . && git commit -a -m "Uploaded by script, no commit msg" & git push"

# Find all git repo folders and run git add + git commit + git push on them
find "$mygit" -name ".git" -type d -exec bash -c "echo '{}' && cd '{}'/.. && $(addcompush)" \;

I also tried diffrent versions of this as explained above:

find "$mygit" -name ".git" -type d -exec bash -c "echo '{}' && cd '{}'/.. && git add . && git commit -a -m "uploaded by script" && git push" \;

This does the git add and commit but it does not push them, my suspicion is that it is due to the &&. But i am totaly lost as of how to fix this.

Do i need to restructure my entire way of approaching this or can i make this work as is?

Body:
Posting my own solution here, not the most elegant solution but it works. The way i see it atm the find command breaks if there is nothing to commit in 1 folder.

Hence i found it to be better to make a script that deals with execution in a much more straight forward way that a 1 liner.

# Location of the git folder collection
mygitfolder=$HOME/github/myrepos

# Loop through all folders and place the names in an array
git_folders=()
while IFS= read -r line; do
    git_folders+=( "$line" )
  done< <(ls ~/github/myrepos/)

# Loop through the array and run the commands needed to automaticly push a repo to github,
# git add, commit, push(IF commit executed sucsessfully meaning it was something to commit in that folder)
for folder in "${git_folders[@]}"
do
   cd "$mygitfolder/$folder"; printf "\n\nChecking the $folder repo "
   git add .
   git commit -a -m "Uploaded by script, no commit msg added"
   if [[ $? -eq 0 ]]; then
     git push
   fi
done


来源: stackexchange

问:
confusion related to implicit contructors and constructor chaining
As per constructor chaining base constructor should be called when a derived class object is created and assigned to base class reference.
And there is no default constructor in base class but then there is an explicit parameterized constructor, so java compiler does not provide default constroctor.
Without the statement "this(10);" compiler complains but then as soon as its added, compiler is fine with it. WHY??

I mean why does it not try to call the base class default constructor after adding "this(10);". It should have done a super call and then executed the added statement.

```<code>class Parent{
    public Parent(int a) {
        System.out.println(a);
    }
}
class Child extends Parent{
    public Child(){
        this(10);//default value
    }
    public Child(int a) {
        super(a);
        System.out.println(a);
    }
}
</code>```

答:
The Java Language Specification (§12.5) defines what happens when you create a new instance; I highlighted the most important parts for your question.

If this constructor begins with an explicit constructor invocation (§8.8.7.1) of another constructor in the same class (using this), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason; otherwise, continue with step 5.

This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using this). If this constructor is for a class other than Object, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (using super). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4.

So, the key points are:

Your first constructor explicitly invokes the second constructor, so step 2 above applies; the second constructor is executed, and then step 3 is skipped.

Step 3 is where the superclass constructor gets called, so that means when a constructor invokes another constructor from the same class, then it does not directly invoke a superclass constructor.

However, if you delete this(10); from the first constructor, then the first constructor does not invoke another constructor of the same class, so step 3 applies, and a superclass constructor is implicitly invoked. This causes an error because there is no superclass constructor that can be implicitly invoked (with no arguments).

ContentLicense: CC BY-SA 4.0

Body:
As per constructor chaining base constructor should be called when a derived class object is created and assigned to base class reference.
And there is no default constructor in base class but then there is an explicit parameterized constructor, so java compiler does not provide default constroctor.
Without the statement "this(10);" compiler complains but then as soon as its added, compiler is fine with it. WHY??

I mean why does it not try to call the base class default constructor after adding "this(10);". It should have done a super call and then executed the added statement.

class Parent{
    public Parent(int a) {
        System.out.println(a);
    }
}
class Child extends Parent{
    public Child(){
        this(10);//default value
    }
    public Child(int a) {
        super(a);
        System.out.println(a);
    }
}


问:
Split array into different size chunks (4, 3, 3, 3, 4, 3, 3, 3, etc)
I have an array like so: [1, 2, 3, 4, 5, 6, 7, 9, 10]. I need to chunk it into different size chunks, yet with a simple pattern of: 4, 3, 3, 3, 4, 3, 3, 3 like so:

```<code>[
    [ // four
        1,
        2,
        3,
        4
    ],
    [ // three (1/3)
        5,
        6,
        7
    ],
    [ // three (2/3)
        8,
        9,
        10
    ],
    [ // three (3/3)
        11,
        12,
        13
    ],
    [ // four
        14,
        15,
        16,
        17
    ],
    [ // three (1/3)
        18,
        19,
        20
    ], // and so on..
]
</code>```

I have tried with this code I have customized:

```<code>const arr; // my array of values
const chuncked = arr.reduce((acc, product, i) => {
    if (i % 3) {
        return acc;
    } else if (!didFourWayReduce) {
        didFourWayReduce = true;
        fourWayReduces++;

        if ((fourWayReduces - 1) % 2) { // only make every second a "4 row"
            return [...acc, arr.slice(i, i + 3)];
        } else {
            return [...acc, arr.slice(i, i + 4)];
        }
    } else {
        didFourWayReduce = false;
        return [...acc, arr.slice(i, i + 3)];
    }
}, []);
</code>```

And it works, almost, expect that the first chunk of threes (1/3) have the last element of the chunk with 4. So 1 key is repeated every first chunk of three. Like so:

```<code>[
    [
        1,
        2,
        3,
        4
    ],
    [
        4, // this one is repeated, and it shouldn't be
        5,
        6
    ]
]
</code>```

答:
This answer is similar to that of Nina Scholz, but uses a for loop, which I personally find more clear.

const arr = Array.from({length: 100}, (_, i) => i + 1);
const sizes = [4, 3, 3, 3];
const result = [];

for (let i = 0, j = 0; i < arr.length; i += sizes[j], j = (j + 1) % sizes.length) {
  result.push(arr.slice(i, i + sizes[j]));
}

console.log(result);```

Body:
I have an array like so: [1, 2, 3, 4, 5, 6, 7, 9, 10]. I need to chunk it into different size chunks, yet with a simple pattern of: 4, 3, 3, 3, 4, 3, 3, 3 like so:

[
    [ // four
        1,
        2,
        3,
        4
    ],
    [ // three (1/3)
        5,
        6,
        7
    ],
    [ // three (2/3)
        8,
        9,
        10
    ],
    [ // three (3/3)
        11,
        12,
        13
    ],
    [ // four
        14,
        15,
        16,
        17
    ],
    [ // three (1/3)
        18,
        19,
        20
    ], // and so on..
]

I have tried with this code I have customized:

const arr; // my array of values
const chuncked = arr.reduce((acc, product, i) => {
    if (i % 3) {
        return acc;
    } else if (!didFourWayReduce) {
        didFourWayReduce = true;
        fourWayReduces++;

        if ((fourWayReduces - 1) % 2) { // only make every second a "4 row"
            return [...acc, arr.slice(i, i + 3)];
        } else {
            return [...acc, arr.slice(i, i + 4)];
        }
    } else {
        didFourWayReduce = false;
        return [...acc, arr.slice(i, i + 3)];
    }
}, []);

And it works, almost, expect that the first chunk of threes (1/3) have the last element of the chunk with 4. So 1 key is repeated every first chunk of three. Like so:

[
    [
        1,
        2,
        3,
        4
    ],
    [
        4, // this one is repeated, and it shouldn't be
        5,
        6
    ]
]


问:
Sort list of alphanumeric strings
I have a list of strings, each of which will something like ';2234661;E3006345_2234661_FRONT_Image_Container;\n' that I need to sort. Each string will start with a semi-colon and different numbers, but I need them all to be sorted according to the image angle (ex. FRONT, BACK, LEFT) in a non-alphabetical order following this ranking:
FRONT
BACK
LEFT
RIGHT
INGREDIENTS
INSTRUCTIONS
INFO
NUTRITION
PRODUCT

Example Input:

```<code>[';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']
</code>```

Desired Output

```<code>[';2234661;FRONT;', ';2234661;BACK;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;INGREDIENTS;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;', ';2234661;NUTRITION;', ';2234661;PRODUCT;']
</code>```

Here is my code, based off of the solution to a similar issue I found here on stackexchange. However, it returns the error "ValueError: substring not found

```<code>galleryImages = [';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']

alphabet = 'FBLRINP'

newGallery = sorted(galleryImages, key=lambda word: [alphabet.index(c) for c in word])

print(newGallery)
</code>```

Title: Sort list of alphanumeric strings

Body:
I have a list of strings, each of which will something like ';2234661;E3006345_2234661_FRONT_Image_Container;\n' that I need to sort. Each string will start with a semi-colon and different numbers, but I need them all to be sorted according to the image angle (ex. FRONT, BACK, LEFT) in a non-alphabetical order following this ranking:
FRONT
BACK
LEFT
RIGHT
INGREDIENTS
INSTRUCTIONS
INFO
NUTRITION
PRODUCT

Example Input:

[';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']

Desired Output

[';2234661;FRONT;', ';2234661;BACK;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;INGREDIENTS;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;', ';2234661;NUTRITION;', ';2234661;PRODUCT;']

Here is my code, based off of the solution to a similar issue I found here on stackexchange. However, it returns the error "ValueError: substring not found

galleryImages = [';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']

alphabet = 'FBLRINP'

newGallery = sorted(galleryImages, key=lambda word: [alphabet.index(c) for c in word])

print(newGallery)

Body:
Try this..

>>> my_list = [';2234661;PRODUCT;', ';2234661;FRONT;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;BACK;', ';2234661;INGREDIENTS;', ';2234661;NUTRITION;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;']

>>> my_sorting_logic  = ['FRONT', 'BACK', 'LEFT', 'RIGHT', 'INGREDIENTS', 'INSTRUCTIONS', 'INFO', 'NUTRITION', 'PRODUCT']

Sort on the basis of key's index

>>> sorted(my_list, key = lambda x : my_sorting_logic.index(x.split(';')[2]))

Output :

[';2234661;FRONT;', ';2234661;BACK;', ';2234661;LEFT;', ';2234661;RIGHT;', ';2234661;INGREDIENTS;', ';2234661;INSTRUCTIONS;', ';2234661;INFO;', ';2234661;NUTRITION;', ';2234661;PRODUCT;']


问:
randomize observations by groups (blocks)
I have a data frame with I obsevations, and each observation belongs to one of g categories.

```<code>set.seed(9782)
I <- 500
g <- 10
library(dplyr)

anon_id <- function(n = 1, length = 12) {
  randomString <- c(1:n)
  for (i in 1:n)
  {
    randomString[i] <- paste(sample(c(0:9, letters, LETTERS),
                                    length, replace = TRUE),
                             collapse = "")
  }
  return(randomString)
}

df <- data.frame(id = anon_id(n = I, length = 16),
                 group = sample(1:g, I, T))
</code>```

I want to randomly assign each observation to one of J "urns", given some vector of probabilities p. That is the probability of being assign to urn J=1 is p[1]. The added complexity is that I want to do this block by block.

If I ignore the blocks, I can do this easily:

```<code>J <- 3
p <- c(0.25, 0.5, 0.25)
df1 <- df %>% mutate(urn = sample(x = c(1:J), size = I, replace = T, prob = p))
</code>```

I thought about this method to do it by "block"

```<code># Block randomization
randomize_block <- function(g) {
  df1 <- df %>% filter(group==g)
  size <- nrow(df1)
  df1 <- df1 %>% mutate(urn = sample(x = c(1:J),
                                     size = size,
                                     replace = T,
                                     prob = p))
  return(df1)

}

df2 <- lapply(1:g, randomize_block)
df2 <- data.table::rbindlist(df2)
</code>```

Is there a better way?

答:
randomizr::block_ra does exactly what you want.  </p>

```<code>library(randomizr)
library(janitor) #just for the tabyl function

block_rand <-  as.tibble(randomizr::block_ra(blocks = df$group, conditions = c("urn_1","urn_2","urn_3")))

df2 <- as.tibble(bind_cols(df, block_rand))

df2 %>% janitor::tabyl(group, value)
</code>```

Body:
I have a data frame with I obsevations, and each observation belongs to one of g categories.

set.seed(9782)
I <- 500
g <- 10
library(dplyr)

anon_id <- function(n = 1, length = 12) {
  randomString <- c(1:n)
  for (i in 1:n)
  {
    randomString[i] <- paste(sample(c(0:9, letters, LETTERS),
                                    length, replace = TRUE),
                             collapse = "")
  }
  return(randomString)
}

df <- data.frame(id = anon_id(n = I, length = 16),
                 group = sample(1:g, I, T))

I want to randomly assign each observation to one of J "urns", given some vector of probabilities p. That is the probability of being assign to urn J=1 is p[1]. The added complexity is that I want to do this block by block.

If I ignore the blocks, I can do this easily:

J <- 3
p <- c(0.25, 0.5, 0.25)
df1 <- df %>% mutate(urn = sample(x = c(1:J), size = I, replace = T, prob = p))

I thought about this method to do it by "block"

# Block randomization
randomize_block <- function(g) {
  df1 <- df %>% filter(group==g)
  size <- nrow(df1)
  df1 <- df1 %>% mutate(urn = sample(x = c(1:J),
                                     size = size,
                                     replace = T,
                                     prob = p))
  return(df1)

}

df2 <- lapply(1:g, randomize_block)
df2 <- data.table::rbindlist(df2)

Is there a better way?

Body:
randomizr::block_ra does exactly what you want.

library(randomizr)
library(janitor) #just for the tabyl function

block_rand <-  as.tibble(randomizr::block_ra(blocks = df$group, conditions = c("urn_1","urn_2","urn_3")))

df2 <- as.tibble(bind_cols(df, block_rand))

df2 %>% janitor::tabyl(group, value)


问:
Angular 8 fails to read response from a request if there was a large blob in it
I'm developing an API that has an endpoint to update a table with a large blob (15MB or so), this api updates the table then responds with a JSON.

When this endpoint receives a small blob (a few bytes), angular can read the JSON and show the result to the user. If this endpoint receives a large blob, it seems the whole request fails, as firefox shows in the console:

I don't think it is a CORS problem because all other requests I make to this server are OK, even this request is OK if the blob is small enough.

I am usgin Angular 8, Python 3 (with Flask) and Mysql, but I don't think it is a problem with the database or server side configuration (for example max_allowed_packet or innodb_log_file_size for mysql and client_max_body_size for nginx) because the server receives those exact same files in the insert endpoint and everything is fine.
If I save a 15MB file it is successful, but if I try to update that file with another file with the exact same size, then the error appears.

Another thing that makes me believe the problem is not on the server side is that nginx access log shows only successful requests (all responded with code 200)

So I think the problem can only be Angular, but since it works if the blob is small, I have absolutely no idea where the problem could be.

Here is the service that makes the request: (insert works fine with all sizes of blobs, update only with small blobs)

```<code>export class documentService {

    constructor(private http: HttpClient, private toastr: ToastrService) { }

    insert(file:File, tags:Tag[], permitions:User[], extraFields:any, type:string){
        const formData = new FormData();
        formData.append('tags', JSON.stringify(tags));
        formData.append('permitions', JSON.stringify(permitions));
        formData.append('binary_data', file);
        formData.append('extraFields', JSON.stringify(extraFields))

        return this.http.post<Resposta>(SERVER+"/document/"+type, formData, {"reportProgress": true})
    }

    update(file:File, tags:Tag[], permitions:Usuario[], docId, extraFields:any, type:string){
        const formData = new FormData();
        formData.append('tags', JSON.stringify(tags));
        formData.append('permitions', JSON.stringify(permitions));
        formData.append('binary_data', file);
        formData.append('extraFields', JSON.stringify(extraFields))
        return this.http.put<Resposta>(SERVER+"/document/"+type+"/"+docId, formData, {"reportProgress": true})
    }
}
</code>```

here is the part of the component that uses the above service:

```<code>this.docService.update(file, tags, permitions, this.doc.id,this.doc, TYPES.INTERNAL).subscribe( r => {
    if(!r.error){
        this.setEditMode(false)
        this.hide()
    }
})
</code>```

And I also have an interceptor:

```<code>export class ApiInterceptor implements HttpInterceptor {
    constructor(private toastr: ToastrService, private progress: ShowProgressService) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        let newHeaders = { 'Authorization': localStorage.getItem('jwt') || ""}
        const cloneReq = req.clone({
            setHeaders: newHeaders
        });

        return next.handle(cloneReq).pipe(
            tap((event: any)=>{
                if(event.body && event.body.msg && event.body.error!=undefined){
                    if(event.body.error){
                        this.toastr.error(event.body.msg)
                    } else{
                        this.toastr.success(event.body.msg)
                    }
                }

                // shows upload progress
                if(event.type === HttpEventType.UploadProgress){
                    let percentDone = Math.round((100 * event.loaded) / event.total);
                    this.progress.showUpload(percentDone)

                }

                if(event.type === HttpEventType.DownloadProgress){
                    let percentDone = Math.round((100 * event.loaded) / event.total);
                    this.progress.showDownload(percentDone)
                }

            })
        );
    }
}
</code>```

Edit 1 - OPTIONS Request:

Request:

```<code>Host: url
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0
Accept: */*
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: authorization
Referer: http://url/dashboard
Origin: http://url
DNT: 1
Connection: keep-alive
</code>```

Response:

```<code>HTTP/1.1 200 OK
Server: nginx/1.10.3
Date: Thu, 13 Feb 2020 20:30:39 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 0
Connection: keep-alive
Allow: GET, HEAD, PUT, OPTIONS, DELETE
Access-Control-Allow-Origin: http://url
Vary: Origin
Access-Control-Allow-Headers: authorization
Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT
</code>```

答:
Based on your OPTIONS response added, it looks like you're not correctly setting the Access-Control-Allow-Origin header in the server's response to the CORS OPTIONS request.

Try setting Access-Control-Allow-Origin: * in your server's response to see if CORS is the issue, then replace the * wildcard with the appropriate origin you'll be using to prevent potentially malicious cross origin requests

Body:
I'm developing an API that has an endpoint to update a table with a large blob (15MB or so), this api updates the table then responds with a JSON.

When this endpoint receives a small blob (a few bytes), angular can read the JSON and show the result to the user. If this endpoint receives a large blob, it seems the whole request fails, as firefox shows in the console:

I don't think it is a CORS problem because all other requests I make to this server are OK, even this request is OK if the blob is small enough.

I am usgin Angular 8, Python 3 (with Flask) and Mysql, but I don't think it is a problem with the database or server side configuration (for example max_allowed_packet or innodb_log_file_size for mysql and client_max_body_size for nginx) because the server receives those exact same files in the insert endpoint and everything is fine.
If I save a 15MB file it is successful, but if I try to update that file with another file with the exact same size, then the error appears.

Another thing that makes me believe the problem is not on the server side is that nginx access log shows only successful requests (all responded with code 200)

So I think the problem can only be Angular, but since it works if the blob is small, I have absolutely no idea where the problem could be.

Here is the service that makes the request: (insert works fine with all sizes of blobs, update only with small blobs)

export class documentService {

    constructor(private http: HttpClient, private toastr: ToastrService) { }

    insert(file:File, tags:Tag[], permitions:User[], extraFields:any, type:string){
        const formData = new FormData();
        formData.append('tags', JSON.stringify(tags));
        formData.append('permitions', JSON.stringify(permitions));
        formData.append('binary_data', file);
        formData.append('extraFields', JSON.stringify(extraFields))

        return this.http.post<Resposta>(SERVER+"/document/"+type, formData, {"reportProgress": true})
    }

    update(file:File, tags:Tag[], permitions:Usuario[], docId, extraFields:any, type:string){
        const formData = new FormData();
        formData.append('tags', JSON.stringify(tags));
        formData.append('permitions', JSON.stringify(permitions));
        formData.append('binary_data', file);
        formData.append('extraFields', JSON.stringify(extraFields))
        return this.http.put<Resposta>(SERVER+"/document/"+type+"/"+docId, formData, {"reportProgress": true})
    }
}

here is the part of the component that uses the above service:

this.docService.update(file, tags, permitions, this.doc.id,this.doc, TYPES.INTERNAL).subscribe( r => {
    if(!r.error){
        this.setEditMode(false)
        this.hide()
    }
})

And I also have an interceptor:

export class ApiInterceptor implements HttpInterceptor {
    constructor(private toastr: ToastrService, private progress: ShowProgressService) {}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        let newHeaders = { 'Authorization': localStorage.getItem('jwt') || ""}
        const cloneReq = req.clone({
            setHeaders: newHeaders
        });

        return next.handle(cloneReq).pipe(
            tap((event: any)=>{
                if(event.body && event.body.msg && event.body.error!=undefined){
                    if(event.body.error){
                        this.toastr.error(event.body.msg)
                    } else{
                        this.toastr.success(event.body.msg)
                    }
                }

                // shows upload progress
                if(event.type === HttpEventType.UploadProgress){
                    let percentDone = Math.round((100 * event.loaded) / event.total);
                    this.progress.showUpload(percentDone)

                }

                if(event.type === HttpEventType.DownloadProgress){
                    let percentDone = Math.round((100 * event.loaded) / event.total);
                    this.progress.showDownload(percentDone)
                }

            })
        );
    }
}

Edit 1 - OPTIONS Request:

Request:

Host: url
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0
Accept: */*
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: authorization
Referer: http://url/dashboard
Origin: http://url
DNT: 1
Connection: keep-alive

Response:

HTTP/1.1 200 OK
Server: nginx/1.10.3
Date: Thu, 13 Feb 2020 20:30:39 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 0
Connection: keep-alive
Allow: GET, HEAD, PUT, OPTIONS, DELETE
Access-Control-Allow-Origin: http://url
Vary: Origin
Access-Control-Allow-Headers: authorization
Access-Control-Allow-Methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT


问:
Why can't SnowSQL 1.2.2 find a version to download?
First thing I do after unpacking the SnowSQL Linux client is try to upgrade it. This has worked very well through at least v1.1.84. Today I downloaded v1.2.2, installed it, and got an error:

```<code>$ ~/bin/snowsql -Uv
No snowsql is available for download: url=https://sfc-repo.snowflakecomputing.com/snowsql, version=1.2
</code>```

The error comes from this download. Has something changed? I get the same error even when I just try to use it with no options at all, or trying to connect by passing my account code and username.

答:
The curl above was missing https and hence gave the wrong impression of 403 forbidden.

Some times due to a caching issue with the downloads it will not autoupgrade. There are two main components, one being bootstrap and the other one being the main snowsql component. The one you see the issue with is the main component (it is auto-downloaded when you run snowsql).

You can force new version download using snowsql -v 1.2.2 as an exmaple.

You can delete/move the .snowsql directory (~/.snowsql or ~/bin/.snowsql) to ensure a new main component version is downloaded by the new bootstrap.

You may also try using the newer versions for which the rpm is available at

https://sfc-repo.snowflakecomputing.com/snowsql/bootstrap/1.2/linux_x86_64/index.html

Body:
First thing I do after unpacking the SnowSQL Linux client is try to upgrade it. This has worked very well through at least v1.1.84. Today I downloaded v1.2.2, installed it, and got an error:

$ ~/bin/snowsql -Uv
No snowsql is available for download: url=https://sfc-repo.snowflakecomputing.com/snowsql, version=1.2

The error comes from this download. Has something changed? I get the same error even when I just try to use it with no options at all, or trying to connect by passing my account code and username.


问:
How to create a loop 1M with random numbers >100000
My teacher asked me to create a loop that will be executed 1M times.
I tried for(long i=0;i<1000000;i++), but the program is crashing. The maximum number that the program accepts is 10.000.

Any ideas? Is this possible?

Also he asked me to create a random number >100.000. I am using rand();. Should I use a different method?

this is the code:

```<code>start_time = clock();
for(long i=0;i<1000000;i++){
   num1 = rand();
   num2=rand();
   gcd1(num1,num2);
}

end_time = clock();

elapsed_time = (end_time - start_time) / CLOCKS_PER_SEC;

printf( "time is %.3f seconds\n", elapsed_time );
system("pause");
</code>```

This the gcd:

```<code>int gcd1(int x, int y){
    int z;
    if (x<y)
        z=x+1;
    else if (y<x)
        z=y+1;
    do{
        z=z-1;
    }
    while((x%z!=0) or (y%z!=0));
        return z;
    }
}
</code>```

答: There is nothing wrong with having a loop that runs from 0 to 1000000. The reason that your program is crashing is something else that you are doing in your program.</p>

ContentLicense: CC BY-SA 3.0

Body:
My teacher asked me to create a loop that will be executed 1M times.
I tried for(long i=0;i<1000000;i++), but the program is crashing. The maximum number that the program accepts is 10.000.

Any ideas? Is this possible?

Also he asked me to create a random number >100.000. I am using rand();. Should I use a different method?

this is the code:

start_time = clock();
for(long i=0;i<1000000;i++){
   num1 = rand();
   num2=rand();
   gcd1(num1,num2);
}

end_time = clock();

elapsed_time = (end_time - start_time) / CLOCKS_PER_SEC;

printf( "time is %.3f seconds\n", elapsed_time );
system("pause");

This the gcd:

int gcd1(int x, int y){
    int z;
    if (x<y)
        z=x+1;
    else if (y<x)
        z=y+1;
    do{
        z=z-1;
    }
    while((x%z!=0) or (y%z!=0));
        return z;
    }
}


问:
Nested tables in email
So, I'm totally losing my mind with an email that I'm trying to format.

I think it has to do with a particular nested table.

The main table is 650px wide and the width of the nested table is set to 100%.

What's happening is that, as soon as I plug in the nested tables, the header and footer images are being reduced by 20px(10+10) on the right side(despite both images being 650 pixels wide).

When I modify the nested tables to make the cellspacing on both sides of the nested tables =0(originally 10px on both sides i.e. 20px in total), then the header and footer images line up correctly but, assuming the cellspacing is set to 10 px on each side of the nested table, then the header and footer images get reduced.

Why is the nested table cellspacing affecting my table header and footer images?

```<code>    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>2020 Preferred Share Outlook with Fiera Capital</title>
<style type="text/css">
<!--
html, body {
    font-family: Arial, Helvetica, sans-serif;
    color: #444;
    font-size: 17px;
    line-height:30px;
    background-color: #FAFAFA;
}
img {
    border:none;
}
sup, sub {
  vertical-align: baseline;
  position: relative;
  top: -0.4em;
}

.disclaimer {
    font-family: Arial, Helvetica, sans-serif;
    color: #666;
    font-size: 12px;
    line-height:16px;
}
.title {
    color: #F60;
    font-weight: bold;
    font-size: 18px;
    line-height: 25px;
}
.title2 {
    color: #F60;
    font-weight: bold;
    font-size: 14px;
    line-height: 20px;
}

a:link {
    color: #F60;
}
a:visited {
    color: #F60;
}
a:hover {
    color: #F60;
}
a:active {
    color: #77881c;
}
.orange {
    color: #F60;
}
.disclaimer{
padding:15px;
    }
.table_data {
    font-size: 9px;
    font-family: Arial, Helvetica, sans-serif;
    border-color: #FDFDFD;
    line-height:12px;
}
.disclaimer1 {  font-family: Arial, Helvetica, sans-serif;
    color: #666;
    font-size: 11px;
    line-height:16px;
}
.details {
    font-size: 13px;
    line-height:20px;
}
-->
</style>
</head>

<body style="margin: 0;">
<table width="101%" height="100%">
  <tr>
    <td><table width="650" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
      <tr>
            <td width="650">
                <img src="https://www.horizonsetfs.com/horizons/media/emails/2020/202002_FieraWebinar/Email_Header.png" alt="2020 Preferred Share Outlook with Fiera Capital" style="border:none"/>
            </td>
       </tr>
       <tr>
          <td align="left" style="padding: 15px 20px 20px 20px;">
            <p class="title">Get the Latest Outlook from Fiera Capital on the Canadian Preferred Shares and Fixed Income Markets</p>
            <p>The Canadian preferred share market has bounced back from its lows in Q3 2019. But Fiera Capital believes there is still significant potential upside left in this asset class, since preferred shares offer higher relative yields compared to bonds, and should have less pressure from new issuances in 2020.</p>
            <p>Fiera Capital’s Nicolas Normandeau, lead portfolio manager for the <a href="http://www.horizonsetfs.com/hpr">Horizons Active Preferred Share ETF (HPR)</a> and the <a href="http://www.horizonsetfs.com/hfp">Horizons Floating Rate Preferred Share ETF (HFP)</a>, will outline his team’s outlook for Canadian preferred shares in 2020, and why he feels they remain a potentially attractive option for Canadian fixed income investors.</p>
            <p><a href="https://attendee.gotowebinar.com/register/6491065155959682573?" target="_blank"><img src="http://horizonsetfs.com/horizons/media/emails/common-images/register_en.png" alt="Register for the webinar Now" style="border:none"/></a></p>

            <table width="100%" cellspacing="10" cellpadding="10" border="0">
                <tbody>
                    <tr>
                        <td width="50%" bgcolor="#EEEEEE"><br><span class="title"><strong>Advisors and Investors Bullish in New Decade<br>
                            <a href="https://www.horizonsetfs.com/sentimentsurvey" target="_blank"><br>
                            <img src="https://www.horizonsetfs.com/horizons/media/emails/2020/202002_FieraWebinar/Sentiment-Survey.jpg" alt="Sentiment Survey Results" style="border:none"></a><br>
                            </strong></span><br>
                            <a href="https://www.horizonsetfs.com/sentimentsurvey" target="_blank">Did you miss our Q1 2020 Sentiment Survey Results?</a> See where Canadian advisors and investors stand on 14 different indices and asset classes, ranging from the NASDAQ-100® to Gold Bullion.<br> <p>Stay tuned for our Q2 2020 Sentiment Survey in March – you could win a $150 Amazon gift card!</p>
                        </td>
                        <td width="" bgcolor="#EEEEEE">
                            <span class="title"><strong>Just Launched: Three New Total Return ETFs</strong></span><br>
                            <a href="https://www.horizonsetfs.com/news/Press-Release/Horizons-ETFs-Launches-Three-New-Total-Return-ETFs" target="_blank"><br>
                            <img src="https://www.horizonsetfs.com/horizons/media/emails/2020/202002_FieraWebinar/Market-Open-pic.png" alt="Launch of new Total Return ETFs" style="border:none"></a><br>
                            On February 6, 2020, Horizons ETFs launched three new ETFs: <a href="https://www.horizonsetfs.com/etf/hulc">HULC</a>, <a href="https://www.horizonsetfs.com/etf/hsav">HSAV</a>, as well as <a href="https://www.horizonsetfs.com/etf/hxcn">HXCN</a>. With $1 billion in seed capital, HXCN is the largest ETF launch in Canadian history. <a href="https://www.horizonsetfs.com/news/Press-Release/Horizons-ETFs-Launches-Three-New-Total-Return-ETFs" target="_blank">Learn more about our new total return ETFs</a> <br> <br> <br> <br>
                        </td>
                    </tr>
                </tbody>
            </table>

            <table width="100%" border="0" cellpadding="0">
                <tbody>
                    <tr>
                    <td width="30%">
                        <img src="https://www.horizonsetfs.com/horizons/media/emails/2020/202002_FieraWebinar/Nicolas-Normandeau.png" alt="Nicolas Normandeau, CFA®, M.SC." style="border:none"/><span class="orange"><strong>Nicolas Normandeau</strong></span>
                        <br>
                        <strong><span style="font-size: 12px;">CFA®, M.SC. – Vice-President and Portfolio Manager, Fixed Income, Fiera Capital</span></strong>
                    </td>
                    <td width="70%">
                        <em>Nicolas Normandeau is a member of Fiera Capital’s Corporate Fixed Income team and a portfolio manager for the firm’s Corporate Fixed Income strategy with 10 years of industry experience. Fiera Capital is one of Canada’s largest managers of fixed income investments and is the sub-advisor for many of <a href="https://www.horizonsetfs.com/horizons/media/pdfs/library/ActiveIncomeETFs_EN.pdf" target="_blank">Horizons ETFs’ fixed income funds.</a></em>
                    </td>
                    <br>
                    </tr>
                </tbody>
            </table>

          </td>
        </tr>

       <tr>
          <td width="650"><img src="https://www.horizonsetfs.com/horizons/media/emails/common-images/footer_en.jpg" alt="Horizons Exchange Traded Funds" /></td>
       </tr>
       <tr>
           <td class="disclaimer"><p class="disclaimer1">*Plus  applicable sales taxes.</p>
             <p class="disclaimer1">Commissions, management fees and expenses all  may be associated with an investment in exchange traded products managed by  Horizons ETFs Management (Canada) Inc. (the "Horizons Exchange Traded  Products"). The Horizons Exchange Traded Products are not guaranteed,  their values change frequently and past performance may not be repeated. The  prospectus contains important detailed information about the Horizons Exchange  Traded Products. <strong>Please read the  relevant prospectus before investing.</strong></p>
             <p class="disclaimer1">Certain statements may constitute a forward looking statement, including those identified by the expressions “anticipate”, “estimate” or “expect” and similar expressions (including grammatical variations thereof) to the extent they relate to the ETFs or Horizons ETFs. The forward-looking statements are not historical facts but reflect the ETFs, the ETF’s managers or Horizons ETFs current expectations regarding future results or events. These forward-looking statements are subject to a number of risks and uncertainties that could cause actual results or events to differ materially from current expectations. These and other factors should be considered carefully and readers should not place undue reliance on the ETFs’ forward looking statements. These forward-looking statements are made as of the date hereof and the ETFs do not undertake to update any forward-looking statement that is contained herein, whether as a result of new information, future events or otherwise, unless required by applicable law.</p>
             <p class="disclaimer1"><sup>1</sup>Horizons Total Return ETFs  (“Horizons Total Return ETFs”) are generally index-tracking ETFs that use an  innovative investment structure known as a Total Return Swap to deliver the  returns of an underlying benchmark in a low-cost and tax-efficient manner.  Unlike a physical replication ETF that typically purchases the securities found  in the relevant benchmark in the same proportions as the benchmark, most  Horizons Total Return ETFs use a synthetic structure that never buys the  securities of a benchmark directly. Instead, the ETF receives the total return  of the benchmark through entering into a Total Return Swap agreement with one  or more counterparties, typically large financial institutions, which will  provide the ETF with the total return of the benchmark in exchange for the  interest earned on the cash held by the ETF. Any distributions which are paid  by the benchmark’s constituents are reflected automatically in the net asset  value (NAV) of the ETF. As a result, the Horizons Total Return ETF receives the  total return of the benchmark (before fees), which is reflected in the ETF’s  share price, and investors are not expected to receive any taxable  distributions. Certain Horizons Total Return ETFs use physical replication  instead of a total return swap, which includes HULC and HSAV. The Horizons Cash  Maximizer ETF does not track a traditional benchmark but rather a compounding  rate of interest paid on a cash deposit that can change over time.</p>
             <p class="disclaimer1">In the past you have provided Horizons ETFs with your email address or your email address is publicly available. You will receive brief news announcements regarding our ETFs and related topics. If you no longer wish to receive these announcements, you may unsubscribe by <a href="%%email_preference_center%%" target="_blank">clicking here</a> and updating your user preferences.</p>
             <p class="disclaimer1"><a href="http://www.horizonsetfs.com/legal/Privacy-of-information" target="_blank">Click here to read our Privacy Policy.</a></p>
             <p class="disclaimer1">Horizons ETFs Management (Canada) Inc.<br />
55 University Avenue, Suite 800<br />
Toronto, Ontario, M5J 2H7</p></td>
        </tr>
  </table></td>
  </tr>
</table>
</body>
</html>
</code>```

答:
Thanks for that Facundo!

Only problem with that approach is that that it strips out the padding on the entire body copy (which is fairly easily added back via a class)

Is there another way to achieve this result?

Title: Nested tables in email

Body:
So, I'm totally losing my mind with an email that I'm trying to format.

I think it has to do with a particular nested table.

The main table is 650px wide and the width of the nested table is set to 100%.

What's happening is that, as soon as I plug in the nested tables, the header and footer images are being reduced by 20px(10+10) on the right side(despite both images being 650 pixels wide).

When I modify the nested tables to make the cellspacing on both sides of the nested tables =0(originally 10px on both sides i.e. 20px in total), then the header and footer images line up correctly but, assuming the cellspacing is set to 10 px on each side of the nested table, then the header and footer images get reduced.

Why is the nested table cellspacing affecting my table header and footer images?

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>2020 Preferred Share Outlook with Fiera Capital</title>

Get the Latest Outlook from Fiera Capital on the Canadian Preferred Shares and Fixed Income Markets

The Canadian preferred share market has bounced back from its lows in Q3 2019. But Fiera Capital believes there is still significant potential upside left in this asset class, since preferred shares offer higher relative yields compared to bonds, and should have less pressure from new issuances in 2020.

Fiera Capital’s Nicolas Normandeau, lead portfolio manager for the Horizons Active Preferred Share ETF (HPR) and the Horizons Floating Rate Preferred Share ETF (HFP), will outline his team’s outlook for Canadian preferred shares in 2020, and why he feels they remain a potentially attractive option for Canadian fixed income investors.

Advisors and Investors Bullish in New Decade

                            Did you miss our Q1 2020 Sentiment Survey Results? See where Canadian advisors and investors stand on 14 different indices and asset classes, ranging from the NASDAQ-100® to Gold Bullion.

Stay tuned for our Q2 2020 Sentiment Survey in March – you could win a $150 Amazon gift card!

                            Just Launched: Three New Total Return ETFs

                            On February 6, 2020, Horizons ETFs launched three new ETFs: HULC, HSAV, as well as HXCN. With $1 billion in seed capital, HXCN is the largest ETF launch in Canadian history. Learn more about our new total return ETFs

                        Nicolas Normandeau

                        CFA®, M.SC. – Vice-President and Portfolio Manager, Fixed Income, Fiera Capital

                        Nicolas Normandeau is a member of Fiera Capital’s Corporate Fixed Income team and a portfolio manager for the firm’s Corporate Fixed Income strategy with 10 years of industry experience. Fiera Capital is one of Canada’s largest managers of fixed income investments and is the sub-advisor for many of Horizons ETFs’ fixed income funds.

*Plus  applicable sales taxes.

Commissions, management fees and expenses all  may be associated with an investment in exchange traded products managed by  Horizons ETFs Management (Canada) Inc. (the "Horizons Exchange Traded  Products"). The Horizons Exchange Traded Products are not guaranteed,  their values change frequently and past performance may not be repeated. The  prospectus contains important detailed information about the Horizons Exchange  Traded Products. Please read the  relevant prospectus before investing.

Certain statements may constitute a forward looking statement, including those identified by the expressions “anticipate”, “estimate” or “expect” and similar expressions (including grammatical variations thereof) to the extent they relate to the ETFs or Horizons ETFs. The forward-looking statements are not historical facts but reflect the ETFs, the ETF’s managers or Horizons ETFs current expectations regarding future results or events. These forward-looking statements are subject to a number of risks and uncertainties that could cause actual results or events to differ materially from current expectations. These and other factors should be considered carefully and readers should not place undue reliance on the ETFs’ forward looking statements. These forward-looking statements are made as of the date hereof and the ETFs do not undertake to update any forward-looking statement that is contained herein, whether as a result of new information, future events or otherwise, unless required by applicable law.

1Horizons Total Return ETFs  (“Horizons Total Return ETFs”) are generally index-tracking ETFs that use an  innovative investment structure known as a Total Return Swap to deliver the  returns of an underlying benchmark in a low-cost and tax-efficient manner.  Unlike a physical replication ETF that typically purchases the securities found  in the relevant benchmark in the same proportions as the benchmark, most  Horizons Total Return ETFs use a synthetic structure that never buys the  securities of a benchmark directly. Instead, the ETF receives the total return  of the benchmark through entering into a Total Return Swap agreement with one  or more counterparties, typically large financial institutions, which will  provide the ETF with the total return of the benchmark in exchange for the  interest earned on the cash held by the ETF. Any distributions which are paid  by the benchmark’s constituents are reflected automatically in the net asset  value (NAV) of the ETF. As a result, the Horizons Total Return ETF receives the  total return of the benchmark (before fees), which is reflected in the ETF’s  share price, and investors are not expected to receive any taxable  distributions. Certain Horizons Total Return ETFs use physical replication  instead of a total return swap, which includes HULC and HSAV. The Horizons Cash  Maximizer ETF does not track a traditional benchmark but rather a compounding  rate of interest paid on a cash deposit that can change over time.

In the past you have provided Horizons ETFs with your email address or your email address is publicly available. You will receive brief news announcements regarding our ETFs and related topics. If you no longer wish to receive these announcements, you may unsubscribe by clicking here and updating your user preferences.

Click here to read our Privacy Policy.

Horizons ETFs Management (Canada) Inc.

55 University Avenue, Suite 800

Toronto, Ontario, M5J 2H7


问:
Makefile rule with multiple targets for single invocation
According to the gnu make documentation, if a rule generates multiple targets by a single invocation (for instance with a recipe executing a tool with multiple output files), you can use the '&:' rule syntax to tell make.
I'm getting warnings when using this syntax, about target '&', however, when having multiple (but unique) targets in multiple rules. As if make mistakes the ampersand for a target name instead of being part of the target-prerequisite separator.

In my original project I've got two rules having multiple targets and a recipe generating those targets from a single statement/tool. The targets are unique for each of the two rules. I've created the following simple example to demonstrate the warning generated by make:

```<code>all: file_abbc

.PHONY: all clean

clean:
    del /Q file_*

file_abbc: file_ab file_bc
    copy file_ab+file_bc file_abbc

file_ab file_bc &: file_a file_b file_c
    copy file_a+file_b file_ab
    copy file_b+file_c file_bc

file_a file_b file_c &: content
    copy content file_a
    copy content file_b
    copy content file_c
</code>```

Warnings from running make on Windows on the above:

Makefile:17: warning: overriding recipe for target '&'

Makefile:13: warning: ignoring old recipe for target '&'

Why is make complaining about target '&' ?

答: You're using an old version of GNU make that doesn't understand &: rules, so just treats & as a file name. Use make --version to see which version you are running and upgrade if it is older that 4.3

Body:
According to the gnu make documentation, if a rule generates multiple targets by a single invocation (for instance with a recipe executing a tool with multiple output files), you can use the '&:' rule syntax to tell make.
I'm getting warnings when using this syntax, about target '&', however, when having multiple (but unique) targets in multiple rules. As if make mistakes the ampersand for a target name instead of being part of the target-prerequisite separator.

In my original project I've got two rules having multiple targets and a recipe generating those targets from a single statement/tool. The targets are unique for each of the two rules. I've created the following simple example to demonstrate the warning generated by make:

all: file_abbc

.PHONY: all clean

clean:
    del /Q file_*

file_abbc: file_ab file_bc
    copy file_ab+file_bc file_abbc

file_ab file_bc &: file_a file_b file_c
    copy file_a+file_b file_ab
    copy file_b+file_c file_bc

file_a file_b file_c &: content
    copy content file_a
    copy content file_b
    copy content file_c

Warnings from running make on Windows on the above:

Makefile:17: warning: overriding recipe for target '&'

Makefile:13: warning: ignoring old recipe for target '&'

Why is make complaining about target '&' ?


问:
When can I consider a RTCPeerConnection to be disconnected?
I'm attempting to detect when the other side of a RTCPeerConnection has disconnected. Currently I'm doing the following with my RTCPeerConnection object:

```<code>rtcPeerConnection.oniceconnectionstatechange = () => {
        const state = rtcPeerConnection.iceConnectionState;

        if (state === "failed" || state === "closed") {
            // connection to the peer is lost and unsalvageable, run cleanup code
        } else if (state === "disconnected") {
            // do nothing in the "disconnected" state as it appears to be a transient
            // state that can easily return to "connected" - I've seen this with Firefox
        }
    };
</code>```

This seems to work in my limited testing with very simply network conditions but the following from MDN gives me pause that it's probably not going to hold up in production:

Of course, "disconnected" and "closed" don't necessarily indicate errors; these can be the result of normal ICE negotiation, so be sure to handle these properly (if at all).

Should I instead be using RTCPeerConnection.onconnectionstatechange and considering the connection permanently closed if RTCPeerConnection.connectionState is "closed", "failed" or "disconnected"?

答:
The specification has very carefully crafted advice on that topic:

Performing an ICE restart is recommended when iceConnectionState transitions to "failed". An application may additionally choose to listen for the iceConnectionState transition to "disconnected" and then use other sources of information (such as using getStats to measure if the number of bytes sent or received over the next couple of seconds increases) to determine whether an ICE restart is advisable.

See the spec and the PR that added this

Mind you that due to bugs Chrome no longer goes to "failed" in unified plan. "closed" can only happen if your code calls pc.close() so is no longer fired in iceconnectionstatechange as of Chrome 80.

Body:
I'm attempting to detect when the other side of a RTCPeerConnection has disconnected. Currently I'm doing the following with my RTCPeerConnection object:

rtcPeerConnection.oniceconnectionstatechange = () => {
        const state = rtcPeerConnection.iceConnectionState;

        if (state === "failed" || state === "closed") {
            // connection to the peer is lost and unsalvageable, run cleanup code
        } else if (state === "disconnected") {
            // do nothing in the "disconnected" state as it appears to be a transient
            // state that can easily return to "connected" - I've seen this with Firefox
        }
    };

This seems to work in my limited testing with very simply network conditions but the following from MDN gives me pause that it's probably not going to hold up in production:

Of course, "disconnected" and "closed" don't necessarily indicate errors; these can be the result of normal ICE negotiation, so be sure to handle these properly (if at all).

Should I instead be using RTCPeerConnection.onconnectionstatechange and considering the connection permanently closed if RTCPeerConnection.connectionState is "closed", "failed" or "disconnected"?


问:
How to run the test classes in particular order using SeleniumWebDriver(Java) with TestNG?
I want to run the Selenium WebDriver (Java) test classes in the particular order using TestNG.

For eg. I have 3 classes such as Test1, Test2 and Test3. I want to run in the order Test2, Test1 and Test3. Is it possible without grouping?

I tried the following way, but I runs in its own order (Alphabetical order).

```<code><suite name="MyTestSuite" verbose="4">

<test name="MyTest">
   <classes>
        <class name="com.mypackage.Test2" />
        <class name="com.mypackage.Test1" />
        <class name="com.mypackage.Test3" />
   </classes>
</test>
</code>```

Is there any other way to do this? Without grouping is this possible?

答:
Try this test plan(.xml)</p>

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
  <suite name="MyTestSuite" preserve-order="true">
     <test name="MyTest">
        <classes>
             <class name="com.mypackage.Test2"> </class>
        </classes>
    </test>
    <test name="MyTest 1">
       <classes>
          <class name="com.mypackage.Test1"> </class>
        </classes>
    </test>
    <test name="MyTest 2">
        <classes>
          <class name="com.mypackage.Test3"> </class>
        </classes>
    </test>
</suite>
</code>```

Body:
I want to run the Selenium WebDriver (Java) test classes in the particular order using TestNG.

For eg. I have 3 classes such as Test1, Test2 and Test3. I want to run in the order Test2, Test1 and Test3. Is it possible without grouping?

I tried the following way, but I runs in its own order (Alphabetical order).

<suite name="MyTestSuite" verbose="4">

<test name="MyTest">
   <classes>
        <class name="com.mypackage.Test2" />
        <class name="com.mypackage.Test1" />
        <class name="com.mypackage.Test3" />
   </classes>
</test>

Is there any other way to do this? Without grouping is this possible?

Body:
Try this test plan(.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
  <suite name="MyTestSuite" preserve-order="true">
     <test name="MyTest">
        <classes>
             <class name="com.mypackage.Test2"> </class>
        </classes>
    </test>
    <test name="MyTest 1">
       <classes>
          <class name="com.mypackage.Test1"> </class>
        </classes>
    </test>
    <test name="MyTest 2">
        <classes>
          <class name="com.mypackage.Test3"> </class>
        </classes>
    </test>
</suite>


问:
In PHP: what is the difference between "return", "yield", "yield from" and mixing both yield and return in same function?
The difference between return and yield seemed clear until I figured out there was also yield from and the possibility to combine both return and yield in the very same function!

My understanding of return was that everything after was not executed, right?

However:

```<code>function generate(): iterable {
    return [1, 2, 3];
}

foreach (generate() as $value) {
    echo $value;
}
</code>```

Produces: "123"

But the following:

```<code>function generate(): iterable {
    return [1, 2, 3];
    yield;
}

foreach (generate() as $value) {
    echo $value;
}
</code>```

Produces nothing! So that means yield is executed?

Is this a bug?

答:
Return

Simply gives back a unique value to the caller.

Yield

Transform the current function/method to return a Generator, which will produce more than a unique value: every times yield is triggered, it gives the value to the caller, one at a time, traditionally using a foreach loop.

Yield + Return

Generators, in addition to generate values, can also, provide a unique returned value. That value won't be part of the looping around the generator, it must be accessed using Generator::getReturn() method.

Return + Yield

This could be seen as a bug, however, it is not.

They are two phases:

From code to bytecode: during this phase, the generate() function is seen to contain the yield keyword, it is therefore marked as producing a Generator.

Execution: Because the return happens to be before the yield, the generator doesn't have the chance to produce any value. However, the [1, 2, 3] array can be retrieved with Generator::getReturn().

A complete annotated example:

```<code>// Generate integers 1 and 2
function generateIntegers1And2(): Generator {
    yield 1;                                  // <--+   <--+   <--+
    yield 2;                                  //  <-+    <-+    <-+
}                                             //    |      |      |
                                              //    |      |      |
foreach (generateIntegers1And2() as $value) { //    |      |      |
    var_dump($value); // Shows 1, then 2          ->*      |      |
}                                                       // |      |
                                                        // |      |
function generateOuterYield(): Generator {              // |      |
    // Yields the generator *itself* returned by           |      |
    // generateIntegers1And2() not the actual values       |      |
    // generated by it.                                    |      |
    // This means we are producing here a generator        |      |
    // of generator of integers.                           |      |
    yield generateIntegers1And2();          // <-+         |      |
}                                             // |         |      |
                                              // |         |      |
foreach (generateOuterYield() as $value) {    // |         |      |
    var_dump($value);                       // ->*         |      |
    // The two levels of imbrication means we have         |      |
    // to loop once more to actually consume               |      |
    // generateIntegers1And2                               |      |
    foreach ($value as $val) {                          // |      |
        var_dump($val); // Shows 1, then 2               ->*      |
    }                                                          // |
}                                                              // |
                                                               // |
// A generator can just be returned as-is:                        |
function generateOuterReturn(): Generator {                    // |
    return generateIntegers1And2();                            // |
}                                                              // |
                                                               // |
// it doesn't change the way it is consumed                       |
foreach (generateOuterReturn() as $value) {                    // |
    var_dump($value); // Shows 1, then 2                          |
}                                                              // |
                                                               // |
function generateOuterYieldFrom(): Generator {                 // |
    // First yield values generated by generateIntegers1And2()    |
    yield from generateIntegers1And2();                        // *<---+
    // then yield integers 3                                           |
    yield 3;                                                     // <--+
    // and 4                                                           |
    yield 4;                                                     //  <-+
}                                                                //    |
                                                                 //    |
foreach (generateOuterYieldFrom() as $value) {                   //    |
    var_dump($value); // Shows 1, 2, 3 and 4                         ->*
}

function generateIntegers56AndReturn(): Generator {
    yield 5;                                                  // <---+
    yield 6;                                                  //  <--+
                                                              //     |
    return ["five", "six"];                       // <--+            |
}                                                 //    |            |
                                                  //    |            |
$gen = generateIntegers56AndReturn();             //    |            |
                                                  //    |            |
// Consume the values **yielded** by                    |            |
// generateIntegers56AndReturn()                        |            |
foreach ($gen as $value) {                        //    |            |
    var_dump($value); // Shows 5, then 6                |          ->*
}                                                 //    |
                                                  //    |
// Access the value **returned** by the generator       |
var_dump($gen->getReturn());                      //  ->*

function wtf(): Generator {
    return ["W", "T", "F", "!"];
    // Without the following line, PHP would complain with a TypeError:
    // Return value of wtf() must be an instance of Generator, array returned.
    // The presence of a yield keyword anywhere inside the function makes it a Generator.
    // However, since we return *before* reaching any *yield*, 42 is never yielded.
    // This is empty generator!
    yield 42;
}

$gen = wtf();

// This foreach loop is not entered!
foreach ($gen as $value) {
    var_dump($value);
}

// However, we can loop on the array *returned* by wtf():
foreach ($gen->getReturn() as $value) {
    echo $value; // Will print: WTF!
}
</code>```

Body:
The difference between return and yield seemed clear until I figured out there was also yield from and the possibility to combine both return and yield in the very same function!

My understanding of return was that everything after was not executed, right?

However:

function generate(): iterable {
    return [1, 2, 3];
}

foreach (generate() as $value) {
    echo $value;
}

Produces: "123"

But the following:

function generate(): iterable {
    return [1, 2, 3];
    yield;
}

foreach (generate() as $value) {
    echo $value;
}

Produces nothing! So that means yield is executed?

Is this a bug?

Body:
Return

Simply gives back a unique value to the caller.

Yield

Transform the current function/method to return a Generator, which will produce more than a unique value: every times yield is triggered, it gives the value to the caller, one at a time, traditionally using a foreach loop.

Yield + Return

Generators, in addition to generate values, can also, provide a unique returned value. That value won't be part of the looping around the generator, it must be accessed using Generator::getReturn() method.

Return + Yield

This could be seen as a bug, however, it is not.

They are two phases:

From code to bytecode: during this phase, the generate() function is seen to contain the yield keyword, it is therefore marked as producing a Generator.

Execution: Because the return happens to be before the yield, the generator doesn't have the chance to produce any value. However, the [1, 2, 3] array can be retrieved with Generator::getReturn().

A complete annotated example:

// Generate integers 1 and 2
function generateIntegers1And2(): Generator {
    yield 1;                                  // <--+   <--+   <--+
    yield 2;                                  //  <-+    <-+    <-+
}                                             //    |      |      |
                                              //    |      |      |
foreach (generateIntegers1And2() as $value) { //    |      |      |
    var_dump($value); // Shows 1, then 2          ->*      |      |
}                                                       // |      |
                                                        // |      |
function generateOuterYield(): Generator {              // |      |
    // Yields the generator *itself* returned by           |      |
    // generateIntegers1And2() not the actual values       |      |
    // generated by it.                                    |      |
    // This means we are producing here a generator        |      |
    // of generator of integers.                           |      |
    yield generateIntegers1And2();          // <-+         |      |
}                                             // |         |      |
                                              // |         |      |
foreach (generateOuterYield() as $value) {    // |         |      |
    var_dump($value);                       // ->*         |      |
    // The two levels of imbrication means we have         |      |
    // to loop once more to actually consume               |      |
    // generateIntegers1And2                               |      |
    foreach ($value as $val) {                          // |      |
        var_dump($val); // Shows 1, then 2               ->*      |
    }                                                          // |
}                                                              // |
                                                               // |
// A generator can just be returned as-is:                        |
function generateOuterReturn(): Generator {                    // |
    return generateIntegers1And2();                            // |
}                                                              // |
                                                               // |
// it doesn't change the way it is consumed                       |
foreach (generateOuterReturn() as $value) {                    // |
    var_dump($value); // Shows 1, then 2                          |
}                                                              // |
                                                               // |
function generateOuterYieldFrom(): Generator {                 // |
    // First yield values generated by generateIntegers1And2()    |
    yield from generateIntegers1And2();                        // *<---+
    // then yield integers 3                                           |
    yield 3;                                                     // <--+
    // and 4                                                           |
    yield 4;                                                     //  <-+
}                                                                //    |
                                                                 //    |
foreach (generateOuterYieldFrom() as $value) {                   //    |
    var_dump($value); // Shows 1, 2, 3 and 4                         ->*
}

function generateIntegers56AndReturn(): Generator {
    yield 5;                                                  // <---+
    yield 6;                                                  //  <--+
                                                              //     |
    return ["five", "six"];                       // <--+            |
}                                                 //    |            |
                                                  //    |            |
$gen = generateIntegers56AndReturn();             //    |            |
                                                  //    |            |
// Consume the values **yielded** by                    |            |
// generateIntegers56AndReturn()                        |            |
foreach ($gen as $value) {                        //    |            |
    var_dump($value); // Shows 5, then 6                |          ->*
}                                                 //    |
                                                  //    |
// Access the value **returned** by the generator       |
var_dump($gen->getReturn());                      //  ->*

function wtf(): Generator {
    return ["W", "T", "F", "!"];
    // Without the following line, PHP would complain with a TypeError:
    // Return value of wtf() must be an instance of Generator, array returned.
    // The presence of a yield keyword anywhere inside the function makes it a Generator.
    // However, since we return *before* reaching any *yield*, 42 is never yielded.
    // This is empty generator!
    yield 42;
}

$gen = wtf();

// This foreach loop is not entered!
foreach ($gen as $value) {
    var_dump($value);
}

// However, we can loop on the array *returned* by wtf():
foreach ($gen->getReturn() as $value) {
    echo $value; // Will print: WTF!
}


答:
use longs, to loop over longer ranges:

```<code>for (long i = 0; i < 1000000L; i++) {
    //do something
}
</code>```

for large randoms, you could cast the return of rand() to long and multiply two together or something like that.  (Heh, probably showing my age by this answer... back when I was coding C regularly, int was only 16 bits. ;)

Title: How to create a loop 1M with random numbers >100000

Body:
use longs, to loop over longer ranges:

for (long i = 0; i < 1000000L; i++) {
    //do something
}

for large randoms, you could cast the return of rand() to long and multiply two together or something like that.  (Heh, probably showing my age by this answer... back when I was coding C regularly, int was only 16 bits. ;)


问:
Calculated total and subtotal using field array on redux-form
With code I gonna provide you how can I calculate total and subtotal on redux form?

```<code>    const calculatedSubtotal = (detail,quantity,price) =>{

     detail = [];

     const subtotals = [];

      detail.map((detailItem,index) =>{

               detailItem[index].quantity = quantity;

               detailItem[index].product.price = price;

         subtotals[index] = detailItem[index].quantity * detailItem[index].product.price;

        return subtotals[index];

           })

         }

  const calculatedTotal = (detail,quantity,price) =>{

     detail = [];

      let total = 0;

       const subtotals = [];

        detail.map((detailItem,index) =>{

                detailItem[index].quantity = quantity;

               detailItem[index].product.price = price;
           subtotals[index] = detailItem[index].quantity * detailItem[index].product.price;

         total += subtotals[index];
         })

      return total;
  }

        componentDidUpdate(prevProps,prevState,snapShot){

          const {change} = prevProps;

          const {detail,quantity,price} = prevProps;

          if(this.props.detail !== prevProps.detail && this.props.quantity !== prevProps.quantity &&
                 this.props.price !== prevProps.price){

            change(`detail[${this.props.index}].subtotal`,calculatedSubtotal(detail,quantity,price));
              change('total',calculatedTotal(detail,quantity,price));
              }
        }

    const valueSelector = formValueSelector('bill');

      const makeStateToProps = () =>{

         const mapStateToProps = (state,props) =>{

                return {

                 detail: valueSelector(state,
              `detail[${props.index}].quantity`,`detail[${props.index}].product.price`,
               `detail[${props.index}].subtotal`
               ),
                quantity: valueSelector(state,`detail[${props.index}].quantity`),
                price: valueSelector(state, `detail[${props.index}].product.price`)

            }

               }

              return mapStateToProps;
           }
</code>```

I've been mistaken in previous post because I was missing two arguments: quantity and price.

More information can be found in How to calculate total and subtotal in redux-form using formValueSelector

Maybe I'm logging out the input of my functions calculatedSubtotal and calculatedTotal

答:
Making some assuptions about the shape of your details Array, you could so something like this:

```<code>const cart = [
  {quantity: 1, product: {price: 5.00}},
  {quantity: 2, product: {price: 1.99}},
];

const calculatedSubtotal = (detail) => {
  return detail.map(detailItem => {
    return detailItem.quantity * detailItem.product.price;
  });
};

const calculateTotalFromSubtotal = subtotals => {
  return subtotals.reduce((grandTotal, itemSubtotal) => {
    return grandTotal + itemSubtotal;
  }, 0);
}

console.log(calculatedSubtotal(cart));
console.log(calculateTotalFromSubtotal(calculatedSubtotal(cart)));
</code>```

Body:
With code I gonna provide you how can I calculate total and subtotal on redux form?

    const calculatedSubtotal = (detail,quantity,price) =>{

     detail = [];

     const subtotals = [];

      detail.map((detailItem,index) =>{

               detailItem[index].quantity = quantity;

               detailItem[index].product.price = price;

         subtotals[index] = detailItem[index].quantity * detailItem[index].product.price;

        return subtotals[index];

           })

         }

  const calculatedTotal = (detail,quantity,price) =>{

     detail = [];

      let total = 0;

       const subtotals = [];

        detail.map((detailItem,index) =>{

                detailItem[index].quantity = quantity;

               detailItem[index].product.price = price;
           subtotals[index] = detailItem[index].quantity * detailItem[index].product.price;

         total += subtotals[index];
         })

      return total;
  }

        componentDidUpdate(prevProps,prevState,snapShot){

          const {change} = prevProps;

          const {detail,quantity,price} = prevProps;

          if(this.props.detail !== prevProps.detail && this.props.quantity !== prevProps.quantity &&
                 this.props.price !== prevProps.price){

            change(`detail[${this.props.index}].subtotal`,calculatedSubtotal(detail,quantity,price));
              change('total',calculatedTotal(detail,quantity,price));
              }
        }

    const valueSelector = formValueSelector('bill');

      const makeStateToProps = () =>{

         const mapStateToProps = (state,props) =>{

                return {

                 detail: valueSelector(state,
              `detail[${props.index}].quantity`,`detail[${props.index}].product.price`,
               `detail[${props.index}].subtotal`
               ),
                quantity: valueSelector(state,`detail[${props.index}].quantity`),
                price: valueSelector(state, `detail[${props.index}].product.price`)

            }

               }

              return mapStateToProps;
           }

I've been mistaken in previous post because I was missing two arguments: quantity and price.

More information can be found in How to calculate total and subtotal in redux-form using formValueSelector

Maybe I'm logging out the input of my functions calculatedSubtotal and calculatedTotal

Body:
Making some assuptions about the shape of your details Array, you could so something like this:

const cart = [
  {quantity: 1, product: {price: 5.00}},
  {quantity: 2, product: {price: 1.99}},
];

const calculatedSubtotal = (detail) => {
  return detail.map(detailItem => {
    return detailItem.quantity * detailItem.product.price;
  });
};

const calculateTotalFromSubtotal = subtotals => {
  return subtotals.reduce((grandTotal, itemSubtotal) => {
    return grandTotal + itemSubtotal;
  }, 0);
}

console.log(calculatedSubtotal(cart));
console.log(calculateTotalFromSubtotal(calculatedSubtotal(cart)));


问:
Why does TypeScript transpilation to target: ES5, Module: CommonJS cause errors in the browser?
I'm working with TypeScript and modules so that I can test with Jest. I am able to pass tests in Jest fine, but the transpiled JavaScript does not run in the browser. I get the error:

```<code>Uncaught ReferenceError: exports is not defined at scripts.js:2
</code>```

The transpiled JavaScript is:

```<code>"use strict";
Object.defineProperty(exports, "__esModule", { value: true }); // this is the offending line
var root = document.documentElement;
exports.root = root;
var button = document.querySelector('button');
if (button) {
    button.addEventListener('click', handleClick);
}
function handleClick() {
    if (root)
        console.log(root.style.backgroundColor);
    var color = '#000000'.replace(/0/g, function () {
        return Math.floor(Math.random() * 16).toString(16);
    });
    if (root) {
        root.style.setProperty('--bg-color', color);
    }
}
exports.handleClick = handleClick;
var sum = function (a, b) {
    return a + b;
};
exports.sum = sum;
</code>```

As TypeScript declares that it "compiles to clean, simple JavaScript code which runs on any browser, in Node.js, or in any JavaScript engine that supports ECMAScript 3 (or newer)," I'm expecting this to run in Chrome.

My tsconfig.json is:

```<code>{
  "compilerOptions": {
    "target": "ES5",
    "module": "CommonJS",
    "allowJs": true,
    "outDir": "./lib",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true
  }
}
</code>```

I am deliberately trying to keep everything as bare bones as possible because I'm trying to learn some specific things about testing, environment set up, and node. It's possible I've gone too minimalist.

If I change the module to ES2015 the transpiled code works. Am I using CommonJS incorrectly? Is that meant to only run on a server?

Thank you in advance.

答:
The ES5 & ES6 & DOM libs should be included in your compilation.
To add these libraries, add lib property in tsconfig.json

{
   "compilerOptions": {
     ...
     "lib": ["es5", "es6", "dom"],
     ...
   }
}
```

Body:
I'm working with TypeScript and modules so that I can test with Jest. I am able to pass tests in Jest fine, but the transpiled JavaScript does not run in the browser. I get the error:

Uncaught ReferenceError: exports is not defined at scripts.js:2

The transpiled JavaScript is:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true }); // this is the offending line
var root = document.documentElement;
exports.root = root;
var button = document.querySelector('button');
if (button) {
    button.addEventListener('click', handleClick);
}
function handleClick() {
    if (root)
        console.log(root.style.backgroundColor);
    var color = '#000000'.replace(/0/g, function () {
        return Math.floor(Math.random() * 16).toString(16);
    });
    if (root) {
        root.style.setProperty('--bg-color', color);
    }
}
exports.handleClick = handleClick;
var sum = function (a, b) {
    return a + b;
};
exports.sum = sum;

As TypeScript declares that it "compiles to clean, simple JavaScript code which runs on any browser, in Node.js, or in any JavaScript engine that supports ECMAScript 3 (or newer)," I'm expecting this to run in Chrome.

My tsconfig.json is:

{
  "compilerOptions": {
    "target": "ES5",
    "module": "CommonJS",
    "allowJs": true,
    "outDir": "./lib",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true
  }
}

I am deliberately trying to keep everything as bare bones as possible because I'm trying to learn some specific things about testing, environment set up, and node. It's possible I've gone too minimalist.

If I change the module to ES2015 the transpiled code works. Am I using CommonJS incorrectly? Is that meant to only run on a server?

Thank you in advance.


问:
I am looking find dups
I am trying to filter out the dups writing a query in Oracle TOAD SQL. Below is the data I have:

```<code>Primary          T_ID           C_ID
2039515494      276162453       20028
2176514662      276721971       5508
2176514662      276721972       5508
</code>```

I am looking to have only

```<code> Primary          T_ID          C_ID
2176514662      276721971       5508
2176514662      276721972       5508
</code>```

答:
You can use a simple exists, I think:

```<code>select t.*
from t
where exists (select 1 from t t2 where t2.primary = t.primary and t2.t_id <> t.t_id);
</code>```

This assumes that t_id is unique.  You might want to include c_id as well for the comparisons.

Title: I am looking find dups

Body:
I am trying to filter out the dups writing a query in Oracle TOAD SQL. Below is the data I have:

Primary          T_ID           C_ID
2039515494      276162453       20028
2176514662      276721971       5508
2176514662      276721972       5508

I am looking to have only

 Primary          T_ID          C_ID
2176514662      276721971       5508
2176514662      276721972       5508

Body:
You can use a simple exists, I think:

select t.*
from t
where exists (select 1 from t t2 where t2.primary = t.primary and t2.t_id <> t.t_id);

This assumes that t_id is unique.  You might want to include c_id as well for the comparisons.


问:
Help me with employee of the month query please
HowI can do a query using the design view to show me the employee with higher sales in pesos per branch if I have 3 tables like the following?

```<code> Branches
 - Branch
 - Id branch

 Employees
 - EmployeeID
 - Employee Name
 - Assigned_branch

 Sales
 - Ticket Id
 - Employee Id
 - Public price
</code>```

How can I get the Name of the employe who has the max sum of public price in all sales one per branch in only one query. I cannot use SQL in this and I really not use access frecuently. Please Help me!

答:
Open a new query, select the option to enter/view SQL code for the query, then paste the following and study the diagram that's created:

```<code>SELECT TOP 1 employeeid, [employee name], branch, sum(price) as total_emp_sales
FROM
    employees AS e
    INNER JOIN branches AS b ON e.assigned_branch = b.[id branch]
    INNER JOIN sales AS s on e.employeeid = s.[employee id]
GROUP BY [employeeid], [employee name], branch
ORDER BY total_emp_sales DESC
</code>```

Also, for future reference, it's not practical for any of us to try and describe how to use the designer to build the exact query you want.  My advice is to get an intro book on SQL, to at least get a working knowledge of the language.  Then you'll have a much better idea of how to use the designer.

Body:
HowI can do a query using the design view to show me the employee with higher sales in pesos per branch if I have 3 tables like the following?

 Branches
 - Branch
 - Id branch

 Employees
 - EmployeeID
 - Employee Name
 - Assigned_branch

 Sales
 - Ticket Id
 - Employee Id
 - Public price

How can I get the Name of the employe who has the max sum of public price in all sales one per branch in only one query. I cannot use SQL in this and I really not use access frecuently. Please Help me!

Body:
Open a new query, select the option to enter/view SQL code for the query, then paste the following and study the diagram that's created:

SELECT TOP 1 employeeid, [employee name], branch, sum(price) as total_emp_sales
FROM
    employees AS e
    INNER JOIN branches AS b ON e.assigned_branch = b.[id branch]
    INNER JOIN sales AS s on e.employeeid = s.[employee id]
GROUP BY [employeeid], [employee name], branch
ORDER BY total_emp_sales DESC

Also, for future reference, it's not practical for any of us to try and describe how to use the designer to build the exact query you want.  My advice is to get an intro book on SQL, to at least get a working knowledge of the language.  Then you'll have a much better idea of how to use the designer.


问:
Google Geolocation API is always returning the same location regardless of cellTower specified
I'm using the Google Geolocation API to approximate location based on cell towers that are visible.  However, I always get the same location as the result.

Using the following body:

```<code>{
    "considerIp": false,
    "radioType": "lte",
    "cellTowers": [{
        "signalStrength": -78,
        "cellId": 133978007,
        "mobileNetworkCode": 410,
        "mobileCountryCode": 310,
        "locationAreaCode": 27196
    }]
}
</code>```

Produces the following result:
{"location": {"lat": 31.968598800000002, "lng": -99.9018131}, "accuracy": 1457406}

The actual location of that tower/cell is approx (32.783062, 96.795769).  In fact, the cell tower specified is take directly from OpenCellID's database (opencellid.org)

If I then select a tower somewhere else (e.g. Palo Alto)

```<code>{
    "considerIp": false,
    "radioType": "lte",
    "cellTowers": [{
        "signalStrength": -78,
        "cellId": 84785686,
        "mobileNetworkCode": 480,
        "mobileCountryCode": 311,
        "locationAreaCode": 7943
    }]
}
</code>```

The response is:
{"location": {"lat": 31.968598800000002, "lng": -99.9018131}, "accuracy": 1457406}
which is exactly the same.

If I can my public IP (via changing VPN end-point location) the results DO change.  Using the same Palo Alto query but changing from a Texas to Chicago end-node my result changes to:
{"location": {"lat": 37.09024, "lng": -95.712891}, "accuracy": 1488703}

It looks like the considerIp=false argument is being ignored and that is only being used instead of the provided cell tower.

Any ideas how to fix this?
Thanks!

答:
I figured it out.  Apparently if the Content-Type is not being explicitly set to application/json then the body is silently ignored and only the local IP is considered.

I would like to request that Google updates the API response body to include something to that effect.

Body:
I'm using the Google Geolocation API to approximate location based on cell towers that are visible.  However, I always get the same location as the result.

Using the following body:

{
    "considerIp": false,
    "radioType": "lte",
    "cellTowers": [{
        "signalStrength": -78,
        "cellId": 133978007,
        "mobileNetworkCode": 410,
        "mobileCountryCode": 310,
        "locationAreaCode": 27196
    }]
}

Produces the following result:
{"location": {"lat": 31.968598800000002, "lng": -99.9018131}, "accuracy": 1457406}

The actual location of that tower/cell is approx (32.783062, 96.795769).  In fact, the cell tower specified is take directly from OpenCellID's database (opencellid.org)

If I then select a tower somewhere else (e.g. Palo Alto)

{
    "considerIp": false,
    "radioType": "lte",
    "cellTowers": [{
        "signalStrength": -78,
        "cellId": 84785686,
        "mobileNetworkCode": 480,
        "mobileCountryCode": 311,
        "locationAreaCode": 7943
    }]
}

The response is:
{"location": {"lat": 31.968598800000002, "lng": -99.9018131}, "accuracy": 1457406}
which is exactly the same.

If I can my public IP (via changing VPN end-point location) the results DO change.  Using the same Palo Alto query but changing from a Texas to Chicago end-node my result changes to:
{"location": {"lat": 37.09024, "lng": -95.712891}, "accuracy": 1488703}

It looks like the considerIp=false argument is being ignored and that is only being used instead of the provided cell tower.

Any ideas how to fix this?
Thanks!


问:
Try/catch not catching error in unawaited async task within WebAPI DelegatingHandler
I'm trying to log a response to a database inside of a delegating handler. Since I want to return the response without waiting for the record to be saved to the database, I want to do that part with an async task.

My problem is, if anything goes wrong within that task, the error cannot be caught and the API crashes with the error

```<code>System.Exception: 'Exception of type 'System.Exception' was thrown.'
</code>```

I've recreated a minimal case below:

```<code>public class LogDelegatingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        try
        {
            //send request and get response
            var response = await base.SendAsync(request, cancellationToken);

            //return response while this runs
            _ = Task.Run(() => Log());
  //Task.Run(() => Log()); //also crashes
  //await Task.Run(() => Log()); //also crashes
            return response;
        }

        catch (Exception e)
        {
           //this is never reached
        }
    }

    private async void Log()
    {

        try
        {
            //this crashes
            throw new Exception("test");
        }
        catch (System.AggregateException e)
        {
           //this is never reached
        }
    }
}
</code>```

After reading SO and finding a thread where the user did care about exceptions thrown, I wanted to ask this where in my case I don't care, but I do want the response to come through first. After reading this
How to safely call an async method in C# without await

I added the _ to dispose of the task and not await it.

答:
That's because you are throwing an Exception but attempt to catch AggregateException.
Try this:

        try
        {
            //this crashes
            throw new Exception("test");
        }
        catch (System.AggregateException e)
        {
           // handle in case of aggregate exception
        }
        catch (Exception ex)
        {
           // in case of other exceptions
        }
```

Body:
I'm trying to log a response to a database inside of a delegating handler. Since I want to return the response without waiting for the record to be saved to the database, I want to do that part with an async task.

My problem is, if anything goes wrong within that task, the error cannot be caught and the API crashes with the error

System.Exception: 'Exception of type 'System.Exception' was thrown.'

I've recreated a minimal case below:

public class LogDelegatingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        try
        {
            //send request and get response
            var response = await base.SendAsync(request, cancellationToken);

            //return response while this runs
            _ = Task.Run(() => Log());
  //Task.Run(() => Log()); //also crashes
  //await Task.Run(() => Log()); //also crashes
            return response;
        }

        catch (Exception e)
        {
           //this is never reached
        }
    }

    private async void Log()
    {

        try
        {
            //this crashes
            throw new Exception("test");
        }
        catch (System.AggregateException e)
        {
           //this is never reached
        }
    }
}

After reading SO and finding a thread where the user did care about exceptions thrown, I wanted to ask this where in my case I don't care, but I do want the response to come through first. After reading this
How to safely call an async method in C# without await

I added the _ to dispose of the task and not await it.