问:
Infinite list in Haskell
I'm trying to define a function that creates infinite list of all possible words in my simple grammar. But ghci freezes when I enter head (generate [] []), although head (generate' [] []) works fine (but I still want an infinite list). What's the problem?

```<code>data Start = Start deriving(Show)
data MyExpr = MyExprStart Start | MyExpr1 MyExpr | MyExpr2 MyExpr deriving(Show)

generate :: [MyExpr] -> [MyExpr] -> [MyExpr]
generate [] []         = generate [MyExprStart Start] []
generate current prev  = generate (concatMap nextExprs current) (prev ++ current)

generate' :: [MyExpr] -> [MyExpr] -> [MyExpr]
generate' [] []         = generate' [MyExprStart Start] []
generate' current prev  =
  if (length current + length prev) < 5 then
    generate' (concatMap nextExprs current) (prev ++ current)
  else prev ++ current

nextExprs :: MyExpr -> [MyExpr]
nextExprs expr = [MyExpr1 expr, MyExpr2 expr]
</code>```

UPD:
Thank you, I got the point. I think I should define my function like that:

```<code>generate :: [MyExpr] -> [MyExpr]
generate []         = generate [MyExprStart Start]
generate current    = current ++ generate (concatMap nextExprs current)
</code>```

答:
```<code>generate :: [MyExpr] -> [MyExpr] -> [MyExpr]
generate ... = generate ...
generate ... = generate ...
</code>```

Any definition of this form will always call itself before producing any output. This kind of inductive structure can be defined only if, at least at some point, it returns some part of the output before recursing, e.g. emitting the first element of the output list.

```<code>generate' :: [MyExpr] -> [MyExpr] -> [MyExpr]
generate' [] []         = generate' [MyExprStart Start] []
generate' current prev  =
  if (length current + length prev) < 5 then
    generate' (concatMap nextExprs current) (prev ++ current)
  else prev ++ current
</code>```

By comparison, in generate' the else branch does not recurse, so it will produce the output. Even if we had something like

```<code>else someNonEmptyList ++ generate' ...
</code>```

this would work, since the first few list elements would be produced.

Further, keep in mind that generating all the possible expressions merging potentially infinite lists with ++ is a bad idea. Indeed, if xs is infinite then xs ++ ys is equal to xs, since ys will never be reached in finite time. You probably want a fair interleaving of xs and ys when they are infinite.

A similar question used the omega monad to achieve the complete enumeration.

Title: Infinite list in Haskell

Body:
I'm trying to define a function that creates infinite list of all possible words in my simple grammar. But ghci freezes when I enter head (generate [] []), although head (generate' [] []) works fine (but I still want an infinite list). What's the problem?

data Start = Start deriving(Show)
data MyExpr = MyExprStart Start | MyExpr1 MyExpr | MyExpr2 MyExpr deriving(Show)

generate :: [MyExpr] -> [MyExpr] -> [MyExpr]
generate [] []         = generate [MyExprStart Start] []
generate current prev  = generate (concatMap nextExprs current) (prev ++ current)

generate' :: [MyExpr] -> [MyExpr] -> [MyExpr]
generate' [] []         = generate' [MyExprStart Start] []
generate' current prev  =
  if (length current + length prev) < 5 then
    generate' (concatMap nextExprs current) (prev ++ current)
  else prev ++ current

nextExprs :: MyExpr -> [MyExpr]
nextExprs expr = [MyExpr1 expr, MyExpr2 expr]

UPD:
Thank you, I got the point. I think I should define my function like that:

generate :: [MyExpr] -> [MyExpr]
generate []         = generate [MyExprStart Start]
generate current    = current ++ generate (concatMap nextExprs current)

Body:
generate :: [MyExpr] -> [MyExpr] -> [MyExpr]
generate ... = generate ...
generate ... = generate ...

Any definition of this form will always call itself before producing any output. This kind of inductive structure can be defined only if, at least at some point, it returns some part of the output before recursing, e.g. emitting the first element of the output list.

generate' :: [MyExpr] -> [MyExpr] -> [MyExpr]
generate' [] []         = generate' [MyExprStart Start] []
generate' current prev  =
  if (length current + length prev) < 5 then
    generate' (concatMap nextExprs current) (prev ++ current)
  else prev ++ current

By comparison, in generate' the else branch does not recurse, so it will produce the output. Even if we had something like

else someNonEmptyList ++ generate' ...

this would work, since the first few list elements would be produced.

Further, keep in mind that generating all the possible expressions merging potentially infinite lists with ++ is a bad idea. Indeed, if xs is infinite then xs ++ ys is equal to xs, since ys will never be reached in finite time. You probably want a fair interleaving of xs and ys when they are infinite.

A similar question used the omega monad to achieve the complete enumeration.


来源: stackexchange

问:
How to sort content of a csv file in java
I have a big csv file that looks like this

```<code> Order ID,Order Priority,Order Quantity,Unit Price,Ship Mode,Customer Name,Customer Segment,Product Category
 3,Low,6,38.94,Regular Air,Muhammed MacIntyre,Small Business,Office Supplies
 293,High,49,208.16,Delivery Truck,Barry French,Consumer,Office Supplies
 293,High,27,8.69,Regular Air,Barry French,Consumer,Office Supplies
 483,High,30,195.99,Regular Air,Clay Rozendal,Corporate,Technology
</code>```

I am able to display it but i don't know how to sort it and display it again sorted. Here's my code so far

```<code>package project1;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws FileNotFoundException {
            Scanner input = new Scanner(System.in);
            int choice=0;
            boolean flag = true;

            while (flag) {
                System.out.println("Enter 1 to display data.");
                System.out.println("Enter 2 to sort data.");
                System.out.println("Enter 3 to idk.");
                System.out.println("Enter 0 to exit.");
                System.out.print("Your choice: ");
                choice = input.nextInt();
                if (choice ==1) {
                    File inputFile = new File("dataToLoad.csv");
                    String line;
                    String delimiter = ",";
                    Scanner in = new Scanner(inputFile);
                    int numberOfLines = 0;
                    int numberOfColumns = 0;
                    while (in.hasNextLine()){
                        line = in.nextLine();
                        numberOfLines++;
                    }
                    in.close();
                    String[][] data = new String[numberOfLines][8];
                    in = new Scanner(inputFile);
                    int currentRow = 0;
                    while (in.hasNextLine()){
                        line = in.nextLine();
                        String[] parts = line.split(delimiter);
                        numberOfColumns = parts.length;
                        for (int i = 0; i<numberOfColumns; i++) {
                            data[currentRow][i] = parts[i];
                        }
                        currentRow++;
                    }
                    in.close();
                    System.out.println(Arrays.deepToString(data));
                    for (int row=0; row<numberOfLines; row++) {
                        for (int col=0; col<numberOfColumns; col++) {
                            System.out.printf("%-20s", data[row][col]);
                        }
                        System.out.println();
                    }
                }
                else {
                    if (choice ==2) {

                    }
                    else
                        if (choice==0) {
                        System.out.println("Good bye!");
                        flag = false;
                    }
                else System.out.println("I am sorry, this is not a valid option. Please try again.");
            }
            }
    }
}
</code>```

As you can see, i give the user the option to display the data, display them sorted (according to id) and i also want the user to choose how to sort the code. I am stuck at sorting.

答:
Stop reinventing the wheel; use a csv open source library (for example, opencsv).

Create a class that represents one row of data in your csv file; I'll refer to this as RowClass.

Read the CSV file one row at a time.  Each row will arrive as a String[].

Create and populate one instance of RowClass per row of the CSV file.

Store the RowClass objects in a List; I'll call this rowList.

Sort rowList using a Comparator that you create.  Create one Comparator for each sort option.

Implement RowClass.toString() to display one row.

ContentLicense: CC BY-SA 3.0

Body:
I have a big csv file that looks like this

 Order ID,Order Priority,Order Quantity,Unit Price,Ship Mode,Customer Name,Customer Segment,Product Category
 3,Low,6,38.94,Regular Air,Muhammed MacIntyre,Small Business,Office Supplies
 293,High,49,208.16,Delivery Truck,Barry French,Consumer,Office Supplies
 293,High,27,8.69,Regular Air,Barry French,Consumer,Office Supplies
 483,High,30,195.99,Regular Air,Clay Rozendal,Corporate,Technology

I am able to display it but i don't know how to sort it and display it again sorted. Here's my code so far

package project1;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws FileNotFoundException {
            Scanner input = new Scanner(System.in);
            int choice=0;
            boolean flag = true;

            while (flag) {
                System.out.println("Enter 1 to display data.");
                System.out.println("Enter 2 to sort data.");
                System.out.println("Enter 3 to idk.");
                System.out.println("Enter 0 to exit.");
                System.out.print("Your choice: ");
                choice = input.nextInt();
                if (choice ==1) {
                    File inputFile = new File("dataToLoad.csv");
                    String line;
                    String delimiter = ",";
                    Scanner in = new Scanner(inputFile);
                    int numberOfLines = 0;
                    int numberOfColumns = 0;
                    while (in.hasNextLine()){
                        line = in.nextLine();
                        numberOfLines++;
                    }
                    in.close();
                    String[][] data = new String[numberOfLines][8];
                    in = new Scanner(inputFile);
                    int currentRow = 0;
                    while (in.hasNextLine()){
                        line = in.nextLine();
                        String[] parts = line.split(delimiter);
                        numberOfColumns = parts.length;
                        for (int i = 0; i<numberOfColumns; i++) {
                            data[currentRow][i] = parts[i];
                        }
                        currentRow++;
                    }
                    in.close();
                    System.out.println(Arrays.deepToString(data));
                    for (int row=0; row<numberOfLines; row++) {
                        for (int col=0; col<numberOfColumns; col++) {
                            System.out.printf("%-20s", data[row][col]);
                        }
                        System.out.println();
                    }
                }
                else {
                    if (choice ==2) {

                    }
                    else
                        if (choice==0) {
                        System.out.println("Good bye!");
                        flag = false;
                    }
                else System.out.println("I am sorry, this is not a valid option. Please try again.");
            }
            }
    }
}

As you can see, i give the user the option to display the data, display them sorted (according to id) and i also want the user to choose how to sort the code. I am stuck at sorting.


问:
How can I use TaskFactory.StartNew<Task<Result>> with async methods?
I have an async Func<> where I "await" for a async method. I want to make a lot of parallel calls to that Func<> using TaskFactory.StartNew, like the below code, but I get the followin error:

error converting 'System.Threading.Tasks.Task<System.Threading.Tasks.Task<Result>>' to 'System.Threading.Tasks.Task<Result>'

How can I have a parallel calls for a async method?

```<code>Func<object, Task<Result>> action = async (object m) =>
{
    try
    {
        return await Send<Message, Result>(m as Message);
    }
    catch (Exception exc)
    {
        Result result = new Result();
        (result as ResponseBaseDto).Success = false;
        (result as ResponseBaseDto).ErrorList = new List<Entities.Common.ErrorDto>()
        {
            new Entities.Common.ErrorDto{ Code = 9999, Message = exc.Message }
        };
        return result;
    }
};

// Error on request.ForEach
request.ForEach(r => sending.Add(taskFactory.StartNew<Task<Result>>(action, r)));
var tareas = sending.ToArray();
await Task.WhenAll(tareas);
return tareas.Select(s => s.Result).ToList();
</code>```

答:
Assuming you are using a taskFactory.StartNew( instead of Task.Run( because you have a special configured TaskFactory you need to unwrap the result of the StartNew, which will be a Task<Task<Result>>. The easiest solution is use the .Unwrap() extension method to unwrap the nested task.

You also should replace the .ForEach(r=> sending.Add( with a .Select(r => statement to reduce the number of times the list is iterated over. If you are returning a IEnumerable<Result> instead of a List<Result> you can remove your final .ToList() too.

```<code>var tareas = request.Select(r => taskFactory.StartNew<Task<Result>>(action, r).Unwrap());
var results = await Task.WhenAll(tareas); //results is a `Result[]`
return results.ToList(); // you may not need this .ToList().
</code>```

If you are not using a special task factory your code can be simplified to

```<code>var tareas = request.Select(r => Task.Run(() => action(r)));
var results = await Task.WhenAll(tareas); //results is a `Result[]`
return results.ToList(); // you may not need this .ToList().
</code>```

Body:
I have an async Func<> where I "await" for a async method. I want to make a lot of parallel calls to that Func<> using TaskFactory.StartNew, like the below code, but I get the followin error:

error converting 'System.Threading.Tasks.Task<System.Threading.Tasks.Task<Result>>' to 'System.Threading.Tasks.Task<Result>'

How can I have a parallel calls for a async method?

Func<object, Task<Result>> action = async (object m) =>
{
    try
    {
        return await Send<Message, Result>(m as Message);
    }
    catch (Exception exc)
    {
        Result result = new Result();
        (result as ResponseBaseDto).Success = false;
        (result as ResponseBaseDto).ErrorList = new List<Entities.Common.ErrorDto>()
        {
            new Entities.Common.ErrorDto{ Code = 9999, Message = exc.Message }
        };
        return result;
    }
};

// Error on request.ForEach
request.ForEach(r => sending.Add(taskFactory.StartNew<Task<Result>>(action, r)));
var tareas = sending.ToArray();
await Task.WhenAll(tareas);
return tareas.Select(s => s.Result).ToList();

Body:
Assuming you are using a taskFactory.StartNew( instead of Task.Run( because you have a special configured TaskFactory you need to unwrap the result of the StartNew, which will be a Task<Task<Result>>. The easiest solution is use the .Unwrap() extension method to unwrap the nested task.

You also should replace the .ForEach(r=> sending.Add( with a .Select(r => statement to reduce the number of times the list is iterated over. If you are returning a IEnumerable<Result> instead of a List<Result> you can remove your final .ToList() too.

var tareas = request.Select(r => taskFactory.StartNew<Task<Result>>(action, r).Unwrap());
var results = await Task.WhenAll(tareas); //results is a `Result[]`
return results.ToList(); // you may not need this .ToList().

If you are not using a special task factory your code can be simplified to

var tareas = request.Select(r => Task.Run(() => action(r)));
var results = await Task.WhenAll(tareas); //results is a `Result[]`
return results.ToList(); // you may not need this .ToList().

ContentLicense: CC BY-SA 4.0


问:
How can I create a column that cumulatively adds the sum of two previous rows based on conditions?
I tried asking this question before but was it was poorly stated. This is a new attempt cause I haven't solved it yet.

I have a dataset with winners, losers, date, winner_points and loser_points.

For each row, I want two new columns, one for the winner and one for the loser that shows how many points they have scored so far (as both winners and losers).

Example data:

```<code>winner <- c(1,2,3,1,2,3,1,2,3)
loser <-  c(3,1,1,2,1,1,3,1,2)
date <- c("2017-10-01","2017-10-02","2017-10-03","2017-10-04","2017-10-05","2017-10-06","2017-10-07","2017-10-08","2017-10-09")
winner_points <- c(2,1,2,1,2,1,2,1,2)
loser_points <- c(1,0,1,0,1,0,1,0,1)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points)
</code>```

I want the output to be:

```<code>winner_points_sum <- c(0, 0, 1, 3, 1, 3, 5, 3, 5)
loser_points_sum <- c(0, 2, 2, 1, 4, 5, 4, 7, 4)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points, winner_points_sum, loser_points_sum)
</code>```

How I've solved it thus far is to do a for loop such as:

```<code>library(dplyr)
test_data$winner_points_sum_loop <- 0
test_data$loser_points_sum_loop <- 0

for(i in row.names(test_data)) {
  test_data[i,]$winner_points_sum_loop <-
    (
    test_data %>%
      dplyr::filter(winner == test_data[i,]$winner & date < test_data[i,]$date) %>%
      dplyr::summarise(points = sum(winner_points, na.rm = TRUE))
  +
    test_data %>%
      dplyr::filter(loser == test_data[i,]$winner & date < test_data[i,]$date) %>%
      dplyr::summarise(points = sum(loser_points, na.rm = TRUE))
    )
}

test_data$winner_points_sum_loop <- unlist(test_data$winner_points_sum_loop)
</code>```

Any suggestions how to tackle this problem? The queries take quite some time when the row numbers add up. I've tried elaborating with the AVE function, I can do it for one column to sum a players point as winner but can't figure out how to add their points as loser.

答:
I finally understood what you want. And I took an approach of getting cumulative points of each player at each point in time and then joining it to the original test_data data frame.

```<code>winner <- c(1,2,3,1,2,3,1,2,3)
loser <-  c(3,1,1,2,1,1,3,1,2)
date <- c("2017-10-01","2017-10-02","2017-10-03","2017-10-04","2017-10-05","2017-10-06","2017-10-07","2017-10-08","2017-10-09")
winner_points <- c(2,1,2,1,2,1,2,1,2)
loser_points <- c(1,0,1,0,1,0,1,0,1)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points)

library(dplyr)
library(tidyr)

cum_points <- test_data %>%
  gather(end_game_status, player_id, winner, loser) %>%
  gather(which_point, how_many_points, winner_points, loser_points) %>%
  filter(
    (end_game_status == "winner" & which_point == "winner_points") |
      (end_game_status == "loser" & which_point == "loser_points")) %>%
  arrange(date = as.Date(date)) %>%
  group_by(player_id) %>%
  mutate(cumulative_points = cumsum(how_many_points)) %>%
  mutate(cumulative_points_sofar = lag(cumulative_points, default = 0))
  select(player_id, date, cumulative_points)

output <- test_data %>%
  left_join(cum_points, by = c('date', 'winner' = 'player_id')) %>%
  rename(winner_points_sum = cumulative_points_sofar) %>%
  left_join(cum_points, by = c('date', 'loser' = 'player_id')) %>%
  rename(loser_points_sum = cumulative_points_sofar)
output
</code>```

Body:
I tried asking this question before but was it was poorly stated. This is a new attempt cause I haven't solved it yet.

I have a dataset with winners, losers, date, winner_points and loser_points.

For each row, I want two new columns, one for the winner and one for the loser that shows how many points they have scored so far (as both winners and losers).

Example data:

winner <- c(1,2,3,1,2,3,1,2,3)
loser <-  c(3,1,1,2,1,1,3,1,2)
date <- c("2017-10-01","2017-10-02","2017-10-03","2017-10-04","2017-10-05","2017-10-06","2017-10-07","2017-10-08","2017-10-09")
winner_points <- c(2,1,2,1,2,1,2,1,2)
loser_points <- c(1,0,1,0,1,0,1,0,1)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points)

I want the output to be:

winner_points_sum <- c(0, 0, 1, 3, 1, 3, 5, 3, 5)
loser_points_sum <- c(0, 2, 2, 1, 4, 5, 4, 7, 4)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points, winner_points_sum, loser_points_sum)

How I've solved it thus far is to do a for loop such as:

library(dplyr)
test_data$winner_points_sum_loop <- 0
test_data$loser_points_sum_loop <- 0

for(i in row.names(test_data)) {
  test_data[i,]$winner_points_sum_loop <-
    (
    test_data %>%
      dplyr::filter(winner == test_data[i,]$winner & date < test_data[i,]$date) %>%
      dplyr::summarise(points = sum(winner_points, na.rm = TRUE))
  +
    test_data %>%
      dplyr::filter(loser == test_data[i,]$winner & date < test_data[i,]$date) %>%
      dplyr::summarise(points = sum(loser_points, na.rm = TRUE))
    )
}

test_data$winner_points_sum_loop <- unlist(test_data$winner_points_sum_loop)

Any suggestions how to tackle this problem? The queries take quite some time when the row numbers add up. I've tried elaborating with the AVE function, I can do it for one column to sum a players point as winner but can't figure out how to add their points as loser.

Body:
I finally understood what you want. And I took an approach of getting cumulative points of each player at each point in time and then joining it to the original test_data data frame.

winner <- c(1,2,3,1,2,3,1,2,3)
loser <-  c(3,1,1,2,1,1,3,1,2)
date <- c("2017-10-01","2017-10-02","2017-10-03","2017-10-04","2017-10-05","2017-10-06","2017-10-07","2017-10-08","2017-10-09")
winner_points <- c(2,1,2,1,2,1,2,1,2)
loser_points <- c(1,0,1,0,1,0,1,0,1)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points)

library(dplyr)
library(tidyr)

cum_points <- test_data %>%
  gather(end_game_status, player_id, winner, loser) %>%
  gather(which_point, how_many_points, winner_points, loser_points) %>%
  filter(
    (end_game_status == "winner" & which_point == "winner_points") |
      (end_game_status == "loser" & which_point == "loser_points")) %>%
  arrange(date = as.Date(date)) %>%
  group_by(player_id) %>%
  mutate(cumulative_points = cumsum(how_many_points)) %>%
  mutate(cumulative_points_sofar = lag(cumulative_points, default = 0))
  select(player_id, date, cumulative_points)

output <- test_data %>%
  left_join(cum_points, by = c('date', 'winner' = 'player_id')) %>%
  rename(winner_points_sum = cumulative_points_sofar) %>%
  left_join(cum_points, by = c('date', 'loser' = 'player_id')) %>%
  rename(loser_points_sum = cumulative_points_sofar)
output


答: The second form with four tables is the correct one. You could delete rel_id from books_users_relationsship as primary key might be composite with both user_id and book_id, just like in groups_books_relationsship table.

ContentLicense: CC BY-SA 2.5

Title: What is the best way to handle these MySQL database relationsships?

Body:
I'm building a small website that let users recommend their favourite books to eachother. So I have two tables, books and groups. A user can have 0 or more books in their library, and a book belongs to 1 or more groups. Currently, my tables look like this:

books table
|---------|------------|---------------|
| book_id | book_title | book_owner_id |
|---------|------------|---------------|
| 22      | something  | 12         |
|---------|------------|---------------|
| 23      | something2 | 12         |
|---------|------------|---------------|

groups table
|----------|------------|---------------|---------|
| group_id | group_name | book_owner_id | book_id |
|----------|------------|---------------|---------|
| 231      | random     | 12            | 22      |
|----------|------------|---------------|---------|
| 231      | random     | 12            | 23      |
|----------|------------|---------------|---------|

As you can see, the relationsships between users+books and books+groups are defined in the tables. Should I define the relationsships in their own tables instead? Something like this:

books table
|---------|------------|
| book_id | book_title |
|---------|------------|
| 22      | something  |
|---------|------------|
| 23      | something2 |
|---------|------------|

books_users_relationsship table
|---------|------------|---------|
| rel_id  | user_id    | book_id |
|---------|------------|---------|
| 1       | 12         | 22   |
|---------|------------|---------|
| 2       | 12         | 23   |
|---------|------------|---------|

groups table
|----------|------------|
| group_id | group_name |
|----------|------------|
| 231      | random     |
|----------|------------|

groups_books_relationsship table
|----------|---------|
| group_id | book_id |
|----------|---------|
| 231      | 22      |
|----------|---------|
| 231      | 23      |
|----------|---------|

Thanks for your time.


问:
pygsheets authentication successful but token file not read back in correctly
I have the google api enabled and an oauth 2.0 id created on google console and i get prompted in a web browser to authorize access but then I get an FileNotFoundError error in Jupyter Labs

gc = pygsheets.authorize(outh_file='client_secret.json')

Authentication successful.
  Storing credentials to C:\Users\me\Documents\Folder\PythonProject\sheets.googleapis.com-python.json

The token file is created successfully but the NotFoundError is looking in a temp folder not the folder it saved the file

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\me\\AppData\\Local\\Temp\\02b35e51-6576-4739-9f1c-135348c707f0\\www.googleapis.com,drive,v3,files,corpora=user&pageSize=500&fields=files%28id%2C+name%29&q=mimeType%3D%27application%2Fvnd.google-apps.spreadsheet%27&supportsTeamDrives=false&includeTeamDriveItems=fal,6fa737f4e6c871f0b9ea9ea38467b8b6'

答:
This is a known bug and is fixed in the trunk. So, either install pygsheets from staging branch

```<code>pip install https://github.com/nithinmurali/pygsheets/archive/staging.zip
</code>```

or as a workaround disable cache

```<code>gc = pygsheets.authorize(outh_file='client_secret.json', no_cache=True)
</code>```

Body:
This is a known bug and is fixed in the trunk. So, either install pygsheets from staging branch

pip install https://github.com/nithinmurali/pygsheets/archive/staging.zip

or as a workaround disable cache

gc = pygsheets.authorize(outh_file='client_secret.json', no_cache=True)


答:
The generate function freezes, because it encodes an infinite recursion. Look: every case of it just calls the function itself. There is no condition when it actually returns something that is not a call to itself. So when you try to run it, it just keeps calling itself forever.

The generate' function, on the other hand, will bail out as soon at the combined length of two input lists exceeds 5. So that's when returns you a result.

To make this function start returning data before evaluating completely (which it can never do), you need to first return the non-recursive cases, and then append the recursive cases to them by calling generate recursively:

```<code>generate = (MyExprStart Start) : [recur e | e <- generate, recur <- [MyExpr1, MyExpr2]]
</code>```

GHCi:

```<code>> head generate
MyExprStart Start
> take 10 generate
[MyExprStart Start, MyExpr1 (MyExprStart Start),
 MyExpr2 (MyExprStart Start), MyExpr1 (MyExpr1 (MyExprStart Start)),
 MyExpr2 (MyExpr1 (MyExprStart Start)),
 MyExpr1 (MyExpr2 (MyExprStart Start)),
 MyExpr2 (MyExpr2 (MyExprStart Start)),
 MyExpr1 (MyExpr1 (MyExpr1 (MyExprStart Start))),
 MyExpr2 (MyExpr1 (MyExpr1 (MyExprStart Start))),
 MyExpr1 (MyExpr2 (MyExpr1 (MyExprStart Start)))]
</code>```

NOTE: the order of generators in the list comprehension is important. If you swap them, the execution will never get to MyExpr2, because it would need to exhaust the generate list first, and that list is infinite.

Title: Infinite list in Haskell

Body:
The generate function freezes, because it encodes an infinite recursion. Look: every case of it just calls the function itself. There is no condition when it actually returns something that is not a call to itself. So when you try to run it, it just keeps calling itself forever.

The generate' function, on the other hand, will bail out as soon at the combined length of two input lists exceeds 5. So that's when returns you a result.

To make this function start returning data before evaluating completely (which it can never do), you need to first return the non-recursive cases, and then append the recursive cases to them by calling generate recursively:

generate = (MyExprStart Start) : [recur e | e <- generate, recur <- [MyExpr1, MyExpr2]]

GHCi:

> head generate
MyExprStart Start
> take 10 generate
[MyExprStart Start, MyExpr1 (MyExprStart Start),
 MyExpr2 (MyExprStart Start), MyExpr1 (MyExpr1 (MyExprStart Start)),
 MyExpr2 (MyExpr1 (MyExprStart Start)),
 MyExpr1 (MyExpr2 (MyExprStart Start)),
 MyExpr2 (MyExpr2 (MyExprStart Start)),
 MyExpr1 (MyExpr1 (MyExpr1 (MyExprStart Start))),
 MyExpr2 (MyExpr1 (MyExpr1 (MyExprStart Start))),
 MyExpr1 (MyExpr2 (MyExpr1 (MyExprStart Start)))]

NOTE: the order of generators in the list comprehension is important. If you swap them, the execution will never get to MyExpr2, because it would need to exhaust the generate list first, and that list is infinite.


问:
If a cells are selected (from more than one sheet) then show message box
For starters, I am self taught and still learning (I learn a great deal from this website). That being said, please do not assume something is obvious. I will need help altering the code if your solution is too complex.

What I want to accomplish is; if you select cell A10 on "Sheet3", "Sheet4", and "Sheet5" then I want a message box to appear with the information from Sheets("Sheet6").Range("A1").

```<code>Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("A10")) Is Nothing Then ' this range is where you click to get the msgbox
                Dim rng As Range, s As String, x As String
                Set rng = Sheets("Sheet6").Range("A1") ' this defines x
                 s = "Define: " ' s is what appears first
                 x = s & rng.Value ' x is what appears after s

                 MsgBox x
        End If
    End If
End Sub
</code>```

What I would like to happen; if you are in "Sheet3", "Sheet4", and "Sheet5" and select A10 in any of those three sheets, it will appear with the message box that is defined in the code.

What is working; currently this is a private sub that is directly in "Sheet5". When it is here, if cell A10 (in "Sheet5") is selected the information from "Sheet6" A1 appears in the message box as I want.

What is not working; because this is a private sub and is inside "Sheet5" I am struggling to get it to work with A10 from "Sheet3" and "Sheet4".

I attempted to alter the code by moving it and declaring it a public sub to work for all sheets but so far am unsuccessful.

答:
Worksheet_SelectionChange has to be in the private module of a worksheet. However it can then call another routine in a public module

So if you put

```<code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)
   CheckSelection target
End Sub
</code>```

Into each of your three sheets, you can then put your code in a public module

```<code>    Public Sub CheckSelection(Target as range)
        etc
</code>```

Body:
For starters, I am self taught and still learning (I learn a great deal from this website). That being said, please do not assume something is obvious. I will need help altering the code if your solution is too complex.

What I want to accomplish is; if you select cell A10 on "Sheet3", "Sheet4", and "Sheet5" then I want a message box to appear with the information from Sheets("Sheet6").Range("A1").

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("A10")) Is Nothing Then ' this range is where you click to get the msgbox
                Dim rng As Range, s As String, x As String
                Set rng = Sheets("Sheet6").Range("A1") ' this defines x
                 s = "Define: " ' s is what appears first
                 x = s & rng.Value ' x is what appears after s

                 MsgBox x
        End If
    End If
End Sub

What I would like to happen; if you are in "Sheet3", "Sheet4", and "Sheet5" and select A10 in any of those three sheets, it will appear with the message box that is defined in the code.

What is working; currently this is a private sub that is directly in "Sheet5". When it is here, if cell A10 (in "Sheet5") is selected the information from "Sheet6" A1 appears in the message box as I want.

What is not working; because this is a private sub and is inside "Sheet5" I am struggling to get it to work with A10 from "Sheet3" and "Sheet4".

I attempted to alter the code by moving it and declaring it a public sub to work for all sheets but so far am unsuccessful.

Body:
Worksheet_SelectionChange has to be in the private module of a worksheet. However it can then call another routine in a public module

So if you put

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
   CheckSelection target
End Sub

Into each of your three sheets, you can then put your code in a public module

    Public Sub CheckSelection(Target as range)
        etc


问:
resize svg icon for google map marker
I'm having problem with icon resizing in google map.
I have an svg file for make it responsive.

this is how I call the svg file

```<code>MyGreenSVG = {
    url: 'greenFill.svg',
    size: new google.maps.Size(20, 35)
};
</code>```

the property: size doesn't change the size of my icon, but only crop it.
the only way is to change the width and height in my svg file, and make 2 versions of it.
so I loose the interest of using svg...

this is a preview of my svg file :

```<code><svg version="1.1"
x="0px" y="0px" width="41.8px" height="74px" viewBox="0 0 41.8 74" enable-background="new 0 0 41.8 74" xml:space="preserve">
</code>```

答:
I know this is an old post, so just an update from me.

This works for me without using MarkerImage, but it's imperative that the svg has its width and height properties set.

And you must use the icon property "scaledSize" to set the size of the icon on the map

Title: resize svg icon for google map marker

Body:
I'm having problem with icon resizing in google map.
I have an svg file for make it responsive.

this is how I call the svg file

MyGreenSVG = {
    url: 'greenFill.svg',
    size: new google.maps.Size(20, 35)
};

the property: size doesn't change the size of my icon, but only crop it.
the only way is to change the width and height in my svg file, and make 2 versions of it.
so I loose the interest of using svg...

this is a preview of my svg file :

<svg version="1.1"
x="0px" y="0px" width="41.8px" height="74px" viewBox="0 0 41.8 74" enable-background="new 0 0 41.8 74" xml:space="preserve">


问:
App developed in Xcode for native iOS
We have our native iOS app developed in Xcode and now software developer is saying that we should upgrade our code to Xcode 9 as we may face issue with the new release on the App Store if we continue using Xcode for development. I would like to know if this is a fact, since I am not from iOS development and I don't know if this is a fact.

Any help in this regarding or a pointer to documentation would be appreciated.

答:
To contrast the other posters here: I'd say it depends. Right now, iTunes Connect accepts updates/uploads for apps built using Xcode 6 (six). There is no hard technical requirement to use Xcode 9 today, and there isn't going to be one in the forseeable future. 2019/2020, maybe, but by then we'll likely also have Xcode 11 or 12.

That said, there are many reasons to actually switch to the most recent Xcode release rather sooner than later, not the least of which is being able to target the current iOS version, iOS 11 and make your app work correctly on the new iPhone X.

Title: App developed in Xcode for native iOS


问:
React prop-type validation with currying functions
I'm relatively new to React and have come across a problem where I am unable to validate the props on a component that is returned from a curried function.

I have tried validating prop-types on both "List" and "Wrapped-Component" but I am still not having any success. How would I go about validating the "data" prop in this specific instance?

import React from "react";
import PropTypes from "prop-types";

const styles = {
  listStyles: {
    display: "flex",
    flexDirection: "row",
    flexWrap: "wrap",
    listStyle: "none",
  },
};

const List = WrappedComponent => ({ data }) => (

    {data &&
      data.map(item => (

          <WrappedComponent {...item} />

      ))}

);

List.propTypes = {
  data: PropTypes.array.isRequired,
};

export default List;```

答:
You're adding propTypes to the outer function not the component itself.</p>

```<code>const makeList = WrappedComponent => {
  const List = ({ data }) => (
    <ul style={styles.listStyles}>
      {data &&
        data.map(item => (
          <div>
            <WrappedComponent {...item} />
          </div>
        ))}
    </ul>
  );

  List.propTypes = {
    data: PropTypes.array.isRequired,
  };

  return List
}
</code>```

Body:
You're adding propTypes to the outer function not the component itself.

const makeList = WrappedComponent => {
  const List = ({ data }) => (
    <ul style={styles.listStyles}>
      {data &&
        data.map(item => (
          <div>
            <WrappedComponent {...item} />
          </div>
        ))}
    </ul>
  );

  List.propTypes = {
    data: PropTypes.array.isRequired,
  };

  return List
}


问:
Why Would a Loop Skip Values?
For some reason a loop I have is leaving every second list-item from an unordered list instead of removing every list-item. And I am very confused as to why.

The code:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">

<title>Debugging</title>
    <script>

    function testingTesting() {
        var itemList = document.getElementsByTagName('LI');

        document.getElementById('demo').innerHTML = itemList.length;

        for (i = 0; i < itemList.length; i++) {
            document.getElementById('skillList').removeChild(itemList[i]);
        }
    }
    </script>
  </head>
  <body>
    <div id="toDisplay">

         <h2>Heading for Reasons</h2>
        <ul id="skillList">
          <li>Alpha</li>
          <li>Bravo</li>
          <li>Charlie</li>
          <li>Delta</li>
          <li>Foxtrot</li>
          <li>Exxon</li>
        </ul>

        <p id="demo"> </p>
    </div>

    <input type="button" value="Sort!" onclick="testingTesting()">

  </body>
</html>
</code>```

The result (in Chrome and Opera) of hitting the sort button once is:

"Heading for Reasons

Bravo
Delta
Exxon
6"

The result when hitting it twice is:

"Heading for Reasons

Delta
3"

Does anyone know why the list items in the itemList Array of modulo 2n + 1 are skipped?

Thank you.

答:
It's because when you remove an item, the index of the next item, as well as the total count, changes. Don't use an incrementer. Try this instead:</p>

```<code>function testingTesting() {
    while (document.getElementsByTagName('LI').length > 0) {
        document.getElementById('skillList').removeChild(document.getElementsByTagName('LI')[0]);
    }
}
</code>```

Title: Why Would a Loop Skip Values?

Body:
For some reason a loop I have is leaving every second list-item from an unordered list instead of removing every list-item. And I am very confused as to why.

The code:

<!DOCTYPE html>

    <meta charset="UTF-8">

<title>Debugging</title>

Heading for Reasons

Alpha

Bravo

Charlie

Delta

Foxtrot

Exxon

    <input type="button" value="Sort!" onclick="testingTesting()">

The result (in Chrome and Opera) of hitting the sort button once is:

"Heading for Reasons

Bravo
Delta
Exxon
6"

The result when hitting it twice is:

"Heading for Reasons

Delta
3"

Does anyone know why the list items in the itemList Array of modulo 2n + 1 are skipped?

Thank you.

Body:
It's because when you remove an item, the index of the next item, as well as the total count, changes. Don't use an incrementer. Try this instead:

function testingTesting() {
    while (document.getElementsByTagName('LI').length > 0) {
        document.getElementById('skillList').removeChild(document.getElementsByTagName('LI')[0]);
    }
}


问:
Explicitly overriding constructors in ActionScript3
All,

I ran into this funny thing in a different post.  It was pointed out to me that you can explicitly override a constructor... which doesn't seem necessary, and I am a little surprised it even compiles.  Take a look:

```<code>public class TestClass
{
    public function TestClass() {}
}

public class TestClass2 extends TestClass
{
    public override function TestClass2() {}
}
</code>```

Explicitly calling override on the constructor might just be a no-op, as it is certainly not necessary.  My question: Is there a subtlety here that I am missing?  Does explicitly overriding the constructor tell the compiler something?

答:
```<code>public class TestClass
{
    public function TestClass() {}
}

public class TestClass2 extends TestClass
{
    public override function TestClass2() {
       super();//this makes call to the default constructor
}
</code>```

Body:
All,

I ran into this funny thing in a different post.  It was pointed out to me that you can explicitly override a constructor... which doesn't seem necessary, and I am a little surprised it even compiles.  Take a look:

public class TestClass
{
    public function TestClass() {}
}

public class TestClass2 extends TestClass
{
    public override function TestClass2() {}
}

Explicitly calling override on the constructor might just be a no-op, as it is certainly not necessary.  My question: Is there a subtlety here that I am missing?  Does explicitly overriding the constructor tell the compiler something?


问:
Roc curve and cut off point. Python
I ran a logistic regression model and made predictions of the logit values. I used this to get the points on the ROC curve:

```<code> from sklearn import metrics
 fpr, tpr, thresholds = metrics.roc_curve(Y_test,p)
</code>```

I know metrics.roc_auc_score gives the area under the ROC curve. Can anyone tell me what command will find the optimal cut-off point (threshold value)?

答:
Vanilla Python Implementation of Youden's J-Score</p>

```<code>def cutoff_youdens_j(fpr,tpr,thresholds):
    j_scores = tpr-fpr
    j_ordered = sorted(zip(j_scores,thresholds))
    return j_ordered[-1][1]
</code>```

Title: Roc curve and cut off point. Python

Body:
I ran a logistic regression model and made predictions of the logit values. I used this to get the points on the ROC curve:

 from sklearn import metrics
 fpr, tpr, thresholds = metrics.roc_curve(Y_test,p)

I know metrics.roc_auc_score gives the area under the ROC curve. Can anyone tell me what command will find the optimal cut-off point (threshold value)?

Body:
Vanilla Python Implementation of Youden's J-Score

def cutoff_youdens_j(fpr,tpr,thresholds):
    j_scores = tpr-fpr
    j_ordered = sorted(zip(j_scores,thresholds))
    return j_ordered[-1][1]


问:
i can't get full webpage
i wanted do http request but it doesnt download full page. only 7300bytes or less from any big webpage
if i try little webpage it download full
i tried different flags but still cant find my mistake

```<code>#define POSIX_C_SOURCE >= 200112L
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
struct addrinfo hints, *res;
int sockfd;
char buf[25056];
int byte_count;

 memset(&hints, 0,sizeof hints);
hints.ai_family=AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo("man7.org","80", &hints, &res);
sockfd = socket(res->ai_family,res->ai_socktype,res->ai_protocol);
printf("Connecting...\n");
connect(sockfd,res->ai_addr,res->ai_addrlen);
printf("Connected!\n");
char *header = "GET /linux/man-pages/man2/recv.2.html HTTP/1.1\r\nHost:
man7.org\r\n\r\n";
send(sockfd,header,strlen(header),0);
printf("GET Sent...\n");
//all right ! now that we're connected, we can receive some data!

byte_count = recv(sockfd,buf,sizeof(buf),0);
printf("recv()'d %d bytes of data in buf\n",byte_count);
printf("%.*s",byte_count,buf); // <-- give printf() the actual data size

return 0;
}
</code>```

exec :

```<code>Connecting...
Connected!
GET Sent...
recv()'d 7300 bytes of data in buf
HTTP/1.1 200 OK
Date: Wed, 06 Dec 2017 16:04:29 GMT
Server: Apache
Last-Modified: Tue, 05 Dec 2017 18:41:34 GMT
ETag: "4d77-64f1-55f9c2f245380"
Accept-Ranges: bytes
Content-Length: 25841
Connection: close
Content-Type: text/html; charset=UTF-8
</code>```

答:
As pointed in the comment, you have to recv repeatedly until the returned value is less or equal to zero. Also in such a simple case I'd recommend to send HTML 1.0 request to avoid chunked answers. Try the following code:

```<code>#define POSIX_C_SOURCE >= 200112L
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
    struct addrinfo hints, *res;
    int sockfd;
    char buf[65536];
    int n, byte_count;

    memset(&hints, 0,sizeof hints);
    hints.ai_family=AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    getaddrinfo("man7.org","80", &hints, &res);
    sockfd = socket(res->ai_family,res->ai_socktype,res->ai_protocol);
    printf("Connecting...\n");
    connect(sockfd,res->ai_addr,res->ai_addrlen);
    printf("Connected!\n");
    char *header = "GET /linux/man-pages/man2/recv.2.html HTTP/1.0\r\nHost:man7.org\r\n\r\n";
    send(sockfd,header,strlen(header),0);
    printf("GET Sent...\n");
//all right ! now that we're connected, we can receive some data!

    byte_count = n = 0;
    do {
        byte_count += n;
        n = recv(sockfd,buf+byte_count,sizeof(buf)-byte_count,0);
    } while (n > 0);
    printf("recv()'d %d bytes of data in buf\n",byte_count);
    printf("%.*s",byte_count,buf); // <-- give printf() the actual data size

    return 0;
}
</code>```

Title: i can't get full webpage

Body:
i wanted do http request but it doesnt download full page. only 7300bytes or less from any big webpage
if i try little webpage it download full
i tried different flags but still cant find my mistake

#define POSIX_C_SOURCE >= 200112L
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
struct addrinfo hints, *res;
int sockfd;
char buf[25056];
int byte_count;

 memset(&hints, 0,sizeof hints);
hints.ai_family=AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo("man7.org","80", &hints, &res);
sockfd = socket(res->ai_family,res->ai_socktype,res->ai_protocol);
printf("Connecting...\n");
connect(sockfd,res->ai_addr,res->ai_addrlen);
printf("Connected!\n");
char *header = "GET /linux/man-pages/man2/recv.2.html HTTP/1.1\r\nHost:
man7.org\r\n\r\n";
send(sockfd,header,strlen(header),0);
printf("GET Sent...\n");
//all right ! now that we're connected, we can receive some data!

byte_count = recv(sockfd,buf,sizeof(buf),0);
printf("recv()'d %d bytes of data in buf\n",byte_count);
printf("%.*s",byte_count,buf); // <-- give printf() the actual data size

return 0;
}

exec :

Connecting...
Connected!
GET Sent...
recv()'d 7300 bytes of data in buf
HTTP/1.1 200 OK
Date: Wed, 06 Dec 2017 16:04:29 GMT
Server: Apache
Last-Modified: Tue, 05 Dec 2017 18:41:34 GMT
ETag: "4d77-64f1-55f9c2f245380"
Accept-Ranges: bytes
Content-Length: 25841
Connection: close
Content-Type: text/html; charset=UTF-8

Body:
As pointed in the comment, you have to recv repeatedly until the returned value is less or equal to zero. Also in such a simple case I'd recommend to send HTML 1.0 request to avoid chunked answers. Try the following code:

#define POSIX_C_SOURCE >= 200112L
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
    struct addrinfo hints, *res;
    int sockfd;
    char buf[65536];
    int n, byte_count;

    memset(&hints, 0,sizeof hints);
    hints.ai_family=AF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    getaddrinfo("man7.org","80", &hints, &res);
    sockfd = socket(res->ai_family,res->ai_socktype,res->ai_protocol);
    printf("Connecting...\n");
    connect(sockfd,res->ai_addr,res->ai_addrlen);
    printf("Connected!\n");
    char *header = "GET /linux/man-pages/man2/recv.2.html HTTP/1.0\r\nHost:man7.org\r\n\r\n";
    send(sockfd,header,strlen(header),0);
    printf("GET Sent...\n");
//all right ! now that we're connected, we can receive some data!

    byte_count = n = 0;
    do {
        byte_count += n;
        n = recv(sockfd,buf+byte_count,sizeof(buf)-byte_count,0);
    } while (n > 0);
    printf("recv()'d %d bytes of data in buf\n",byte_count);
    printf("%.*s",byte_count,buf); // <-- give printf() the actual data size

    return 0;
}


问:
How to query sequelize model by association, but include all associated objects?

Trying to query by all association's attribute, but get all associations

```<code># FAQs: { id: 1, name: 'How to do it?' }, { id: 2, name: 'How to FIX it?' }
# tags: { id: 1, slug: 'api' }, { id: 2, slug: 'beta' }
# taggings: { id: 1, faqId: 1, mainEntityId: 1, mainEntityType: 'faq' }, { id: 2, faqId: 1, mainEntityId: 2, mainEntityType: 'faq' }

const query = { slugs: ['api'] }
const foundFAQs = await this.models.FAQ.findAll({
  where: {
    '$taggings.tag.slug$': { $in: query.slugs },
  },
  include: [{
    model: this.models.Tagging,
    as: "taggings",
    include: [{
      model: this.models.Tag,
      as: 'tag',
    }],
  }],
})
</code>```

My model definition:

```<code>models.Tagging.belongsTo(models.Tag, { as: 'tag', onDelete: 'cascade' });
models.Tag.hasMany(models.Tagging, { as: 'taggings', onDelete: 'cascade' });
models.Tag.belongsToMany(models.FAQ, { through: models.Tagging, as: 'faqs' });
models.FAQ.hasMany(models.Tagging, { as: 'taggings', onDelete: 'cascade' });
models.FAQ.belongsToMany(models.Tag, { through: models.Tagging, as: 'tags' });
</code>```

What do you expect to happen?

I want to get all FAQs what has associated TAG api and have all its tags.

Object:
    {
    id: 1,
    name: 'How to do it?',
    tags: [
    { id: 1, slug: 'api' },
    { id: 2, slug: 'beta' }
    ]
    }

What is actually happening?

Query returns object:
    {
      id: 1,
      name: 'How to do it?',
      tags: [
        { id: 1, slug: 'api' }
      ]
    }

Output

```<code>SELECT \"faq\".\"id\", \"faq\".\"name\", \"faq\".\"bankId\", \"faq\".\"priority\",
\"faq\".\"publishedLocales\", \"faq\".\"createdAt\", \"faq\".\"updatedAt\", \"taggings\".\"id\"
AS \"taggings.id\", \"taggings\".\"tagId\" AS \"taggings.tagId\", \"taggings\".\"locked\"
AS \"taggings.locked\", \"taggings\".\"sdkId\" AS \"taggings.sdkId\", \"taggings\".\"guideId\"
AS \"taggings.guideId\", \"taggings\".\"newsId\" AS \"taggings.newsId\", \"taggings\".\"faqId\"
AS \"taggings.faqId\", \"taggings\".\"apiId\" AS \"taggings.apiId\", \"taggings\".\"createdAt\"
AS \"taggings.createdAt\", \"taggings\".\"updatedAt\" AS \"taggings.updatedAt\", \"taggings->tag\".\"id\"
AS \"taggings.tag.id\", \"taggings->tag\".\"name\" AS \"taggings.tag.name\", \"taggings->tag\".\"slug\"
AS \"taggings.tag.slug\", \"taggings->tag\".\"tagType\" AS \"taggings.tag.tagType\", \"taggings->tag\".\"mainEntityId\"
AS \"taggings.tag.mainEntityId\", \"taggings->tag\".\"createdAt\"
AS \"taggings.tag.createdAt\", \"taggings->tag\".\"updatedAt\"
AS \"taggings.tag.updatedAt\" FROM \"faqs\" AS \"faq\" INNER JOIN \"taggings\"
AS \"taggings\" ON \"faq\".\"id\" = \"taggings\".\"faqId\" LEFT OUTER JOIN \"tags\"
AS \"taggings->tag\" ON \"taggings\".\"tagId\" = \"taggings->tag\".\"id\" WHERE \"faq\".\"bankId\" = 'bank.csas'
AND \"taggings->tag\".\"slug\" IN ('faq') ORDER BY \"faq\".\"priority\" DESC;
</code>```

Dialect: postgres

Dialect version: pg@^6.1.0

Database version: PostgreSQL 10.1

Sequelize version: 4.23.2

Tested with the latest release: No (4.23.2)

Node: 8.6.0

I am not sure if it is a bug or I'm doing something wrong.

Thanks

答:
You're looking to include all related data for each record, but filter those records on that related data. You're going to want to get Sequelize to generate SQL similar to:

```<code>SELECT "faq"."id", ....
FROM "faqs" AS "faq"
INNER JOIN "taggings" AS "taggings" ON "faq"."id" = "taggings"."faqId"
LEFT OUTER JOIN "tags" AS "taggings->tag" ON "taggings"."tagId" = "taggings->tag"."id"
LEFT OUTER JOIN "tags" AS "taggings->tagdata" ON "taggings"."tagId" = "taggings->tagdata"."id"
WHERE "faq"."bankId" = 'bank.csas' AND "taggings->tag"."slug" IN ('faq')
ORDER BY "faq"."priority" DESC;
</code>```

Something like this might work:

```<code>const foundFAQs = await this.models.FAQ.findAll({
  where: {
    '$taggings.tag.slug$': { $in: query.slugs },
  },
  include: [{
    model: this.models.Tagging,
    as: "taggings",
    include: [{
      model: this.models.Tag,
      as: 'tag',
    },{
      model: this.models.Tag,
      as: 'tagdata',
    }],
  }],
})
</code>```

The idea here is that you're performing a join on which you are filtering, and then another join to get the extra records for the filtered rows.

Body:
Trying to query by all association's attribute, but get all associations

# FAQs: { id: 1, name: 'How to do it?' }, { id: 2, name: 'How to FIX it?' }
# tags: { id: 1, slug: 'api' }, { id: 2, slug: 'beta' }
# taggings: { id: 1, faqId: 1, mainEntityId: 1, mainEntityType: 'faq' }, { id: 2, faqId: 1, mainEntityId: 2, mainEntityType: 'faq' }

const query = { slugs: ['api'] }
const foundFAQs = await this.models.FAQ.findAll({
  where: {
    '$taggings.tag.slug$': { $in: query.slugs },
  },
  include: [{
    model: this.models.Tagging,
    as: "taggings",
    include: [{
      model: this.models.Tag,
      as: 'tag',
    }],
  }],
})

My model definition:

models.Tagging.belongsTo(models.Tag, { as: 'tag', onDelete: 'cascade' });
models.Tag.hasMany(models.Tagging, { as: 'taggings', onDelete: 'cascade' });
models.Tag.belongsToMany(models.FAQ, { through: models.Tagging, as: 'faqs' });
models.FAQ.hasMany(models.Tagging, { as: 'taggings', onDelete: 'cascade' });
models.FAQ.belongsToMany(models.Tag, { through: models.Tagging, as: 'tags' });

What do you expect to happen?

I want to get all FAQs what has associated TAG api and have all its tags.

Object:
    {
    id: 1,
    name: 'How to do it?',
    tags: [
    { id: 1, slug: 'api' },
    { id: 2, slug: 'beta' }
    ]
    }

What is actually happening?

Query returns object:
    {
      id: 1,
      name: 'How to do it?',
      tags: [
        { id: 1, slug: 'api' }
      ]
    }

Output

SELECT \"faq\".\"id\", \"faq\".\"name\", \"faq\".\"bankId\", \"faq\".\"priority\",
\"faq\".\"publishedLocales\", \"faq\".\"createdAt\", \"faq\".\"updatedAt\", \"taggings\".\"id\"
AS \"taggings.id\", \"taggings\".\"tagId\" AS \"taggings.tagId\", \"taggings\".\"locked\"
AS \"taggings.locked\", \"taggings\".\"sdkId\" AS \"taggings.sdkId\", \"taggings\".\"guideId\"
AS \"taggings.guideId\", \"taggings\".\"newsId\" AS \"taggings.newsId\", \"taggings\".\"faqId\"
AS \"taggings.faqId\", \"taggings\".\"apiId\" AS \"taggings.apiId\", \"taggings\".\"createdAt\"
AS \"taggings.createdAt\", \"taggings\".\"updatedAt\" AS \"taggings.updatedAt\", \"taggings->tag\".\"id\"
AS \"taggings.tag.id\", \"taggings->tag\".\"name\" AS \"taggings.tag.name\", \"taggings->tag\".\"slug\"
AS \"taggings.tag.slug\", \"taggings->tag\".\"tagType\" AS \"taggings.tag.tagType\", \"taggings->tag\".\"mainEntityId\"
AS \"taggings.tag.mainEntityId\", \"taggings->tag\".\"createdAt\"
AS \"taggings.tag.createdAt\", \"taggings->tag\".\"updatedAt\"
AS \"taggings.tag.updatedAt\" FROM \"faqs\" AS \"faq\" INNER JOIN \"taggings\"
AS \"taggings\" ON \"faq\".\"id\" = \"taggings\".\"faqId\" LEFT OUTER JOIN \"tags\"
AS \"taggings->tag\" ON \"taggings\".\"tagId\" = \"taggings->tag\".\"id\" WHERE \"faq\".\"bankId\" = 'bank.csas'
AND \"taggings->tag\".\"slug\" IN ('faq') ORDER BY \"faq\".\"priority\" DESC;

Dialect: postgres

Dialect version: pg@^6.1.0

Database version: PostgreSQL 10.1

Sequelize version: 4.23.2

Tested with the latest release: No (4.23.2)

Node: 8.6.0

I am not sure if it is a bug or I'm doing something wrong.

Thanks

Body:
You're looking to include all related data for each record, but filter those records on that related data. You're going to want to get Sequelize to generate SQL similar to:

SELECT "faq"."id", ....
FROM "faqs" AS "faq"
INNER JOIN "taggings" AS "taggings" ON "faq"."id" = "taggings"."faqId"
LEFT OUTER JOIN "tags" AS "taggings->tag" ON "taggings"."tagId" = "taggings->tag"."id"
LEFT OUTER JOIN "tags" AS "taggings->tagdata" ON "taggings"."tagId" = "taggings->tagdata"."id"
WHERE "faq"."bankId" = 'bank.csas' AND "taggings->tag"."slug" IN ('faq')
ORDER BY "faq"."priority" DESC;

Something like this might work:

const foundFAQs = await this.models.FAQ.findAll({
  where: {
    '$taggings.tag.slug$': { $in: query.slugs },
  },
  include: [{
    model: this.models.Tagging,
    as: "taggings",
    include: [{
      model: this.models.Tag,
      as: 'tag',
    },{
      model: this.models.Tag,
      as: 'tagdata',
    }],
  }],
})

The idea here is that you're performing a join on which you are filtering, and then another join to get the extra records for the filtered rows.


问:
How to get list of files on Mac that have been tagged by Finder with a color?
I'd like to tag some files on my Mac with Finder under a certain color tag, and then be able to get that list of files using a Python or bash script. Is it possible to get the list of tags associated with a file via the command line or a Python script?</p>

答:
Late to the party here, but this is something that has been bugging me too — and I eventually came up with a run-round for tech-shy people that requires no line-command coding, just ordinary Finder commands and SimpleText. Try the following:

open a Finder window containing the tagged files and Select All

right-click on the selected files to get Contextual Menu and choose "Copy [x number of] files". If it doesn't say "Copy [x number of] files" but just "Copy [filename] you've accidentally deselected the files; reselect all, and try right-clicking again.

open SimpleText. Make sure that it is set to use Plain Text and NOT Rich Text. (Menu Bar: Format>Make Plain Text/Rich Text). If it is set to Rich Text, this technique will not work: you will get a document containing the actual files rather than a list of their names!

paste. This should paste a list of the filenames of all selected files, one per line, in the order in which they appear in the Finder. Hurrah!

Hope this works for you. It changed my life.


问:
Calling a Vba script in a HTML5 page
I create a script in Vba allowing to compare reports in Word and I would like to create a page in HTML allowing to launch the Vba script after clicking a button.

When I try to do that, I obtain the message "ReferenceError: myFunction is not defined" in Firefox and Chrome. If I try the same on IE, I obtain the error "'myFunction' is undefined".

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Reports Comparison</title>
    <script type="text/vbscript" src="myScript.vbs"></script>
  </head>
  <body>
    <input type="button" value="Test" onClick="myFunction()">
  </body>
</html>
</code>```

myFunction is correctly defined in the file myScript.vbs :

```<code>Sub myFunction ()
    Dim strFolderA As String
    Dim strFolderB As String
    Dim strFolderC As String
    Dim strFileSpec As String
    Dim strFileName As String
    Dim objDocA As Word.Document
    Dim objDocB As Word.Document
    Dim objDocC As Word.Document
    strFolderA = InputBox("Enter path to base documents:")
    strFolderB = InputBox("Enter path to new documents:")
    strFolderC = InputBox("Enter path for document comparisons to be saved:")
    strFileSpec = "*.docx"
    strFileName = Dir(strFolderA & strFileSpec)
    Do While strFileName <> vbNullString
        Set objDocA = Documents.Open(strFolderA & strFileName)
        Set objDocB = Documents.Open(strFolderB & strFileName)
        Application.CompareDocuments _
            OriginalDocument:=objDocA, _
            RevisedDocument:=objDocB, _
            Destination:=wdCompareDestinationNew
        objDocA.Close
        objDocB.Close
        Set objDocC = ActiveDocument
        objDocC.SaveAs FileName:=strFolderC & strFileName
        objDocC.Close SaveChanges:=False
        strFileName = Dir
    Loop
    Set objDocA = Nothing
    Set objDocB = Nothing
End Sub
</code>```

Could you please help me to do that?

Regards

答:
VBScript can only be used in Internet Explorer. And even then it won't work by default, you have to enable "Enterprise Mode" to enable backwards compatibility and various other flags to allow the browser access to the file system. You also can't work with a Word document like this without some extra legwork since Word won't be defined here.

There is a new Javascript API that you might be able to leverage instead but again this isn't for use in the context of a browser. But it would let you add some functionality to word itself.

https://dev.office.com/reference/add-ins/javascript-api-for-office

Title: Calling a Vba script in a HTML5 page

Body:
I create a script in Vba allowing to compare reports in Word and I would like to create a page in HTML allowing to launch the Vba script after clicking a button.

When I try to do that, I obtain the message "ReferenceError: myFunction is not defined" in Firefox and Chrome. If I try the same on IE, I obtain the error "'myFunction' is undefined".

<!DOCTYPE html>

    <title>Reports Comparison</title>

    <input type="button" value="Test" onClick="myFunction()">

myFunction is correctly defined in the file myScript.vbs :

Sub myFunction ()
    Dim strFolderA As String
    Dim strFolderB As String
    Dim strFolderC As String
    Dim strFileSpec As String
    Dim strFileName As String
    Dim objDocA As Word.Document
    Dim objDocB As Word.Document
    Dim objDocC As Word.Document
    strFolderA = InputBox("Enter path to base documents:")
    strFolderB = InputBox("Enter path to new documents:")
    strFolderC = InputBox("Enter path for document comparisons to be saved:")
    strFileSpec = "*.docx"
    strFileName = Dir(strFolderA & strFileSpec)
    Do While strFileName <> vbNullString
        Set objDocA = Documents.Open(strFolderA & strFileName)
        Set objDocB = Documents.Open(strFolderB & strFileName)
        Application.CompareDocuments _
            OriginalDocument:=objDocA, _
            RevisedDocument:=objDocB, _
            Destination:=wdCompareDestinationNew
        objDocA.Close
        objDocB.Close
        Set objDocC = ActiveDocument
        objDocC.SaveAs FileName:=strFolderC & strFileName
        objDocC.Close SaveChanges:=False
        strFileName = Dir
    Loop
    Set objDocA = Nothing
    Set objDocB = Nothing
End Sub

Could you please help me to do that?

Regards


问:
Class 'App\Proyect' not found
I am developing web based on proyects using laravel 5.5 when I execute http://127.0.0.1:8000/proyectos occurred following error.

Class 'App\Proyect' not found

```<code>namespace IntelabProyect\Http\Controllers;

use Illuminate\Http\Request;

use App\Proyect;

class FrontController extends Controller
{

    public function welcome()
    {
        //retorno de la vista
        return view('welcome');

    }
    /*public function nosotros()
    {
        //retorno de la vista
        return view('nosotros');
    }*/

    public function proyectos()
    {
        $proyects = Proyect::paginate(10);
        //retorno de la vista
        return view('proyectos')->with(compact('proyects'));
    }
}
</code>```

答:
It seems like you have changed Laravel default App namespace to IntelabProyect. You might need to try following things,

Change use App\Proyect; to use IntelabProyect\Proyect; on the controller.

Make sure Proyect class declared inside IntelabProyect namespace (not App).

The file is located under app directory and its name is exactly Proyect.php

Title: Class 'App\Proyect' not found

Body:
I am developing web based on proyects using laravel 5.5 when I execute http://127.0.0.1:8000/proyectos occurred following error.

Class 'App\Proyect' not found

namespace IntelabProyect\Http\Controllers;

use Illuminate\Http\Request;

use App\Proyect;

class FrontController extends Controller
{

    public function welcome()
    {
        //retorno de la vista
        return view('welcome');

    }
    /*public function nosotros()
    {
        //retorno de la vista
        return view('nosotros');
    }*/

    public function proyectos()
    {
        $proyects = Proyect::paginate(10);
        //retorno de la vista
        return view('proyectos')->with(compact('proyects'));
    }
}


问:
Invoking aws lambda without output file
I'm trying to invoke a lambda on AWS using CLI:

```<code>aws lambda invoke --function-name GetErrorLambda --payload '{"body":"{\"Id\":[\"321\",\"123\"]}"}' \output.
</code>```

I would like to know if there's a way to print the output on the cli instead of create a file.

Thanks in advance.

答:
It's not possible to output directly to the terminal after invoking a lambda function. This is likely by design as the output could easily be greater than the buffer size for a window.

A simple workaround would be to simply 'cat' out the contents of the output file following the cli command like so:

aws lambda invoke --function-name GetErrorLambda --payload '{"body":"{\"Id\":[\"321\",\"123\"]}"}' \output. && cat outputFileName.txt

Title: Invoking aws lambda without output file

Body:
I'm trying to invoke a lambda on AWS using CLI:

aws lambda invoke --function-name GetErrorLambda --payload '{"body":"{\"Id\":[\"321\",\"123\"]}"}' \output.

I would like to know if there's a way to print the output on the cli instead of create a file.

Thanks in advance.


问:
Garbage Collector overhead limit exceeded Caused By Array Creation

Hello,

My program spent a lot of Time creating Object in the Heap Memory , so at certain  Time i get this Error:

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded

I can't Put my Full Application in this discussion So i created A prototype to explain what My program is doing.

The part of my program that deal with Creating Object looks as Follows:

```<code>**The Calling Program :**

public class Example {

public static void main(String[] args) {
        ArrayList list = new ArrayList();
        for (int i = 0; i < 5000; i++) {
            for (int j = 0; j < 5000; j++) {
                if (i==j)
                    continue;
                int weight = new Random().nextInt();
                Edge edge = new Edge(new Vertex(i+""), new Vertex(j+""),weight);
                list.add(edge);
            }
        }
  }
</code>```

}

The Class Vertex :

```<code>public class Vertex {
    private String sequence ;

    public Vertex() {
    }

    public Vertex(String seq) {
        this.sequence = seq;
    }

}
</code>```

The Class Edge :

```<code>public class Edge {

    private Vertex source;
    private Vertex destination;
    private int weight;

    public Edge() {

    }

    public Edge(Vertex source, Vertex destination, int weight) {
        int[][] array = new int[500][500];
        //here i need the array to do some calculation
        anotherClass.someCalculation(array,source,destination);
        this.source = source;
        this.destination = destination;
        this.weight = weight;

    }
}
</code>```

So as you can see:

I have 5000 Vertices , i need To create 5000*5000 Edges , each edge has An array of length 500*500.

For this reason the memory allocated in the Heap Memory end at certain time,the problem as i understood from many disctions I read is that there is no guaranty that the Garbage Collector Will free memory.

So what are the solution for this problem ? normally I don't Need The Edge's Array after constructing the Edge;the array is only needed during the construction of The Edges.

Another question : How can I minimize the Memory Utilisation in my Program ? I tried To turn the int array to char array but it didn't help.

Many Thanks

答:
It's important to know that an array index reference is 4 bytes. So a two-dimensional array defined as 500, 500 is 1MB without any data being stored. You're also creating 5000 x 5000 of them. Just the arrays with no other data will be over 25TB.

A GC overhead limit reached occurs when the GC is spending most of its time garbage collecting with view results. And this would be expected since the all of the arrays being created are reachable from the main thread.

You should create and expand arrays as you need it (think of an ArrayList) or only create the arrays when you need them.

If you ABSOLUTELY need all the edges in memory you will either need to increase the heap or learn to serialize the results and load only what you need for calculations.

Body:
Hello,

My program spent a lot of Time creating Object in the Heap Memory , so at certain  Time i get this Error:

Exception in thread "main" java.lang.OutOfMemoryError: GC overhead limit exceeded

I can't Put my Full Application in this discussion So i created A prototype to explain what My program is doing.

The part of my program that deal with Creating Object looks as Follows:

**The Calling Program :**

public class Example {

public static void main(String[] args) {
        ArrayList list = new ArrayList();
        for (int i = 0; i < 5000; i++) {
            for (int j = 0; j < 5000; j++) {
                if (i==j)
                    continue;
                int weight = new Random().nextInt();
                Edge edge = new Edge(new Vertex(i+""), new Vertex(j+""),weight);
                list.add(edge);
            }
        }
  }

}

The Class Vertex :

public class Vertex {
    private String sequence ;

    public Vertex() {
    }

    public Vertex(String seq) {
        this.sequence = seq;
    }

}

The Class Edge :

public class Edge {

    private Vertex source;
    private Vertex destination;
    private int weight;

    public Edge() {

    }

    public Edge(Vertex source, Vertex destination, int weight) {
        int[][] array = new int[500][500];
        //here i need the array to do some calculation
        anotherClass.someCalculation(array,source,destination);
        this.source = source;
        this.destination = destination;
        this.weight = weight;

    }
}

So as you can see:

I have 5000 Vertices , i need To create 5000*5000 Edges , each edge has An array of length 500*500.

For this reason the memory allocated in the Heap Memory end at certain time,the problem as i understood from many disctions I read is that there is no guaranty that the Garbage Collector Will free memory.

So what are the solution for this problem ? normally I don't Need The Edge's Array after constructing the Edge;the array is only needed during the construction of The Edges.

Another question : How can I minimize the Memory Utilisation in my Program ? I tried To turn the int array to char array but it didn't help.

Many Thanks


问:
Authenticate client id and client secret on Spring oauth/token request with LDAP

I'm investigating how the client id and client secret can be authenticated with LDAP.

Note: this Kotlin code...

```<code>@Configuration
@EnableAuthorizationServer
class OAuth2AuthorizationServerConfig() : AuthorizationServerConfigurerAdapter() {
</code>```

I'm relatively new to Spring and it seems that this is not something I should be trying to? However, it seems like a useful option. Why? Because it allows me to delegate the client secret management to an LDAP directory and, effectively, allow my ops team to change the secret (in some managed way of coure). With this my application does not need to know the secret. This seems pretty neat?

The oauth end point is basic auth - this seems to be what Spring gives me with the  @EnableAuthorizationServer annotation. Requests to the http://somehost/oauth/token specify grant_type:client_credentials.

I created code to get an arbitrary token (sandbox)...and what I'd like is to just specify the client and scopes that apply to that client and not specify the secret...

```<code>@Throws(Exception::class)
override fun configure(
        clients: ClientDetailsServiceConfigurer
) {
    // Inlining will create a store per credential entry
    val serviceBuilder = clients.inMemory()
    serviceBuilder.withClient("user").secret("test").scopes("XXX")
}
</code>```

I have tried loads of different ideas to add an LDAP Authentication Provider to the managed set of providers in the ProviderManager and thus far have failed. If I debug into the authenticate method at run time I only always have the AnonymousAuthenticationProvider and DaoAuthenticationProvider

The following probably shows my inexperience but here's one example and please read past the probable crazyness - just trying to see if I can inject an LDAPAuthenticationProvider...

```<code>@Autowired
lateinit var providerMan: AuthenticationManager

@Throws(Exception::class)
override fun configure(endpoints: AuthorizationServerEndpointsConfigurer) {
    (providerMan as ProviderManager).providers.add(0,
            LdapAuthenticationProvider(
                    PasswordComparisonAuthenticator(PasswordPolicyAwareContextSource("ldap://something"))
            )
    )
}
</code>```

Question is therefore fairly simple...
Is there a way to add an LdapAuthenticationProvider such that I can use LDAP to authenticate the client id and client secret?

答:
I wanted to add some elaboration to the answer for the community.

I have a prototype working thanks to the advice.
I'm using Apache LDAP API to connect to an LDAP server.

The solution is fairly simple - simply create a ClientDetailsService that retrieves the LDAP entry that matches the clientId passed to loadClientByClientId and return an appropriate ClientDetails object (use BaseClientDetails provided by Spring).

You also need to create a custom PasswordEncoder or set the right encoder if Spring gives you the necessary:

```<code>override fun configure(security: AuthorizationServerSecurityConfigurer) {
    security.passwordEncoder(SomePasswordEncoder)
}
</code>```

The default is a plain text password encoder.

Body:
I'm investigating how the client id and client secret can be authenticated with LDAP.

Note: this Kotlin code...

@Configuration
@EnableAuthorizationServer
class OAuth2AuthorizationServerConfig() : AuthorizationServerConfigurerAdapter() {

I'm relatively new to Spring and it seems that this is not something I should be trying to? However, it seems like a useful option. Why? Because it allows me to delegate the client secret management to an LDAP directory and, effectively, allow my ops team to change the secret (in some managed way of coure). With this my application does not need to know the secret. This seems pretty neat?

The oauth end point is basic auth - this seems to be what Spring gives me with the  @EnableAuthorizationServer annotation. Requests to the http://somehost/oauth/token specify grant_type:client_credentials.

I created code to get an arbitrary token (sandbox)...and what I'd like is to just specify the client and scopes that apply to that client and not specify the secret...

@Throws(Exception::class)
override fun configure(
        clients: ClientDetailsServiceConfigurer
) {
    // Inlining will create a store per credential entry
    val serviceBuilder = clients.inMemory()
    serviceBuilder.withClient("user").secret("test").scopes("XXX")
}

I have tried loads of different ideas to add an LDAP Authentication Provider to the managed set of providers in the ProviderManager and thus far have failed. If I debug into the authenticate method at run time I only always have the AnonymousAuthenticationProvider and DaoAuthenticationProvider

The following probably shows my inexperience but here's one example and please read past the probable crazyness - just trying to see if I can inject an LDAPAuthenticationProvider...

@Autowired
lateinit var providerMan: AuthenticationManager

@Throws(Exception::class)
override fun configure(endpoints: AuthorizationServerEndpointsConfigurer) {
    (providerMan as ProviderManager).providers.add(0,
            LdapAuthenticationProvider(
                    PasswordComparisonAuthenticator(PasswordPolicyAwareContextSource("ldap://something"))
            )
    )
}

Question is therefore fairly simple...
Is there a way to add an LdapAuthenticationProvider such that I can use LDAP to authenticate the client id and client secret?

Body:
I wanted to add some elaboration to the answer for the community.

I have a prototype working thanks to the advice.
I'm using Apache LDAP API to connect to an LDAP server.

The solution is fairly simple - simply create a ClientDetailsService that retrieves the LDAP entry that matches the clientId passed to loadClientByClientId and return an appropriate ClientDetails object (use BaseClientDetails provided by Spring).

You also need to create a custom PasswordEncoder or set the right encoder if Spring gives you the necessary:

override fun configure(security: AuthorizationServerSecurityConfigurer) {
    security.passwordEncoder(SomePasswordEncoder)
}

The default is a plain text password encoder.


问:
Encryption Algorithm
I am creating an application which uses a steganography algorithm. Now I can encrypt and decrypt text. But I want my application to ask for password after encrypting the text into the image, so that whenever someone will decrypt the image it would ask for the password for authentication. Is this even possible? If yes, how?</p>

答:
Yes, it's possible. You can use any symmetric key algorithm, e.g. AES. But be sure the encoding/decoding isn't losing any bit.

I've used digital signature with QR codes before and it was changing some bits because it encoded them as ISO-8859-1. My solution was use Base64 before embed into the code. It required more space, but was safer.

Title: Encryption Algorithm


问:
How to handle javascript error from vbs?
I'm trying to put watermarks to pdf file. I wrote vbs script. It works, but when pdf is signed, my script can't add watermark.
VBS "On Error Resume Next" and Err object doesn't provide error info...
How to catch js error?

Here's  part of .vbs script

```<code>...
Set objPDDoc = CreateObject("AcroExch.PDDoc")
objPDDoc.Open(dpath & fileobj.Name)
Set jso = objPDDoc.GetJSObject
Call jso.addWatermarkFromText("text", jso.app.constants.align.left,  "Arial", 14, jso.Color.blue, 0, jso.numPages, True, True, True, jso.app.constants.align.left, jso.app.constants.align.bottom, 0.4, 35, False, 0.9, False, 0, 1)
...
</code>```

and error (on string with 'Call jso.addWatermarkFromText')

```<code>---------------------------
Windows Script Host
---------------------------
Script: C:\pdf_sign_frd\print_sign.vbs
Line:   463
Char:   4
Error:  NotAllowedError: Запрещен доступ к данному свойству или методу.
Code:   800A03E9
Source: Acrobat JavaScript
</code>```

答:
The "securityHandler" property will tell you if the file is protected and  can't be modified. Document security and signatures will set the securityHandler to something other than null. When it's null, the watermark can be applied. </p>

```<code>If IsNull(jso.securityHandler) Then
...
End If
</code>```

Body:
I'm trying to put watermarks to pdf file. I wrote vbs script. It works, but when pdf is signed, my script can't add watermark.
VBS "On Error Resume Next" and Err object doesn't provide error info...
How to catch js error?

Here's  part of .vbs script

...
Set objPDDoc = CreateObject("AcroExch.PDDoc")
objPDDoc.Open(dpath & fileobj.Name)
Set jso = objPDDoc.GetJSObject
Call jso.addWatermarkFromText("text", jso.app.constants.align.left,  "Arial", 14, jso.Color.blue, 0, jso.numPages, True, True, True, jso.app.constants.align.left, jso.app.constants.align.bottom, 0.4, 35, False, 0.9, False, 0, 1)
...

and error (on string with 'Call jso.addWatermarkFromText')

---------------------------
Windows Script Host
---------------------------
Script: C:\pdf_sign_frd\print_sign.vbs
Line:   463
Char:   4
Error:  NotAllowedError: Запрещен доступ к данному свойству или методу.
Code:   800A03E9
Source: Acrobat JavaScript

Body:
The "securityHandler" property will tell you if the file is protected and  can't be modified. Document security and signatures will set the securityHandler to something other than null. When it's null, the watermark can be applied.

If IsNull(jso.securityHandler) Then
...
End If


问:
UIImageView's shadow gets bigger than intended when shadowPath is set
```<code>CGRect rect = biggerImageView.bounds;
if([biggerImageView.layer respondsToSelector:@selector(setShadowColor:)])
{
    float shadowOffset = rect.size.width * 0.02;
    biggerImageView.layer.shadowColor = [UIColor colorWithWhite: 0.25 alpha: 0.55].CGColor;
    biggerImageView.layer.shadowOffset = CGSizeMake(shadowOffset, shadowOffset);
    biggerImageView.layer.shadowOpacity = 0.8;
    //      biggerImageView.layer.shadowPath = [UIBezierPath bezierPathWithRect: rect].CGPath;
}
</code>```

The commented out line causes the shadow becomes bigger than intended.

(vertically longer shadows on top and bottom)

I looked up CALayer reference but got no clue there.

答:
That is probably because the UIView bounds is not the real one yet. (Like in awakeFromNib or viewDidLoad)

Wait for the view layoutSubviews or viewController viewWillLayoutSubviews to be called, and update the path of your shadow there.

I created this swift extension to add the same shadow (with cornerRadius support) everywhere I need to :

```<code>import UIKit

extension UIView {
    /// Call this from `layoutSubviews` or `viewWillLayoutSubviews`.
    /// The shadow will be the same color as this view background.
    func layoutShadow() {

        // Update frame
        if let shadowView = superview?.viewWithTag(978654123) {
            shadowView.frame = frame
            shadowView.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath
            return
        }

        // Create the shadow the first time
        let shadowView = UIView(frame: frame)
        shadowView.tag = 978654123
        shadowView.translatesAutoresizingMaskIntoConstraints = false
        superview?.insertSubview(shadowView, belowSubview: self)

        shadowView.layer.shadowColor = (backgroundColor ?? UIColor.black).cgColor
        shadowView.layer.shadowOpacity = 0.8
        shadowView.layer.shadowOffset = CGSize(width: -2.0, height: 4.0)
        shadowView.layer.shadowRadius = 4.0
        shadowView.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath
    }
}
</code>```

Body:
CGRect rect = biggerImageView.bounds;
if([biggerImageView.layer respondsToSelector:@selector(setShadowColor:)])
{
    float shadowOffset = rect.size.width * 0.02;
    biggerImageView.layer.shadowColor = [UIColor colorWithWhite: 0.25 alpha: 0.55].CGColor;
    biggerImageView.layer.shadowOffset = CGSizeMake(shadowOffset, shadowOffset);
    biggerImageView.layer.shadowOpacity = 0.8;
    //      biggerImageView.layer.shadowPath = [UIBezierPath bezierPathWithRect: rect].CGPath;
}

The commented out line causes the shadow becomes bigger than intended.

(vertically longer shadows on top and bottom)

I looked up CALayer reference but got no clue there.

Body:
That is probably because the UIView bounds is not the real one yet. (Like in awakeFromNib or viewDidLoad)

Wait for the view layoutSubviews or viewController viewWillLayoutSubviews to be called, and update the path of your shadow there.

I created this swift extension to add the same shadow (with cornerRadius support) everywhere I need to :

import UIKit

extension UIView {
    /// Call this from `layoutSubviews` or `viewWillLayoutSubviews`.
    /// The shadow will be the same color as this view background.
    func layoutShadow() {

        // Update frame
        if let shadowView = superview?.viewWithTag(978654123) {
            shadowView.frame = frame
            shadowView.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath
            return
        }

        // Create the shadow the first time
        let shadowView = UIView(frame: frame)
        shadowView.tag = 978654123
        shadowView.translatesAutoresizingMaskIntoConstraints = false
        superview?.insertSubview(shadowView, belowSubview: self)

        shadowView.layer.shadowColor = (backgroundColor ?? UIColor.black).cgColor
        shadowView.layer.shadowOpacity = 0.8
        shadowView.layer.shadowOffset = CGSize(width: -2.0, height: 4.0)
        shadowView.layer.shadowRadius = 4.0
        shadowView.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: layer.cornerRadius).cgPath
    }
}


问:
How to do container rollbacks using a multi docker configuration on elasticbeanstalk
I'm using EB to run multiple Docker containers using there multi docker configuration which makes use of ECS.

I want to find out how I can manage container rollbacks? At the moment if I push something to GitHub, my code-pipeline initiates a code-build, my code-build then push the built container to our ECS registry with the latest tag.

I have setup my image inside the container definition which points to the latest container. Now I believe EB automatically pulls the new containers - This can cause problem as I don't have a way to fallback to the previous version if something fails inside of it.

Our flow looks like this:

Push to git

Codebuild -> Push built container to ECS registry

EB points to the latest image

What our flow needs to look like:

Push to git

Codebuild -> Push built container to ECS registry

EB points to the latest image

Does the node app fail? Is there an error? If so: roll back to the previous container version

答:
Latest tag is evil, especially with autoscaling group.

As I can see you have 2 options

You can use blue/green deployment

You can use immutable environment updates


问:
Kotlin explain me about Backing Fields
I have been looking at Kotlin official tutorial. I came across the topic called Backing Fields

It says,

Classes in Kotlin cannot have fields. However, sometimes it is necessary to have a backing field when using custom accessors. For these purposes, Kotlin provides an automatic backing field which can be accessed using the field identifier:

```<code>var counter = 0 // the initializer value is written directly to the backing field
    set(value) {
        if (value >= 0) field = value
    }
</code>```

I got the above from this official link

My question is, is the "field" pointing to counter variable ?

Can someone please provide me an example for the backing field or describe me in an understanding word ?

答:
How it works , let's understand by an example , consider this

```<code>class Person {
   var name: String = ""
}
</code>```

If nothing is specified, the property(name) uses the default getter and setter. It can, of course,
be modified to run whatever custom behaviour you need, without having to change
the existing code:

So if want set custom behaviour to name property than we modify above class to this

```<code>class Person {

   var name: String = ""
   get() = field.toUpperCase()
   set(value) {
     field = "Name: $value"
  }

}
</code>```

If the property needs access to its own value in a custom getter or setter (as in this
case), it requires the creation of a backing field. It can be accessed by using field, a
reserved word, and will be automatically created by the compiler when it finds that
it’s being used.

Title: Kotlin explain me about Backing Fields

Body:
I have been looking at Kotlin official tutorial. I came across the topic called Backing Fields

It says,

Classes in Kotlin cannot have fields. However, sometimes it is necessary to have a backing field when using custom accessors. For these purposes, Kotlin provides an automatic backing field which can be accessed using the field identifier:

var counter = 0 // the initializer value is written directly to the backing field
    set(value) {
        if (value >= 0) field = value
    }

I got the above from this official link

My question is, is the "field" pointing to counter variable ?

Can someone please provide me an example for the backing field or describe me in an understanding word ?

Body:
How it works , let's understand by an example , consider this

class Person {
   var name: String = ""
}

If nothing is specified, the property(name) uses the default getter and setter. It can, of course,
be modified to run whatever custom behaviour you need, without having to change
the existing code:

So if want set custom behaviour to name property than we modify above class to this

class Person {

   var name: String = ""
   get() = field.toUpperCase()
   set(value) {
     field = "Name: $value"
  }

}

If the property needs access to its own value in a custom getter or setter (as in this
case), it requires the creation of a backing field. It can be accessed by using field, a
reserved word, and will be automatically created by the compiler when it finds that
it’s being used.


问:
Wordpress 404 cannot be found error when linking to envato theme via FTP
I am trying to setup a new Wordpress website which I think I have done correctly. However, when uploading a theme via FTP (could not be done via the dashboard) and then link to it inside the dashboard, I keep getting a 404 cannot be found error. Also what concerns me is that when I try to link to it (via FTP) it shows the absolute path on the 404 error page. So confused!

This is the url: http://ldnapprenticeships.co.uk/var/www/vhosts/ldnapprenticeships.co.uk/httpdocs/wp-content/themes/uncode/library/css/

Please forgive me, I have very limited knowledge backend! Any help would be greatly appreciated! :)

答:
If you are looking for the URL of the page you gave it is actually:
http://ldnapprenticeships.co.uk/wp-content/themes/uncode/library/css/

```<code>var/www/vhosts/ldnapprenticeships.co.uk/httpdocs/wp-content/themes/uncode/library/css/
</code>```

is the server path.

Body:
If you are looking for the URL of the page you gave it is actually:
http://ldnapprenticeships.co.uk/wp-content/themes/uncode/library/css/

var/www/vhosts/ldnapprenticeships.co.uk/httpdocs/wp-content/themes/uncode/library/css/

is the server path.


问:
F# Continuation-based tail-recursion
I have a function

```<code>let rec f n = function | 0          -> 1
                       | k when k>0 -> n * (f n (k-1))
                       | _          -> failwith "illegal argument"
</code>```

Which takes an int n and multiplies it by itself k times. Example:

```<code>f 3 3
val it : int = 27
</code>```

Now, I have rewritten it as a tail-recursive function to try and get a better understanding of it all:

```<code>let fT n y =
    let rec loop acc = function
        | 0          -> 1
        | k when k>0 -> n * (loop acc (k-1))
        | _          -> failwith "illegal argument"
    loop 0 y
</code>```

I'd be interested in doing the same using continuation-based tail-recursion, but I'm a little stuck on what it should do though:

```<code>let rec fC n c =
    match n with
    | 0          -> c 1
    | k when k>0 -> n * (fC n (fun x -> ...) //Not sure what to do here
</code>```

Any hints?

答:
In the recursive case you need to construct another continuation which receives the result from the recursive call, then calls the initial continuation with the result multiplied by the current value of n:

```<code>let rec fC n y c =
    match y with
    | 0 -> c 1
    | k when k > 0 -> fC n (k-1) (fun r -> c (n * r))
    | _ -> failwith "illegal argument"
</code>```

then

```<code>fT 3 3
> 27

fC 3 3 id
> 27
</code>```

Title: F# Continuation-based tail-recursion

Body:
I have a function

let rec f n = function | 0          -> 1
                       | k when k>0 -> n * (f n (k-1))
                       | _          -> failwith "illegal argument"

Which takes an int n and multiplies it by itself k times. Example:

f 3 3
val it : int = 27

Now, I have rewritten it as a tail-recursive function to try and get a better understanding of it all:

let fT n y =
    let rec loop acc = function
        | 0          -> 1
        | k when k>0 -> n * (loop acc (k-1))
        | _          -> failwith "illegal argument"
    loop 0 y

I'd be interested in doing the same using continuation-based tail-recursion, but I'm a little stuck on what it should do though:

let rec fC n c =
    match n with
    | 0          -> c 1
    | k when k>0 -> n * (fC n (fun x -> ...) //Not sure what to do here

Any hints?

Body:
In the recursive case you need to construct another continuation which receives the result from the recursive call, then calls the initial continuation with the result multiplied by the current value of n:

let rec fC n y c =
    match y with
    | 0 -> c 1
    | k when k > 0 -> fC n (k-1) (fun r -> c (n * r))
    | _ -> failwith "illegal argument"

then

fT 3 3
> 27

fC 3 3 id
> 27


问:
Sharepoint list returning null for custom columns
I have a office 365 sharepoint list with the following columns:
Title, URL, Category, DepartmentHead, and Email. The values for DepartmentHead and Email are returning null. These were two columns that I've just added as "single line of text" columns.  Why would they be returning null in my api response???

Here is the api call I'm using: /api/spdata/GetListItems('${this.listName}')/items

答:
I eventually figured out that what I wanted was a person object in which I would need to expand in my query to retrieve the email instead of just a text email column. Ended up with the following data url to fetch the items. I believe the issue before was that I was not using the internal name for the column. I found the name by going to the sharepoint list settings and clicking the column name.  Once on that page, the column name is displayed in the url at the top of the page.

/api/spdata/GetListItems('${this.allContentListName}')/items?$expand=DepartmentHead&$select=*,DepartmentHead/JobTitle,DepartmentHead/Id,DepartmentHead/EMail,DepartmentHead/Title&$filter=OData__ModerationStatus eq 0;


问:
Cassandra nodetool Status show me error . i want to know the status of my cassandra node

Cassandra Nodetool Status show me error when i run Nodetool status command. I want to know the Status of my Cassandra node.

答:
You will get this error when Cassandra is not running, check whether Cassandra is running or not. If running you may need to check the hostname configuration.

To configure the hostname Visit https://www.liquidweb.com/kb/error-failed-to-connect-to-127-0-0-17199-connection-refused-cassandra-solved/


问:
Why Would a Loop Skip Values?
For some reason a loop I have is leaving every second list-item from an unordered list instead of removing every list-item. And I am very confused as to why.

The code:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">

<title>Debugging</title>
    <script>

    function testingTesting() {
        var itemList = document.getElementsByTagName('LI');

        document.getElementById('demo').innerHTML = itemList.length;

        for (i = 0; i < itemList.length; i++) {
            document.getElementById('skillList').removeChild(itemList[i]);
        }
    }
    </script>
  </head>
  <body>
    <div id="toDisplay">

         <h2>Heading for Reasons</h2>
        <ul id="skillList">
          <li>Alpha</li>
          <li>Bravo</li>
          <li>Charlie</li>
          <li>Delta</li>
          <li>Foxtrot</li>
          <li>Exxon</li>
        </ul>

        <p id="demo"> </p>
    </div>

    <input type="button" value="Sort!" onclick="testingTesting()">

  </body>
</html>
</code>```

The result (in Chrome and Opera) of hitting the sort button once is:

"Heading for Reasons

Bravo
Delta
Exxon
6"

The result when hitting it twice is:

"Heading for Reasons

Delta
3"

Does anyone know why the list items in the itemList Array of modulo 2n + 1 are skipped?

Thank you.

答:
When you start you loop over this array (pseudocode)

```<code>[Alpha,Bravo,Charlie,Delta,Foxtrot,Exxon]
</code>```

Then you execute

```<code>removeChild(itemList[0])
</code>```

So your array is:

```<code>[Bravo,Charlie,Delta,Foxtrot,Exxon]
</code>```

Now you go on and execute:

```<code>removeChild(itemList[1])
</code>```

So you delete Charlie element (element 1 of array). The result is:

```<code>[Bravo,Delta,Foxtrot,Exxon]
</code>```

Final result will be:

```<code>[Bravo,Delta,Exxon]
</code>```

On second click the process is the same.

Title: Why Would a Loop Skip Values?

Body:
For some reason a loop I have is leaving every second list-item from an unordered list instead of removing every list-item. And I am very confused as to why.

The code:

<!DOCTYPE html>

    <meta charset="UTF-8">

<title>Debugging</title>

Heading for Reasons

Alpha

Bravo

Charlie

Delta

Foxtrot

Exxon

    <input type="button" value="Sort!" onclick="testingTesting()">

The result (in Chrome and Opera) of hitting the sort button once is:

"Heading for Reasons

Bravo
Delta
Exxon
6"

The result when hitting it twice is:

"Heading for Reasons

Delta
3"

Does anyone know why the list items in the itemList Array of modulo 2n + 1 are skipped?

Thank you.

Body:
When you start you loop over this array (pseudocode)

[Alpha,Bravo,Charlie,Delta,Foxtrot,Exxon]

Then you execute

removeChild(itemList[0])

So your array is:

[Bravo,Charlie,Delta,Foxtrot,Exxon]

Now you go on and execute:

removeChild(itemList[1])

So you delete Charlie element (element 1 of array). The result is:

[Bravo,Delta,Foxtrot,Exxon]

Final result will be:

[Bravo,Delta,Exxon]

On second click the process is the same.