问:
How to break this while(true) loop?
Hi I am trying to break from this loop and return the coordinates when both if statements are true. However the loop is never ending.
How can I fix it?

```<code>public static String[] positionQuery(int dim, Scanner test_in) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Provide origin and destination coordinates.");
        System.out.println("Enter two positions between A1-H8:");
        while(true) {
            String line = scanner.nextLine();
            String[] coordinates = line.split(" ");
            if(coordinates.length == 2) {
                String origin = coordinates[0];
                String dest = coordinates[1];
                if(validCoordinate(origin, dim) && validCoordinate(dest,dim)) {
                    return coordinates;
                }
            }
            System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
        }
    }
</code>```

I guess I have a problem with validCoordinates, because I am only getting true with validCoordinates, but couldn't find what I am doing wrong.

```<code>public static boolean validCoordinate(String coordinate, int dimension) {
        boolean isValidCoordinate;
        String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        int [] numbers = new int [dimension];
        int one = 1;
        for(int i = 0; i < dimension; i++){
            numbers[i] = one + i;
        }
        for(int i = 0; i < dimension; i++){
            if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
                for(int j = 0; j < dimension; j++) {
                    if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                        return true;
                    }
                }
            }
        }

        return false;
    }
</code>```

答:
Your validcoordinate is incorrect, it only checks the first few values specified by the dimension argument in the alphabet array.

Try this

public static boolean validCoordinate(String coordinate, int dimension) {
        boolean isValidCoordinate;
        String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        int [] numbers = new int [dimension];
        for(int i = 0; i < dimension; i++){
            numbers[i] = 1 + i;
        }
        if(Arrays.asList(alphabet).contains(Character.toString(coordinate.charAt(0)))) {
            for(int j = 0; j < dimension; j++) {
              if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                  return true;
              }
            }
        }
        return false;
    }
```

<p>you can definitely improve this code and I will leave that as a challenge to you.</p>

<p>here is the associated repl
https://repl.it/@Blakeinstein/question60251495</p>

<p>ninja edit:
I suggest you to modify your positionquery</p>

<pre class="lang-java prettyprint-override"><code>public static String[] positionQuery(int dim) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Provide origin and destination coordinates.");
        System.out.println("Enter two positions between A1-H8:");
        while(true) {
            String line = scanner.nextLine();
            String[] coordinates = line.split(" ");
            if(coordinates.length == 2) {
                String origin = coordinates[0];
                String dest = coordinates[1];
                if(validCoordinate(origin, dim) && validCoordinate(dest,dim)) {
                    return coordinates;
                }
                else{
                  System.out.println("Coordinates are not valid");
                }
            }
            else{
              System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
            }
        }
    }
</code>```

Title: How to break this while(true) loop?

Body:
Hi I am trying to break from this loop and return the coordinates when both if statements are true. However the loop is never ending.
How can I fix it?

public static String[] positionQuery(int dim, Scanner test_in) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Provide origin and destination coordinates.");
        System.out.println("Enter two positions between A1-H8:");
        while(true) {
            String line = scanner.nextLine();
            String[] coordinates = line.split(" ");
            if(coordinates.length == 2) {
                String origin = coordinates[0];
                String dest = coordinates[1];
                if(validCoordinate(origin, dim) && validCoordinate(dest,dim)) {
                    return coordinates;
                }
            }
            System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
        }
    }

I guess I have a problem with validCoordinates, because I am only getting true with validCoordinates, but couldn't find what I am doing wrong.

public static boolean validCoordinate(String coordinate, int dimension) {
        boolean isValidCoordinate;
        String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        int [] numbers = new int [dimension];
        int one = 1;
        for(int i = 0; i < dimension; i++){
            numbers[i] = one + i;
        }
        for(int i = 0; i < dimension; i++){
            if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
                for(int j = 0; j < dimension; j++) {
                    if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                        return true;
                    }
                }
            }
        }

        return false;
    }

Body:
Your validcoordinate is incorrect, it only checks the first few values specified by the dimension argument in the alphabet array.

Try this

public static boolean validCoordinate(String coordinate, int dimension) {
        boolean isValidCoordinate;
        String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        int [] numbers = new int [dimension];
        for(int i = 0; i < dimension; i++){
            numbers[i] = 1 + i;
        }
        if(Arrays.asList(alphabet).contains(Character.toString(coordinate.charAt(0)))) {
            for(int j = 0; j < dimension; j++) {
              if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                  return true;
              }
            }
        }
        return false;
    }

you can definitely improve this code and I will leave that as a challenge to you.

here is the associated repl
https://repl.it/@Blakeinstein/question60251495

ninja edit:
I suggest you to modify your positionquery

public static String[] positionQuery(int dim) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Provide origin and destination coordinates.");
        System.out.println("Enter two positions between A1-H8:");
        while(true) {
            String line = scanner.nextLine();
            String[] coordinates = line.split(" ");
            if(coordinates.length == 2) {
                String origin = coordinates[0];
                String dest = coordinates[1];
                if(validCoordinate(origin, dim) && validCoordinate(dest,dim)) {
                    return coordinates;
                }
                else{
                  System.out.println("Coordinates are not valid");
                }
            }
            else{
              System.out.println("ERROR: Please enter valid coordinate pair separated by space.");
            }
        }
    }


来源: stackexchange

问:
How to read a specific line from 2 text file in VB.NET
I am creating a program that is supposed to ReadLine text into a 2 text file
I am able to read the text from the text file but I do not know how to control a specific line.

Number1.txt lines

```<code>1:1
2:2
3:3
4:4
5:5
6:6
...
EOF
</code>```

Number2.txt lines

```<code>Save
Skip
Discount
...
EOF
</code>```

I want Read Line Output :-

```<code>1:1 save
2:2 save
3:3 save
1:1 Skip
2:2 Skip
3:3 Skip
1:1 Discount
2:2 Discount
3:3 Discount
4:4 save
5:5 save
6:6 save
4:4 Skip
5:5 Skip
6:6 Skip
4:4 Discount
5:5 Discount
6:6 Discount
...
EOF
</code>```

3 lines text1 To 1 line text2
iF EOF text2 exit loop
i cant Write this Code Please Help me
Any help would be appreciated. Thanks!

答:
You need 3 nested loops. But I would create a helper function as iterator. This makes it easier to use the output.

```<code>Private Shared Iterator Function Combine(
    ByVal numbers1 As String(), ByVal numbers2 As String()) As IEnumerable(Of String)

    Dim repetitions As Integer = 3

    Dim i1 As Integer = 0
    While i1 < numbers1.Length
        For i2 As Integer = 0 To numbers2.Length - 1
            Dim rep As Integer = 0
            While rep < repetitions AndAlso i1 + rep < numbers1.Length
                Yield $"{numbers1(i1 + rep)} {numbers2(i2)}"
                rep += 1
            End While
        Next
        i1 += repetitions
    End While
End Function
</code>```

The deepest nested While-loop also tests i1 + rep < numbers1.Length to ensure that Number1.txt files having a number of lines not being multiples of 3 do not throw an index out of bound exception.

Then you can write the output file with

```<code>Dim numbers1 As String() = File.ReadAllLines("Number1.txt")
Dim numbers2 As String() = File.ReadAllLines("Number2.txt")
File.WriteAllLines("File3.txt", Combine(numbers1, numbers2))
</code>```

See also:

Iterators (Visual Basic) (Microsoft Docs)

File.ReadAllLines Method (Microsoft Docs)

ContentLicense: CC BY-SA 4.0

Body:
I am creating a program that is supposed to ReadLine text into a 2 text file
I am able to read the text from the text file but I do not know how to control a specific line.

Number1.txt lines

1:1
2:2
3:3
4:4
5:5
6:6
...
EOF

Number2.txt lines

Save
Skip
Discount
...
EOF

I want Read Line Output :-

1:1 save
2:2 save
3:3 save
1:1 Skip
2:2 Skip
3:3 Skip
1:1 Discount
2:2 Discount
3:3 Discount
4:4 save
5:5 save
6:6 save
4:4 Skip
5:5 Skip
6:6 Skip
4:4 Discount
5:5 Discount
6:6 Discount
...
EOF

3 lines text1 To 1 line text2
iF EOF text2 exit loop
i cant Write this Code Please Help me
Any help would be appreciated. Thanks!

Body:
You need 3 nested loops. But I would create a helper function as iterator. This makes it easier to use the output.

Private Shared Iterator Function Combine(
    ByVal numbers1 As String(), ByVal numbers2 As String()) As IEnumerable(Of String)

    Dim repetitions As Integer = 3

    Dim i1 As Integer = 0
    While i1 < numbers1.Length
        For i2 As Integer = 0 To numbers2.Length - 1
            Dim rep As Integer = 0
            While rep < repetitions AndAlso i1 + rep < numbers1.Length
                Yield $"{numbers1(i1 + rep)} {numbers2(i2)}"
                rep += 1
            End While
        Next
        i1 += repetitions
    End While
End Function

The deepest nested While-loop also tests i1 + rep < numbers1.Length to ensure that Number1.txt files having a number of lines not being multiples of 3 do not throw an index out of bound exception.

Then you can write the output file with

Dim numbers1 As String() = File.ReadAllLines("Number1.txt")
Dim numbers2 As String() = File.ReadAllLines("Number2.txt")
File.WriteAllLines("File3.txt", Combine(numbers1, numbers2))

See also:

Iterators (Visual Basic) (Microsoft Docs)

File.ReadAllLines Method (Microsoft Docs)


问:
write one specific formula in python
I have a question, everyone knows how can I write this formula with python?

答:
```<code>def formula(rx, cx, wx, cub, wub):
    return rx * min(cub/cx, (wub/wx) ** 3)
</code>```

Title: write one specific formula in python


问:
List manually installed apt packages on Debian 10 (Buster)
It was always nice to see which packages I manually installed using apt install.

Because I could then remove the packages I no longer need.

But I can't find a command working on Debian 10 (Buster) with APT version 1.8.2.

Is there a command showing all manually packages without their dependencies?

I tried the commands in these posts:

Listing all user-installed packages in Debian

How to list manually installed packages

How to list all installed packages

答:
This Bash command will print all manually installed packages minus the ones that came from your Debian installation (in other words, the packages that you installed with apt install):

sudo grep -oP "Unpacking \K[^: ]+" /var/log/installer/syslog \
  | sort -u | comm -13 /dev/stdin <(apt-mark showmanual | sort)
```

It was tested in Debian 10 (Buster). sudo is needed to search through /var/log/installer/syslog. You could also save this installer package list somewhere else if you don't want to use sudo every time.

Body:
This Bash command will print all manually installed packages minus the ones that came from your Debian installation (in other words, the packages that you installed with apt install):

sudo grep -oP "Unpacking \K[^: ]+" /var/log/installer/syslog \
  | sort -u | comm -13 /dev/stdin <(apt-mark showmanual | sort)

It was tested in Debian 10 (Buster). sudo is needed to search through /var/log/installer/syslog. You could also save this installer package list somewhere else if you don't want to use sudo every time.


问:
Cross Domain Web Worker?
I have https://domain1.com (domain1) and https://domain2.com (domain2).

Domain2 serves a page containing javascript with this header:

```<code>"Access-Control-Allow-Origin: *"
</code>```

Domain1 runs some javascript code that invokes:

```<code>new Worker("//domain2.com/script.js")
</code>```

Browsers throw security exceptions.

Since starting writing this question, I have got around this problem by ajaxing the script, blobbing it and running it from that, but am I missing something in the original idea?

答:
Note: does not seem to work since Chrome v93+, but John Hou's solution works like a charm! (though it's much easier nowadays to use fetch to retrieve the code instead of XMLHttpRequest)

It's pretty funny, but importScripts() inside the worker does not have the same origin restriction. So I used this plain workaround:

const workerUrl = 'https://domain2.com/script.js';
const workerBlob = new Blob([
    'importScripts(' + JSON.stringify(workerUrl) + ')',
], {type: 'application/javascript'});
const blobUrl = window.URL.createObjectURL(workerBlob);
const worker = new Worker(blobUrl);
```

Somewhat simpler than fetching script manually.

Title: Cross Domain Web Worker?

Body:
I have https://domain1.com (domain1) and https://domain2.com (domain2).

Domain2 serves a page containing javascript with this header:

"Access-Control-Allow-Origin: *"

Domain1 runs some javascript code that invokes:

new Worker("//domain2.com/script.js")

Browsers throw security exceptions.

Since starting writing this question, I have got around this problem by ajaxing the script, blobbing it and running it from that, but am I missing something in the original idea?

Body:
Note: does not seem to work since Chrome v93+, but John Hou's solution works like a charm! (though it's much easier nowadays to use fetch to retrieve the code instead of XMLHttpRequest)

It's pretty funny, but importScripts() inside the worker does not have the same origin restriction. So I used this plain workaround:

const workerUrl = 'https://domain2.com/script.js';
const workerBlob = new Blob([
    'importScripts(' + JSON.stringify(workerUrl) + ')',
], {type: 'application/javascript'});
const blobUrl = window.URL.createObjectURL(workerBlob);
const worker = new Worker(blobUrl);

Somewhat simpler than fetching script manually.


问:
Memory management with low memory: finding and tracking duplicates of random function return values
Lets assume i have a function that takes 32bit integer in, and returns random 32bit integer out.

Now, i want to see how many and which duplicate values this function will return on all possible input values from 0 to 2^32-1. I could make this easy if i had more than 4gigs free ram, but i dont have more than 1gig ram.

I tried to map the calculated values on disk, using 4gig file where one byte represented how many duplicates it had got, but i noticed the approximated finishing time will be 25 days in the future with my HDD speeds! (i had to use SSD in fear of breaking my HDD...)

So, now the next step is to calculate this all in RAM and not use disk at all, but i ran at wall when thinking how to solve this elegantly. The only method i could think of was to loop (2^32)*(2^32) times the function, but this is obviously even slower than my HDD method.

What i need now is some nasty ideas to speed this up!

Edit: The function isnt really a random function, but similar to a random function, but the fact is you dont need to know anything about the function, its not the problem here. I want to see all the duplicates by my bare eyes, not just some mathematical guessing how many there could be. Why im doing this? Out of curiosity :)

答:
The unaskable question: Why?. what are you trying to achieve?

Is this some kind of Monte-Carlo experiment?

If not, just look up the implementation algorithn of your (P)RNG and it will tell you exactly what the distribution of values is going to be.

Have a look at Boost.Random for more choices than you can fathom, and it will have e.g. uniform_int<> and variate generators that can limit your output range while still having well-defined guarantees on distribution of values across the output domain

ContentLicense: CC BY-SA 3.0


问:
How can I to transmit at least a "couple of bytes" on the local network (UEFI DXE)
I need to write driver (DXE), that can transmit "couple of bytes" from virtual machine (QEMU) to the host system (OS - Ubuntu). I've read the UEFI_Spec and Guide for developers, but I still don't understand, how to write the code and what protocol should I use (tried to use TCPv4 but can't even LocateHandleBuffer).

```<code>EFI_STATUS Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiTcp4ProtocolGuid, NULL, &HandleCount, &HandleBuffer);
</code>```

I get:

```<code>EFI_UNSUPPORTED
</code>```

If somebody can explain me or can show examples of the code, I'll be very grateful. Thanks.

答:
For most network related protocols you first have to use the corresponding "Service Binding Protocol" to get a handle which contains the protocol you are looking for.

Use this steps to access the Tcp4Protocol:

```<code>gBS->LocateHandleBuffer(ByProtovol,gEfiTcp4ServiceBindingProtocolGuid, NULL, &HandleCount, &HandleBuffer);
// Loop over the HandleBuffer Array and pick the one you need
gBS->HandleProtocol(HandleBuffer[YourIndex], &gEfiTcp4ServiceBindingProtocolGuid, &Tcp4SBProtocol);
Tcp4SBProtocol->CreateChild(Tcp4SBProtocol, &Tcp4Handle);
gBS->HandleProtocol(Tcp4Handle, &gEfiTcp4ProtocolGuid, &Tcp4Protocol);
</code>```

To check if a NIC is available you can use:

```<code>// This should return EFI_SUCCESS
gBS->LocateProtocol(&gEfiSimpleNetworkProtocolGuid, NULL, &SimpleNetworkProtocol);
</code>```

There is a complete code sample for the HttpProtocol inside the Uefi specification (starting at page 1548), the Tcp4Protocol is not very different.

Body:
I need to write driver (DXE), that can transmit "couple of bytes" from virtual machine (QEMU) to the host system (OS - Ubuntu). I've read the UEFI_Spec and Guide for developers, but I still don't understand, how to write the code and what protocol should I use (tried to use TCPv4 but can't even LocateHandleBuffer).

EFI_STATUS Status = gBS->LocateHandleBuffer(ByProtocol, &gEfiTcp4ProtocolGuid, NULL, &HandleCount, &HandleBuffer);

I get:

EFI_UNSUPPORTED

If somebody can explain me or can show examples of the code, I'll be very grateful. Thanks.

Body:
For most network related protocols you first have to use the corresponding "Service Binding Protocol" to get a handle which contains the protocol you are looking for.

Use this steps to access the Tcp4Protocol:

gBS->LocateHandleBuffer(ByProtovol,gEfiTcp4ServiceBindingProtocolGuid, NULL, &HandleCount, &HandleBuffer);
// Loop over the HandleBuffer Array and pick the one you need
gBS->HandleProtocol(HandleBuffer[YourIndex], &gEfiTcp4ServiceBindingProtocolGuid, &Tcp4SBProtocol);
Tcp4SBProtocol->CreateChild(Tcp4SBProtocol, &Tcp4Handle);
gBS->HandleProtocol(Tcp4Handle, &gEfiTcp4ProtocolGuid, &Tcp4Protocol);

To check if a NIC is available you can use:

// This should return EFI_SUCCESS
gBS->LocateProtocol(&gEfiSimpleNetworkProtocolGuid, NULL, &SimpleNetworkProtocol);

There is a complete code sample for the HttpProtocol inside the Uefi specification (starting at page 1548), the Tcp4Protocol is not very different.


问:
Having trouble reading the images using open cv
I have a folder name "seg_train" in which I have 6 labeled folders: building, tree, street, glacier, forest, sea and mountain. I am trying to read all the images in these folders using open cv and for that I have written a function but I don't know what I am doing wrong. There are approximately 14000 files in these 6 folders all together but the function I wrote is reading only 2300 from one folder. Could you please help?
Here's the python code

result- Shape of Images: (2382, 150, 150, 3)

Shape of Labels: (2382,)

i was expecting (14000,150,150,3)

```<code>for image_file in os.listdir(r'C:/Users/dhvan/Desktop/intel-image-classification/seg_train/seg_train/'+ labels):
    image = cv2.imread(r'C:/Users/dhvan/Desktop/intel-image-classification/seg_train/seg_train/' + labels + r'/'+ image_file)
    image = cv2.resize(image,(150,150))

    Images.append(image)
    Labels.append(label)
return shuffle(Images,Labels,random_state=812490023)
</code>```

答:
I suggest the code below. Also I think if you try to read in 14000 images of size (150,150,3) you will get a resource exhaust error because this will use a very large amount
of memory. If you are building a CNN classifier I recommend you read the images in in batches using the Keras ImageDataGenerator.flowfrom directory, documentation is here
https://keras.io/preprocessing/image/</p>

```<code>import os
dir=r'C:/Users/dhvan/Desktop/intel-image-classification/seg_train/seg_train'
path_to_labels=os.path.join (dir, 'labels')
dir_list=os.listdir(path_to_labels)
for images in dir_list:
    path_to_images=os.path.join (path_to_labels, images)
    cv2.imread(path_to_images)
</code>```

Body:
I have a folder name "seg_train" in which I have 6 labeled folders: building, tree, street, glacier, forest, sea and mountain. I am trying to read all the images in these folders using open cv and for that I have written a function but I don't know what I am doing wrong. There are approximately 14000 files in these 6 folders all together but the function I wrote is reading only 2300 from one folder. Could you please help?
Here's the python code

result- Shape of Images: (2382, 150, 150, 3)

Shape of Labels: (2382,)

i was expecting (14000,150,150,3)

for image_file in os.listdir(r'C:/Users/dhvan/Desktop/intel-image-classification/seg_train/seg_train/'+ labels):
    image = cv2.imread(r'C:/Users/dhvan/Desktop/intel-image-classification/seg_train/seg_train/' + labels + r'/'+ image_file)
    image = cv2.resize(image,(150,150))

    Images.append(image)
    Labels.append(label)
return shuffle(Images,Labels,random_state=812490023)

Body:
I suggest the code below. Also I think if you try to read in 14000 images of size (150,150,3) you will get a resource exhaust error because this will use a very large amount
of memory. If you are building a CNN classifier I recommend you read the images in in batches using the Keras ImageDataGenerator.flowfrom directory, documentation is here
https://keras.io/preprocessing/image/

import os
dir=r'C:/Users/dhvan/Desktop/intel-image-classification/seg_train/seg_train'
path_to_labels=os.path.join (dir, 'labels')
dir_list=os.listdir(path_to_labels)
for images in dir_list:
    path_to_images=os.path.join (path_to_labels, images)
    cv2.imread(path_to_images)


问:
SQL join greater than / less then
I have 2 tables

I
So i need to get a table in which rows will be excluded for which the date for each "id" is more than in the second table "datestop"

I tried inner join with double condition:
id = id and Date < DateStop, but in this way also excluded rows which not contained in table 2 (id1)

For imagine, thats what i want to get:

答:
I would use NOT EXISTS which is very efficient:

```<code>select t1.*
from table1 t1
where not exists (
  select 1 from table2 t2
  where t2.id = t1.id and t2.datestop <= t1.date
)
</code>```

It's not clear if you need the value of Status must be 'Stopped' for your requirement.

So maybe you need to change the WHERE clause of the subquery to:

```<code>where t2.id = t1.id and t2.datestop <= t1.date and t2.status = 'Stopped'
</code>```

Title: SQL join greater than / less then

Body:
I would use NOT EXISTS which is very efficient:

select t1.*
from table1 t1
where not exists (
  select 1 from table2 t2
  where t2.id = t1.id and t2.datestop <= t1.date
)

It's not clear if you need the value of Status must be 'Stopped' for your requirement.

So maybe you need to change the WHERE clause of the subquery to:

where t2.id = t1.id and t2.datestop <= t1.date and t2.status = 'Stopped'


问:
Error when creating summary table with table1: "invalid model formula in ExtractVars"
I am using table1 package for first time.
I am trying to create a summary table of descriptive statistics

This is my code

```<code>data <- read_excel("correct file path",
                      skip= 1,)

mydata <-  data[, -c(19:40)]
i <-  c(5:18)

mydata[, i] <- apply(mydata[, i],2, function(x) as.numeric(as.character(x)))

mydata <-  na.omit(mydata)

table1::label(dat$Sex) <- "Sex"
table1::label(dat$Age) <- "Age"
table1::label(dat$SBP) <- "SBP"
table1::label(dat$DBP) <- "DBP"
table1::label(dat$BMI) <- "BMI"
table1::label(dat$WHR) <- "waist:Hip"
table1::label(dat$`LTM %`) <- "% Lean tissue mass"
table1::label(dat$`FM %`) <- "% Fat mass"

sumtab <- table1::table1(~Sex + Age + SBP + DBP + BMI + WHR + 'LTM %' + 'FM %' , data = dat)
</code>```

I get the following error

```<code>Error in terms.formula(formula, data = data) :
  invalid model formula in ExtractVars
</code>```

I cannot see what I've done wrong

答:
The issue is with single quotes ('), instead use backquotes

```<code>sumtab <- table1::table1(~Sex + Age + SBP + DBP + BMI +
            WHR + `LTM %` + `FM %` , data = dat)
</code>```

Using a reproducible example

```<code>library(table1)
 table1(~ sex + age + wt  + 'LTM %', data=dat)
</code>```

Error in terms.formula(formula, data = data) :    invalid model
  formula in ExtractVars

single quote results in error as in the OP's post

```<code>table1(~ sex + age + wt  + `LTM %`, data=dat)
</code>```

-output

data

```<code>set.seed(24)
dat <- expand.grid(id=1:10, sex=c("Male", "Female"), treat=c("Treated", "Placebo"))
dat$age <- runif(nrow(dat), 10, 50)
dat$age[3] <- NA  # Add a missing value
dat$wt <- exp(rnorm(nrow(dat), log(70), 0.2))
dat$`LTM %` <-  sample(40:50, nrow(dat), replace = TRUE)
label(dat$sex) <- "Sex"
label(dat$age) <- "Age"
label(dat$treat) <- "Treatment Group"
label(dat$wt) <- "Weight"
label(dat$`LTM %`) <- "% Lean tissue mass"
</code>```

Body:
I am using table1 package for first time.
I am trying to create a summary table of descriptive statistics

This is my code

data <- read_excel("correct file path",
                      skip= 1,)

mydata <-  data[, -c(19:40)]
i <-  c(5:18)

mydata[, i] <- apply(mydata[, i],2, function(x) as.numeric(as.character(x)))

mydata <-  na.omit(mydata)

table1::label(dat$Sex) <- "Sex"
table1::label(dat$Age) <- "Age"
table1::label(dat$SBP) <- "SBP"
table1::label(dat$DBP) <- "DBP"
table1::label(dat$BMI) <- "BMI"
table1::label(dat$WHR) <- "waist:Hip"
table1::label(dat$`LTM %`) <- "% Lean tissue mass"
table1::label(dat$`FM %`) <- "% Fat mass"

sumtab <- table1::table1(~Sex + Age + SBP + DBP + BMI + WHR + 'LTM %' + 'FM %' , data = dat)

I get the following error

Error in terms.formula(formula, data = data) :
  invalid model formula in ExtractVars

I cannot see what I've done wrong

Body:
The issue is with single quotes ('), instead use backquotes

sumtab <- table1::table1(~Sex + Age + SBP + DBP + BMI +
            WHR + `LTM %` + `FM %` , data = dat)

Using a reproducible example

library(table1)
 table1(~ sex + age + wt  + 'LTM %', data=dat)

Error in terms.formula(formula, data = data) :    invalid model
  formula in ExtractVars

single quote results in error as in the OP's post

table1(~ sex + age + wt  + `LTM %`, data=dat)

-output

data

set.seed(24)
dat <- expand.grid(id=1:10, sex=c("Male", "Female"), treat=c("Treated", "Placebo"))
dat$age <- runif(nrow(dat), 10, 50)
dat$age[3] <- NA  # Add a missing value
dat$wt <- exp(rnorm(nrow(dat), log(70), 0.2))
dat$`LTM %` <-  sample(40:50, nrow(dat), replace = TRUE)
label(dat$sex) <- "Sex"
label(dat$age) <- "Age"
label(dat$treat) <- "Treatment Group"
label(dat$wt) <- "Weight"
label(dat$`LTM %`) <- "% Lean tissue mass"


问:
help with a PHP regex to extract text around a string
I am trying to use a regular expression and it's just breaking my brain.  I'll think I have it and the the script just breaks. I need to try to give people a way to report their location via SMS. I ask them to text me a string that looks like this:

I give up, stopping for the night.
  Find me at Main Street and Pine,
  Atlanta, GA.

And I want to break it at Find me at. I need to capture everything to the right of that (essentially their street corner) and I need to be able to detect if they didn't use proper capitalization for Find.

Any suggestions?

答:
The following regex will work for you:

Find me at (.*)$

If you want it to ignore the case, you can specify it using the IgnoreCase option (?i:)


问:
OutputFileResults returned by OnImageSavedCallback has an invalid Uri
I am using CameraX API to take pictures in my android app, save them and then display them from their path. With the previous version alpha-09 I was able to do so with onImageSaved(File file). However with the alpha-10 I have to use onImageSaved(OutputFileResults outputFileResults) and then get the path from the uri retrieved by the outputFileResults. But the Uri I get is always wrong. For instance when my image is saved at: "/external/images/media/1581680878237.jpg" I get the uri's path: "/external/images/media/113758".

Here is my code:

```<code>ContentValues contentValues = new ContentValues();
                    contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, "NEW_IMAGE");
                    contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");

                    ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(
                            activity.getContentResolver(),
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            contentValues).build();

                    imageCapture.takePicture(outputFileOptions, Runnable::run, new ImageCapture.OnImageSavedCallback() {
                        @Override
                        public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                            Uri uri = outputFileResults.getSavedUri();
                            if(uri != null){
                                System.out.println("URI PATH" + uri.getPath());
                                System.out.println("URI PATH" + uri.toString());
                                activity.runOnUiThread(cameraProvider::unbindAll);
                                galleryAddPic(uri);
                                Bundle params = new Bundle();
                                params.putString("FILE_PATH", uri.getPath());
                                Navigation.findNavController(root).navigate(R.id.navigation_edit_image, params);
                            }
                        }

                        @Override
                        public void onError(@NonNull ImageCaptureException exception) {
                            exception.printStackTrace();
                        }
                    });
</code>```

答:
So I finally managed to save the image taken by ImageCapture by using an other method (especially an other ImageCapture.OutputFileOptions.Builde). I didn't use an Uri object to save the image but a File object.

```<code>                File mImageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "YOUR_DIRECTORY");
                boolean isDirectoryCreated = mImageDir.exists() || mImageDir.mkdirs();
                if(isDirectoryCreated){
                    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/YOUR_DIRECTORY", "YOUR_IMAGE.jpg");
                    ImageCapture.OutputFileOptions.Builder outputFileOptionsBuilder =
                            new ImageCapture.OutputFileOptions.Builder(file);
                    imageCapture.takePicture(outputFileOptionsBuilder.build(), Runnable::run, new ImageCapture.OnImageSavedCallback() {
                        @Override
                        public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                            Bundle params = new Bundle();
                            params.putString("FILE_PATH", file.getPath());
                            Navigation.findNavController(root).navigate(R.id.navigation_edit_image, params);
                        }

                        @Override
                        public void onError(@NonNull ImageCaptureException exception) {
                            exception.printStackTrace();
                        }
                    });
                }
</code>```

Be aware that if you use outputFileResults.getSavedUri() with this method you will always have a null uri.

Body:
I am using CameraX API to take pictures in my android app, save them and then display them from their path. With the previous version alpha-09 I was able to do so with onImageSaved(File file). However with the alpha-10 I have to use onImageSaved(OutputFileResults outputFileResults) and then get the path from the uri retrieved by the outputFileResults. But the Uri I get is always wrong. For instance when my image is saved at: "/external/images/media/1581680878237.jpg" I get the uri's path: "/external/images/media/113758".

Here is my code:

ContentValues contentValues = new ContentValues();
                    contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, "NEW_IMAGE");
                    contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");

                    ImageCapture.OutputFileOptions outputFileOptions = new ImageCapture.OutputFileOptions.Builder(
                            activity.getContentResolver(),
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            contentValues).build();

                    imageCapture.takePicture(outputFileOptions, Runnable::run, new ImageCapture.OnImageSavedCallback() {
                        @Override
                        public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                            Uri uri = outputFileResults.getSavedUri();
                            if(uri != null){
                                System.out.println("URI PATH" + uri.getPath());
                                System.out.println("URI PATH" + uri.toString());
                                activity.runOnUiThread(cameraProvider::unbindAll);
                                galleryAddPic(uri);
                                Bundle params = new Bundle();
                                params.putString("FILE_PATH", uri.getPath());
                                Navigation.findNavController(root).navigate(R.id.navigation_edit_image, params);
                            }
                        }

                        @Override
                        public void onError(@NonNull ImageCaptureException exception) {
                            exception.printStackTrace();
                        }
                    });

Body:
So I finally managed to save the image taken by ImageCapture by using an other method (especially an other ImageCapture.OutputFileOptions.Builde). I didn't use an Uri object to save the image but a File object.

                File mImageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "YOUR_DIRECTORY");
                boolean isDirectoryCreated = mImageDir.exists() || mImageDir.mkdirs();
                if(isDirectoryCreated){
                    File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/YOUR_DIRECTORY", "YOUR_IMAGE.jpg");
                    ImageCapture.OutputFileOptions.Builder outputFileOptionsBuilder =
                            new ImageCapture.OutputFileOptions.Builder(file);
                    imageCapture.takePicture(outputFileOptionsBuilder.build(), Runnable::run, new ImageCapture.OnImageSavedCallback() {
                        @Override
                        public void onImageSaved(@NonNull ImageCapture.OutputFileResults outputFileResults) {
                            Bundle params = new Bundle();
                            params.putString("FILE_PATH", file.getPath());
                            Navigation.findNavController(root).navigate(R.id.navigation_edit_image, params);
                        }

                        @Override
                        public void onError(@NonNull ImageCaptureException exception) {
                            exception.printStackTrace();
                        }
                    });
                }

Be aware that if you use outputFileResults.getSavedUri() with this method you will always have a null uri.


答:
We can add more columns in the group_by

```<code>library(dplyr)
pa <- pa %>%
          group_by(`subject-id`, `activity label`) %>%
          mutate(timestamp = (timestamp - first(timestamp))/10E8))
</code>```

Title: How to set time equal to zero by two different groups?

Body:
If I have a data frame that has many rows like this:

 subject-id activity label    timestamp          x         y          z
1       1600              A 2.522077e+14 -0.3647613  8.793503  1.0550842
2       1600              A 2.522077e+14 -0.8797302  9.768784  1.0169983
3       1600              A 2.522078e+14  2.0014954 11.109070   2.619156
4       1600              A 2.522078e+14  0.4506226 12.651642 0.18455505
5       1600              A 2.522079e+14 -2.1643524 13.928436 -4.4224854
6       1600              A 2.522079e+14 -4.3327790 13.361191 -0.7188721
.
.
.
  subject-id activity label    timestamp           x          y          z
991      1600             B 2.519876e+14  1.37554930 15.3750460  2.9716187
992      1600             B 2.519877e+14 -3.93443300 17.5387880  2.1100159
993      1600             B 2.519877e+14 -0.08773804 12.7915650 -1.4541016
994      1600             B 2.519878e+14  2.03874200  3.0771484 -1.0537262
995      1600             B 2.519878e+14 -2.55847170 -2.7386780 -2.0985107
996      1600             B 2.519879e+14 -1.35530090  0.3884125 -0.6598511
.
.
.
  subject-id activity label timestamp          x         y           z
24551       1601              A  12865.64  4.7034090  9.127296  0.06404489
24552       1601              A  12865.68  5.3546320 15.635334 -0.62907650
24553       1601              A  12865.72  6.3997010 12.926893  0.45010993
24554       1601              A  12865.76 10.5320930 13.207614 -1.02471830
24555       1601              A  12865.80 16.1297360  2.683301  1.14263270
24556       1601              A  12865.84  0.3932476  6.549937 -3.78224020

How can I set the time equal to zero by group "subject-id" AND "activity label"? I want to subtract off the first time for every instance of that group. Like this:

  subject-id activity label    timestamp          x         y          z
1       1600              A            0 -0.3647613  8.793503  1.0550842
2       1600              A      .050354 -0.8797302  9.768784  1.0169983
3       1600              A      .100708  2.0014954 11.109070   2.619156
4       1600              A      .151062  0.4506226 12.651642 0.18455505
.
.
.
  subject-id activity label    timestamp           x          y          z
991      1600             B            0  1.37554930 15.3750460  2.9716187
992      1600             B      .049355 -3.93443300 17.5387880  2.1100159
993      1600             B      .100601 -0.08773804 12.7915650 -1.4541016
.
.
.
  subject-id activity label timestamp          x         y           z
24551       1601              A         0  4.7034090  9.127296  0.06404489
24552       1601              A       .04  5.3546320 15.635334 -0.62907650
24553       1601              A      .085  6.3997010 12.926893  0.45010993

Note: I made up some numbers to demonstrate what I mean.

What I have tried: I tried using dplyr and grouped by "activity label". can I group twice?

pa <- as.data.frame(pa %>% group_by(`activity label`) %>% mutate(timestamp = (timestamp - first(timestamp))/10E8))

Body:
We can add more columns in the group_by

library(dplyr)
pa <- pa %>%
          group_by(`subject-id`, `activity label`) %>%
          mutate(timestamp = (timestamp - first(timestamp))/10E8))


问:
How do I take an on click off of a gallery?
I found a JQUERY gallery that I really like however I am having issues with it.
I love the gallery however it will only appear once you click on a city name on the page.
I wondered if anyone knew how to make it work without clicking anything so the gallery will just appear by its self? I have been racking my brain all day!

Download zip here and has a link to preview the final result!
http://tympanus.net/codrops/2010/10/07/slider-gallery/

I have come to the conclusion that the problem is on the index page with the java at the bottom opposed to the external java files in the zip file the creator provides.

If anyone know and could give me a hand I would be beyond grateful!

Thanks in advance!!

code

```<code>        $(function() {
            //caching
            //the main wrapper of the gallery
            var $fp_gallery         = $('#fp_gallery')
            //the overlay when the large image is displayed
            var $fp_overlay         = $('#fp_overlay');
            //image loading status
            var $fp_loading         = $('#fp_loading');
            //the next and previous buttons
            var $fp_next            = $('#fp_next');
            var $fp_prev            = $('#fp_prev');
            //the close button
            var $fp_close           = $('#fp_close');
            //the main container for the thumbs structure
            var $fp_thumbContainer  = $('#fp_thumbContainer');
            //wrapper of jquery ui slider
            var $fp_scrollWrapper   = $('#fp_scrollWrapper');
            //total number of images
            var nmb_images=0;
            //which gallery is clicked (index)
            var gallery_idx=-1;
            //scroller wrapper
            var $fp_thumbScroller   = $('#fp_thumbScroller');
            //jquery ui slider
            var $slider             = $('#slider');
            //the links of the galleries (the cities)
            var $fp_galleries       = $('#fp_galleryList > li');
            //current image being viewed
            var current             = 0;

            //some control flags:
            //prevent fast clicks on next and previous
            var photo_nav           = true;

            //User clicks on a city / gallery;
            $fp_galleries.bind('click',function(){
                $fp_galleries.removeClass('current');
                var $gallery        = $(this);
                $gallery.addClass('current');
                var gallery_index   = $gallery.index();
                if(gallery_idx == gallery_index) return;
                gallery_idx         = gallery_index;
                //close the gallery and slider if opened
                if($fp_thumbContainer.data('opened')==true){
                    $fp_scrollWrapper.fadeOut();
                    $fp_thumbContainer.stop()
                                      .animate({'height':'0px'},200,function(){
                                        openGallery($gallery);
                                      });
                }
                else
                    openGallery($gallery);
            });

            //opens a gallery after cliking on a city / gallery
            function openGallery($gallery){
                //current gets reseted
                current             = 0;
                //wrapper of each content div, where each image is
                var $fp_content_wrapper = $fp_thumbContainer.find('.container:nth-child('+parseInt(gallery_idx+1)+')');
                //hide all the other galleries thumbs wrappers
                $fp_thumbContainer.find('.container').not($fp_content_wrapper).hide();
                //and show this one
                $fp_content_wrapper.show();
                //total number of images
                nmb_images          = $fp_content_wrapper.children('div').length;
                //calculate width,
                //padding left
                //and padding right for content wrapper
                var w_width     = 0;
                var padding_l   = 0;
                var padding_r   = 0;
                //center of screen
                var center      = $(window).width()/2;
                var one_divs_w  = 0;
                /*
                Note:
                the padding left is the center minus half of the width of the first content div
                the padding right is the center minus half of the width of the last content div
                */
                $fp_content_wrapper.children('div').each(function(i){
                    var $div        = $(this);
                    var div_width   = $div.width();
                    w_width         +=div_width;
                    //if first one, lets calculate the padding left
                    if(i==0)
                        padding_l = center - (div_width/2);
                    //if last one, lets calculate the padding right
                    if(i==(nmb_images-1)){
                        padding_r = center - (div_width/2);
                        one_divs_w= div_width;
                    }
                }).end().css({
                    'width'             : w_width + 'px',
                    'padding-left'      : padding_l + 'px',
                    'padding-right'     : padding_r + 'px'
                });

                //scroll all left;
                $fp_thumbScroller.scrollLeft(w_width);

                //innitialize the slider
                $slider.slider('destroy').slider({
                    orientation : 'horizontal',
                    max         : w_width -one_divs_w,//total width minus one content div width
                    min         : 0,
                    value       : 0,
                    slide       : function(event, ui) {
                        $fp_thumbScroller.scrollLeft(ui.value);
                    },
                    stop: function(event, ui) {
                        //when we stop sliding
                        //we may want that the closest picture to the center
                        //of the window stays centered. Uncomment the following line
                        //if you want that behaviour
                        checkClosest();
                    }
                });
                //open the gallery and show the slider
                $fp_thumbContainer.animate({'height':'240px'},200,function(){
                    $(this).data('opened',true);
                    $fp_scrollWrapper.fadeIn();
                });

                //scroll all right;
                $fp_thumbScroller.stop()
                                 .animate({'scrollLeft':'0px'},2000,'easeInOutExpo');

                //User clicks on a content div (image)
                $fp_content_wrapper.find('.content')
                                 .bind('click',function(e){
                    var $current    = $(this);
                    //track the current one
                    current         = $current.index();
                    //center and show this image
                    //the second parameter set to true means we want to
                    //display the picture after the image is centered on the screen
                    centerImage($current,true,600);
                    e.preventDefault();
                });
            }

            //while the gallery scrolls we want that the slider scrolls as well
            $fp_thumbScroller.scroll(function(){
                $slider.slider('value',parseInt($fp_thumbScroller.scrollLeft(),10));
            });

            //User clicks next button (preview mode)
            $fp_next.bind('click',function(){
                if(photo_nav){
                    photo_nav = false;
                navigate(1);
                }
            });

            //User clicks previous button (preview mode)
            $fp_prev.bind('click',function(){
                if(photo_nav){
                    photo_nav = false;
                navigate(0);
                }
            });

            //User clicks next button (thumbs)
            $('#fp_next_thumb').click(function(){
                slideThumb(1);
            });

            //User clicks previous button (thumbs)
            $('#fp_prev_thumb').click(function(){
                slideThumb(0);
            });

            //User clicks close button
            $fp_close.bind('click',function(){
                if(!photo_nav) return;
                //windows scroll if any
                var windowS         = $(window).scrollTop();
                //the large image being viewed
                var $large_img      = $('#fp_preview');
                //the current thumb
                var $current        = $fp_thumbScroller.find('.container:nth-child('+parseInt(gallery_idx+1)+')')
                                                       .find('.content:nth-child('+parseInt(current+1)+')');
                //offset values of current thumb
                var current_offset  = $current.offset();
                //the large image will animate in the direction of the center
                //after that it is removed from the DOM
                $large_img.stop().animate({
                    'top'           : current_offset.top + windowS + 'px',
                    'left'          : $(window).width()/2 - $current.width()/2 + 'px',
                    'width'         : $current.width() + 'px',
                    'height'        : $current.height() + 'px',
                    'opacity'       : 0
                },800,function(){
                    $(this).remove();
                //hide the overlay, and the next, previous and close buttons
                hidePreviewFunctions();
            });

            });
</code>```

答:
In case someone is looking for a solution. To auto load gallery 1, I used .load() function.

Change the value of the gallery you want to auto load.
var gallery_index   = 0;

```<code>$(window).load(function() {
              //$fp_galleries.removeClass('current');
                var $gallery        = $(this);
                $gallery.addClass('current');
                var gallery_index   = 0;

                if(gallery_idx == gallery_index) return;
                gallery_idx         = gallery_index;
                //close the gallery and slider if opened
                if($fp_thumbContainer.data('opened')==true){
                    $fp_scrollWrapper.fadeOut();
                    /*$fp_thumbContainer.stop()
                                      .animate({'height':'0px'},200,function(){*/
                                        openGallery($gallery);
                                      //});
                }
                else
                    openGallery($gallery);
            });
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I found a JQUERY gallery that I really like however I am having issues with it.
I love the gallery however it will only appear once you click on a city name on the page.
I wondered if anyone knew how to make it work without clicking anything so the gallery will just appear by its self? I have been racking my brain all day!

Download zip here and has a link to preview the final result!
http://tympanus.net/codrops/2010/10/07/slider-gallery/

I have come to the conclusion that the problem is on the index page with the java at the bottom opposed to the external java files in the zip file the creator provides.

If anyone know and could give me a hand I would be beyond grateful!

Thanks in advance!!

code

        $(function() {
            //caching
            //the main wrapper of the gallery
            var $fp_gallery         = $('#fp_gallery')
            //the overlay when the large image is displayed
            var $fp_overlay         = $('#fp_overlay');
            //image loading status
            var $fp_loading         = $('#fp_loading');
            //the next and previous buttons
            var $fp_next            = $('#fp_next');
            var $fp_prev            = $('#fp_prev');
            //the close button
            var $fp_close           = $('#fp_close');
            //the main container for the thumbs structure
            var $fp_thumbContainer  = $('#fp_thumbContainer');
            //wrapper of jquery ui slider
            var $fp_scrollWrapper   = $('#fp_scrollWrapper');
            //total number of images
            var nmb_images=0;
            //which gallery is clicked (index)
            var gallery_idx=-1;
            //scroller wrapper
            var $fp_thumbScroller   = $('#fp_thumbScroller');
            //jquery ui slider
            var $slider             = $('#slider');
            //the links of the galleries (the cities)
            var $fp_galleries       = $('#fp_galleryList > li');
            //current image being viewed
            var current             = 0;

            //some control flags:
            //prevent fast clicks on next and previous
            var photo_nav           = true;

            //User clicks on a city / gallery;
            $fp_galleries.bind('click',function(){
                $fp_galleries.removeClass('current');
                var $gallery        = $(this);
                $gallery.addClass('current');
                var gallery_index   = $gallery.index();
                if(gallery_idx == gallery_index) return;
                gallery_idx         = gallery_index;
                //close the gallery and slider if opened
                if($fp_thumbContainer.data('opened')==true){
                    $fp_scrollWrapper.fadeOut();
                    $fp_thumbContainer.stop()
                                      .animate({'height':'0px'},200,function(){
                                        openGallery($gallery);
                                      });
                }
                else
                    openGallery($gallery);
            });

            //opens a gallery after cliking on a city / gallery
            function openGallery($gallery){
                //current gets reseted
                current             = 0;
                //wrapper of each content div, where each image is
                var $fp_content_wrapper = $fp_thumbContainer.find('.container:nth-child('+parseInt(gallery_idx+1)+')');
                //hide all the other galleries thumbs wrappers
                $fp_thumbContainer.find('.container').not($fp_content_wrapper).hide();
                //and show this one
                $fp_content_wrapper.show();
                //total number of images
                nmb_images          = $fp_content_wrapper.children('div').length;
                //calculate width,
                //padding left
                //and padding right for content wrapper
                var w_width     = 0;
                var padding_l   = 0;
                var padding_r   = 0;
                //center of screen
                var center      = $(window).width()/2;
                var one_divs_w  = 0;
                /*
                Note:
                the padding left is the center minus half of the width of the first content div
                the padding right is the center minus half of the width of the last content div
                */
                $fp_content_wrapper.children('div').each(function(i){
                    var $div        = $(this);
                    var div_width   = $div.width();
                    w_width         +=div_width;
                    //if first one, lets calculate the padding left
                    if(i==0)
                        padding_l = center - (div_width/2);
                    //if last one, lets calculate the padding right
                    if(i==(nmb_images-1)){
                        padding_r = center - (div_width/2);
                        one_divs_w= div_width;
                    }
                }).end().css({
                    'width'             : w_width + 'px',
                    'padding-left'      : padding_l + 'px',
                    'padding-right'     : padding_r + 'px'
                });

                //scroll all left;
                $fp_thumbScroller.scrollLeft(w_width);

                //innitialize the slider
                $slider.slider('destroy').slider({
                    orientation : 'horizontal',
                    max         : w_width -one_divs_w,//total width minus one content div width
                    min         : 0,
                    value       : 0,
                    slide       : function(event, ui) {
                        $fp_thumbScroller.scrollLeft(ui.value);
                    },
                    stop: function(event, ui) {
                        //when we stop sliding
                        //we may want that the closest picture to the center
                        //of the window stays centered. Uncomment the following line
                        //if you want that behaviour
                        checkClosest();
                    }
                });
                //open the gallery and show the slider
                $fp_thumbContainer.animate({'height':'240px'},200,function(){
                    $(this).data('opened',true);
                    $fp_scrollWrapper.fadeIn();
                });

                //scroll all right;
                $fp_thumbScroller.stop()
                                 .animate({'scrollLeft':'0px'},2000,'easeInOutExpo');

                //User clicks on a content div (image)
                $fp_content_wrapper.find('.content')
                                 .bind('click',function(e){
                    var $current    = $(this);
                    //track the current one
                    current         = $current.index();
                    //center and show this image
                    //the second parameter set to true means we want to
                    //display the picture after the image is centered on the screen
                    centerImage($current,true,600);
                    e.preventDefault();
                });
            }

            //while the gallery scrolls we want that the slider scrolls as well
            $fp_thumbScroller.scroll(function(){
                $slider.slider('value',parseInt($fp_thumbScroller.scrollLeft(),10));
            });

            //User clicks next button (preview mode)
            $fp_next.bind('click',function(){
                if(photo_nav){
                    photo_nav = false;
                navigate(1);
                }
            });

            //User clicks previous button (preview mode)
            $fp_prev.bind('click',function(){
                if(photo_nav){
                    photo_nav = false;
                navigate(0);
                }
            });

            //User clicks next button (thumbs)
            $('#fp_next_thumb').click(function(){
                slideThumb(1);
            });

            //User clicks previous button (thumbs)
            $('#fp_prev_thumb').click(function(){
                slideThumb(0);
            });

            //User clicks close button
            $fp_close.bind('click',function(){
                if(!photo_nav) return;
                //windows scroll if any
                var windowS         = $(window).scrollTop();
                //the large image being viewed
                var $large_img      = $('#fp_preview');
                //the current thumb
                var $current        = $fp_thumbScroller.find('.container:nth-child('+parseInt(gallery_idx+1)+')')
                                                       .find('.content:nth-child('+parseInt(current+1)+')');
                //offset values of current thumb
                var current_offset  = $current.offset();
                //the large image will animate in the direction of the center
                //after that it is removed from the DOM
                $large_img.stop().animate({
                    'top'           : current_offset.top + windowS + 'px',
                    'left'          : $(window).width()/2 - $current.width()/2 + 'px',
                    'width'         : $current.width() + 'px',
                    'height'        : $current.height() + 'px',
                    'opacity'       : 0
                },800,function(){
                    $(this).remove();
                //hide the overlay, and the next, previous and close buttons
                hidePreviewFunctions();
            });

            });

Body:
In case someone is looking for a solution. To auto load gallery 1, I used .load() function.

Change the value of the gallery you want to auto load.
var gallery_index   = 0;

$(window).load(function() {
              //$fp_galleries.removeClass('current');
                var $gallery        = $(this);
                $gallery.addClass('current');
                var gallery_index   = 0;

                if(gallery_idx == gallery_index) return;
                gallery_idx         = gallery_index;
                //close the gallery and slider if opened
                if($fp_thumbContainer.data('opened')==true){
                    $fp_scrollWrapper.fadeOut();
                    /*$fp_thumbContainer.stop()
                                      .animate({'height':'0px'},200,function(){*/
                                        openGallery($gallery);
                                      //});
                }
                else
                    openGallery($gallery);
            });


问:
upload chromdriver to AWS Lambda Layer (Ruby 2.5)
I tried upload AWS Lambda Layer to upload chromedriver within 50MB.
but it didn't work..
(chromedriver zip packege upload is worked, but if i inspect lambda directory, it could't found.)

```<code>def test(event:, context:)
    p Dir["/opt/**/*.*"]
end
=>
[
  "/opt/lib/ascii_and_mic.so",
  "/opt/lib/cyrillic_and_mic.so",
  ...
  (but not found chromedriver zip package)
]
</code>```

anyone know how to upload chromedriver to AWS Lambda Layer?

P.S : AWS Lambda is based Ruby 2.5

答:
For creating the archive for the layer do this:</p>

```<code>bundle install --path vendor/bundle
cd vendor/bundle
mkdir ruby/gems
mv ruby/2.5.0 ruby/gems/
zip -r layer.zip ruby/gems/2.5.0/
</code>```

Body:
I tried upload AWS Lambda Layer to upload chromedriver within 50MB.
but it didn't work..
(chromedriver zip packege upload is worked, but if i inspect lambda directory, it could't found.)

def test(event:, context:)
    p Dir["/opt/**/*.*"]
end
=>
[
  "/opt/lib/ascii_and_mic.so",
  "/opt/lib/cyrillic_and_mic.so",
  ...
  (but not found chromedriver zip package)
]

anyone know how to upload chromedriver to AWS Lambda Layer?

P.S : AWS Lambda is based Ruby 2.5

Body:
For creating the archive for the layer do this:

bundle install --path vendor/bundle
cd vendor/bundle
mkdir ruby/gems
mv ruby/2.5.0 ruby/gems/
zip -r layer.zip ruby/gems/2.5.0/


问:
How slow is Slowly Changing Dimensions?
How often dimensions change in a slowly changing scenario?

I'm looking at SQL Server Temporal tables for Slowly Changing Dimensions (Type 2). Some of the dimension tables update quite frequently (daily! In  that sense, they are not truly 'slowly changing'. They are not truly dimensions in strict sense).

Is it common for a dimension to change daily?

答:
"Speed" of dimension change should be considered relatively to the speed of change in fact tables.

If a dimension changes daily, but fact tables change every minute, it might be fine.

If a dimension changes daily and fact tables change daily, most likely it's a design mistake. What you currently have is not normal and you need to fix the design.

Often the root of the problem is a confusion between dimension and fact - if a designer models facts as dimensional attributes, the dimension will change too fast. For example, if you add Price to Product dimension, and prices change daily, you will convert "slow change" into a "rapid change". A solution here is to separate prices into a fact table that contains price history.

In less obvious cases, a common solution is to separate fast-changing attributes into a "mini-dimension". For example, if some customer attributes change much faster than the rest, split the table into "Customer" and "Customer Profile" dimensions. Such "mini-dimensions" are also called "Type 4" change in the dimensional design.

You can see an example here:

SCD Type 4, a Solution for Rapidly Changing Dimension

Title: How slow is Slowly Changing Dimensions?


问:
Laravel Vue error when trying to use chart.js with Laravel-charts package
I'm using Laravel charts from https://charts.erik.cat/ and I noticed that I'm getting the error below.

I also noticed that the error disappears when I remove this line (related to rendering which I placed in the layout before yielding the content):
But when I do that, the charts don't work.

```<code>{!! $chart->script() !!}
</code>```

In the content I placed:

```<code>{!! $chart->container() !!}
</code>```

I'm guessing there is some conflict with app.js?

```<code>app.js:38309 [Vue warn]: Error compiling template:

Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed.

191|
192|          </main>
193|                    <script type="text/javascript">
   |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
194|      var ctvChart = document.getElementById('mzaqnvhkcsrjgeoxdwuipybtl').getContext('2d');
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
195|      function mzaqnvhkcsrjgeoxdwuipybtl_create(data) {
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
196|          mzaqnvhkcsrjgeoxdwuipybtl_rendered = true;
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
197|          document.getElementById("mzaqnvhkcsrjgeoxdwuipybtl_loader").style.display = 'none';
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
198|          document.getElementById("mzaqnvhkcsrjgeoxdwuipybtl").style.display = 'block';
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
199|          window.mzaqnvhkcsrjgeoxdwuipybtl = new Chart(document.getElementById("mzaqnvhkcsrjgeoxdwuipybtl").getContext("2d"), {
   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.
.
.(...there is more)
</code>```

答:
I fixed it by moving

```<code>{!! $chart->script() !!}
</code>```

outside of the  tags in the layout.
I'm not sure why but it doesn't show that warning anymore.

Body:
I'm using Laravel charts from https://charts.erik.cat/ and I noticed that I'm getting the error below.

I also noticed that the error disappears when I remove this line (related to rendering which I placed in the layout before yielding the content):
But when I do that, the charts don't work.

{!! $chart->script() !!}

In the content I placed:

{!! $chart->container() !!}

I'm guessing there is some conflict with app.js?

app.js:38309 [Vue warn]: Error compiling template:

Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as

Body:
I fixed it by moving

{!! $chart->script() !!}

outside of the  tags in the layout.
I'm not sure why but it doesn't show that warning anymore.


问:
oracle update with correlated query
What is the correct answer? Choose two.

Examine this SQL statement:

```<code>UPDATE orders o
SET customer_name = (
    SELECT cust_last_name FROM customers  WHERE customer_id=o.customer_id
);
</code>```

Which two are true?

A. The subquery is executed before the UPDATE statement is executed.

B. All existing rows in the ORDERS table are updated.

C. The subquery is executed for every updated row in the ORDERS
table.

D. The UPDATE statement executes successfully even if the subquery
selects multiple rows.

E. The subquery is not a correlated subquery.

I know B is correct, but all other selection I believe is incorrect.

A. Subquery executes for every row that the outer query returns, so
it should execute after the outer query.

C. NOT for every updated row, it is for every row that the outer
query returns.

D. I tried. It causes an error ORA-01427: single-row subquery returns
more than one row

E. It is a correlated subquery.

答:
Consider option C:

C. The subquery is executed for every updated row in the ORDERS table.

You said:

NOT for every updated row, it is for every row that the outer query returns.

Yes. The subquery is indeed executed for every row in the outer query (let apart possible optimizations applied by the database). And every row in the outer query is updated - as you spotted, since you already, and correctly, selected option B: all existing rows in the ORDERS table are updated.

Note: your arguments against options A, D and 3 are valid.

Title: oracle update with correlated query

Body:
What is the correct answer? Choose two.

Examine this SQL statement:

UPDATE orders o
SET customer_name = (
    SELECT cust_last_name FROM customers  WHERE customer_id=o.customer_id
);

Which two are true?

A. The subquery is executed before the UPDATE statement is executed.

B. All existing rows in the ORDERS table are updated.

C. The subquery is executed for every updated row in the ORDERS
table.

D. The UPDATE statement executes successfully even if the subquery
selects multiple rows.

E. The subquery is not a correlated subquery.

I know B is correct, but all other selection I believe is incorrect.

A. Subquery executes for every row that the outer query returns, so
it should execute after the outer query.

C. NOT for every updated row, it is for every row that the outer
query returns.

D. I tried. It causes an error ORA-01427: single-row subquery returns
more than one row

E. It is a correlated subquery.


问:
Listing all user-installed packages in Debian
For a cyber security competition I participate in, I'm given a Debian virtual machine with many packages installed and asked to clean extraneous or malicious packages.

In the past, I've used dpkg -l | grep [searchterm] and a list of common packages to preform this task. However, this is extremely inefficient and time-consuming.

To speed up my task, is there a way to search through the list of packages installed on a system for which processes have been installed by a user and are not system "default" packages?

答:
The following Bash command works for me in Debian 10 (buster). It prints all manually installed packages minus the ones that came from your Debian installation (in other words, the packages that you installed with apt install):

sudo grep -oP "Unpacking \K[^: ]+" /var/log/installer/syslog \
  | sort -u | comm -13 /dev/stdin <(apt-mark showmanual | sort)
```

sudo is needed to search through /var/log/installer/syslog. You could also save this installer package list somewhere else if you don't want to use sudo every time.

Body:
The following Bash command works for me in Debian 10 (buster). It prints all manually installed packages minus the ones that came from your Debian installation (in other words, the packages that you installed with apt install):

sudo grep -oP "Unpacking \K[^: ]+" /var/log/installer/syslog \
  | sort -u | comm -13 /dev/stdin <(apt-mark showmanual | sort)

sudo is needed to search through /var/log/installer/syslog. You could also save this installer package list somewhere else if you don't want to use sudo every time.


问:
I want to prevent diagonal movement in Pygame
I'm working on making a version of the game snake and I'm trying to prevent diagonal movement. Is there a way to prevent multiple KEYDOWN events

This is my helper function that detects KEYDOWN events.

def _keydown_events(self, event):
    '''Responds to pressing keystrokes'''
    if event.type == pg.KEYDOWN:
        if event.key == pg.K_q:
            pg.display.quit()
            running = False
            sys.exit()
        elif event.key == pg.K_RIGHT:
            self.snake.move_right = True
        elif event.key == pg.K_LEFT:
            self.snake.move_left = True
        elif event.key == pg.K_UP:
            self.snake.move_up = True
        elif event.key == pg.K_DOWN:
            self.snake.move_down = True
```

答:
You have to ensure that just self.snake.move_right, self.snake.move_left, self.snake.move_up or  self.snake.move_down is set, but never 2 or more states simultaneously. e.g:

def _keydown_events(self, event):
    '''Responds to pressing keystrokes'''
    if event.type == pg.KEYDOWN:
        if event.key == pg.K_q:
            pg.display.quit()
            running = False
            sys.exit()
        elif if event.key in [pg.K_RIGHT, pg.K_LEFT, pg.K_UP, pg.K_DOWN]:
            self.snake.move_right = False
            self.snake.move_left = False
            self.snake.move_up = False
            self.snake.move_down = False
            if event.key == pg.K_RIGHT:
                self.snake.move_right = True
            elif event.key == pg.K_LEFT:
                self.snake.move_left = True
            elif event.key == pg.K_UP:
                self.snake.move_up = True
            elif event.key == pg.K_DOWN:
                self.snake.move_down = True
```

<hr>

<p>Anyway I recommend to remove the states <code>self.snake.move_right</code>, <code>self.snake.move_left</code>, <code>self.snake.move_up</code> or  <code>self.snake.move_down</code>.<br>
Use a single state which indicates the direction of the snake. Add a state <code>move_dir</code> and assign <code>pygame.key.name(event.key)</code>. The value of <code>move_dir</code> becomes "right", "left", "up" respectively "down" for <kbd>RIGHT</kbd>, <kbd>LEFT</kbd>, <kbd>UP</kbd> or <kbd>DOWN</kbd>. e.g: </p>

<pre class="lang-py prettyprint-override"><code>def _keydown_events(self, event):
    '''Responds to pressing keystrokes'''
    if event.type == pg.KEYDOWN:
        if event.key == pg.K_q:
            pg.display.quit()
            running = False
            sys.exit()

        elif if event.key in [pg.K_RIGHT, pg.K_LEFT, pg.K_UP, pg.K_DOWN]:
            # move_dir becomes "right", "left", "up" or "down"
            self.snake.move_dir = pygame.key.name(event.key)
</code>```

Of course you can state the move vector directly:

def _keydown_events(self, event):
    '''Responds to pressing keystrokes'''
    if event.type == pg.KEYDOWN:
        if event.key == pg.K_q:
            pg.display.quit()
            running = False
            sys.exit()

        elif if event.key in [pg.K_RIGHT, pg.K_LEFT, pg.K_UP, pg.K_DOWN]:

            move_dirs = {pg.K_RIGHT: (1, 0), pg.K_LEFT: (-1, 0),
                         pg.K_UP: (0, -1), pg.K_DOWN: (0, 1)}
            self.snake.move_dir = move_dirs[event.key]
```

Body:
You have to ensure that just self.snake.move_right, self.snake.move_left, self.snake.move_up or  self.snake.move_down is set, but never 2 or more states simultaneously. e.g:

def _keydown_events(self, event):
    '''Responds to pressing keystrokes'''
    if event.type == pg.KEYDOWN:
        if event.key == pg.K_q:
            pg.display.quit()
            running = False
            sys.exit()
        elif if event.key in [pg.K_RIGHT, pg.K_LEFT, pg.K_UP, pg.K_DOWN]:
            self.snake.move_right = False
            self.snake.move_left = False
            self.snake.move_up = False
            self.snake.move_down = False
            if event.key == pg.K_RIGHT:
                self.snake.move_right = True
            elif event.key == pg.K_LEFT:
                self.snake.move_left = True
            elif event.key == pg.K_UP:
                self.snake.move_up = True
            elif event.key == pg.K_DOWN:
                self.snake.move_down = True

Anyway I recommend to remove the states self.snake.move_right, self.snake.move_left, self.snake.move_up or  self.snake.move_down.

Use a single state which indicates the direction of the snake. Add a state move_dir and assign pygame.key.name(event.key). The value of move_dir becomes "right", "left", "up" respectively "down" for RIGHT, LEFT, UP or DOWN. e.g:

def _keydown_events(self, event):
    '''Responds to pressing keystrokes'''
    if event.type == pg.KEYDOWN:
        if event.key == pg.K_q:
            pg.display.quit()
            running = False
            sys.exit()

        elif if event.key in [pg.K_RIGHT, pg.K_LEFT, pg.K_UP, pg.K_DOWN]:
            # move_dir becomes "right", "left", "up" or "down"
            self.snake.move_dir = pygame.key.name(event.key)

Of course you can state the move vector directly:

def _keydown_events(self, event):
    '''Responds to pressing keystrokes'''
    if event.type == pg.KEYDOWN:
        if event.key == pg.K_q:
            pg.display.quit()
            running = False
            sys.exit()

        elif if event.key in [pg.K_RIGHT, pg.K_LEFT, pg.K_UP, pg.K_DOWN]:

            move_dirs = {pg.K_RIGHT: (1, 0), pg.K_LEFT: (-1, 0),
                         pg.K_UP: (0, -1), pg.K_DOWN: (0, 1)}
            self.snake.move_dir = move_dirs[event.key]


答: preg_match("/[Ff]ind me at (.+)/", "I give up, find me at street 1 and street 2") will capture everything after the "find me at"

Title: help with a PHP regex to extract text around a string

Body:
I am trying to use a regular expression and it's just breaking my brain.  I'll think I have it and the the script just breaks. I need to try to give people a way to report their location via SMS. I ask them to text me a string that looks like this:

I give up, stopping for the night.
  Find me at Main Street and Pine,
  Atlanta, GA.

And I want to break it at Find me at. I need to capture everything to the right of that (essentially their street corner) and I need to be able to detect if they didn't use proper capitalization for Find.

Any suggestions?


问:
How to manually change diverging colors in leaflet map/R?
I have produced a map of Denmark

```<code>library(leaflet.extras)
library(leaflet)

#Data

folk1 <- readr::read_csv2("http://api.statbank.dk/v1/data/folk1a/CSV?OMR%C3%85DE=*")

municipalityDK("INDHOLD","OMRÅDE",data=folk1,legend=T,pal = "GnBu") %>%
  setMapWidgetStyle(list(background= "white"))
</code>```

Which looks like:

However, I have not succeeded in finding a color palette that visualizes data the way I prefer. I have used those listed here.

I would like the color palette to look like this:

Can this be done manually?

答:
You can create a custom palette with RColorBrewer:

```<code>library(RColorBrewer)

colfunc <- colorRampPalette(c("#2C77BF", "red"))
</code>```

Then include your custom palette and number of selected colors in your map:

```<code>municipalityDK("INDHOLD","OMRÅDE",data=folk1,legend=T,pal = colfunc(10)) %>%
  setMapWidgetStyle(list(background= "white"))
</code>```

Map

Body:
I have produced a map of Denmark

library(leaflet.extras)
library(leaflet)

#Data

folk1 <- readr::read_csv2("http://api.statbank.dk/v1/data/folk1a/CSV?OMR%C3%85DE=*")

municipalityDK("INDHOLD","OMRÅDE",data=folk1,legend=T,pal = "GnBu") %>%
  setMapWidgetStyle(list(background= "white"))

Which looks like:

However, I have not succeeded in finding a color palette that visualizes data the way I prefer. I have used those listed here.

I would like the color palette to look like this:

Can this be done manually?

Body:
You can create a custom palette with RColorBrewer:

library(RColorBrewer)

colfunc <- colorRampPalette(c("#2C77BF", "red"))

Then include your custom palette and number of selected colors in your map:

municipalityDK("INDHOLD","OMRÅDE",data=folk1,legend=T,pal = colfunc(10)) %>%
  setMapWidgetStyle(list(background= "white"))

Map


问:
Intercept *all* requests from Android WebView
The title says it all. I would like to know about everything what the WebView is asking for. Some weird limitations like not knowing about XHR POST are not acceptable. In other words, something like iOS have in NSURLProtocol. That one is application-wide hook. I don't need such level of control, WebView-instance-specific hook would be good enough. Now, i know that nothing like that exists on Android out of the box. I know about shouldOverrideUrlLoading and shouldInterceptRequest, but it's largely unusable. I need to know about requests (method, HTTP version, headers, you know) not just merely the URL strings. Moreover the intercepting is awkwardly synchronous. What happens if shouldInterceptRequest call is blocked because i need to ask a different server for related resource? It appears to me being designed just for a local resource caching.

On the other hand, i am willing to throw anything at the problem. Some kind of native library, hooking into low level internals? Extending Chromium interfaces with help of an existing project (pwnall, mogoweb)? Reflecting into the existing webkit class privates? Application-specific proxy? Any insights appreciated. I have read through two dozens of existing SO questions. They all either suggest a partial hack (like working around XHR POST deficiency with JavaScript) or it goes unresponded altogether, very often.

答:
Try with inspeckage:

https://github.com/ac-pm/Inspeckage

It needs Xposed and root access to work. I've been able to see WebView requests from apps. Im figuring out how to recreate them with Python's requests module.

Hope that helps.


问:
Google Script - Email - Html for loop
I have recently been working on a script to send an email from a google spreadsheet when one or more values in a certain column are changed.

Below my email function:

```<code>function sendEmail(list){
  var recipient="emaild@gmail.com";
  var subject="Multiples prices have changed";
  var body = "";
  for(var i=0; i<list.length;i++){ // Get throught the list to write the body
    body=body + list[i][0] + " price has changed by " + list[i][1] + "\%\n";
  }
  MailApp.sendEmail(recipient, subject, body);
}
</code>```

list[i][0]

return the product title

listi

return the Δ%

So, The email body that I riceve is only text, I.e.:

```<code>product 1 price has changed by 20%
product 2 price has changed by 5%
product 3 price has changed by 15%
</code>```

I would like to inset a bit of style in order to riceve an email body like this:

Any help?

答:
```<code>function sendEmail(){
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var list=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn()).getValues();
  var recipient="emaild@gmail.com";
  var subject="Multiples prices have changed";
  var html='<style>td{border:px solid black;}#td1{font-size:22;color:black;font-weight:bold;}#td2{font-size:16;color:red;}{</style><table>';
  for(var i=0; i<list.length;i++){
    html+=Utilities.formatString('<tr><td id="td1">%s</td></tr><tr><td id="td2">%s</td></tr>',list[i][0],`${list[i][1]} ${list[i][2]}.`);
  }
  GmailApp.sendEmail(recipient, subject,'',{htmlBody: html});
  //var ui=HtmlService.createHtmlOutput(html);
  //SpreadsheetApp.getUi().showModelessDialog(ui, 'Price Changes')
}
</code>```

Here's what my spreadsheet looks like:

And here's the CSV of my data:

```<code>Product,Direction,Amount
Product1,price has increased ,10
Product2,price has increased ,20
Product3,price has increased ,30
Product4,price has increased ,40
Product5,price has increased ,50
Product6,price has increased ,60
</code>```

Title: Google Script - Email - Html for loop

Body:
I have recently been working on a script to send an email from a google spreadsheet when one or more values in a certain column are changed.

Below my email function:

function sendEmail(list){
  var recipient="emaild@gmail.com";
  var subject="Multiples prices have changed";
  var body = "";
  for(var i=0; i<list.length;i++){ // Get throught the list to write the body
    body=body + list[i][0] + " price has changed by " + list[i][1] + "\%\n";
  }
  MailApp.sendEmail(recipient, subject, body);
}

list[i][0]

return the product title

listi

return the Δ%

So, The email body that I riceve is only text, I.e.:

product 1 price has changed by 20%
product 2 price has changed by 5%
product 3 price has changed by 15%

I would like to inset a bit of style in order to riceve an email body like this:

Any help?

Body:
function sendEmail(){
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var list=sh.getRange(2,1,sh.getLastRow()-1,sh.getLastColumn()).getValues();
  var recipient="emaild@gmail.com";
  var subject="Multiples prices have changed";
  var html='<style>td{border:px solid black;}#td1{font-size:22;color:black;font-weight:bold;}#td2{font-size:16;color:red;}{</style><table>';
  for(var i=0; i<list.length;i++){
    html+=Utilities.formatString('<tr><td id="td1">%s</td></tr><tr><td id="td2">%s</td></tr>',list[i][0],`${list[i][1]} ${list[i][2]}.`);
  }
  GmailApp.sendEmail(recipient, subject,'',{htmlBody: html});
  //var ui=HtmlService.createHtmlOutput(html);
  //SpreadsheetApp.getUi().showModelessDialog(ui, 'Price Changes')
}

Here's what my spreadsheet looks like:

And here's the CSV of my data:

Product,Direction,Amount
Product1,price has increased ,10
Product2,price has increased ,20
Product3,price has increased ,30
Product4,price has increased ,40
Product5,price has increased ,50
Product6,price has increased ,60


问:
hello-jni NDK sample - ndk-build fails
I am following the steps on http://developer.android.com/sdk/ndk/overview.html to build the hello-jni sample, however when I get to Step 2 to run

```<code>cd $NDK-ROOT/samples/hello-jni
$NDK-ROOT/ndk-build
</code>```

in the Cygwin command prompt, I receive the following error messages:

```<code>/bin/sh: -c: line 0: unexpected EOF while looking for matching `''
/bin/sh: -c: line 1: syntax error: unexpected end of file
Android NDK: Host awk tool is outdated. Please define HOST_AWK to point to Gawk
or Nawk !
</code>```

I have Cygwin 1.7.9, Gnu Make 3.8.2, and Gawk 3.1.8 on my Windows machine, along with the r5b release of the Android NDK.
I also have set the HOST_AWK environment variable, which points to my Gawk folder.

Unfortunatley the sample cannot run successfully without this step, (if I run hello-jni, I immediately receive an UnsatisfiedLinkError exception).

Below is the portion of the init.mk file on my machine (found in NDK_ROOT/build/core) which creates this error:

```<code># Location of all awk scripts we use
BUILD_AWK := $(NDK_ROOT)/build/awk

AWK_TEST := $(shell $(HOST_AWK) -f $(BUILD_AWK)/check-awk.awk)
$(call ndk_log,Host awk test returned: $(AWK_TEST))
ifneq ($(AWK_TEST),Pass)
$(call __ndk_info,Host awk tool is outdated. Please define HOST_AWK to point to Gawk or     Nawk !)
$(call __ndk_error,Aborting.)
endif
</code>```

Thank-you for your help

答: Instead of HOST_AWK=gawk.exe, just do HOST_AWK=gawk

Title: hello-jni NDK sample - ndk-build fails

Body:
I am following the steps on http://developer.android.com/sdk/ndk/overview.html to build the hello-jni sample, however when I get to Step 2 to run

cd $NDK-ROOT/samples/hello-jni
$NDK-ROOT/ndk-build

in the Cygwin command prompt, I receive the following error messages:

/bin/sh: -c: line 0: unexpected EOF while looking for matching `''
/bin/sh: -c: line 1: syntax error: unexpected end of file
Android NDK: Host awk tool is outdated. Please define HOST_AWK to point to Gawk
or Nawk !

I have Cygwin 1.7.9, Gnu Make 3.8.2, and Gawk 3.1.8 on my Windows machine, along with the r5b release of the Android NDK.
I also have set the HOST_AWK environment variable, which points to my Gawk folder.

Unfortunatley the sample cannot run successfully without this step, (if I run hello-jni, I immediately receive an UnsatisfiedLinkError exception).

Below is the portion of the init.mk file on my machine (found in NDK_ROOT/build/core) which creates this error:

# Location of all awk scripts we use
BUILD_AWK := $(NDK_ROOT)/build/awk

AWK_TEST := $(shell $(HOST_AWK) -f $(BUILD_AWK)/check-awk.awk)
$(call ndk_log,Host awk test returned: $(AWK_TEST))
ifneq ($(AWK_TEST),Pass)
$(call __ndk_info,Host awk tool is outdated. Please define HOST_AWK to point to Gawk or     Nawk !)
$(call __ndk_error,Aborting.)
endif

Thank-you for your help


问:
'didSelectRowAt' is not being called
i have a question about the UITableView delegate function didSelectRowAt. Everything is working fine but unfortunately the didSelectRowAt is not called. I read in some other stackoverflow question about the problem and tried some solutions out but none of them works for me. I made a subclass of the tableview which is the delegate himself:

```<code>class MyTableView : UITableView, UITableViewDelegate{

    override func awakeFromNib() {

        super.awakeFromNib()

        separatorStyle = .none

        backgroundView = nil
        backgroundColor = UIColor.clear

        isScrollEnabled = false

        delegate = self
        isEditing = false
        allowsSelection = true

    }

//    func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
//
//    this is working
//
//    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        print("not called")

    }

}
</code>```

So all subclasses of MyTableView will implement the datasource stuff and this also working fine (in case somehow will mentioned this).

The strange thing is that didHighlightRowAt is called, so the delegate somehow works. Only the didSelectRowAt which I want is not being called.

By the way there aren't any UITapGestureRecognizer.

Can somehow give me any advice here. Are there properties which are wrong?

答:
I added a mechanism to hide keyboard when tapping out of text field:

```<code>    ...

    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap(recognizer:)))
    tapRecognizer.numberOfTapsRequired = 1
    self.view.addGestureRecognizer(tapRecognizer)
}

@objc func handleSingleTap(recognizer: UITapGestureRecognizer) {
    self.view.endEditing(true)
}
</code>```

The handleSingleTap stole the event. I removed everything above, and used this instead:

```<code>override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    view.endEditing(true)
}
</code>```

And editing came back!

Title: 'didSelectRowAt' is not being called

Body:
i have a question about the UITableView delegate function didSelectRowAt. Everything is working fine but unfortunately the didSelectRowAt is not called. I read in some other stackoverflow question about the problem and tried some solutions out but none of them works for me. I made a subclass of the tableview which is the delegate himself:

class MyTableView : UITableView, UITableViewDelegate{

    override func awakeFromNib() {

        super.awakeFromNib()

        separatorStyle = .none

        backgroundView = nil
        backgroundColor = UIColor.clear

        isScrollEnabled = false

        delegate = self
        isEditing = false
        allowsSelection = true

    }

//    func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) {
//
//    this is working
//
//    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        print("not called")

    }

}

So all subclasses of MyTableView will implement the datasource stuff and this also working fine (in case somehow will mentioned this).

The strange thing is that didHighlightRowAt is called, so the delegate somehow works. Only the didSelectRowAt which I want is not being called.

By the way there aren't any UITapGestureRecognizer.

Can somehow give me any advice here. Are there properties which are wrong?

Body:
I added a mechanism to hide keyboard when tapping out of text field:

    ...

    let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleSingleTap(recognizer:)))
    tapRecognizer.numberOfTapsRequired = 1
    self.view.addGestureRecognizer(tapRecognizer)
}

@objc func handleSingleTap(recognizer: UITapGestureRecognizer) {
    self.view.endEditing(true)
}

The handleSingleTap stole the event. I removed everything above, and used this instead:

override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
    view.endEditing(true)
}

And editing came back!


问:
why doesn't this function return a value?
Learning javascript, I am trying understand why the following function doesn't return true or false. When I step through the code with debugger I see that it steps into either return true or return false case.

```<code>doesNumExistInArray = (objArray, num) => {
    Object.keys(objArray).forEach(key => {
      if (objArray[key].number === parseInt(num)) {
        return true;
      } else {
        return false;
      }
    });
  };
</code>```

But calling isDuplicate = doesNumExistInArray(objects, num) always assigns isDuplicate undefined. What am I missing?

答:
doesNumExistInArray is a function, but it does not return anything. It actually runs, with Array.forEach, what's called an "anonymous function" that loops over the keys in objArray.

Basically, Array.forEach does something for each element and returns nothing (like a void in other languages), where Array.map returns some modified version of the original array. Let's use Array.map to turn the array into a list of Booleans denoting whether or not the objArray key is equal to the number given as an argument (will look like [true, false, false] for input 1), then use Array.reduce to sum the booleans where true => 1 and false => 0. Basically, summing a list of booleans will give you the number of true values - if that number is not zero, we found a match.

That might seem really complicated, but this algorithm would work in Python and other frameworks where you want to check if there's at least one true value in a list of booleans.

doesNumExistInArray = (objArray, num) => Object.keys(objArray).map(
    key => objArray[key].number === parseInt(num)
  ).reduce((a,b) => a + b) > 0;

var objArray = [
  {
    number: 1,
  },
  {
    number: 2,
  },
  {
    number: 3
  }
];

console.log("doesNumExistInArray(objArray, 1) =>", doesNumExistInArray(objArray, 1));
console.log("doesNumExistInArray(objArray, 5) =>", doesNumExistInArray(objArray, 5));

// see that Array.forEach returns undefined
console.log("[1,2,3].forEach((x) => x * 2)=>\n", [1,2,3].forEach((x) => x * 2))

// whereas Array.map returns callback output
console.log("[1,2,3].map((x) => x * 2)=>\n", [1,2,3].map((x) => x * 2))```

Body:
Learning javascript, I am trying understand why the following function doesn't return true or false. When I step through the code with debugger I see that it steps into either return true or return false case.

doesNumExistInArray = (objArray, num) => {
    Object.keys(objArray).forEach(key => {
      if (objArray[key].number === parseInt(num)) {
        return true;
      } else {
        return false;
      }
    });
  };

But calling isDuplicate = doesNumExistInArray(objects, num) always assigns isDuplicate undefined. What am I missing?