问:
How to append new array in multidimensional array? [Swift]
How to add new item to multiple dimension array?

```<code>    struct Cat: Codable { var childrens: [Cat]? var name: String? var colour: String? }
</code>```

This is my current array

```<code>var currentShop = [
            [
                "children": [
                    [
                        "children": [],
                        "name": "Tom",
                        "colour": "Brown"
                    ],
                    [
                        "children": [],
                        "name": "Anggie",
                        "colour": "White"
                    ],
                    [
                        "children": [
                            [
                                "children": [],
                                "name": "Lily",
                                "colour": "White"
                            ]
                        ],
                        "name": "Snowy",
                        "colour": "White"
                    ],
                ],
                "name": "Sandy",
                "colour": "Brown"
            ],
            [
                "children": [],
                "name": "Mike",
                "colour": "Black"
            ],
            [
                "children": [],
                "name": "Tommy",
                "colour": "White"
            ],
            "name": "Blackie",
            "colour": "Black"
        ]
</code>```

New Array

```<code>var newChildren = [
            [
                "children": [],
                "name": "Pus",
                "colour": "White"
            ],
            [
                "children": [],
                "name": "Boots",
                "colour": "White"
            ]
]
</code>```

Adding in the new children for Cat name under Snowy.
How do I able to update the cats in the currentShop array?

My current code to find the parent

```<code>func updateCatShop(parentName:String, Cats: [Cat], newCats:[Cat] ) -> [Cat] {
    var catList = Cats for var cat in Cats {
        if(cat.name == parentName) {
            var updateCats = cat.childrens! + newCats cat.childrens = updateCats
        } else {
            for (_, childCat) in cat.childrens!.enumerated(){
                updateCatShop(parentName: parentName, Cats: [childCat], newCats: newCats)
            }
        }
    }
    return catList
}

var currentShop = updateCatShop(parentName:"Snowy", Cats:currentShop, newCats: newChildren)
</code>```

What would be the best way to update a multiple dimension object?

答:
This is not a complete answer but a suggestion of a direction to go in order to improve your data model and make it easier to work with.

Currently you are using recursive Structs and that is making it difficult to work with. But... you still need to keep the relationship between parents and children.

I am presuming too that your Shop will keep track only of cats (and parents and children) who are in stock in the shop.

An initial improvement of your data model might be something like this...

```<code>struct Cat {
    let id: String
    let name: String
    let colour: String
    var children: [String] // this is now an array of IDs
}
</code>```

Now you can maintain a one dimensional array of Cats... or... even better... a Shop.

```<code>struct Shop {
    var cats: [String: Cat]

    func add(cat: Cat, parentID: String?) {
        cats[cat.id] = cat

        if let parentID = parentID,
           let parentCat = cats[parentID] {
            parentCat.children.append(cat.id)
        }
    }
}
</code>```

Or something along the lines of this. This will need tweaking as it may not update the array of children properly.

You would also have to make sure that the cat IDs are unique.

The next iteration of this would be to store your data either in CoreData or in some other storage like Firestore etc... Where you can much more easily store lots of cats in lots of shops and having a nice data model becomes more important.

Body:
How to add new item to multiple dimension array?

    struct Cat: Codable { var childrens: [Cat]? var name: String? var colour: String? }

This is my current array

var currentShop = [
            [
                "children": [
                    [
                        "children": [],
                        "name": "Tom",
                        "colour": "Brown"
                    ],
                    [
                        "children": [],
                        "name": "Anggie",
                        "colour": "White"
                    ],
                    [
                        "children": [
                            [
                                "children": [],
                                "name": "Lily",
                                "colour": "White"
                            ]
                        ],
                        "name": "Snowy",
                        "colour": "White"
                    ],
                ],
                "name": "Sandy",
                "colour": "Brown"
            ],
            [
                "children": [],
                "name": "Mike",
                "colour": "Black"
            ],
            [
                "children": [],
                "name": "Tommy",
                "colour": "White"
            ],
            "name": "Blackie",
            "colour": "Black"
        ]

New Array

var newChildren = [
            [
                "children": [],
                "name": "Pus",
                "colour": "White"
            ],
            [
                "children": [],
                "name": "Boots",
                "colour": "White"
            ]
]

Adding in the new children for Cat name under Snowy.
How do I able to update the cats in the currentShop array?

My current code to find the parent

func updateCatShop(parentName:String, Cats: [Cat], newCats:[Cat] ) -> [Cat] {
    var catList = Cats for var cat in Cats {
        if(cat.name == parentName) {
            var updateCats = cat.childrens! + newCats cat.childrens = updateCats
        } else {
            for (_, childCat) in cat.childrens!.enumerated(){
                updateCatShop(parentName: parentName, Cats: [childCat], newCats: newCats)
            }
        }
    }
    return catList
}

var currentShop = updateCatShop(parentName:"Snowy", Cats:currentShop, newCats: newChildren)

What would be the best way to update a multiple dimension object?

Body:
This is not a complete answer but a suggestion of a direction to go in order to improve your data model and make it easier to work with.

Currently you are using recursive Structs and that is making it difficult to work with. But... you still need to keep the relationship between parents and children.

I am presuming too that your Shop will keep track only of cats (and parents and children) who are in stock in the shop.

An initial improvement of your data model might be something like this...

struct Cat {
    let id: String
    let name: String
    let colour: String
    var children: [String] // this is now an array of IDs
}

Now you can maintain a one dimensional array of Cats... or... even better... a Shop.

struct Shop {
    var cats: [String: Cat]

    func add(cat: Cat, parentID: String?) {
        cats[cat.id] = cat

        if let parentID = parentID,
           let parentCat = cats[parentID] {
            parentCat.children.append(cat.id)
        }
    }
}

Or something along the lines of this. This will need tweaking as it may not update the array of children properly.

You would also have to make sure that the cat IDs are unique.

The next iteration of this would be to store your data either in CoreData or in some other storage like Firestore etc... Where you can much more easily store lots of cats in lots of shops and having a nice data model becomes more important.


来源: stackexchange

问:
Subquery returns more than 1 row MySQL?
```<code>SELECT *,
       CASE MinPrice WHEN Bandung THEN 'Bandung'
                     WHEN `Vendor Bandung` THEN 'Vendor Bandung'
                     WHEN Jakarta THEN 'Jakarta'
                     WHEN KJ THEN 'KJ'
                     ELSE 'unknown'
                     END AREA,
       (SELECT trx.sumber_id FROM `transactions` AS trx WHERE cte.item_id = trx.item_id AND cte.MinPrice = trx.price) AS `sumber_id`
FROM
(
SELECT item_id ,
       MAX(CASE WHEN vendor_id = 2
                THEN price
                END) AS Bandung,
       MAX(CASE WHEN vendor_id = 3
                THEN price
                END) AS `Vendor Bandung`,
       MAX(CASE WHEN vendor_id = 4
                THEN price
                END) AS Jakarta,
       MAX(CASE WHEN vendor_id = 5
                THEN price
                END) AS KJ,
       MIN(NULLIF(price, 0)) MinPrice
FROM
    transactions

 WHERE `start_periode` = '2020-02-17'
GROUP BY `item_id`, `start_periode`
) cte;
</code>```

i got error :
Query: SELECT *, CASE MinPrice WHEN Bandung THEN 'Bandung' WHEN Vendor Bandung THEN 'Vendor Bandung' WHEN Jakarta THEN 'Jakarta' WHEN...

Error Code: 1242

```<code>Subquery returns more than 1 row
</code>```

答:
I would just write this query as:</p>

```<code>SELECT
    t1.item_id,
    t1.sumber_id,
    COALESCE(t2.min_price, 0) AS min_price
FROM transactions t1
LEFT JOIN
FROM
(
    SELECT item_id, MIN(price) AS min_price
    FROM transactions
    WHERE start_periode = '2020-02-17' AND vendor_id IN (2,3,4,5)
    GROUP BY item_id
) t2
    ON t1.item_id = t2.item_id;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Subquery returns more than 1 row MySQL?

Body:
SELECT *,
       CASE MinPrice WHEN Bandung THEN 'Bandung'
                     WHEN `Vendor Bandung` THEN 'Vendor Bandung'
                     WHEN Jakarta THEN 'Jakarta'
                     WHEN KJ THEN 'KJ'
                     ELSE 'unknown'
                     END AREA,
       (SELECT trx.sumber_id FROM `transactions` AS trx WHERE cte.item_id = trx.item_id AND cte.MinPrice = trx.price) AS `sumber_id`
FROM
(
SELECT item_id ,
       MAX(CASE WHEN vendor_id = 2
                THEN price
                END) AS Bandung,
       MAX(CASE WHEN vendor_id = 3
                THEN price
                END) AS `Vendor Bandung`,
       MAX(CASE WHEN vendor_id = 4
                THEN price
                END) AS Jakarta,
       MAX(CASE WHEN vendor_id = 5
                THEN price
                END) AS KJ,
       MIN(NULLIF(price, 0)) MinPrice
FROM
    transactions

 WHERE `start_periode` = '2020-02-17'
GROUP BY `item_id`, `start_periode`
) cte;

i got error :
Query: SELECT *, CASE MinPrice WHEN Bandung THEN 'Bandung' WHEN Vendor Bandung THEN 'Vendor Bandung' WHEN Jakarta THEN 'Jakarta' WHEN...

Error Code: 1242

Subquery returns more than 1 row

Body:
I would just write this query as:

SELECT
    t1.item_id,
    t1.sumber_id,
    COALESCE(t2.min_price, 0) AS min_price
FROM transactions t1
LEFT JOIN
FROM
(
    SELECT item_id, MIN(price) AS min_price
    FROM transactions
    WHERE start_periode = '2020-02-17' AND vendor_id IN (2,3,4,5)
    GROUP BY item_id
) t2
    ON t1.item_id = t2.item_id;


问:
Comparison between Verdaccio and Github package registry
I'm looking for some comparison between this to registry, did anyone try both?

Why I should use one or another?

What are the pros and cons of each registry?

答:
I'm verdaccio maintainer, so I'll try to give you an un-opinionated answer.

Why I should use one or another?

First of all, both are different in many aspects, thus, the answer would be up to your needs. For what do you need a private registry?

```<code>                                       Verdaccio  GitHub Registry
</code>```

```<code>    Host private packages                ✅            ✅ (*)
    Host scoped private packages         ✅            ✅
    Host non-scoped private packages     ✅            ❌
    Proxy packages (npmjs)               ✅            ❌
    SAAS service registry                ❌            ✅
    Self-hosted registry                 ✅            ❌
    Custom authentication                ✅            ❌
    Code Privacy                         ✅            ❌
    High amount of users                 ❌            ✅
    Customization                        ✅            ❌
    Support all npm commands             ❌            ❌
    npm audit                            ✅            ❌
    run locally                          ✅            ❌
    offline                              ✅            ❌
</code>```

This is just on top of my head. I'm sure there are more differences. Verdaccio can be SASS and also self-hosted, thus, differences are noticeable.

So, now think about your needs, then chose the one the most fits to you.

What are the pros and cons of each registry?

Mostly what I answer above, the big pro for GitHub is a huge infrastructure and most likely will not fail and you don't have to worry about host a registry by yourself. While Verdaccio is highly customizable and can run wherever you want, either for run E2E testing, cache some packages for future travels or minimize issues with npmjs, simply run a private registry in your organization or learn some Node.js publishing locally.

(*) Host private packages: At time of this writing is free, but most likely will turn be a paid service for private packages, and free for public ones.
Hopefully my answer helps you to understand the difference between both services.

Body:
I'm verdaccio maintainer, so I'll try to give you an un-opinionated answer.

Why I should use one or another?

First of all, both are different in many aspects, thus, the answer would be up to your needs. For what do you need a private registry?

                                       Verdaccio  GitHub Registry

    Host private packages                ✅            ✅ (*)
    Host scoped private packages         ✅            ✅
    Host non-scoped private packages     ✅            ❌
    Proxy packages (npmjs)               ✅            ❌
    SAAS service registry                ❌            ✅
    Self-hosted registry                 ✅            ❌
    Custom authentication                ✅            ❌
    Code Privacy                         ✅            ❌
    High amount of users                 ❌            ✅
    Customization                        ✅            ❌
    Support all npm commands             ❌            ❌
    npm audit                            ✅            ❌
    run locally                          ✅            ❌
    offline                              ✅            ❌

This is just on top of my head. I'm sure there are more differences. Verdaccio can be SASS and also self-hosted, thus, differences are noticeable.

So, now think about your needs, then chose the one the most fits to you.

What are the pros and cons of each registry?

Mostly what I answer above, the big pro for GitHub is a huge infrastructure and most likely will not fail and you don't have to worry about host a registry by yourself. While Verdaccio is highly customizable and can run wherever you want, either for run E2E testing, cache some packages for future travels or minimize issues with npmjs, simply run a private registry in your organization or learn some Node.js publishing locally.

(*) Host private packages: At time of this writing is free, but most likely will turn be a paid service for private packages, and free for public ones.
Hopefully my answer helps you to understand the difference between both services.


问:
Reference foreign keys using SSIS-Lookup
I am asking for help on the following topic. I am trying to create an ETL process with two Excel data sources (S1 ~300 rows and S2 ~7000 rows). S1 contains project information and employee details and S2 contains the amount of hours, which each employee worked in which project at a timestamp.

I want to insert the amount of hours, which each employee worked in each project at a timestamp, into the fact table by referencing to the existing primary keys in the dimension tables. If an entry is not present in the dimension tables already, i want to add a new entry first and use the newly generated id. The destination table structure looks as follows (Data Warehouse, Star Schema):Destination Table Structure

In SSIS, i created three Data Flow tasks for filling the Dimension Tables (project, employee and time) with distinct values (using group by, as S1 and S2 contain a lot of duplicate rows)first, and a fourth data flow task (see image below) to insert the FactTable data, and this is where I'm running into problems:

Data Flow Task FactTable

I am using three LookUp functions to retrieve the foreignKeys project_id, employee_id and time_id from the Dimension tables (using project name, employee number and timestamp). If the id is found, it is passed on all the way to Merge Join 1, if not, a new Dimension Entry is created (lets say project) and the generated project_id passed on instead. Same goes for employee and time respectively.

There is two issues with this:

1) The "amount of hours" (passed by Multicast four, see image above) is not matched in the final result (No Match)

2) The amount of rows being inserted keeps increasing forever (Endless Join, I belive due to the Merge joins).

What I've tried:

I have used one UNION instead of three Merge Joins before, but this resulted in the foreign keys being in seperate rows each, instead of merged together.

I used Merge (instead of Merge Join) and combined the join as well as sort conditions in as I fell all possible ways.

I understand that this scenario might be confusing for everybody else, but thank your for taking time looking at it! Any help is greatly appreciated.

答:
Solved it

For anybody having similar issues:

Seperate Data Flows for filling Dimension Tables with those filling Fact Tables will do the trick.
Its a clean solution and easier to debug.

Also: Dont run the LookUp Functions in parallel, but rather one after each other and pass on the attributes. Saves unnecessary Merges as well.

So as a Sum Up:
Four Data Flow Tasks, three for filling dimension tables ONLY and one for filling fact tables ONLY.

Loading Multiple Tables using SSIS keeping foreign key relationships
The answer posted by onupdatecascade is basically it.

Good luck!


问:
Nesting tibbles and performing calculations on each with a group_by
I want to find out what the dominant class of of each id_b is. To calculate it I need to find out the sum of size per class for each id_b. Whichever class is largest is the new dominant class assigned to id_b.

The script below does what I want it to do but it feels quite clunky and over complicated. I've not worked with nested data much before so I'm not sure if I've used the best methods possible Can anyone think of a neater way of achieving the same output in tidyverse or data.table?

Thanks!

```<code>library(tidyverse)

# sample data
set.seed(123)
input <- tibble(id_a = c(letters[seq(1,10)]),
                size = runif(10, min = 10, max = 50),
                class = c("x","x","y","x","y",
                          "y","x","y","x","x"),
                id_b = c("A1","A1","B1","B1","B1",
                         "C1","C1","C1","D1","E1"))
print(input)

</code>```

```<code>   id_a   size class id_b
   <chr> <dbl> <chr> <chr>
 1 a      23.6 x     A1
 2 b      43.6 x     A1
 3 c      23.9 y     B1
 4 d      23.4 x     B1
 5 e      29.1 y     B1
 6 f      45.7 y     C1
 7 g      44.6 x     C1
 8 h      25.6 y     C1
 9 i      41.1 x     D1
10 j      48.4 x     E1
</code>```

```<code># nest input to create a nested tibble for each id_b
input_nest <- input %>% group_by(id_b) %>% nest()

# calculate dominant class
input_nest_dominant <- input_nest %>% mutate(DOMINANT_CLASS = lapply(data, function(x){
  # group each nested tibble by class, and calculate total size. Then find the biggest size and extract
  # the class value
  output <- x %>% group_by(class) %>%
            summarise(total_size = sum(size)) %>%
            top_n(total_size, n = 1) %>%
            pull(class)
  return(output)
} ))

# unnest to end up with a tibble
input_nest_dominant_clean <- input_nest_dominant %>%
                             unnest(cols = c(DOMINANT_CLASS)) %>%
                             select(-data) %>%
                             ungroup()

print(input_nest_dominant_clean)
</code>```

```<code>  id_b  DOMINANT_CLASS
  <chr> <chr>
1 A1    x
2 B1    y
3 C1    y
4 D1    x
5 E1    x
</code>```

答:
From this example, you don't need nest at all, just calculate it using group_by and summarize.

input %>%
  group_by(id_b, class) %>%
  summarize(size = sum(size)) %>%
  group_by(id_b) %>%
  summarize(DOMINANT_CLASS = class[which.max(size)])
#> # A tibble: 5 x 2
#>   id_b  DOMINANT_CLASS
#>   <chr> <chr>
#> 1 A1    x
#> 2 B1    y
#> 3 C1    y
#> 4 D1    x
#> 5 E1    x
```

Body:
I want to find out what the dominant class of of each id_b is. To calculate it I need to find out the sum of size per class for each id_b. Whichever class is largest is the new dominant class assigned to id_b.

The script below does what I want it to do but it feels quite clunky and over complicated. I've not worked with nested data much before so I'm not sure if I've used the best methods possible Can anyone think of a neater way of achieving the same output in tidyverse or data.table?

Thanks!

library(tidyverse)

# sample data
set.seed(123)
input <- tibble(id_a = c(letters[seq(1,10)]),
                size = runif(10, min = 10, max = 50),
                class = c("x","x","y","x","y",
                          "y","x","y","x","x"),
                id_b = c("A1","A1","B1","B1","B1",
                         "C1","C1","C1","D1","E1"))
print(input)

   id_a   size class id_b
   <chr> <dbl> <chr> <chr>
 1 a      23.6 x     A1
 2 b      43.6 x     A1
 3 c      23.9 y     B1
 4 d      23.4 x     B1
 5 e      29.1 y     B1
 6 f      45.7 y     C1
 7 g      44.6 x     C1
 8 h      25.6 y     C1
 9 i      41.1 x     D1
10 j      48.4 x     E1

# nest input to create a nested tibble for each id_b
input_nest <- input %>% group_by(id_b) %>% nest()

# calculate dominant class
input_nest_dominant <- input_nest %>% mutate(DOMINANT_CLASS = lapply(data, function(x){
  # group each nested tibble by class, and calculate total size. Then find the biggest size and extract
  # the class value
  output <- x %>% group_by(class) %>%
            summarise(total_size = sum(size)) %>%
            top_n(total_size, n = 1) %>%
            pull(class)
  return(output)
} ))

# unnest to end up with a tibble
input_nest_dominant_clean <- input_nest_dominant %>%
                             unnest(cols = c(DOMINANT_CLASS)) %>%
                             select(-data) %>%
                             ungroup()

print(input_nest_dominant_clean)

  id_b  DOMINANT_CLASS
  <chr> <chr>
1 A1    x
2 B1    y
3 C1    y
4 D1    x
5 E1    x


问:
What is the reason to initialize or assign an empty string literal to a pointer to char in C, or a pointer to const char in C++?
My question is actually quite simply for those who might know about it, but I ask because I'm not aware of this technique already.

What is the reason for initializing or assigning an empty string literal to a pointer to char in C, or a pointer to const char in C++?

Like f.e.:

```<code>char* p = "";
</code>```

or

```<code>char* p;
p = "";
</code>```

Or, as suggested in the comments, in C++:

```<code>const char* p = "";
</code>```

or

```<code>const char* p;
p = "";
</code>```

I do often see this technique, but don't understand why someone shall assign an empty string literal to a char pointer (or pointer to const char for C++) or where this is coming from.

I have read Initialize a string in C to empty string, but this question is focused on initializing a char array with an empty string.

And I have also read: Initializing a string with the empty string, but this question covers an incorrect approach to assign an empty string to a pointer earlier returned by a malloc() function.

答:
What is the reason to initialize or assign an empty string literal to a pointer to char in C or a pointer to const char in C++?

To me it seems that there is a misunderstanding here. The pointer is not initialized with an empty string. It is initialized to point to an empty string (a string literal that the compiler placed somewhere in memory). That's a major difference.

Consider this code:

```<code>char* p = "";
printf("%p\n", (void*)p);
p = "test";
printf("%p\n", (void*)p);
</code>```

Possible output:

```<code>0x563e72497007
0x563e72497008
</code>```

In these cases p holds a memory address where the compiler placed the two string literals (i.e. "" at 0x563e72497007 and "test" at 0x563e72497008). So in that memory you have:

```<code>0x563e72497007 '\0'                  (i.e. the empty string that only consists
                                           a string termination character`)

0x563e72497008 't' 'e' 's' 't' '\0'  (i.e. the string "test")
</code>```

So again - p is not initialized/assigned with the strings, it is initialized/assigned to point to strings.

Why would you want to initialize a pointer to point to an empty string?

Well, it's like any other variable that you initialize... You do it because you want the variable to have a known value in case it's used before any other assignment is made to it. So just like doing int i = 0;.

In other words - you do char* p = ""; to make sure that p points to a valid C-style string.

A very simple example:

```<code>char* p = "";
if (answerIsWrong())
{
    p = "not";
}
printf("The answer is %s correct\n", p);
</code>```

Depending on the return value from the function answerIsWrong() this may print:

```<code>The answer is correct
</code>```

or

```<code>The answer is not correct
</code>```

In the first case it's important the p was initialized to point to an empty string.

However, if you know that you'll never use p before it's assigned a new value, there is obviously no reason to initialize it! However, some programmers prefer to always initialize all variables - even if they assign another value before use.

Example:

```<code>char* p = "";  // No reason for this initialization
               // p will be assigned another value before it's used

if (answerIsWrong())
{
    p = " not ";
}
else
{
    p = " absolutely ";
}
printf("The answer is %s correct\n", p);
</code>```

Body:
My question is actually quite simply for those who might know about it, but I ask because I'm not aware of this technique already.

What is the reason for initializing or assigning an empty string literal to a pointer to char in C, or a pointer to const char in C++?

Like f.e.:

char* p = "";

or

char* p;
p = "";

Or, as suggested in the comments, in C++:

const char* p = "";

or

const char* p;
p = "";

I do often see this technique, but don't understand why someone shall assign an empty string literal to a char pointer (or pointer to const char for C++) or where this is coming from.

I have read Initialize a string in C to empty string, but this question is focused on initializing a char array with an empty string.

And I have also read: Initializing a string with the empty string, but this question covers an incorrect approach to assign an empty string to a pointer earlier returned by a malloc() function.

Body:
What is the reason to initialize or assign an empty string literal to a pointer to char in C or a pointer to const char in C++?

To me it seems that there is a misunderstanding here. The pointer is not initialized with an empty string. It is initialized to point to an empty string (a string literal that the compiler placed somewhere in memory). That's a major difference.

Consider this code:

char* p = "";
printf("%p\n", (void*)p);
p = "test";
printf("%p\n", (void*)p);

Possible output:

0x563e72497007
0x563e72497008

In these cases p holds a memory address where the compiler placed the two string literals (i.e. "" at 0x563e72497007 and "test" at 0x563e72497008). So in that memory you have:

0x563e72497007 '\0'                  (i.e. the empty string that only consists
                                           a string termination character`)

0x563e72497008 't' 'e' 's' 't' '\0'  (i.e. the string "test")

So again - p is not initialized/assigned with the strings, it is initialized/assigned to point to strings.

Why would you want to initialize a pointer to point to an empty string?

Well, it's like any other variable that you initialize... You do it because you want the variable to have a known value in case it's used before any other assignment is made to it. So just like doing int i = 0;.

In other words - you do char* p = ""; to make sure that p points to a valid C-style string.

A very simple example:

char* p = "";
if (answerIsWrong())
{
    p = "not";
}
printf("The answer is %s correct\n", p);

Depending on the return value from the function answerIsWrong() this may print:

The answer is correct

or

The answer is not correct

In the first case it's important the p was initialized to point to an empty string.

However, if you know that you'll never use p before it's assigned a new value, there is obviously no reason to initialize it! However, some programmers prefer to always initialize all variables - even if they assign another value before use.

Example:

char* p = "";  // No reason for this initialization
               // p will be assigned another value before it's used

if (answerIsWrong())
{
    p = " not ";
}
else
{
    p = " absolutely ";
}
printf("The answer is %s correct\n", p);


问:
Parse short US date into yyyy-MM-dd, java
I want to parse the date "3/27/11" which I think is equal to US short date.

```<code>DateFormat df1 = new SimpleDateFormat("MM/dd/yy");
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date) df1.parseObject("03/27/11");
System.out.println("New date: " + df2.format(date));
</code>```

I found the code above in several java tutorials but it doesn't seem to work.
For some how I get,

```<code>Exception in thread "main" java.lang.AssertionError: Default directory must be absolute/non-UNC
</code>```

Here is what I want to achieve,

input: 3/27/11

(03/27/11 should also be a valid input)

output: 2011-03-27

Thanks in advance!

答:
You can also do it like this

```<code>String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";

//Instance of the calender class in the utill package
Calendar cal = Calendar.getInstance();

//A class that was used to get the date time stamp
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
</code>```

To print out the time you say

```<code>System.out.println(sdf.format(cal.getTime()) );
</code>```

Cheers

ContentLicense: CC BY-SA 3.0

Body:
I want to parse the date "3/27/11" which I think is equal to US short date.

DateFormat df1 = new SimpleDateFormat("MM/dd/yy");
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date) df1.parseObject("03/27/11");
System.out.println("New date: " + df2.format(date));

I found the code above in several java tutorials but it doesn't seem to work.
For some how I get,

Exception in thread "main" java.lang.AssertionError: Default directory must be absolute/non-UNC

Here is what I want to achieve,

input: 3/27/11

(03/27/11 should also be a valid input)

output: 2011-03-27

Thanks in advance!

Body:
You can also do it like this

String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";

//Instance of the calender class in the utill package
Calendar cal = Calendar.getInstance();

//A class that was used to get the date time stamp
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);

To print out the time you say

System.out.println(sdf.format(cal.getTime()) );

Cheers


问:
How to add header to a dataset in R?
I need to read the ''wdbc.data' in the following data folder:
http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/

Doing this in R is easy using command read.csv but as the header is missing how can I add it? I have the information but don't know how to do this and I'd prefer do not edit the data file.

答:
this should work out,

```<code>      kable(dt) %>%
      kable_styling("striped") %>%
      add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2, "Group 3" = 2))
#OR
kable(dt) %>%
  kable_styling(c("striped", "bordered")) %>%
  add_header_above(c(" ", "Group 1" = 2, "Group 2" = 2, "Group 3" = 2)) %>%
  add_header_above(c(" ", "Group 4" = 4, "Group 5" = 2)) %>%
  add_header_above(c(" ", "Group 6" = 6))
</code>```

for more you can check the link

Title: How to add header to a dataset in R?

Body:
this should work out,

      kable(dt) %>%
      kable_styling("striped") %>%
      add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2, "Group 3" = 2))
#OR
kable(dt) %>%
  kable_styling(c("striped", "bordered")) %>%
  add_header_above(c(" ", "Group 1" = 2, "Group 2" = 2, "Group 3" = 2)) %>%
  add_header_above(c(" ", "Group 4" = 4, "Group 5" = 2)) %>%
  add_header_above(c(" ", "Group 6" = 6))

for more you can check the link


问:
react filtering an object of arrays
I'm trying to find a better way to remove value pairs of an object that contain an empty string ""

my current state is:

```<code> this.state = {

            searchParams:{
                query: '',
                colors: [],
                text: '',
                legalities: '',
                setName: '',
                pageSize: 4
            }
}
</code>```

I know this won't work with my state since it isn't an array, but something like this is what i'm trying to achieve right now

```<code>var search = this.state.searchParams.filter(function (el) {
            return el !== "";
          });
</code>```

could anyone point me in the right direction and explain a better way to do this with an object, thanks :) ?

答:
the most simple way is by using Object.keys method and then iterate the whole object. then check if searchParams[ele] is true and add in another object.

```<code>    var newObj = {};
    Object.keys(this.state.searchParams).forEach(ele => {
      if (searchParams[ele]) {
        newObj = { ...newObj, [ele]: searchParams[ele] };
      }
    });
    console.log(newObj); // new object generated with empty values eliminated
this.setState({searchParams:newObj})
</code>```

Title: react filtering an object of arrays

Body:
I'm trying to find a better way to remove value pairs of an object that contain an empty string ""

my current state is:

 this.state = {

            searchParams:{
                query: '',
                colors: [],
                text: '',
                legalities: '',
                setName: '',
                pageSize: 4
            }
}

I know this won't work with my state since it isn't an array, but something like this is what i'm trying to achieve right now

var search = this.state.searchParams.filter(function (el) {
            return el !== "";
          });

could anyone point me in the right direction and explain a better way to do this with an object, thanks :) ?

Body:
the most simple way is by using Object.keys method and then iterate the whole object. then check if searchParams[ele] is true and add in another object.

    var newObj = {};
    Object.keys(this.state.searchParams).forEach(ele => {
      if (searchParams[ele]) {
        newObj = { ...newObj, [ele]: searchParams[ele] };
      }
    });
    console.log(newObj); // new object generated with empty values eliminated
this.setState({searchParams:newObj})


问:
How can I compare two similar PHP xdebug trace files efficiently?
I have two xdebug trace files, about 25 MB each. One of them led to an error and I'm trying to find the spot where the two execution sequences deviated. The problem is that there are a bunch of irrelevant differences between the two files that I want to ignore, such as remote port numbers, query times and other database statistics.

My first attempt at solving this was to open the trace files in excel and remove the execution times which are obviously different most of the time. Then I tried using compare/merge apps to get rid of the other irrelevant differences. For example I replaced the remote portnumbers in both of the files with a placeholder string PORT_NUMBER. Some of the differences are repeated again and again so I need to be able to search and replace globally. The problem is that all of the apps I've tried are extremely slow and often crash. They can't handle rendering with word wrap, search and replace or even simple editing with files this big.

I've tried many compare/merge apps including DiffMerge, WinMerge, KDiff3, Meld, Notepad++, Eclipse and Visual Studio Code. I don't think that using diff and sed together would work, because I need to see in-line differences and jump to different parts of the large file quickly. I also would have to copy and paste the differences from diff to use in sed and they use another terminal for sed. There are also special characters and extremely long lines, so I don't think sed is a good option.

I'd like to find a way to use the trace files to find the point of deviation in the execution sequence.

答:
The best way to do this, is by having two "computerized" trace files (it's xdebug.trace_format=1). This format is tab separated, which makes it easier to write a script that goes through them and does the comparison. You can ignore arguments to methods/functions etc too, as well as even compare return values if you wish to do so.

There is a mini script in Xdebug's contrib directory (https://github.com/xdebug/xdebug/blob/master/contrib/tracefile-analyser.php) that shows a little about how to do that.

If you can't create them again, then you are going to be up for a much harder task. The first thing I would do is to strip out all the arguments (with a regexp). VIM would probably be your best bet handling two 25MB files.


问:
Drop the columns in pandas dataframe
col_exclusions = ['numerator','Numerator' 'Denominator', "denominator"]

dataframe

```<code>id prim_numerator sec_Numerator tern_Numerator tern_Denominator final_denominator Result

1       12                23           45          54                      56         Fail
</code>```

Final output is id and Result

答:
You can be explicit and use del for columns that contain the suffixes in your input list:

```<code>for column in df.columns:
    if any([column.endswith(suffix) for suffix in col_exclusions]):
        del df[column]
</code>```

Title: Drop the columns in pandas dataframe

Body:
col_exclusions = ['numerator','Numerator' 'Denominator', "denominator"]

dataframe

id prim_numerator sec_Numerator tern_Numerator tern_Denominator final_denominator Result

1       12                23           45          54                      56         Fail

Final output is id and Result

Body:
You can be explicit and use del for columns that contain the suffixes in your input list:

for column in df.columns:
    if any([column.endswith(suffix) for suffix in col_exclusions]):
        del df[column]


问:
Best way to implement dynamic array of inputs in React
Currently I have implemented it using plain javascript array. But there seems to be few problems.

onChange, onDelete has to iterate all over the array which could be better like O(1)

When some item gets deleted key property of other items get changed. I'm not sure if it's bad or not.

Using immutable.js can get rid of problem 1. Is number 2 really a problem? Is there a better alternative than immutable.js?
Maybe I'm not asking the right questions, what's the best way?

import React, { useState } from "react";

export default function() {
    const [rows, setRows] = useState([""]);

    const onChange = (e, i) => {
        setRows(rows.map((row, index) => (index !== i ? row : e.target.value)));
    };

    const onDelete = i => {
        setRows(rows.filter((_, index) => i !== index));
    };

    return (
        <>
            {rows.map((row, index) => {
                return (

                        <input value={row} onChange={e => onChange(e, index)} />
                        {index !== 0 && (
                            <button onClick={() => onDelete(index)}>
                                - delete row
                            </button>
                        )}

                );
            })}

            <button onClick={() => setRows(rows.concat([""]))}>
                + add row
            </button>
        </>
    );
}
```

<p><strong>UPDATE</strong></p>

<p>I tried using <code>immutable-js</code> <code>OrderedMap</code>. Now <code>key</code> property of elements won't change and <code>onChange</code> and <code>onDelete</code> won't iterate over everything. Is this better than before?</p>

```import React, { useState } from "react";
import { OrderedMap } from "immutable";

export default function() {
    const [inputState, setInputState] = useState({
        rows: OrderedMap(),
        nextKey: Number.MIN_VALUE,
    });

    function onChange(k, v) {
        setInputState({
            ...inputState,
            rows: inputState.rows.update(k, () => v),
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        setInputState({
            rows: rows.set(nextKey, ""),
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(k) {
        setInputState({
            ...inputState,
            rows: inputState.rows.delete(k),
        });
    }

    return (
        <>
            {inputState.rows.entrySeq().map(([k, v]) => {
                return (

                        <input
                            value={v}
                            onChange={({ target: { value } }) => {
                                onChange(k, value);
                            }}
                        />
                        <button onClick={() => deleteItem(k)}>-</button>

                );
            })}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}
```

<p><strong>UPDATE: 2</strong>
Also tried using plain javascript <code>Map</code>.</p>

<pre class="lang-js prettyprint-override"><code>import React, { useState } from "react";

export default function() {
    const [inputState, setInputState] = useState({
        rows: new Map(),
        nextKey: Number.MIN_VALUE,
    });

    function onChange(k, v) {
        const { rows, nextKey } = inputState;
        rows.set(k, v);
        setInputState({
            nextKey,
            rows,
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        rows.set(nextKey, "");
        setInputState({
            rows,
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(k) {
        const { rows, nextKey } = inputState;
        rows.delete(k);
        setInputState({
            nextKey,
            rows,
        });
    }

    const uiList = [];

    for (const [k, v] of inputState.rows.entries()) {
        uiList.push(
            <div key={k}>
                <input
                    value={v}
                    onChange={({ target: { value } }) => {
                        onChange(k, value);
                    }}
                />
                <button onClick={() => deleteItem(k)}>-</button>
            </div>
        );
    }

    return (
        <>
            {uiList}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}
</code>```

UPDATE 3
Using plain array but with key property.

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

export default function() {
    const [inputState, setInputState] = useState({
        rows: [],
        nextKey: Number.MIN_VALUE,
    });

    function onChange(i, v) {
        const { rows, nextKey } = inputState;
        rows[i].value = v;
        setInputState({
            nextKey,
            rows,
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        rows.push({ key: nextKey, value: "" });
        setInputState({
            rows,
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(i) {
        const { rows, nextKey } = inputState;
        rows.splice(i, 1);
        setInputState({
            nextKey,
            rows,
        });
    }

    return (
        <>
            {inputState.rows.map(({ key, value }, index) => {
                return (
                    <div key={key}>
                        <input
                            value={value}
                            onChange={({ target: { value } }) => {
                                onChange(index, value);
                            }}
                        />
                        <button onClick={() => deleteItem(index)}>-</button>
                    </div>
                );
            })}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}
</code>```

答:
Without index we can do using the Map and Map retrieval is faster, below code you can try.</p>

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

export default function() {
    const [rows, setRows] = useState(new Map());

    const onUpdate = (key, value) => {
        setRows(prev => new Map(prev).set(key, { key, value}));
    }
    const onDelete = (key) => {
        setRows(prev => new Map(prev).delete(key));
    }
    return (
        <>
            {[...rows].map((row, index) => (typeof row[1].value !== "undefined") && (
                <div key={index}>
                    <input value={row[1].value} onChange={e =>  onUpdate(row[1].key, e.target.value)} />
                    <button onClick={() => onDelete(row[1].key)}>- delete row</button>
                </div>
            ))}

            <button onClick={() => onUpdate(rows.size, "")}>
                + add row
            </button>
        </>
    );
}
</code>```

Body:
Currently I have implemented it using plain javascript array. But there seems to be few problems.

onChange, onDelete has to iterate all over the array which could be better like O(1)

When some item gets deleted key property of other items get changed. I'm not sure if it's bad or not.

Using immutable.js can get rid of problem 1. Is number 2 really a problem? Is there a better alternative than immutable.js?
Maybe I'm not asking the right questions, what's the best way?

import React, { useState } from "react";

export default function() {
    const [rows, setRows] = useState([""]);

    const onChange = (e, i) => {
        setRows(rows.map((row, index) => (index !== i ? row : e.target.value)));
    };

    const onDelete = i => {
        setRows(rows.filter((_, index) => i !== index));
    };

    return (
        <>
            {rows.map((row, index) => {
                return (

                        <input value={row} onChange={e => onChange(e, index)} />
                        {index !== 0 && (
                            <button onClick={() => onDelete(index)}>
                                - delete row
                            </button>
                        )}

                );
            })}

            <button onClick={() => setRows(rows.concat([""]))}>
                + add row
            </button>
        </>
    );
}

UPDATE

I tried using immutable-js OrderedMap. Now key property of elements won't change and onChange and onDelete won't iterate over everything. Is this better than before?

import React, { useState } from "react";
import { OrderedMap } from "immutable";

export default function() {
    const [inputState, setInputState] = useState({
        rows: OrderedMap(),
        nextKey: Number.MIN_VALUE,
    });

    function onChange(k, v) {
        setInputState({
            ...inputState,
            rows: inputState.rows.update(k, () => v),
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        setInputState({
            rows: rows.set(nextKey, ""),
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(k) {
        setInputState({
            ...inputState,
            rows: inputState.rows.delete(k),
        });
    }

    return (
        <>
            {inputState.rows.entrySeq().map(([k, v]) => {
                return (

                        <input
                            value={v}
                            onChange={({ target: { value } }) => {
                                onChange(k, value);
                            }}
                        />
                        <button onClick={() => deleteItem(k)}>-</button>

                );
            })}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}

UPDATE: 2
Also tried using plain javascript Map.

import React, { useState } from "react";

export default function() {
    const [inputState, setInputState] = useState({
        rows: new Map(),
        nextKey: Number.MIN_VALUE,
    });

    function onChange(k, v) {
        const { rows, nextKey } = inputState;
        rows.set(k, v);
        setInputState({
            nextKey,
            rows,
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        rows.set(nextKey, "");
        setInputState({
            rows,
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(k) {
        const { rows, nextKey } = inputState;
        rows.delete(k);
        setInputState({
            nextKey,
            rows,
        });
    }

    const uiList = [];

    for (const [k, v] of inputState.rows.entries()) {
        uiList.push(

                <input
                    value={v}
                    onChange={({ target: { value } }) => {
                        onChange(k, value);
                    }}
                />
                <button onClick={() => deleteItem(k)}>-</button>

        );
    }

    return (
        <>
            {uiList}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}

UPDATE 3
Using plain array but with key property.

import React, { useState } from "react";

export default function() {
    const [inputState, setInputState] = useState({
        rows: [],
        nextKey: Number.MIN_VALUE,
    });

    function onChange(i, v) {
        const { rows, nextKey } = inputState;
        rows[i].value = v;
        setInputState({
            nextKey,
            rows,
        });
    }

    function addRow() {
        const { rows, nextKey } = inputState;
        rows.push({ key: nextKey, value: "" });
        setInputState({
            rows,
            nextKey: nextKey + 1,
        });
    }

    function deleteItem(i) {
        const { rows, nextKey } = inputState;
        rows.splice(i, 1);
        setInputState({
            nextKey,
            rows,
        });
    }

    return (
        <>
            {inputState.rows.map(({ key, value }, index) => {
                return (

                        <input
                            value={value}
                            onChange={({ target: { value } }) => {
                                onChange(index, value);
                            }}
                        />
                        <button onClick={() => deleteItem(index)}>-</button>

                );
            })}
            <button onClick={addRow}>+ add row</button>
        </>
    );
}

Body:
Without index we can do using the Map and Map retrieval is faster, below code you can try.

import React, { useState } from "react";

export default function() {
    const [rows, setRows] = useState(new Map());

    const onUpdate = (key, value) => {
        setRows(prev => new Map(prev).set(key, { key, value}));
    }
    const onDelete = (key) => {
        setRows(prev => new Map(prev).delete(key));
    }
    return (
        <>
            {[...rows].map((row, index) => (typeof row[1].value !== "undefined") && (
                <div key={index}>
                    <input value={row[1].value} onChange={e =>  onUpdate(row[1].key, e.target.value)} />
                    <button onClick={() => onDelete(row[1].key)}>- delete row</button>
                </div>
            ))}

            <button onClick={() => onUpdate(rows.size, "")}>
                + add row
            </button>
        </>
    );
}


问:
Why does BS4 (from BeautifulSoup) return only [ ] when using the .select()?
The following code only returns empty brackets. I have looked at this post Why does bs4 return tags and then an empty list to this find_all() method? but it is different because I am not using the find_all(), rather .select(). Please note, I changed "nth-child" to "nth-of-type" to avoid an error.

```<code>    import bs4
    import requests
    res = requests.get('http://www.sharkresearchcommittee.com/pacific_coast_shark_news.htm')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')
soup.select('body > div > div:nth-of-type(2) > center > table > tbody > tr:nth-of-type(1) >td:nth-of-type(2) > p:nth-of-type(8) > strong:nth-of-type(1) > font')
</code>```

The output is [ ]

答:
tbody was the problem in my case.

I found it by adding selector levels one by one and detected that producing an empty list.

Body:
The following code only returns empty brackets. I have looked at this post Why does bs4 return tags and then an empty list to this find_all() method? but it is different because I am not using the find_all(), rather .select(). Please note, I changed "nth-child" to "nth-of-type" to avoid an error.

    import bs4
    import requests
    res = requests.get('http://www.sharkresearchcommittee.com/pacific_coast_shark_news.htm')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')
soup.select('body > div > div:nth-of-type(2) > center > table > tbody > tr:nth-of-type(1) >td:nth-of-type(2) > p:nth-of-type(8) > strong:nth-of-type(1) > font')

The output is [ ]


问:
How to execute a function when some item renders in react native?
I have a sectionlist of Contacts where I am displaying both device and online contacts of a user. The online contacts api doesnt give me all the contacts at once. So I have to implement some pagination. I am also fetching all device contacts and first page of online contacts and sorting them to show in sectionlist, but the problem is, to load more contacts, i have to keep track of the last item rendered in my state and in the render function I am calling pagination function to load more contacts. and then i am updating the state of fetched online contact. But its an unsafe operation, is there a better way to achieve this?

I want to execute a function when the specific item renders and it can update the state.

Here is some code: ContactList.tsx

import React, { Component } from "react";
import {
    View,
    StyleSheet,
    SectionListData,
    SectionList,
    Text
} from "react-native";

import { Contact } from "../../models/contact";
import ContactItem from "./contact-item";

export interface ContactsProps {
    onlineContacts: Contact[];
    deviceContacts: Contact[];
    fetchMoreITPContacts: () => void;
}

export interface ContactsState {
    loading: boolean;
    error: Error | null;
    data: SectionListData<Contact>[];
    lastItem: Contact;
    selectedItems: [];
    selectableList: boolean;
}

class ContactList extends Component<ContactsProps, ContactsState> {
    private sectionNames = [];

    constructor(props: ContactsProps, state: ContactsState) {
        super(props, state);
        this.state = {
            loading: false,
            error: null,
            data: [],
            lastItem: this.props.onlineContacts[this.props.onlineContacts.length - 1]
        };
        for (var i = 65; i < 91; ++i) {
            this.sectionNames.push({
                title: String.fromCharCode(i),
                data: []
            });
        }
    }

    private buildSectionData = contacts => {
        this.sort(contacts);
        const data = [];
        const contactData = this.sectionNames;
        contacts.map(contact => {
            const index = contact.name.charAt(0).toUpperCase();
            if (!data[index]) {
                data[index] = [];
                contactData.push({
                    title: index,
                    data: []
                })
            }
            data[index].push(contact);
        });
        for (const index in data) {
            const idx = contactData.findIndex(x => x.title === index);
            contactData[idx].data.push(...data[index]);
        }
        this.setState({
            loading: false,
            error: null,
            lastItem: contacts[contacts.length - 1],
            data: [...contactData]
        });
    };

    private sort(contacts) {
        contacts.sort((a, b) => {
            if (a.name > b.name) {
                return 1;
            }
            if (b.name > a.name) {
                return -1;
            }
            return 0;
        });
    }

    componentDidMount() {
        const contacts = [].concat(
            this.props.deviceContacts,
            this.props.onlineContacts
        );
        this.buildSectionData(contacts);
    }

    componentDidUpdate(
        prevProps: Readonly<ContactsProps>,
        prevState: Readonly<ContactsState>,
        snapshot?: any
    ): void {
        if (this.props.onlineContacts !== prevProps.onlineContacts) {
            const from = this.props.itpContacts.slice(
                prevProps.onlineContacts.length,
                this.props.onlineContacts.length
            );
            this.buildSectionData(from);
        }
    }

    renderItem(item: any) {
        if (!!this.state.lastItem && !this.state.loading)
            if (item.item.id === this.state.lastItem.id) {
                this.setState({
                    loading: true
                });
                this.props.fetchMoreOnlineContacts();
            }
        return <ContactItem item={item.item} />;
    }

    render() {
        return (
            <View style={styles.container}>
                <SectionList
                    sections={this.state.data}
                    keyExtractor={(item, index) => item.id}
                    renderItem={this.renderItem.bind(this)}
                    renderSectionHeader={({ section }) =>
                        section.data.length > 0 ? (
                            <Text style={styles.sectionTitle}>
                                {section.title}
                            </Text>
                        ) : null
                    }
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    sectionTitle: {
        paddingBottom: 30,

        paddingLeft: 25,
        fontWeight: "bold",
        fontSize: 20
    }
});

export default ContactList;

```

答:
Yeah after some thoughts I got the answer may be.
instead of calling fetchMoreContacts from renderItem I passed the lastItem as a prop to the ContactItem component.
and in the constructor I checked If the item is lastItem and called to fetchMoreContact.
and it worked!


问:
React React setState not updating on First attempt
I have to show conditionally a div on the same class components. But the state changes updates only from second click.

this is my code

```<code> constructor(props) {
    super(props);
    this.state = {
        openSignIn: false
    };
    this.handleOpenSignIn = this.handleOpenSignIn.bind(this);
}
</code>```

setState

```<code>    handleOpenSignIn() {
       this.setState({ openSignIn: true });
    }
</code>```

and i have to show an element if 'openSignIn' is true

```<code><button className="nav-link px-4 border rounded-sm whiteBtn" onClick={() => this.handleOpenSignIn()}>Login</button>

{this.state.openSignIn &&
    <div>Show</div>
}
</code>```

The div showing only click two times on the button.
am very new in React js.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      openSignIn: false
    };
    this.handleOpenSignIn = this.handleOpenSignIn.bind(this);
  }

  handleOpenSignIn() {
    this.setState({
      openSignIn: true
    });
  }

  render() {
    return (

        <button
          className="nav-link px-4 border rounded-sm whiteBtn"
          onClick={() => this.handleOpenSignIn()}
        >
          Login
        </button>
        {this.state.openSignIn &&
Show
}

    );
  }
}

 ReactDOM.render(<App/>, document.getElementById('root'))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root" /></code>```

答:
But It works exactly..

Open code sandbox to run your code

Body:
I have to show conditionally a div on the same class components. But the state changes updates only from second click.

this is my code

 constructor(props) {
    super(props);
    this.state = {
        openSignIn: false
    };
    this.handleOpenSignIn = this.handleOpenSignIn.bind(this);
}

setState

    handleOpenSignIn() {
       this.setState({ openSignIn: true });
    }

and i have to show an element if 'openSignIn' is true

<button className="nav-link px-4 border rounded-sm whiteBtn" onClick={() => this.handleOpenSignIn()}>Login</button>

{this.state.openSignIn &&

Show

}

The div showing only click two times on the button.
am very new in React js.

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      openSignIn: false
    };
    this.handleOpenSignIn = this.handleOpenSignIn.bind(this);
  }

  handleOpenSignIn() {
    this.setState({
      openSignIn: true
    });
  }

  render() {
    return (

        <button
          className="nav-link px-4 border rounded-sm whiteBtn"
          onClick={() => this.handleOpenSignIn()}
        >
          Login
        </button>
        {this.state.openSignIn &&
Show
}

    );
  }
}

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


问:
How to forecast for future dates using time series forecasting in Python?
I am new to time series forecasting and have made the following model:

```<code>df = pd.read_csv('timeseries_data.csv', index_col="Month")

# ARMA
from statsmodels.tsa.arima_model import ARMA
from random import random
# contrived dataset
data = df
# fit model
model = ARMA(data, order=(2, 1))
model_fit = model.fit(disp=False)
# make prediction
yhat = model_fit.predict()
print(yhat)
</code>```

The above code predicts for the data points in df. But what should I do if I want to predict for some future date? For example: For the entire year of 2022?

答:
I found the solution, it was actually very simple:</p>

```<code>arma_df = model_fit.predict(start='2020-01-01', end='2023-12-01')
</code>```

Body:
I am new to time series forecasting and have made the following model:

df = pd.read_csv('timeseries_data.csv', index_col="Month")

# ARMA
from statsmodels.tsa.arima_model import ARMA
from random import random
# contrived dataset
data = df
# fit model
model = ARMA(data, order=(2, 1))
model_fit = model.fit(disp=False)
# make prediction
yhat = model_fit.predict()
print(yhat)

The above code predicts for the data points in df. But what should I do if I want to predict for some future date? For example: For the entire year of 2022?

Body:
I found the solution, it was actually very simple:

arma_df = model_fit.predict(start='2020-01-01', end='2023-12-01')


问:
Unable to connect to database using Win Auth on from ASP.Net web app hosted in IIS7
I've a web application hosted on Windows Server 2008 64 Bit with IIS 7 and SQL Server 2008. The web application pool account is Network Service and I've added this account to SQL Server 2008 logins and mapped to user in database with dbowner rights.

This Web site is in ASP.Net 2.0 and it's using Forms Authentication to secure access to some of its resources(not all) so Anonymous Access, Imersonation=True and Forms Authentication is Enabled in IIS 7. Web application is utilizing Membership Provider Controls.

When the website starts; inside the "Application starts" it tries to connect to database and read some startup configurations. The connection string for database is saved in web.config. Following is the connection string.

```<code>Data Source=XXXXX; Initial Catalog=XXXXX; Integrated Security=SSPI; Trusted_Connection=True;
</code>```

However When the application starts it failed to connect to database and I found following 3 entries in Event Log.

SSPI handshake failed with error code
  0x8009030c while establishing a
  connection with integrated security;
  the connection has been closed.
  [CLIENT: ]

Login failed. The login is from an
  untrusted domain and cannot be used
  with Windows authentication. [CLIENT:
  ]

```<code>Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 4/26/2011 9:22:05 PM
Event time (UTC): 4/26/2011 6:22:05 PM
Event ID: 71a4b2cd8d40492ab89af3430cf42ea5
Event sequence: 2
Event occurrence: 1
Event detail code: 0

Application information:
    Application domain: /LM/W3SVC/5/ROOT-1-129483157247676684
    Trust level: Full
    Application Virtual Path: /
    Application Path: C:\LMS Projects\Deployment\Web Applications\Microsoft Dynamics CRM Customer LMS Portal\
    Machine name: LMS

Process information:
    Process ID: 3688
    Process name: w3wp.exe
    Account name: NT AUTHORITY\NETWORK SERVICE

Exception information:
    Exception type: LoyaltyException
    Exception message: Exception of type 'LMS.Helpers.LoyaltyException' was thrown.

Request information:
    Request URL: http://localhost:6666/default.aspx
    Request path: /default.aspx
    User host address: ::1
    User:
    Is authenticated: False
    Authentication Type:
    Thread account name: NT AUTHORITY\NETWORK SERVICE

Thread information:
    Thread ID: 4
    Thread account name: NT AUTHORITY\NETWORK SERVICE
    Is impersonating: False
    Stack trace:    at ASP.global_asax.Application_Start() in c:\LMS Projects\Deployment\Web Applications\Microsoft Dynamics CRM Customer LMS Portal\Global.asax:line 27
</code>```

The exception shown above is custom exception which I throws after handling the platform exception so not to be mistaken with the error in the code. This code is working fine on Windows Server 2003 and IIS 6.0 environment.

答: Was not able to find any answer to this. We decided to move to IIS 6.0 environment where this is working fine now.</p>

Body:
I've a web application hosted on Windows Server 2008 64 Bit with IIS 7 and SQL Server 2008. The web application pool account is Network Service and I've added this account to SQL Server 2008 logins and mapped to user in database with dbowner rights.

This Web site is in ASP.Net 2.0 and it's using Forms Authentication to secure access to some of its resources(not all) so Anonymous Access, Imersonation=True and Forms Authentication is Enabled in IIS 7. Web application is utilizing Membership Provider Controls.

When the website starts; inside the "Application starts" it tries to connect to database and read some startup configurations. The connection string for database is saved in web.config. Following is the connection string.

Data Source=XXXXX; Initial Catalog=XXXXX; Integrated Security=SSPI; Trusted_Connection=True;

However When the application starts it failed to connect to database and I found following 3 entries in Event Log.

SSPI handshake failed with error code
  0x8009030c while establishing a
  connection with integrated security;
  the connection has been closed.
  [CLIENT: ]

Login failed. The login is from an
  untrusted domain and cannot be used
  with Windows authentication. [CLIENT:
  ]

Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 4/26/2011 9:22:05 PM
Event time (UTC): 4/26/2011 6:22:05 PM
Event ID: 71a4b2cd8d40492ab89af3430cf42ea5
Event sequence: 2
Event occurrence: 1
Event detail code: 0

Application information:
    Application domain: /LM/W3SVC/5/ROOT-1-129483157247676684
    Trust level: Full
    Application Virtual Path: /
    Application Path: C:\LMS Projects\Deployment\Web Applications\Microsoft Dynamics CRM Customer LMS Portal\
    Machine name: LMS

Process information:
    Process ID: 3688
    Process name: w3wp.exe
    Account name: NT AUTHORITY\NETWORK SERVICE

Exception information:
    Exception type: LoyaltyException
    Exception message: Exception of type 'LMS.Helpers.LoyaltyException' was thrown.

Request information:
    Request URL: http://localhost:6666/default.aspx
    Request path: /default.aspx
    User host address: ::1
    User:
    Is authenticated: False
    Authentication Type:
    Thread account name: NT AUTHORITY\NETWORK SERVICE

Thread information:
    Thread ID: 4
    Thread account name: NT AUTHORITY\NETWORK SERVICE
    Is impersonating: False
    Stack trace:    at ASP.global_asax.Application_Start() in c:\LMS Projects\Deployment\Web Applications\Microsoft Dynamics CRM Customer LMS Portal\Global.asax:line 27

The exception shown above is custom exception which I throws after handling the platform exception so not to be mistaken with the error in the code. This code is working fine on Windows Server 2003 and IIS 6.0 environment.


Title: Arranging timestamp according to required condition

Body:
I've list of timestamp values stored in a nested list below.

[[1462692695.0, 1462857370.0, 1463297496.0],

[1466695088.0, 1466933174.0, 1467067583.0, 1467252502.0, 1467253381.0],

[1455009108.0, 1455218354.0, 1455221295.0],

[1456098479.0, 1456242604.0, 1456277812.0, 1456683177.0]]

And I want to find the difference between second and first, third and second and so on.. for each of the nested list values.

For example:
The newly created difference list:

[[164675,440126],
 [...,...,...,...],
....]

Body:
Since you tagged dataframe, here's a pandas solution:

x = [[1462692695.0, 1462857370.0, 1463297496.0], [1466695088.0, 1466933174.0, 1467067583.0, 1467252502.0, 1467253381.0], [1455009108.0, 1455218354.0, 1455221295.0], [1456098479.0, 1456242604.0, 1456277812.0, 1456683177.0]]

df = pd.DataFrame(x)

print (df.diff(axis=1).stack().groupby(level=0).apply(list).tolist())

Or use nested list comprehension:

print ([[b-a for a,b in zip(i, i[1:])] for i in x])

Result:

[[164675.0, 440126.0], [238086.0, 134409.0, 184919.0, 879.0], [209246.0, 2941.0], [144125.0, 35208.0, 405365.0]]


问:
How can I reduce the repetitive work of this jquery source?
```<code>   $("#sel1").click(function () {
    $("#itemed1").attr("src", "../img/tab_img_01_on.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel2").click(function () {
    $("#itemed2").attr("src", "../img/tab_img_02_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel3").click(function () {
    $("#itemed3").attr("src", "../img/tab_img_03_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel4").click(function () {
    $("#itemed4").attr("src", "../img/tab_img_04_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
});
</code>```

Hello This JQuery code is a source that changes the image when you click on the element.
It works fine, but I have a lot of iterations,
so I want to reduce my code. What should I use?

答:
Please refer below code.

$("[id^=sel]").on('click', function() {
      var selectionID = ["sel1", "sel2", "sel3", "sel4"];
      var itemID = ["itemed1", "itemed2", "itemed3", "itemed4"];
      var selectedButton = $(this).attr("value");
      $(this).find("span").addClass("add");
      var indexID = selectionID.indexOf(selectedButton) + 1;
      $("#itemed" + indexID).attr("src", "../img/tab_img_0" + indexID + "_on.png");
      selectionID = selectionID.filter(e => e !== selectedButton);
      itemID = itemID.filter(e => e !== itemID[indexID - 1]);
      for (var i = 0; i < selectionID.length; i++) {
        $("#" + selectionID[i]).find("span").removeClass("add");
        $("#" + itemID[i]).attr("src", "../img/tab_img_0" + itemID[i].charAt(itemID[i].length - 1) + ".png");
      }

    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.add {
      background: blue;
    }</code>```

    <button value="sel1" id="sel1">sel1</button>

    <button value="sel2" id="sel2">sel2</button>

    <button value="sel3" id="sel3">sel3</button>

    <button value="sel4" id="sel4">sel4</button>

    ```

Body:
   $("#sel1").click(function () {
    $("#itemed1").attr("src", "../img/tab_img_01_on.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel2").click(function () {
    $("#itemed2").attr("src", "../img/tab_img_02_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel3").click(function () {
    $("#itemed3").attr("src", "../img/tab_img_03_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed4").attr("src", "../img/tab_img_04.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel4").find("span").removeClass("add");
});
$("#sel4").click(function () {
    $("#itemed4").attr("src", "../img/tab_img_04_on.png");
    $("#itemed1").attr("src", "../img/tab_img_01.png");
    $("#itemed2").attr("src", "../img/tab_img_02.png");
    $("#itemed3").attr("src", "../img/tab_img_03.png");
    $(this).find("span").addClass("add");
    $("#sel1").find("span").removeClass("add");
    $("#sel2").find("span").removeClass("add");
    $("#sel3").find("span").removeClass("add");
});

Hello This JQuery code is a source that changes the image when you click on the element.
It works fine, but I have a lot of iterations,
so I want to reduce my code. What should I use?

Body:
Please refer below code.

$("[id^=sel]").on('click', function() {
      var selectionID = ["sel1", "sel2", "sel3", "sel4"];
      var itemID = ["itemed1", "itemed2", "itemed3", "itemed4"];
      var selectedButton = $(this).attr("value");
      $(this).find("span").addClass("add");
      var indexID = selectionID.indexOf(selectedButton) + 1;
      $("#itemed" + indexID).attr("src", "../img/tab_img_0" + indexID + "_on.png");
      selectionID = selectionID.filter(e => e !== selectedButton);
      itemID = itemID.filter(e => e !== itemID[indexID - 1]);
      for (var i = 0; i < selectionID.length; i++) {
        $("#" + selectionID[i]).find("span").removeClass("add");
        $("#" + itemID[i]).attr("src", "../img/tab_img_0" + itemID[i].charAt(itemID[i].length - 1) + ".png");
      }

    });

.add {
      background: blue;
    }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

    <button value="sel1" id="sel1"><span>sel1</span></button><br/>
    <button value="sel2" id="sel2"><span>sel2</span></button><br/>
    <button value="sel3" id="sel3"><span>sel3</span></button><br/>
    <button value="sel4" id="sel4"><span>sel4</span></button><br/>

    <img src="" id="itemed1">
    <img src="" id="itemed2">
    <img src="" id="itemed3">
    <img src="" id="itemed4">


问:
How to validate form field in PHP using Object Oriented Technique
I have created a class 'validate' to validate two fields i.e 'firstname' and 'lastname'. It is not working fine, it is showing error when field is empty but when I submit the form with non-empty fields the error is still there. How to execute this on form submission?</p>

```<code> <?php

  class validation {

  public $firstName, $lastName, $errorFirstName = '', $errorLastName = '';

  function __constructor($fName, $lName){
    $this->firstName = $fName;
    $this->lastName = $lName;
  }

  function check(){

      if($_SERVER["REQUEST_METHOD"] == "POST"){
        if(empty($this->firstName)){
        $this->errorFirstName = 'First name is required';
       } else {
        $this->errorFirstName = 'Input is okay';
       }

     if(empty($this->lastName)){
         $this->errorLastName = 'Last name is required';
      }  else {
       $this->errorLastName = 'Input is okay';
      }
    }
   }
  }

 $obj = new validation($_POST['firstname'], $_POST['lastname']);
 $obj->check();
 $errorF = $obj->errorFirstName;
 $errorL = $obj->errorLastName;

 ?>

  <!DOCTYPE html>
  <html lang = "en-US" dir = "ltr">
   <head>
    <title>Home</title>
    <meta charset = "UTF-8"/>
   </head>
   <body>
   <form method = "POST" action="<?php echo $_SERVER["PHP_SELF"]?>">
    <label>First Name: </label>
    <input type = "text" name = "firstname" placeholder = "John"/>
    <p class = "error"><?php echo $errorF;?></p>
    <label>Last Name: </label>
    <input type = "text" name = "lastname" placeholder = "Doe"/>
    <p class = "error"><?php echo $errorL;?></p>
    <input type="submit">
   </form>
  </body>
 </html>
</code>```

答:
Do make a validator class.

Forms usually consist of multiple fields meaning that in suggested approach where you try/catch error while setting up the object will fail on a single field, when you might be having multiple invalid fields and on form submit you want that all fields are validated and all errors returned so they can be presented at the same time.

```<code><?php

class MyValidator
{
    /**
     * Is form valid;
     *
     * @var bool
     */
    private $isValid = true;
    /**
     * List of errors, assoc array with error messages one per fieldName
     *
     * @var array
     */
    private $errors = [];

    /**
     * Check if form is valid
     *
     * @return bool
     */
    public function isValid(): bool
    {
        return $this->isValid;
    }

    /**
     * Get error message
     *
     * @param $fieldName
     * @return mixed|string
     */
    public function getError($fieldName)
    {
        return isset($this->errors[$fieldName]) ? $this->errors['fieldName'] : '';
    }

    /**
     * @param array $rules list of rules
     * @param array $payload list of form parameters
     * @return bool Return validation result, same as isValid
     */
    public function validate(array $rules, array $payload)
    {
        foreach ($rules as $rule) {
            if (!$this->validateRequired($rule, $payload)) {
                continue;
            }
            switch ($rule['type']) {
                case 'string':
                    $this->validateString($rule, $payload);
                    break;
                case 'email':
                    $this->validateEmail($rule, $payload);
                    break;
                    //extend with other validation rules as needed
            }
        }

        return $this->isValid();
    }

    public function validateRequired(array $rule, array $payload)
    {
        if (true === $rule['required'] && !isset($payload[$rule['fieldName']])) {
            $this->isValid = false;
            $this->errors[$rule['fieldName']] = 'This field is required';

            return false;
        }

        return true;
    }

    public function validateString($rule, $payload)
    {
        // Checkup logic, set $this->isValid to false if not valid, add
        // See add $this->errors[$rule['fieldname']] = 'your message';
    }

    public function validateEmail($rule, $payload)
    {
        // Checkup logic, set $this->isValid to false if not valid, add
        // See add $this->errors[$rule['fieldname']] = 'your message';
    }

}

// Call validator by giving validator ruleset in the format

$rules = [
    [
        'fieldName' => 'firstName',
        'type' => 'string',
        'minLength' => 10,
        'maxLength' => 20,
        'required' => true,
    ],
    [
        'fieldName' => 'email',
        'type' => 'email',
        'required' => true,
    ]
];

$validator = new MyValidator();
$isValid = $validator->validate($rules, $_POST);

// if false do repeat form with error messages shown
// use $validator->getError('firstName'); to get error message for a field.
</code>```

Body:
I have created a class 'validate' to validate two fields i.e 'firstname' and 'lastname'. It is not working fine, it is showing error when field is empty but when I submit the form with non-empty fields the error is still there. How to execute this on form submission?

 <?php

  class validation {

  public $firstName, $lastName, $errorFirstName = '', $errorLastName = '';

  function __constructor($fName, $lName){
    $this->firstName = $fName;
    $this->lastName = $lName;
  }

  function check(){

      if($_SERVER["REQUEST_METHOD"] == "POST"){
        if(empty($this->firstName)){
        $this->errorFirstName = 'First name is required';
       } else {
        $this->errorFirstName = 'Input is okay';
       }

     if(empty($this->lastName)){
         $this->errorLastName = 'Last name is required';
      }  else {
       $this->errorLastName = 'Input is okay';
      }
    }
   }
  }

 $obj = new validation($_POST['firstname'], $_POST['lastname']);
 $obj->check();
 $errorF = $obj->errorFirstName;
 $errorL = $obj->errorLastName;

 ?>

  <!DOCTYPE html>

    <title>Home</title>
    <meta charset = "UTF-8"/>

   <form method = "POST" action="<?php echo $_SERVER["PHP_SELF"]?>">
    First Name:
    <input type = "text" name = "firstname" placeholder = "John"/>

<?php echo $errorF;?>

    Last Name:
    <input type = "text" name = "lastname" placeholder = "Doe"/>

<?php echo $errorL;?>

    <input type="submit">
   </form>

Body:
Do make a validator class.

Forms usually consist of multiple fields meaning that in suggested approach where you try/catch error while setting up the object will fail on a single field, when you might be having multiple invalid fields and on form submit you want that all fields are validated and all errors returned so they can be presented at the same time.

<?php

class MyValidator
{
    /**
     * Is form valid;
     *
     * @var bool
     */
    private $isValid = true;
    /**
     * List of errors, assoc array with error messages one per fieldName
     *
     * @var array
     */
    private $errors = [];

    /**
     * Check if form is valid
     *
     * @return bool
     */
    public function isValid(): bool
    {
        return $this->isValid;
    }

    /**
     * Get error message
     *
     * @param $fieldName
     * @return mixed|string
     */
    public function getError($fieldName)
    {
        return isset($this->errors[$fieldName]) ? $this->errors['fieldName'] : '';
    }

    /**
     * @param array $rules list of rules
     * @param array $payload list of form parameters
     * @return bool Return validation result, same as isValid
     */
    public function validate(array $rules, array $payload)
    {
        foreach ($rules as $rule) {
            if (!$this->validateRequired($rule, $payload)) {
                continue;
            }
            switch ($rule['type']) {
                case 'string':
                    $this->validateString($rule, $payload);
                    break;
                case 'email':
                    $this->validateEmail($rule, $payload);
                    break;
                    //extend with other validation rules as needed
            }
        }

        return $this->isValid();
    }

    public function validateRequired(array $rule, array $payload)
    {
        if (true === $rule['required'] && !isset($payload[$rule['fieldName']])) {
            $this->isValid = false;
            $this->errors[$rule['fieldName']] = 'This field is required';

            return false;
        }

        return true;
    }

    public function validateString($rule, $payload)
    {
        // Checkup logic, set $this->isValid to false if not valid, add
        // See add $this->errors[$rule['fieldname']] = 'your message';
    }

    public function validateEmail($rule, $payload)
    {
        // Checkup logic, set $this->isValid to false if not valid, add
        // See add $this->errors[$rule['fieldname']] = 'your message';
    }

}

// Call validator by giving validator ruleset in the format

$rules = [
    [
        'fieldName' => 'firstName',
        'type' => 'string',
        'minLength' => 10,
        'maxLength' => 20,
        'required' => true,
    ],
    [
        'fieldName' => 'email',
        'type' => 'email',
        'required' => true,
    ]
];

$validator = new MyValidator();
$isValid = $validator->validate($rules, $_POST);

// if false do repeat form with error messages shown
// use $validator->getError('firstName'); to get error message for a field.


问:
plotting time series grouped by hour and day of week
I have hourly timeseries data for over a year, and wish to plot average hourly measurements for each day of the week. I have run the following code and my data is in the following format (i previously created columns for days of week).

```<code>df = df.groupby([df['date_UTC'].dt.hour, df['w_day']]).pm2_5_ugm3.mean().reset_index().dropna()

date_UTC    w_day   pm2_5_ugm3
0   0   Friday  11.868802
1   0   Monday  12.741524
2   0   Saturday    13.346273
3   0   Sunday  13.093804
4   0   Thursday    14.525096
... ... ... ...
163 23  Saturday    12.836788
164 23  Sunday  12.712683
165 23  Thursday    12.046935
166 23  Tuesday 12.043133
167 23  Wednesday   14.164027
</code>```

I ultimately want a plot that looks something like below, but I am not sure exactly how to plot it using seaborn/matplotlib.

UPDATE:

I used the suggestion of @Arnold Vialfont which basically gets me the results I am looking for, but facetplot doesnt seem to allow me to plot a legend when I introduce hue. I then used factorplot however it doesnt seem that this plot can produce a lineplot, which is what I need. Is there a way to use factorplot and have hue produce a legend?

```<code>col_order=["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

sns.set_style("white")
ax = sns.FacetGrid(df, col="w_day", col_wrap=7, height=6, col_order=col_order, hue ='Zone')
ax.map(sns.lineplot, "date_UTC", "pm2_5_ugm3")
</code>```

Hue not producing legend

Here using factorplot i have a legend but cant produce a line plot as desired.

```<code>ax = sns.catplot(x="date_UTC", y="pm2_5_ugm3", col="w_day", hue = 'Zone',
                data=df, ci=None, aspect=.6)
</code>```

答: After doing some more research it seems the best way to achieve what I want is to use Seaborn's relplot, since this combines both lineplot and facetgrid. </p>

Body:
I have hourly timeseries data for over a year, and wish to plot average hourly measurements for each day of the week. I have run the following code and my data is in the following format (i previously created columns for days of week).

df = df.groupby([df['date_UTC'].dt.hour, df['w_day']]).pm2_5_ugm3.mean().reset_index().dropna()

date_UTC    w_day   pm2_5_ugm3
0   0   Friday  11.868802
1   0   Monday  12.741524
2   0   Saturday    13.346273
3   0   Sunday  13.093804
4   0   Thursday    14.525096
... ... ... ...
163 23  Saturday    12.836788
164 23  Sunday  12.712683
165 23  Thursday    12.046935
166 23  Tuesday 12.043133
167 23  Wednesday   14.164027

I ultimately want a plot that looks something like below, but I am not sure exactly how to plot it using seaborn/matplotlib.

UPDATE:

I used the suggestion of @Arnold Vialfont which basically gets me the results I am looking for, but facetplot doesnt seem to allow me to plot a legend when I introduce hue. I then used factorplot however it doesnt seem that this plot can produce a lineplot, which is what I need. Is there a way to use factorplot and have hue produce a legend?

col_order=["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]

sns.set_style("white")
ax = sns.FacetGrid(df, col="w_day", col_wrap=7, height=6, col_order=col_order, hue ='Zone')
ax.map(sns.lineplot, "date_UTC", "pm2_5_ugm3")

Hue not producing legend

Here using factorplot i have a legend but cant produce a line plot as desired.

ax = sns.catplot(x="date_UTC", y="pm2_5_ugm3", col="w_day", hue = 'Zone',
                data=df, ci=None, aspect=.6)


问:
Persisting form data in Java Beans
When I send a data through a form, I use reusable component JavaBean to store the data and retrieve it using get property and pass that data where ever I need it in the application.

But if I restart the web server, whatever data I had passed to that JavaBean will be lost and again I need pass the data to that Java Bean. Is there anyway to pass the data to the JavaBean and store (set) it permanently, so that i can access it even in the case of server restart?

答: There are many ways to persist the data across server restarts ( to a database, or a file for example ), but I find this scenario a little strange. What if two users set the same java bean? Who takes precedence? Or is the beans contents on a per user basis?</p>

Title: Persisting form data in Java Beans


问:
TFS Visual Studio 2017: Search for a file by name in source control
Our application code is spread over many dozens of folders in a nested hierarchy, and we have several hundred files making up the application.

So I wanted to know if there is a way to search for files by their name in the Visual Studio 2017 version of TFS ?

I spotted Q & A as per:
TFS: Search for a file by name in source control

but this answer seems no longer applicable for TFS and Visual Studio 2017.

I can, of course use tools outside of TFS (like the "Search Everything" app) and then navigate to the same folder and file in TFS.

I just felt that surely there must be a way of doing this file search within TFS ?

I have tried the search option in Team Explorer but I'm not sure how to use this ... not sure if this works ?

i.e.

答:
There is not any out of box feature to do this in Visual Studio 2017/Team Explorer2017 directly. If you want to search folders/files by name:

For TFS 2017, you can use Code Search if it's been configured by
your TFS admin. This is through web portal, more details please refer
this doc-- Search your code

For earlier TFS versions, you can create a local workspace and "get"
that specific version locally. Then use the built in search in your
OS (such as Windows file explorer)  to find what you are looking for.

Hope this helps.


问:
TYPO3 9.5: evaluating fluid conditions for typoscript libs
In TYPO3 8.5 I often used fluid conditions like this:

```<code><f:if condition="{f:cObject(typoscriptObjectPath: 'lib.cookiepid')}">
</code>```

In TYPO3 8.5 I did not define the lib, if I would not need it (depending on certain page pids f.eg.)

TYPO3 9.5 throws error:

```<code>#1540246570 TYPO3Fluid\Fluid\Core\ViewHelper\Exception
No Content Object definition found at TypoScript object path "lib.cookiepid"
</code>```

In TYPO 9.5 I could only avoid this error, when I define this lib in TS.

what would be the best practice to avoid this error ?
Is it possible without rewriting much code ?

答:
I'd set it to the following if I wanted it to be false:</p>

```<code>lib.cookiepid = TEXT
</code>```

Body:
In TYPO3 8.5 I often used fluid conditions like this:

<f:if condition="{f:cObject(typoscriptObjectPath: 'lib.cookiepid')}">

In TYPO3 8.5 I did not define the lib, if I would not need it (depending on certain page pids f.eg.)

TYPO3 9.5 throws error:

#1540246570 TYPO3Fluid\Fluid\Core\ViewHelper\Exception
No Content Object definition found at TypoScript object path "lib.cookiepid"

In TYPO 9.5 I could only avoid this error, when I define this lib in TS.

what would be the best practice to avoid this error ?
Is it possible without rewriting much code ?

Body:
I'd set it to the following if I wanted it to be false:

lib.cookiepid = TEXT