问:
Redirect doesn't work on a custom plugin wordpress
I'm trying to redirect when a file has been uploaded in media library to crop/resize it.
I'm adding a custom template and try to redirect after the admin add a media to library (admin panel).
But when I upload media I've got an error in wordpress : "An error occurred during upload. Please try again later."
And nothing comes.
My file is uploaded and saved but doesn't show in media library.
I've traveled through many topics but didn't find an answer. Maybe I can't redirect like that in a plugin.

I've got two php file in wp-contents/plugins/myplugin/plugin.php and custom-template.php

```<code><?php
/*
Plugin name: Waouh_pictures
Description:
Version: 1.0
Author: Waouh
*/
require_once("lib/shortpixel-php-req.php");

if(!defined('ABSPATH'))
exit;

class plugin{
  public function __construct(){

    // Some code here

    /* Add cropping template to wordpress */
    function page_template( $page_template )
    {
      if ( is_page( 'cropping-waouh' ) ) {
        $page_template = dirname( __FILE__ ) . '/crop_waouh.php';
      }
      return $page_template;
    }

    add_filter( 'page_template', 'page_template' );

    /* Redirect to cropping-waouh when a file is uploaded */
    function redirect_to_crop( $upload ) {
      $url = get_site_url() . "/cropping-waouh";
      wp_redirect( $url );
      exit;
      return $upload;
    }

    add_filter( 'wp_handle_upload', 'redirect_to_crop' );
  }
}
new plugin();
?>
</code>```

And my custom template :

```<code><?php
/* Template Name:  Cropping Waouh */
echo 'This is my cropping page :)';
?>
</code>```

Network console log

Pretty sure I'm doing wrong but I'm new to wordpress and I'm open to any constructive comments.
If you need more informations just ask. Thank you in advance.

答:
It seems like I can't do it that way so the thing I've done was to do it with jQuery.
I'm adding a button on my media library and hide the one who already exists.

```<code>jQuery(document).ready(function($){
  $("#wp-media-grid > a").after("<form action=\"/wp-content/plugins/waouh_pictures/function.php\"><input type=\"file\" id=\"button_upload_waouh\" name=\"filename\" method=\"POST\"><input type=\"submit\" value=\"Ajouter\"></form>");
  $("#wp-media-grid > a").hide();
});
</code>```

And I can modify the file before uploading it into the server using croppie.

I hope I could help someone with that.

Body:
I'm trying to redirect when a file has been uploaded in media library to crop/resize it.
I'm adding a custom template and try to redirect after the admin add a media to library (admin panel).
But when I upload media I've got an error in wordpress : "An error occurred during upload. Please try again later."
And nothing comes.
My file is uploaded and saved but doesn't show in media library.
I've traveled through many topics but didn't find an answer. Maybe I can't redirect like that in a plugin.

I've got two php file in wp-contents/plugins/myplugin/plugin.php and custom-template.php

<?php
/*
Plugin name: Waouh_pictures
Description:
Version: 1.0
Author: Waouh
*/
require_once("lib/shortpixel-php-req.php");

if(!defined('ABSPATH'))
exit;

class plugin{
  public function __construct(){

    // Some code here

    /* Add cropping template to wordpress */
    function page_template( $page_template )
    {
      if ( is_page( 'cropping-waouh' ) ) {
        $page_template = dirname( __FILE__ ) . '/crop_waouh.php';
      }
      return $page_template;
    }

    add_filter( 'page_template', 'page_template' );

    /* Redirect to cropping-waouh when a file is uploaded */
    function redirect_to_crop( $upload ) {
      $url = get_site_url() . "/cropping-waouh";
      wp_redirect( $url );
      exit;
      return $upload;
    }

    add_filter( 'wp_handle_upload', 'redirect_to_crop' );
  }
}
new plugin();
?>

And my custom template :

<?php
/* Template Name:  Cropping Waouh */
echo 'This is my cropping page :)';
?>

Network console log

Pretty sure I'm doing wrong but I'm new to wordpress and I'm open to any constructive comments.
If you need more informations just ask. Thank you in advance.

Body:
It seems like I can't do it that way so the thing I've done was to do it with jQuery.
I'm adding a button on my media library and hide the one who already exists.

jQuery(document).ready(function($){
  $("#wp-media-grid > a").after("<form action=\"/wp-content/plugins/waouh_pictures/function.php\"><input type=\"file\" id=\"button_upload_waouh\" name=\"filename\" method=\"POST\"><input type=\"submit\" value=\"Ajouter\"></form>");
  $("#wp-media-grid > a").hide();
});

And I can modify the file before uploading it into the server using croppie.

I hope I could help someone with that.


来源: stackexchange

问:
Does c++ compiler protect const memory address from any change?
I wanted to prove that there is nothing known as (A protected memory address) and the whole story is just about the compiler, or the OS, or whatever application the hosted app is running on just make some checking on read and write requests the hosted app send to its superior process and this superior app or whatever you call it decide if this child process has the right to read or write to this specific memory location but this c++ code doesn't work in this essence so why :

```<code>#include <iostream>
int main()
{
    const int x = 10;
    std::cout << &x << std::endl; // So i can view address of x
    std::cout << "x Before is equal "<< x <<std::endl;

    int y ;
    std:: cin >> std::hex >>y;

    int *pinter = (int*)y ;
    *pinter = 20;
    std::cout << "x After is equal "<< x <<std::endl;
}
</code>```

This code is supposed to get around the concept of c++ compiler setting x variable type to const int so that neither pointer to the variable (unlike in C in which pointers to constants can change the value of constant ) nor references to the variable can change the variable so this code is supposed to get address of variable x (of course after it's printed out) and then a pointer do the rest of the work , so what i messed here , cause it seams like this memory location is hardware protected( I know it's not but I am very confused)

答:
const is provided to:
1. Annotate that the value is not supposed to be changed
2. Allow the compiler to optimize the code better because of the fact that it’s not supposed to be changed.

You didn’t have to jump through all of these hoops, you could have just used ‘const_cast’ to change the const’ness.

The compiler “helps” you to enforce the const’ness but as you shown, there are many ways to bypass it. If you will change a const value will yield UB.

ContentLicense: CC BY-SA 4.0

Body:
I wanted to prove that there is nothing known as (A protected memory address) and the whole story is just about the compiler, or the OS, or whatever application the hosted app is running on just make some checking on read and write requests the hosted app send to its superior process and this superior app or whatever you call it decide if this child process has the right to read or write to this specific memory location but this c++ code doesn't work in this essence so why :

#include <iostream>
int main()
{
    const int x = 10;
    std::cout << &x << std::endl; // So i can view address of x
    std::cout << "x Before is equal "<< x <<std::endl;

    int y ;
    std:: cin >> std::hex >>y;

    int *pinter = (int*)y ;
    *pinter = 20;
    std::cout << "x After is equal "<< x <<std::endl;
}

This code is supposed to get around the concept of c++ compiler setting x variable type to const int so that neither pointer to the variable (unlike in C in which pointers to constants can change the value of constant ) nor references to the variable can change the variable so this code is supposed to get address of variable x (of course after it's printed out) and then a pointer do the rest of the work , so what i messed here , cause it seams like this memory location is hardware protected( I know it's not but I am very confused)


问:
Inventory design approach (inheritance vs generics)
Greetings!
I am trying to decide on which is the best approach to implement a following scenario:

Vehicle and Part are both "entites" which can be an Item in an Inventory.
Vehicle has the usual VIN, Year, Make, Model, Type, etc, etc... while Part has PartNumber, QuantityOnHand, IsPartOfSet, Vendor...
When "stocked" in an Inventory as an Item, both have RetailPrice, PurchasePrice, PurchaseDate but at the same time they have a lot of other properties that are not in common
(e.g Vehicle has CurrentMileage, NewOrUsed, etc... etc.. while Part has TreshholdCount, LastCountDate, etc, etc..)
So as you can see both Part and Vehicle can be in Inventory, but they have very few properties that are share (more that they don't)...

With scenario above, I am trying to decide between several approaches:

Option 1 - Separate classes for everything (no inheritance)

Vehicle - common vehicle properties (VIN, year, make, model, etc, etc)

VehicleInventoryItem - has a reference to Vehicle and contains other inventory specific properties (pricing, warranties, status)

VehicleInventoryManager - singleton with business logic add, remove, notify, etc, etc

Part

PartInventoryItem

PartInventoryManager

I think this approach is most flexible while it suffers for some property repetition. Managers also can have very different methods...

Option 2 - Base class simple inheritance

Vehicle - same as option 1

Part - same as option 1

InventoryItem  - base class

VehicleInventoryItem - extends InventoryItem, references Vehicle

PartInventoryItem - extends InventoryItem, references Part

InventoryManager - all methods accept InventoryItem as parameters

With this approach, I am worried about InventoryManager being polluted with different operations needed for parts vs vehicles

Option 3 - Generics

Item - where T will be part or vehicle (I can even go more specific then, e.g. - VehicleItem : Item)

Inventory - holds reference to Item

InventoryManager - singleton that operates on T

In this approach, there is less classes but again I am worried about InventoryManager

Recap

Vehicle and Part share very few properties when "stocked" in Inventory.

Inventory management for Vehicle and Part will also be mostly different (parts are "reordered" when qty on hand is low, when vehicle is sold similar one may be purchased but it is unique)

In my scenario there will be no other objects/models that will be "stockable" (being in Inventory of any kind)

Questions

What does community think? Is there another approach (perhaps interfaces?)
If 2 domain objects share at least 1 property (e.g. PurchasePrice), should that warrant having some sort of inheritance (e.g. option 2 or 3)

答:
I would create a base class: Let's call it InventoryItem containing all the shared properties (RetailPrice, PurchasePrice, PurchaseDate etc.)

Part and Vehicle would then inherit from InventoryItem and extend it with whatever properties they need.

I would then create a base class called InventoryManager which VehicleManager and PartManager inherits from. InventoryManager would contain all the shared logic for managing the inventory and the sub classes would extend it with whatever functionality they need.

I get the impression that you are pretty early in the design process. I wouldn't bother trying to nail the perfect design for this, this early. Just build something basic and change and extend it as you go along, because when you start to build and use the API you will understand the problem better.

"When in doubt, leave it out."

ContentLicense: CC BY-SA 3.0


问:
renew token in signalR after expired token
I create a realtime connection via SignalR From client(angular 9) and server(asp.net core 3.1) and Authorize hub by JWT Token such as below code :

```<code> private createConnection() {
      this.hubConnection = new HubConnectionBuilder().withUrl(`${this.appConfig.hubEndpoint}/Hubs`,
        { accessTokenFactory: () => jwtToken })
        .withAutomaticReconnect()
        .build();
  }

  private startConnection(): void {
    this.hubConnection
      .start()
      .then(() => {
        this.connectionIsEstablished = true;
        this.connectionEstablished.emit(true);
      })
      .catch(err => {
        console.log('Error while establishing connection, retrying...');
      });
  }
</code>```

this works fine until the token expired. According to my research, after receiving the new token with the refresh token, the previous connection should be stopped and a new connection should be created with the new token.
Now I want to know how should I do this? Do I have to constantly check the token? Or should this be addressed by sending each request to the server?

答:
When the token will expire the connection will be droped by the server and you will have the error on the server side. I believe is the 405 error code Method now allowed that you will get.

So what you need is catch this token expiration error and drop the connection so you can start a new one with the new token.

Body:
I create a realtime connection via SignalR From client(angular 9) and server(asp.net core 3.1) and Authorize hub by JWT Token such as below code :

 private createConnection() {
      this.hubConnection = new HubConnectionBuilder().withUrl(`${this.appConfig.hubEndpoint}/Hubs`,
        { accessTokenFactory: () => jwtToken })
        .withAutomaticReconnect()
        .build();
  }

  private startConnection(): void {
    this.hubConnection
      .start()
      .then(() => {
        this.connectionIsEstablished = true;
        this.connectionEstablished.emit(true);
      })
      .catch(err => {
        console.log('Error while establishing connection, retrying...');
      });
  }

this works fine until the token expired. According to my research, after receiving the new token with the refresh token, the previous connection should be stopped and a new connection should be created with the new token.
Now I want to know how should I do this? Do I have to constantly check the token? Or should this be addressed by sending each request to the server?


问:
GROUP BY and DISTINCT ON working differently for tables and views
I have a table Design and a view on that table called ArchivedDesign. The view is declared as:

```<code>CREATE OR REPLACE VIEW public."ArchivedDesign" ("RootId",  "Id", "Created", "CreatedBy", "Modified", "ModifiedBy", "VersionStatusId", "OrganizationId")
AS
SELECT DISTINCT ON (des."RootId") "RootId", des."Id", des."Created", des."CreatedBy", des."Modified", des."ModifiedBy", des."VersionStatusId", des."OrganizationId"
FROM public."Design" AS des
JOIN public."VersionStatus" AS vt ON des."VersionStatusId" = vt."Id"
WHERE vt."Code" = 'Archived'
ORDER BY "RootId", des."Modified" DESC;
</code>```

Then, I have a large query which gets a short summary of latest changes, thumbnails, etc. The whole query is not important, but it contains two almost identical subqueries - one for the main table and and one for the view.

```<code>SELECT DISTINCT ON (1) x."Id",
                TRIM(con."Name") AS "Contributor",
                extract(epoch from x."Modified") * 1000 AS "Modified",
                x."VersionStatusId",
                x."OrganizationId"
FROM public."Design" AS x
JOIN "Contributor" AS con ON con."DesignId" = x."Id"
WHERE x."OrganizationId" = ANY (ARRAY[]::uuid[])
AND x."VersionStatusId" = ANY (ARRAY[]::uuid[])
GROUP BY x."Id", con."Name"
ORDER BY x."Id";
</code>```

and

```<code>SELECT DISTINCT ON (1) x."Id",
                TRIM(con."Name") AS "Contributor",
                extract(epoch from x."Modified") * 1000 AS "Modified",
                x."VersionStatusId",
                x."OrganizationId"
FROM public."ArchivedDesign" AS x
JOIN "Contributor" AS con ON con."DesignId" = x."Id"
WHERE x."OrganizationId" = ANY (ARRAY[]::uuid[])
AND x."VersionStatusId" = ANY (ARRAY[]::uuid[])
GROUP BY x."Id", con."Name"
ORDER BY x."Id";
</code>```

Link to SQL fiddle: http://sqlfiddle.com/#!17/d1d0f/1

The query is valid for the table, but fails for the view with an error column x."Modified" must appear in the GROUP BY clause or be used in an aggregate function. I don't understand why there is a difference in the behavior of those two queries? How do I fix the view query to work the same way as the table query?

My ultimate goal is to replace all table sub-queries with view sub-queries so we can easily separate draft, active and archived designs.

答:
You get that  error because when you query the table directly, Postgres is able to identify the primary key of the table and knows that grouping by it is enough.

Quote from the manual

When GROUP BY is present, or any aggregate functions are present, it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions or when the ungrouped column is functionally dependent on the grouped columns, since there would otherwise be more than one possible value to return for an ungrouped column. A functional dependency exists if the grouped columns (or a subset thereof) are the primary key of the table containing the ungrouped column

(emphasis mine)

When querying the view, Postgres isn't able to detect that functional dependency that makes it possible to have a "shortened" GROUP BY when querying the table directly.

Body:
I have a table Design and a view on that table called ArchivedDesign. The view is declared as:

CREATE OR REPLACE VIEW public."ArchivedDesign" ("RootId",  "Id", "Created", "CreatedBy", "Modified", "ModifiedBy", "VersionStatusId", "OrganizationId")
AS
SELECT DISTINCT ON (des."RootId") "RootId", des."Id", des."Created", des."CreatedBy", des."Modified", des."ModifiedBy", des."VersionStatusId", des."OrganizationId"
FROM public."Design" AS des
JOIN public."VersionStatus" AS vt ON des."VersionStatusId" = vt."Id"
WHERE vt."Code" = 'Archived'
ORDER BY "RootId", des."Modified" DESC;

Then, I have a large query which gets a short summary of latest changes, thumbnails, etc. The whole query is not important, but it contains two almost identical subqueries - one for the main table and and one for the view.

SELECT DISTINCT ON (1) x."Id",
                TRIM(con."Name") AS "Contributor",
                extract(epoch from x."Modified") * 1000 AS "Modified",
                x."VersionStatusId",
                x."OrganizationId"
FROM public."Design" AS x
JOIN "Contributor" AS con ON con."DesignId" = x."Id"
WHERE x."OrganizationId" = ANY (ARRAY[]::uuid[])
AND x."VersionStatusId" = ANY (ARRAY[]::uuid[])
GROUP BY x."Id", con."Name"
ORDER BY x."Id";

and

SELECT DISTINCT ON (1) x."Id",
                TRIM(con."Name") AS "Contributor",
                extract(epoch from x."Modified") * 1000 AS "Modified",
                x."VersionStatusId",
                x."OrganizationId"
FROM public."ArchivedDesign" AS x
JOIN "Contributor" AS con ON con."DesignId" = x."Id"
WHERE x."OrganizationId" = ANY (ARRAY[]::uuid[])
AND x."VersionStatusId" = ANY (ARRAY[]::uuid[])
GROUP BY x."Id", con."Name"
ORDER BY x."Id";

Link to SQL fiddle: http://sqlfiddle.com/#!17/d1d0f/1

The query is valid for the table, but fails for the view with an error column x."Modified" must appear in the GROUP BY clause or be used in an aggregate function. I don't understand why there is a difference in the behavior of those two queries? How do I fix the view query to work the same way as the table query?

My ultimate goal is to replace all table sub-queries with view sub-queries so we can easily separate draft, active and archived designs.


问:
Is there a free or opensource barcode reader
I am working on python script. And need to scan some PDF417 baracodes. Is there any free or opensource library for this.
I found dynamsoft barcode reader which is very good at this but its need a paid version to use.</p>

答:
You can consider using Zxing. Zxing is a free open source library that can scan PDF417 barcodes, you can get the source code from the link below:

https://github.com/zxing/zxing

Hope this can help you.


问:
R Rearrange columns in dataframe based on date values in column names
I've got a dataframe that has monthly survey scores for a certain hospitals. Each month, we store the score obtained by the hospital (_Score column) and the corresponding average score for all hospitals for that month (_Average column).

Here's a short sample of what it looks like -

```<code>df = data.frame(Hospital=c(rep("Hospital A",10),rep("Hospital B",10),rep("Hospital C",10),rep("Hospital D",10)),
                Question=c(rep("Q1",40)),
                key=c(rep(c("2020-01-31_Average","2020-01-31_Score","2020-02-29_Average","2020-02-29_Score",
                      "2020-03-31_Average","2020-03-31_Score","2020-04-30_Average","2020-04-30_Score",
                      "2020-05-31_Average","2020-05-31_Score"),4)),
                value=c(round(runif(40,0,1),2)))

library(tidyr)
df = df %>% spread(key,value)
</code>```

I would like to transform this dataframe such that -

1) The first two columns, Hospital and Question remain the same

2) _Score columns for the three most recent months only are kept

3) _Average column for the most recent month is kept

4) Ideally, the columns need to be reordered from oldest to most recent (i.e. in the following order: Month M-2_Score, Month M-1_Score, Month M_Score, Month M_Average)

5) Calculate a column Variance at the end, which is the difference between Score M and Score M-1

What I'm trying to achieve

Using dplyr, this can be done manually by reordering the columns. But I'm looking for a way to build a logic that automatically reorders columns for the 3 most recent months in the sequence described above. By taking the date values embedded in the column names and reordering according to them.

The resulting table would look like this -

```<code>#Final table
df_transformed = df %>%
  select(1:2,8,10,12,11) %>%
  mutate(Variance=.[[5]]-.[[4]])
</code>```

Any tips on how to do this more efficiently using the date values in the column names would be highly appreciated.

答:
This is a possible solution if the columns in your dataset are already ordered chronologically

```<code># create vectors of variables: 3 last "_Score" and 1 last "_Average"
score_vars <- tail(names(df)[grep("_Score", names(df))], 3)
average_var <- tail(names(df)[grep("_Average", names(df))], 1)

df %>%
  select(Hospital, Question, !!score_vars, !!average_var) %>%
  mutate(Variance = !!rlang::sym(score_vars[3]) - !!rlang::sym(score_vars[2]))
</code>```

Output

```<code># Hospital Question 2020-03-31_Score 2020-04-30_Score 2020-05-31_Score 2020-05-31_Average Variance
# 1 Hospital A       Q1             0.28             0.69             0.31               0.94    -0.38
# 2 Hospital B       Q1             0.19             0.41             0.27               0.91    -0.14
# 3 Hospital C       Q1             0.53             0.03             0.25               0.05     0.22
# 4 Hospital D       Q1             0.43             0.59             0.46               0.36    -0.13
</code>```

Body:
I've got a dataframe that has monthly survey scores for a certain hospitals. Each month, we store the score obtained by the hospital (_Score column) and the corresponding average score for all hospitals for that month (_Average column).

Here's a short sample of what it looks like -

df = data.frame(Hospital=c(rep("Hospital A",10),rep("Hospital B",10),rep("Hospital C",10),rep("Hospital D",10)),
                Question=c(rep("Q1",40)),
                key=c(rep(c("2020-01-31_Average","2020-01-31_Score","2020-02-29_Average","2020-02-29_Score",
                      "2020-03-31_Average","2020-03-31_Score","2020-04-30_Average","2020-04-30_Score",
                      "2020-05-31_Average","2020-05-31_Score"),4)),
                value=c(round(runif(40,0,1),2)))

library(tidyr)
df = df %>% spread(key,value)

I would like to transform this dataframe such that -

1) The first two columns, Hospital and Question remain the same

2) _Score columns for the three most recent months only are kept

3) _Average column for the most recent month is kept

4) Ideally, the columns need to be reordered from oldest to most recent (i.e. in the following order: Month M-2_Score, Month M-1_Score, Month M_Score, Month M_Average)

5) Calculate a column Variance at the end, which is the difference between Score M and Score M-1

What I'm trying to achieve

Using dplyr, this can be done manually by reordering the columns. But I'm looking for a way to build a logic that automatically reorders columns for the 3 most recent months in the sequence described above. By taking the date values embedded in the column names and reordering according to them.

The resulting table would look like this -

#Final table
df_transformed = df %>%
  select(1:2,8,10,12,11) %>%
  mutate(Variance=.[[5]]-.[[4]])

Any tips on how to do this more efficiently using the date values in the column names would be highly appreciated.

Body:
This is a possible solution if the columns in your dataset are already ordered chronologically

# create vectors of variables: 3 last "_Score" and 1 last "_Average"
score_vars <- tail(names(df)[grep("_Score", names(df))], 3)
average_var <- tail(names(df)[grep("_Average", names(df))], 1)

df %>%
  select(Hospital, Question, !!score_vars, !!average_var) %>%
  mutate(Variance = !!rlang::sym(score_vars[3]) - !!rlang::sym(score_vars[2]))

Output

# Hospital Question 2020-03-31_Score 2020-04-30_Score 2020-05-31_Score 2020-05-31_Average Variance
# 1 Hospital A       Q1             0.28             0.69             0.31               0.94    -0.38
# 2 Hospital B       Q1             0.19             0.41             0.27               0.91    -0.14
# 3 Hospital C       Q1             0.53             0.03             0.25               0.05     0.22
# 4 Hospital D       Q1             0.43             0.59             0.46               0.36    -0.13


问:
Python Scaling loops
For each letter in the alphabet. The code should go to website.com/a and grab a table. Then it should check for a next button grab the link and makesoup and grab the next table and repeat until there is no valid next link. Then move to website.com/b(next letter in alphabet) and repeat. But I can only get as far as 2 pages for each letter. the first for loop grabs page 1 and the second grabs page 2 for each letter. I know I could write a loop for as many pages as needed but that is not scalable. How can I fix this?

```<code>from nfl_fun import make_soup
import urllib.request
import os
from string import ascii_lowercase
import requests

letter = ascii_lowercase
link = "https://www.nfl.com"

for letter in ascii_lowercase:
    soup = make_soup(f"https://www.nfl.com/players/active/{letter}")
    for tbody in soup.findAll("tbody"):
        for tr in tbody.findAll("a"):
            if tr.has_attr("href"):
                print(tr.attrs["href"])

for letter in ascii_lowercase:
    soup = make_soup(f"https://www.nfl.com/players/active/{letter}")
    for page in soup.footer.findAll("a", {"nfl-o-table-pagination__next"}):
        pagelink = ""
        footer = ""
        footer = page.attrs["href"]
        pagelink = f"{link}{footer}"
        print(footer)
        getpage = requests.get(pagelink)
        if getpage.status_code == 200:
            next_soup = make_soup(pagelink)
            for next_page in next_soup.footer.findAll("a", {"nfl-o-table-pagination__next"}):
                print(getpage)
                for tbody in next_soup.findAll("tbody"):
                    for tr in tbody.findAll("a"):
                        if tr.has_attr("href"):
                            print(tr.attrs["href"])
                            soup = next_soup

</code>```

Thank You again,

答:
There is an element in there that says when the "Next" button is inactive. So that'll tell you you are on the last page. So what you can do is a while loop, and just keep going to the next page, until it reaches the last page (Ie "Next" is inactive) and then tell it to stop the loop and go to the next letter:

```<code>from bs4 import BeautifulSoup
from string import ascii_lowercase
import requests
import pandas as pd
import re

letters = ascii_lowercase
link = "https://www.nfl.com"

results = pd.DataFrame()
for letter in letters:
    continueToNextPage = True
    after = ''
    page=1
    while continueToNextPage == True:
        # Get the Table
        url = f"https://www.nfl.com/players/active/{letter}?query={letter}&after={after}"
        response = requests.get(url, 'html.parser')
        soup = BeautifulSoup(response.text, 'html.parser')

        temp_df = pd.read_html(response.text)[0]
        results = results.append(temp_df, sort=False).reset_index(drop=True)

        print ("{letter}: Page: {page}".format(letter=letter.upper(), page=page))

        # Check if next page is inactive
        buttons = soup.find('div', {'class':'nfl-o-table-pagination__buttons'})
        regex = re.compile('.*pagination__next.*is-inactive.*')
        if buttons.find('span', {'class':regex}):
            continueToNextPage = False
        else:
            after = buttons.find('a', {'title':'Next'})['href'].split('after=')[-1]
            page+=1
</code>```

Output:

```<code>print (results)
                  Player          Current Team Position Status
0         Chidobe Awuzie        Dallas Cowboys       CB    ACT
1             Josh Avery      Seattle Seahawks       DT    ACT
2           Genard Avery   Philadelphia Eagles       DE    ACT
3        Anthony Averett      Baltimore Ravens       CB    ACT
4              Lee Autry         Chicago Bears       DT    ACT
5           Denico Autry    Indianapolis Colts       DT    ACT
6           Tavon Austin        Dallas Cowboys       WR    UFA
7        Blessuan Austin         New York Jets       CB    ACT
8         Antony Auclair  Tampa Bay Buccaneers       TE    ACT
9      Jeremiah Attaochu        Denver Broncos       LB    ACT
10       Hunter Atkinson       Atlanta Falcons       OT    ACT
11           John Atkins         Detroit Lions       DE    ACT
12           Geno Atkins    Cincinnati Bengals       DT    ACT
13        Marcell Ateman     Las Vegas Raiders       WR    ACT
14          George Aston       New York Giants       RB    ACT
15    Dravon Askew-Henry       New York Giants       DB    ACT
16          Devin Asiasi  New England Patriots       TE    ACT
17    George Asafo-Adjei       New York Giants       OT    ACT
18             Ade Aruna     Las Vegas Raiders       DE    ACT
19       Grayland Arnold   Philadelphia Eagles      SAF    ACT
20            Dan Arnold     Arizona Cardinals       TE    ACT
21         Damon Arnette     Las Vegas Raiders       CB    UDF
22     Ray-Ray Armstrong        Dallas Cowboys       LB    UFA
23     Ka'John Armstrong        Denver Broncos       OT    ACT
24     Dorance Armstrong        Dallas Cowboys       DE    ACT
25     Cornell Armstrong        Houston Texans       CB    ACT
26       Terron Armstead    New Orleans Saints       OT    ACT
27      Ryquell Armstead  Jacksonville Jaguars       RB    ACT
28         Arik Armstead   San Francisco 49ers       DE    ACT
29            Alex Armah     Carolina Panthers       FB    ACT
                 ...                   ...      ...    ...
3180       Clive Walford        Miami Dolphins       TE    UFA
3181        Cameron Wake      Tennessee Titans       DE    UFA
3182     Corliss Waitman   Pittsburgh Steelers        P    ACT
3183         Rick Wagner     Green Bay Packers       OT    ACT
3184        Bobby Wagner      Seattle Seahawks      MLB    ACT
3185        Ahmad Wagner         Chicago Bears       WR    ACT
3186        Colby Wadman        Denver Broncos        P    ACT
3187      Christian Wade         Buffalo Bills       RB    ACT
3188     LaAdrian Waddle         Buffalo Bills       OT    UFA
3189      Oshane Ximines       New York Giants       LB    ACT
3190        Trevon Young      Cleveland Browns       DE    ACT
3191           Sam Young     Las Vegas Raiders       OT    ACT
3192         Kenny Young      Los Angeles Rams      ILB    ACT
3193         Chase Young   Washington Redskins       DE    UDF
3194        Bryson Young       Atlanta Falcons       DE    ACT
3195        Isaac Yiadom        Denver Broncos       CB    ACT
3196         T.J. Yeldon         Buffalo Bills       RB    ACT
3197         Deon Yelder    Kansas City Chiefs       TE    ACT
3198         Rock Ya-Sin    Indianapolis Colts       CB    ACT
3199     Eddie Yarbrough     Minnesota Vikings       DE    ACT
3200       Marshal Yanda      Baltimore Ravens       OG    ACT
3201         Tavon Young      Baltimore Ravens       CB    ACT
3202     Brandon Zylstra     Carolina Panthers       WR    ACT
3203       Jabari Zuniga         New York Jets       DE    UDF
3204       Greg Zuerlein        Dallas Cowboys        K    ACT
3205        Isaiah Zuber  New England Patriots       WR    ACT
3206       Justin Zimmer      Cleveland Browns       DT    ACT
3207      Anthony Zettel     Minnesota Vikings       DE    ACT
3208       Kevin Zeitler       New York Giants       OG    ACT
3209   Olamide Zaccheaus       Atlanta Falcons       WR    ACT

[3210 rows x 4 columns]
</code>```

Title: Python Scaling loops

Body:
For each letter in the alphabet. The code should go to website.com/a and grab a table. Then it should check for a next button grab the link and makesoup and grab the next table and repeat until there is no valid next link. Then move to website.com/b(next letter in alphabet) and repeat. But I can only get as far as 2 pages for each letter. the first for loop grabs page 1 and the second grabs page 2 for each letter. I know I could write a loop for as many pages as needed but that is not scalable. How can I fix this?

from nfl_fun import make_soup
import urllib.request
import os
from string import ascii_lowercase
import requests

letter = ascii_lowercase
link = "https://www.nfl.com"

for letter in ascii_lowercase:
    soup = make_soup(f"https://www.nfl.com/players/active/{letter}")
    for tbody in soup.findAll("tbody"):
        for tr in tbody.findAll("a"):
            if tr.has_attr("href"):
                print(tr.attrs["href"])

for letter in ascii_lowercase:
    soup = make_soup(f"https://www.nfl.com/players/active/{letter}")
    for page in soup.footer.findAll("a", {"nfl-o-table-pagination__next"}):
        pagelink = ""
        footer = ""
        footer = page.attrs["href"]
        pagelink = f"{link}{footer}"
        print(footer)
        getpage = requests.get(pagelink)
        if getpage.status_code == 200:
            next_soup = make_soup(pagelink)
            for next_page in next_soup.footer.findAll("a", {"nfl-o-table-pagination__next"}):
                print(getpage)
                for tbody in next_soup.findAll("tbody"):
                    for tr in tbody.findAll("a"):
                        if tr.has_attr("href"):
                            print(tr.attrs["href"])
                            soup = next_soup

Thank You again,

Body:
There is an element in there that says when the "Next" button is inactive. So that'll tell you you are on the last page. So what you can do is a while loop, and just keep going to the next page, until it reaches the last page (Ie "Next" is inactive) and then tell it to stop the loop and go to the next letter:

from bs4 import BeautifulSoup
from string import ascii_lowercase
import requests
import pandas as pd
import re

letters = ascii_lowercase
link = "https://www.nfl.com"

results = pd.DataFrame()
for letter in letters:
    continueToNextPage = True
    after = ''
    page=1
    while continueToNextPage == True:
        # Get the Table
        url = f"https://www.nfl.com/players/active/{letter}?query={letter}&after={after}"
        response = requests.get(url, 'html.parser')
        soup = BeautifulSoup(response.text, 'html.parser')

        temp_df = pd.read_html(response.text)[0]
        results = results.append(temp_df, sort=False).reset_index(drop=True)

        print ("{letter}: Page: {page}".format(letter=letter.upper(), page=page))

        # Check if next page is inactive
        buttons = soup.find('div', {'class':'nfl-o-table-pagination__buttons'})
        regex = re.compile('.*pagination__next.*is-inactive.*')
        if buttons.find('span', {'class':regex}):
            continueToNextPage = False
        else:
            after = buttons.find('a', {'title':'Next'})['href'].split('after=')[-1]
            page+=1

Output:

print (results)
                  Player          Current Team Position Status
0         Chidobe Awuzie        Dallas Cowboys       CB    ACT
1             Josh Avery      Seattle Seahawks       DT    ACT
2           Genard Avery   Philadelphia Eagles       DE    ACT
3        Anthony Averett      Baltimore Ravens       CB    ACT
4              Lee Autry         Chicago Bears       DT    ACT
5           Denico Autry    Indianapolis Colts       DT    ACT
6           Tavon Austin        Dallas Cowboys       WR    UFA
7        Blessuan Austin         New York Jets       CB    ACT
8         Antony Auclair  Tampa Bay Buccaneers       TE    ACT
9      Jeremiah Attaochu        Denver Broncos       LB    ACT
10       Hunter Atkinson       Atlanta Falcons       OT    ACT
11           John Atkins         Detroit Lions       DE    ACT
12           Geno Atkins    Cincinnati Bengals       DT    ACT
13        Marcell Ateman     Las Vegas Raiders       WR    ACT
14          George Aston       New York Giants       RB    ACT
15    Dravon Askew-Henry       New York Giants       DB    ACT
16          Devin Asiasi  New England Patriots       TE    ACT
17    George Asafo-Adjei       New York Giants       OT    ACT
18             Ade Aruna     Las Vegas Raiders       DE    ACT
19       Grayland Arnold   Philadelphia Eagles      SAF    ACT
20            Dan Arnold     Arizona Cardinals       TE    ACT
21         Damon Arnette     Las Vegas Raiders       CB    UDF
22     Ray-Ray Armstrong        Dallas Cowboys       LB    UFA
23     Ka'John Armstrong        Denver Broncos       OT    ACT
24     Dorance Armstrong        Dallas Cowboys       DE    ACT
25     Cornell Armstrong        Houston Texans       CB    ACT
26       Terron Armstead    New Orleans Saints       OT    ACT
27      Ryquell Armstead  Jacksonville Jaguars       RB    ACT
28         Arik Armstead   San Francisco 49ers       DE    ACT
29            Alex Armah     Carolina Panthers       FB    ACT
                 ...                   ...      ...    ...
3180       Clive Walford        Miami Dolphins       TE    UFA
3181        Cameron Wake      Tennessee Titans       DE    UFA
3182     Corliss Waitman   Pittsburgh Steelers        P    ACT
3183         Rick Wagner     Green Bay Packers       OT    ACT
3184        Bobby Wagner      Seattle Seahawks      MLB    ACT
3185        Ahmad Wagner         Chicago Bears       WR    ACT
3186        Colby Wadman        Denver Broncos        P    ACT
3187      Christian Wade         Buffalo Bills       RB    ACT
3188     LaAdrian Waddle         Buffalo Bills       OT    UFA
3189      Oshane Ximines       New York Giants       LB    ACT
3190        Trevon Young      Cleveland Browns       DE    ACT
3191           Sam Young     Las Vegas Raiders       OT    ACT
3192         Kenny Young      Los Angeles Rams      ILB    ACT
3193         Chase Young   Washington Redskins       DE    UDF
3194        Bryson Young       Atlanta Falcons       DE    ACT
3195        Isaac Yiadom        Denver Broncos       CB    ACT
3196         T.J. Yeldon         Buffalo Bills       RB    ACT
3197         Deon Yelder    Kansas City Chiefs       TE    ACT
3198         Rock Ya-Sin    Indianapolis Colts       CB    ACT
3199     Eddie Yarbrough     Minnesota Vikings       DE    ACT
3200       Marshal Yanda      Baltimore Ravens       OG    ACT
3201         Tavon Young      Baltimore Ravens       CB    ACT
3202     Brandon Zylstra     Carolina Panthers       WR    ACT
3203       Jabari Zuniga         New York Jets       DE    UDF
3204       Greg Zuerlein        Dallas Cowboys        K    ACT
3205        Isaiah Zuber  New England Patriots       WR    ACT
3206       Justin Zimmer      Cleveland Browns       DT    ACT
3207      Anthony Zettel     Minnesota Vikings       DE    ACT
3208       Kevin Zeitler       New York Giants       OG    ACT
3209   Olamide Zaccheaus       Atlanta Falcons       WR    ACT

[3210 rows x 4 columns]


问:
Retrieve URL Parameters
I'm creating an app where each list will have multiple tasks.

The URL for creating a new task would be like /lists/:listId/tasks

In my app.js I'm doing this to redirect that URL to a specific route file called tasks.js:

```<code>app.use('/lists/:listId/tasks', tasks);
</code>```

Then in my tasks.js I'm doing the following:

```<code>router.post('/', (req, res) => {
  console.log(req.params.listId) //This doesn't work.
});
</code>```

How can I get the params from the tasks.js?. Also, if there is a better way to implement what I want, I would be more than happy to see it.

答:
A workaround I've adopted for this scenario is the following:

app.use('/lists/:listId/tasks', (req, res, next) => {
    res.local.params = req.params;  //in res.local you can store whatever you want
    next();
}, tasks);
```

Then you can access res.local from tasks.js routes.

Title: Retrieve URL Parameters

Body:
I'm creating an app where each list will have multiple tasks.

The URL for creating a new task would be like /lists/:listId/tasks

In my app.js I'm doing this to redirect that URL to a specific route file called tasks.js:

app.use('/lists/:listId/tasks', tasks);

Then in my tasks.js I'm doing the following:

router.post('/', (req, res) => {
  console.log(req.params.listId) //This doesn't work.
});

How can I get the params from the tasks.js?. Also, if there is a better way to implement what I want, I would be more than happy to see it.

Body:
A workaround I've adopted for this scenario is the following:

app.use('/lists/:listId/tasks', (req, res, next) => {
    res.local.params = req.params;  //in res.local you can store whatever you want
    next();
}, tasks);

Then you can access res.local from tasks.js routes.


问:
Cognito user pool "username" appears as id not email, how to fix it?
I'm using Amazon Cognito user pools, and i choose to have users signup/In with their emails. According to online guides, when choosing so, the user pool should list users with "username" value as their email, but this is not the case, i'm seeing the "id" which is also referred to as "sub" as the "username" field!
it has the UUID format.

Any ideas how to get username shows the email?
** Note: I'm talking about showing users from AWS cognito console.
Attached is a screenshot

答:
That seems to happen when you chose to signup with either email or phone.
Apparently in that configuration Cognito generates 'username' using the sub...

I would suggest configuring Congito to use 'username' and then on signup set up the 'username' to email, you can also pass email (and phone) as additional attributes.

I hope that helps


问:
Jquery blackout + popup problem
Js Fiddle

I'm struggling to understand what is wrong with this code. I am basically trying to make the page 'blackout' and then display the hidden div inside the new div I have create in the JS.

The first line seems to work, creating a blackout div and fading it over the whole page. But the rest of the jquery just doesn't seem to work, because after that a div should be created (forgottenpassword) which is placed inside the wrapper div and then the emailSignupBox should be placed into the fogottenpassword div which should slide down and display.

I'm also getting an error on Firebug saying:

$("").css("opacity",
  0.8).appendTo("body").delay is not a function
  Line 44

答:
You need to load jQuery 1.4 or higher, because .delay() is added in 1.4:
http://api.jquery.com/delay/

Working example:
http://jsfiddle.net/PjpWC/

Title: Jquery blackout + popup problem


问:
How to design Login use MVVM+Databinding in android studio?
I am a newcomer and have no programming experience. Now I use CODELABS.developer.google.com and developer.android.com to learn java +android, but I have encountered problems when designing the "login" module. This problem has taken me 3 days. I search for solutions on Google every day, but I still haven't solved it.

Error:

```<code>C:\Users\Admin\AndroidStudioProjects\exmaple\app\build\generated\data_binding_base_class_source_out\debug\out\com\exmaple\databinding\FragmentEmailEditBinding.java:15: ����: �Ҳ�������
import com.exmaple.ViewModel;
                  ^
  ����:   �� ViewModel
  λ��: ����� com.exmaple

C:\Users\Admin\AndroidStudioProjects\exmaple\app\build\generated\data_binding_base_class_source_out\debug\out\com\exmaple\databinding\FragmentEmailEditBinding.java:33: ����: �����ViewModel.Login������
  protected ViewModel.Login.EmailAuthViewModel mEmailAuthViewModel;
                           ^
</code>```

LoginActivity.java

```<code>public class LoginActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        FragmentEmailEditBinding binding = DataBindingUtil.setContentView(this,R.layout.fragment_email_edit);
        EmailAuthViewModel emailAuthViewModel = new ViewModelProvider(this).get(EmailAuthViewModel.class);
        binding.getEmailAuthViewModel();
        binding.setLifecycleOwner(this);

        FragmentManager fragmentManager = getSupportFragmentManager();
        EmailAuthFragment emailAuthFragment = new EmailAuthFragment();
        fragmentManager.beginTransaction()
                .add(R.id.frag_signIn,emailAuthFragment).commit();
    }
}
</code>```

fragment_email_edit.xml

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="emailAuthViewModel"
            type="com.example.ViewModel.Login.EmailAuthViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="8dp">

        <EditText
            android:id="@+id/fieldEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:text="@={emailAuthViewModel.email}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintBottom_toTopOf="@id/fieldPassword"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.25"
            app:layout_constraintVertical_chainStyle="packed" />

        <EditText
            android:id="@+id/fieldPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:hint="@string/hint_password"
            android:inputType="textPassword"
            android:text="@{emailAuthViewModel.password}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/fieldEmail"
            app:layout_constraintVertical_bias="0.25"
            app:layout_constraintVertical_chainStyle="packed" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
</code>```

EmailAuthViewModel.java

```<code>public class EmailAuthViewModel extends ViewModel {

    public MutableLiveData<String> email = new MutableLiveData<>();
    public MutableLiveData<String> password = new MutableLiveData<>();

    public EmailAuthViewModel(MutableLiveData<String> email, MutableLiveData<String> password) {
        this.email = email;
        this.password = password;
    }
}
</code>```

EmailAuthModel.java

```<code>class EmailAuthModel {

}
</code>```

答:
My guess would be that this line binding.getEmailAuthViewModel();
 throws NPE since you didn't pass the viewmodel to binding anywhere. I think you want to pass viewmodel to databinding file, not get from it.

Body:
I am a newcomer and have no programming experience. Now I use CODELABS.developer.google.com and developer.android.com to learn java +android, but I have encountered problems when designing the "login" module. This problem has taken me 3 days. I search for solutions on Google every day, but I still haven't solved it.

Error:

C:\Users\Admin\AndroidStudioProjects\exmaple\app\build\generated\data_binding_base_class_source_out\debug\out\com\exmaple\databinding\FragmentEmailEditBinding.java:15: ����: �Ҳ�������
import com.exmaple.ViewModel;
                  ^
  ����:   �� ViewModel
  λ��: ����� com.exmaple

C:\Users\Admin\AndroidStudioProjects\exmaple\app\build\generated\data_binding_base_class_source_out\debug\out\com\exmaple\databinding\FragmentEmailEditBinding.java:33: ����: �����ViewModel.Login������
  protected ViewModel.Login.EmailAuthViewModel mEmailAuthViewModel;
                           ^

LoginActivity.java

public class LoginActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        FragmentEmailEditBinding binding = DataBindingUtil.setContentView(this,R.layout.fragment_email_edit);
        EmailAuthViewModel emailAuthViewModel = new ViewModelProvider(this).get(EmailAuthViewModel.class);
        binding.getEmailAuthViewModel();
        binding.setLifecycleOwner(this);

        FragmentManager fragmentManager = getSupportFragmentManager();
        EmailAuthFragment emailAuthFragment = new EmailAuthFragment();
        fragmentManager.beginTransaction()
                .add(R.id.frag_signIn,emailAuthFragment).commit();
    }
}

fragment_email_edit.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="emailAuthViewModel"
            type="com.example.ViewModel.Login.EmailAuthViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="8dp">

        <EditText
            android:id="@+id/fieldEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:text="@={emailAuthViewModel.email}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintBottom_toTopOf="@id/fieldPassword"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.25"
            app:layout_constraintVertical_chainStyle="packed" />

        <EditText
            android:id="@+id/fieldPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:hint="@string/hint_password"
            android:inputType="textPassword"
            android:text="@{emailAuthViewModel.password}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/fieldEmail"
            app:layout_constraintVertical_bias="0.25"
            app:layout_constraintVertical_chainStyle="packed" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

EmailAuthViewModel.java

public class EmailAuthViewModel extends ViewModel {

    public MutableLiveData<String> email = new MutableLiveData<>();
    public MutableLiveData<String> password = new MutableLiveData<>();

    public EmailAuthViewModel(MutableLiveData<String> email, MutableLiveData<String> password) {
        this.email = email;
        this.password = password;
    }
}

EmailAuthModel.java

class EmailAuthModel {

}


问:
No variables show up on inspector, first person controller
I followed this video ( https://www.youtube.com/watch?v=_QajrabyTJ ) 1:1 exactly, and when I tried to go and edit the mouse sensitivity variable, no boxes show up in the script component for me to edit the number.

Here is the code that I took from the video:

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseLook : MonoBehaviour
{
    public float mouseSensitivity = 100f;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse  Y")* mouseSensitivity * Time.deltaTime;
    }
}
</code>```

答:
I cant comment yet, so have to write it as answer:
In this line:

```<code>float mouseY = Input.GetAxis("Mouse  Y")* mouseSensitivity * Time.deltaTime;
</code>```

you have a double space between "Mouse" and "Y", code wouldn`t work.

Also, see your console for warnings and errors - while you have it not fixed, changes not applied to scripts. As mentioned in comments, your script must be named exactly as "MouseLook.cs".

Body:
I followed this video ( https://www.youtube.com/watch?v=_QajrabyTJ ) 1:1 exactly, and when I tried to go and edit the mouse sensitivity variable, no boxes show up in the script component for me to edit the number.

Here is the code that I took from the video:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseLook : MonoBehaviour
{
    public float mouseSensitivity = 100f;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse  Y")* mouseSensitivity * Time.deltaTime;
    }
}

Body:
I cant comment yet, so have to write it as answer:
In this line:

float mouseY = Input.GetAxis("Mouse  Y")* mouseSensitivity * Time.deltaTime;

you have a double space between "Mouse" and "Y", code wouldn`t work.

Also, see your console for warnings and errors - while you have it not fixed, changes not applied to scripts. As mentioned in comments, your script must be named exactly as "MouseLook.cs".


问:
Getting date time string into google calendar format
I have a c# DateTime object and I'm trying to convert it to a google calendar event link date time string. I use a calendar link generator here and I get a date time string that looks like this

dates=20170829T180000Z%2F20170829T190000Z

where the start time is 11:00AM and the second time is 12:00PM

how do I format my string to get this?

I have this so far

```<code>var FormattedStartDateTime = newEvent.EventDateTime.ToString("yyyyDDmm")
</code>```

this will get me the date but how do I get the rest? I think the rest is in seconds, maybe from Jan 1, but not sure and is there a way to include the 'T' and 'Z' at the end? Or do I need to create my own string like this after I get the seconds?

答:
I used</p>

```<code>Date.ToString("yyyyMMddTHHmmss")
</code>```

Body:
I have a c# DateTime object and I'm trying to convert it to a google calendar event link date time string. I use a calendar link generator here and I get a date time string that looks like this

dates=20170829T180000Z%2F20170829T190000Z

where the start time is 11:00AM and the second time is 12:00PM

how do I format my string to get this?

I have this so far

var FormattedStartDateTime = newEvent.EventDateTime.ToString("yyyyDDmm")

this will get me the date but how do I get the rest? I think the rest is in seconds, maybe from Jan 1, but not sure and is there a way to include the 'T' and 'Z' at the end? Or do I need to create my own string like this after I get the seconds?

Body:
I used

Date.ToString("yyyyMMddTHHmmss")


问:
Trying to test the google spreadsheet in apps script using multiple sheets force to go to a specific sheet without using the URL
I am using a number of sheets and want to force my script to go to a specific sheet but instead it stays on the active sheet that was just created in my script ?

Note: I do not want to use the URL but the actual name of the spread sheet instead, and think I have to use the setActiveSheet() but have not been able to find any information but that it does not use a string but instead you have to use the object from the parent class ?

The script is showing in the log the word "Master_Approval" and is the wrong sheet  the name of the active sheet.

```<code>var Sprsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = Sprsheet.getActiveSheet();
var mySheet = sheet.getSheetName();

if (sheet.getSheetName() == "2020Members") {
  Logger.log('THE ACTIVE SHEETS NAME is :' + mySheet);
}
else {

  Logger.log('THE WRONG ACTIVE SHEETS NAME is :' + mySheet);
  // Force to the correct sheet !
  var sheetDataAsArr = sprSheet.getSheetByName("2020Members");
  var sheet = sprSheet.getActiveSheet();
  var mySheet = sheet.getSheetName();
  Logger.log('THE ACTIVE SHEETS NAME is :' + mySheet);
}
</code>```

It should show the "2020Members" but is not and if the test fails I want to force the active sheet to be "2020Members" and not the sheet we are in currently.

```<code>var sheetDataAsArr = sprSheet.getSheetByName("2020Members");
var mainSheet = sheetDataAsArr.getActiveSheet();
Logger.log('THE ACTIVE is :' + mainSheet);
var sheet = sprSheet.setActiveSheet(mainSheet);
var mySheet = sheet.getSheetName();
Logger.log('THE ACTIVE SHEETS NAME is :' + mySheet);
</code>```

What is wrong above?

答:
What is wrong above ?

Answer:

In your last code snippet you have some lines incorrectly written:

Each instance of sprSheet needs to be Sprsheet.

You need to use getSheetName() on mainSheet to log the name of the sheet

The line sprSheet.setActiveSheet(mainSheet) is setting the active sheet to whatever the active sheet already is, you need to use setActiveSheet(sheetDataAsArr)

Full Code:

```<code>function myFunction(){
  var Sprsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = Sprsheet.getActiveSheet();
  var mySheet = sheet.getSheetName();

  if (sheet.getSheetName() == "2020Members") {
    Logger.log('THE ACTIVE SHEETS NAME is :' + mySheet);
  }
  else {
    var sheetDataAsArr = Sprsheet.getSheetByName("2020Members");
    var mainSheet = Sprsheet.getActiveSheet();
    Logger.log('THE ACTIVE is :' + mainSheet.getSheetName());
    var sheet = Sprsheet.setActiveSheet(sheetDataAsArr);
    var mySheet = sheet.getSheetName();
    Logger.log('THE ACTIVE SHEETS NAME is :' + mySheet);
  }
}
</code>```

Something to note: Google Sheets does have some strange behaviour with bound script files and sometimes the script tab will 'lose' it's bound status to the Spreadsheet if both are open and left unattended for long periods of time; this however can be fixed by reloading the Spreadsheet.

Related Questions:

How to make all sheets of a Google spreadsheet show A1 in upper left?

Body:
I am using a number of sheets and want to force my script to go to a specific sheet but instead it stays on the active sheet that was just created in my script ?

Note: I do not want to use the URL but the actual name of the spread sheet instead, and think I have to use the setActiveSheet() but have not been able to find any information but that it does not use a string but instead you have to use the object from the parent class ?

The script is showing in the log the word "Master_Approval" and is the wrong sheet  the name of the active sheet.

var Sprsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = Sprsheet.getActiveSheet();
var mySheet = sheet.getSheetName();

if (sheet.getSheetName() == "2020Members") {
  Logger.log('THE ACTIVE SHEETS NAME is :' + mySheet);
}
else {

  Logger.log('THE WRONG ACTIVE SHEETS NAME is :' + mySheet);
  // Force to the correct sheet !
  var sheetDataAsArr = sprSheet.getSheetByName("2020Members");
  var sheet = sprSheet.getActiveSheet();
  var mySheet = sheet.getSheetName();
  Logger.log('THE ACTIVE SHEETS NAME is :' + mySheet);
}

It should show the "2020Members" but is not and if the test fails I want to force the active sheet to be "2020Members" and not the sheet we are in currently.

var sheetDataAsArr = sprSheet.getSheetByName("2020Members");
var mainSheet = sheetDataAsArr.getActiveSheet();
Logger.log('THE ACTIVE is :' + mainSheet);
var sheet = sprSheet.setActiveSheet(mainSheet);
var mySheet = sheet.getSheetName();
Logger.log('THE ACTIVE SHEETS NAME is :' + mySheet);

What is wrong above?

Body:
What is wrong above ?

Answer:

In your last code snippet you have some lines incorrectly written:

Each instance of sprSheet needs to be Sprsheet.

You need to use getSheetName() on mainSheet to log the name of the sheet

The line sprSheet.setActiveSheet(mainSheet) is setting the active sheet to whatever the active sheet already is, you need to use setActiveSheet(sheetDataAsArr)

Full Code:

function myFunction(){
  var Sprsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = Sprsheet.getActiveSheet();
  var mySheet = sheet.getSheetName();

  if (sheet.getSheetName() == "2020Members") {
    Logger.log('THE ACTIVE SHEETS NAME is :' + mySheet);
  }
  else {
    var sheetDataAsArr = Sprsheet.getSheetByName("2020Members");
    var mainSheet = Sprsheet.getActiveSheet();
    Logger.log('THE ACTIVE is :' + mainSheet.getSheetName());
    var sheet = Sprsheet.setActiveSheet(sheetDataAsArr);
    var mySheet = sheet.getSheetName();
    Logger.log('THE ACTIVE SHEETS NAME is :' + mySheet);
  }
}

Something to note: Google Sheets does have some strange behaviour with bound script files and sometimes the script tab will 'lose' it's bound status to the Spreadsheet if both are open and left unattended for long periods of time; this however can be fixed by reloading the Spreadsheet.

Related Questions:

How to make all sheets of a Google spreadsheet show A1 in upper left?


问:
UIScrollView Content Offset on Initialization
We are currently working in an older codebase for our iOS application and are running into a weird bug where the UIScrollViews paging is not matching on the initialization but only once a user selects the button to change the view.

Expected Result:

The result we have:

Each ScrollView has three slides nested inside of them. We initialize the ScrollView like this:

```<code>override init(frame: CGRect) {
    super.init(frame: frame)
    self.commonInit()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.commonInit()
}

private func commonInit() {

    Bundle.main.loadNibNamed("DIScrollView", owner: self, options: nil)
    contentView.frame = self.bounds
    addSubview(contentView)
    contentView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
    contentView.layer.borderColor = UIColor.white.cgColor
    contentView.layer.borderWidth = 2.0

    scrollView.delegate = self
    setUpScrollViewer()
}
</code>```

You can see we call to set up the ScrollView and that is done like this:

```<code>public func setUpScrollViewer() {

    let slides = self.createSlides()
    let defaultIndex = 1
    scrollView.Initialize(slides: slides, scrollToIndex: defaultIndex)

    pageControl.numberOfPages = slides.count
    pageControl.currentPage = defaultIndex
}
</code>```

Now that all the content is available for each slide, we want to handle the content and we do so with a ScrollView extension:

```<code>extension UIScrollView {

//this function adds slides to the scrollview and constraints to the subviews (slides)
//to ensure the subviews are properly sized
func Initialize(slides:[UIView], scrollToIndex:Int) {

    //Take second slide to base size from
    let frameWidth = slides[1].frame.size.width

    self.contentSize = CGSize(width: frameWidth * CGFloat(slides.count), height: 1)

    for i in 0 ..< slides.count {

        //turn off auto contstraints. We will be setting our own
        slides[i].translatesAutoresizingMaskIntoConstraints = false

        self.addSubview(slides[i])

        //pin the slide to the scrollviewers edges
        if i == slides.startIndex {
            slides[i].leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
        } else { //pin each subsequent slides leading edge to the previous slides trailing anchor
            slides[i].leadingAnchor.constraint(equalTo: slides[i - 1].trailingAnchor).isActive = true
        }

        slides[i].topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        slides[i].widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
        slides[i].heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
    }

    //the last slides trailing needs to be pinned to the scrollviewers trailing.
    slides.last?.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true

    self.scrollRectToVisible(CGRect(x: frameWidth * CGFloat(scrollToIndex), y: 0, width: frameWidth, height: 1), animated: false)

}

}
</code>```

I have tried manually setting contentOffset and nothing seems to be adjusting on the initialization. If the user selects the button it hides and then unhides it to display it properly with no logic adjusting this. Giving me the impression this issue is on the init.

Summary:
When the main view loads, the scrollView is showing me the first slide in the index when i need to be focused on the second slide. However if the user hides and then unhides the scrollView it works as intended.

How do i get the UIScrollView to actually load and initialize updating the scrollView to show the second slide and not initialize on the first slide?

答:
Use constraints for your contentView instead setting frame and autoresizingMask.

Call view.layoutIfNeeded() in the viewController before scrollRectToVisible or setContentOffset(I prefer the last)

Body:
We are currently working in an older codebase for our iOS application and are running into a weird bug where the UIScrollViews paging is not matching on the initialization but only once a user selects the button to change the view.

Expected Result:

The result we have:

Each ScrollView has three slides nested inside of them. We initialize the ScrollView like this:

override init(frame: CGRect) {
    super.init(frame: frame)
    self.commonInit()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.commonInit()
}

private func commonInit() {

    Bundle.main.loadNibNamed("DIScrollView", owner: self, options: nil)
    contentView.frame = self.bounds
    addSubview(contentView)
    contentView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
    contentView.layer.borderColor = UIColor.white.cgColor
    contentView.layer.borderWidth = 2.0

    scrollView.delegate = self
    setUpScrollViewer()
}

You can see we call to set up the ScrollView and that is done like this:

public func setUpScrollViewer() {

    let slides = self.createSlides()
    let defaultIndex = 1
    scrollView.Initialize(slides: slides, scrollToIndex: defaultIndex)

    pageControl.numberOfPages = slides.count
    pageControl.currentPage = defaultIndex
}

Now that all the content is available for each slide, we want to handle the content and we do so with a ScrollView extension:

extension UIScrollView {

//this function adds slides to the scrollview and constraints to the subviews (slides)
//to ensure the subviews are properly sized
func Initialize(slides:[UIView], scrollToIndex:Int) {

    //Take second slide to base size from
    let frameWidth = slides[1].frame.size.width

    self.contentSize = CGSize(width: frameWidth * CGFloat(slides.count), height: 1)

    for i in 0 ..< slides.count {

        //turn off auto contstraints. We will be setting our own
        slides[i].translatesAutoresizingMaskIntoConstraints = false

        self.addSubview(slides[i])

        //pin the slide to the scrollviewers edges
        if i == slides.startIndex {
            slides[i].leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true
        } else { //pin each subsequent slides leading edge to the previous slides trailing anchor
            slides[i].leadingAnchor.constraint(equalTo: slides[i - 1].trailingAnchor).isActive = true
        }

        slides[i].topAnchor.constraint(equalTo: self.topAnchor).isActive = true
        slides[i].widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true
        slides[i].heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true
    }

    //the last slides trailing needs to be pinned to the scrollviewers trailing.
    slides.last?.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true

    self.scrollRectToVisible(CGRect(x: frameWidth * CGFloat(scrollToIndex), y: 0, width: frameWidth, height: 1), animated: false)

}

}

I have tried manually setting contentOffset and nothing seems to be adjusting on the initialization. If the user selects the button it hides and then unhides it to display it properly with no logic adjusting this. Giving me the impression this issue is on the init.

Summary:
When the main view loads, the scrollView is showing me the first slide in the index when i need to be focused on the second slide. However if the user hides and then unhides the scrollView it works as intended.

How do i get the UIScrollView to actually load and initialize updating the scrollView to show the second slide and not initialize on the first slide?


问:
ChartJS: Show default tooltip onclick
I have a chart.js line chart displaying properly. When you hover over the y-axis gridlines, the tooltips display as they should.

I'm trying to convert this to function on a touchscreen, so there is no hover. Is there a way to add a simple parameter to make the tooltip show on both hover and onclick?

Note, I know I could add a custom tooltip and add all of that functionality - I'm trying to see if there's just a parameter I can add as I don't need a custom tooltip.

答:
For ChartJS version 2.8.0, you will need to add both the click and mouseout events to make the tooltip behave the desired way.

The click event would make the tooltip to appear when point is clicked and the mouseout event would hide the tooltip when the mouse pointer is moved outside of the chart canvas area which is the desired behavior.

Note: Without adding the mouseout event the tooltip would not hide even when the mouse is moved or clicked outside the chart canvas area.

Code:

```<code>options: {
  events: ["click", "mouseout"],
....
...
</code>```

Title: ChartJS: Show default tooltip onclick

Body:
For ChartJS version 2.8.0, you will need to add both the click and mouseout events to make the tooltip behave the desired way.

The click event would make the tooltip to appear when point is clicked and the mouseout event would hide the tooltip when the mouse pointer is moved outside of the chart canvas area which is the desired behavior.

Note: Without adding the mouseout event the tooltip would not hide even when the mouse is moved or clicked outside the chart canvas area.

Code:

options: {
  events: ["click", "mouseout"],
....
...


问:
Google apps script converting date within formula
I'm using Google Apps Script to create a new set of tabs within a sheet, and everything is going well apart from one date within a formula. The code I'm using is

```<code>function MakeANewDaySheet() {
  var date = Utilities.formatDate(new Date(), "GMT", "dd/MM/yyyy")
  var spreadsheet = SpreadsheetApp.getActive();
...
...
  spreadsheet.getRange('O2').activate();
  spreadsheet.getCurrentCell().setFormula("=iferror(indirect(" + date + '!$B3),\"Please select a department\")')
}
</code>```

The formula I want the script to put in the cell points to another sheet that's created during this script, and its name is simply today's date. When the formula is entered using the script it puts ' around the year, which I cant seem to stop it doing.

I'm wanting to use the formula '=iferror(indirect(02/06/2020!$B3),"Please select a department")'
and its giving me '=iferror(indirect(2/6/'2020'!$B3),"Please select a department")'

I've tried changing around between " and ', including \ and not, hoping it was that easy, but no luck.

Can anyone point out what is probably (hopefully) a simple syntax error.

答:
This is how you would reference another sheet (tab) with INDIRECT:

```<code>=INDIRECT("'"&"03/06/2020"&"'!"&"$B3")
</code>```

To set this formula via Apps Script, you have to use the escape character (\") each time a there is double quote in the formula. So you can do this:

var formula = "=IFERROR(INDIRECT(\"'\"&\"" + date + "\"&\"'!\"&\"$B3\"), \"Please select a department\")";
spreadsheet.getCurrentCell().setFormula(formula);
```

<h3>Note:</h3>

<p>Also, if you want to set this formula to <code>O2</code>, there is not need to activate the cell first, you can just do this:</p>

<pre class="lang-js prettyprint-override"><code>spreadsheet.getRange('O2').setFormula(formula);
</code>```

Reference:

INDIRECT

Body:
I'm using Google Apps Script to create a new set of tabs within a sheet, and everything is going well apart from one date within a formula. The code I'm using is

function MakeANewDaySheet() {
  var date = Utilities.formatDate(new Date(), "GMT", "dd/MM/yyyy")
  var spreadsheet = SpreadsheetApp.getActive();
...
...
  spreadsheet.getRange('O2').activate();
  spreadsheet.getCurrentCell().setFormula("=iferror(indirect(" + date + '!$B3),\"Please select a department\")')
}

The formula I want the script to put in the cell points to another sheet that's created during this script, and its name is simply today's date. When the formula is entered using the script it puts ' around the year, which I cant seem to stop it doing.

I'm wanting to use the formula '=iferror(indirect(02/06/2020!$B3),"Please select a department")'
and its giving me '=iferror(indirect(2/6/'2020'!$B3),"Please select a department")'

I've tried changing around between " and ', including \ and not, hoping it was that easy, but no luck.

Can anyone point out what is probably (hopefully) a simple syntax error.

Body:
This is how you would reference another sheet (tab) with INDIRECT:

=INDIRECT("'"&"03/06/2020"&"'!"&"$B3")

To set this formula via Apps Script, you have to use the escape character (\") each time a there is double quote in the formula. So you can do this:

var formula = "=IFERROR(INDIRECT(\"'\"&\"" + date + "\"&\"'!\"&\"$B3\"), \"Please select a department\")";
spreadsheet.getCurrentCell().setFormula(formula);

Note:

Also, if you want to set this formula to O2, there is not need to activate the cell first, you can just do this:

spreadsheet.getRange('O2').setFormula(formula);

Reference:

INDIRECT


问:
DateTime.Now vs. DateTime.UtcNow
I've been wondering what exactly are the principles of how the two properties work. I know the second one is universal and basically doesn't deal with time zones, but can someone explain in detail how they work and which one should be used in what scenario?</p>

答:
DateTime has no idea what time zones are. It always assumes you're at your local time. UtcNow only means "Subtract my timezone from the time".

If you want to use timezone-aware dates, use DateTimeOffset, which represents a date/time with a timezone. I had to learn that the hard way.

OwnerDisplayName: Slavo

ContentLicense: CC BY-SA 2.5

Title: DateTime.Now vs. DateTime.UtcNow

LastEditorDisplayName: Jedi Master Spooky

OwnerDisplayName: Omer van Kloeten


问:
Am i violating any NF RULE on my database design?
Good day!

I am a newbie on creating database... I need to create a db for my recruitment web application.

My database schema is as follows:

NOTE: I included the applicant_id on other tables... e.g. exam, interview, exam type.

Am i violating any normalization rule? If i do, what do you recommend to improve my design? Thank you

答:
I think that your DB structure has a lot of limitation for future usage. For example you can even have a description of the exam because this stable store the score and exam date. It may by that this kind of information are already stored in another system and you have to design only the result container. But even then the exam, screen and interview are just a form of test, that why the information about should be stored in one table and distinguished by some type id. If you decide to this approach you have to create another table to store the information about result

So the definition of that should look more like this:

```<code>TEST
 TEST_ID
 TEST_TYPE_ID ref TEST_TYPE - Table that define the test type
 TEST_REQUIRED_SCORE - The value of the score that need to be reach to pass the exam.
 ... - Many others properties of TEST like duration, expire date, active inactive etc.

APPLICANT_RESULTS
 APPLICANT_ID ref APPLICANT
 TEST_ID = ref TEST
 TESTS_DATE - The day of exam
 TEST_START - The time when the test has started
 TEST_FINISH - The time when the test has ended
 APPLICANT_RESULT - The applicant result of taken test.
</code>```

This kind of structure is more flexible and give the easy way to specify the requirements between the test in table like this

```<code>TEST_REQUIREMENTS - Table that specify the test hierarchy and limitation
 TEST_ID ref TEST
 REQUIRED_TEST ref TEST
 ORDER - the order of exams
</code>```

Another scenario is that in the future your employer will want to switch to an e-exam system. In that case only think what you will need are:

Create table that will store the question definition (one question can be used in exam, screen or interview)

Crate table that will store the question answers.

Create table that will store the information about the test question.

Create table for storing the answer for each question given from applicant.

A trigger that will update the over all score of test.

Body:
I think that your DB structure has a lot of limitation for future usage. For example you can even have a description of the exam because this stable store the score and exam date. It may by that this kind of information are already stored in another system and you have to design only the result container. But even then the exam, screen and interview are just a form of test, that why the information about should be stored in one table and distinguished by some type id. If you decide to this approach you have to create another table to store the information about result

So the definition of that should look more like this:

TEST
 TEST_ID
 TEST_TYPE_ID ref TEST_TYPE - Table that define the test type
 TEST_REQUIRED_SCORE - The value of the score that need to be reach to pass the exam.
 ... - Many others properties of TEST like duration, expire date, active inactive etc.

APPLICANT_RESULTS
 APPLICANT_ID ref APPLICANT
 TEST_ID = ref TEST
 TESTS_DATE - The day of exam
 TEST_START - The time when the test has started
 TEST_FINISH - The time when the test has ended
 APPLICANT_RESULT - The applicant result of taken test.

This kind of structure is more flexible and give the easy way to specify the requirements between the test in table like this

TEST_REQUIREMENTS - Table that specify the test hierarchy and limitation
 TEST_ID ref TEST
 REQUIRED_TEST ref TEST
 ORDER - the order of exams

Another scenario is that in the future your employer will want to switch to an e-exam system. In that case only think what you will need are:

Create table that will store the question definition (one question can be used in exam, screen or interview)

Crate table that will store the question answers.

Create table that will store the information about the test question.

Create table for storing the answer for each question given from applicant.

A trigger that will update the over all score of test.


问:
Get the key names of the object with value equals to something
Is there a better way to get the key names of the object with value equals to cat?

```<code>import { toPairs } from 'lodash'

const options = {
  x: 'cont',
  y: undefined,
  color: 'cat',
  radius: 'cat'
}

const catNames = toPairs(options).map(([name, type]) => type === 'cat' ? name : null).filter(n => n)
// [ 'color', 'radius' ]
</code>```

答:
ES6+ in one line

```<code>let key = Object.keys(obj).find(k=> obj[k] === value);
</code>```

Get all the keys with

```<code>let keys = Object.keys(obj).filter( k => obj[k] === value);
</code>```

Body:
Is there a better way to get the key names of the object with value equals to cat?

import { toPairs } from 'lodash'

const options = {
  x: 'cont',
  y: undefined,
  color: 'cat',
  radius: 'cat'
}

const catNames = toPairs(options).map(([name, type]) => type === 'cat' ? name : null).filter(n => n)
// [ 'color', 'radius' ]

Body:
ES6+ in one line

let key = Object.keys(obj).find(k=> obj[k] === value);

Get all the keys with

let keys = Object.keys(obj).filter( k => obj[k] === value);


问:
change specific columns name in one Go in Python
my dataframe-:

```<code>Unnamed: 0     AsF      demos   Unnamed: 1  Unnamed: 2  Unnamed: 3  Unnamed: 4
1               2        3        3            3           3          3
2               3        4        6             6          6          6

Expected result-:

               AsF     demos
1               2        3        3            3           3          3
2               3        4        6             6          6          6

i tried
df.rename( columns={'Unnamed: 0':'','Unnamed: 1':''}, inplace=True)

</code>```

But I can't do that, because number of this kind of columns("unnamed:0") is not fix

I want to do this,because when i convert DF into CSV, it comes with "Unnamed" name that I do not want.

Thanks in Advance

答:
Fortunately, .rename()'s column param can also get a function, and not just a dict!

you can write a simple lambda to check the prefix of the column name, like this:

df = df.rename(columns=lambda col: '' if col.startswith('Unnamed:') else col)
```

Body:
my dataframe-:

Unnamed: 0     AsF      demos   Unnamed: 1  Unnamed: 2  Unnamed: 3  Unnamed: 4
1               2        3        3            3           3          3
2               3        4        6             6          6          6

Expected result-:

               AsF     demos
1               2        3        3            3           3          3
2               3        4        6             6          6          6

i tried
df.rename( columns={'Unnamed: 0':'','Unnamed: 1':''}, inplace=True)

But I can't do that, because number of this kind of columns("unnamed:0") is not fix

I want to do this,because when i convert DF into CSV, it comes with "Unnamed" name that I do not want.

Thanks in Advance


问:
How to split names with numbers from one common file into separate files by numbers (Names with identical numbers in one file and others in another)
```<code>student = ['Ted 904', 'John 904', 'Dan 905', 'Peter 905', 'Michael 906']
with open('a.txt', "w") as myfile:
        for c in student:
                myfile.write("%s\n" % c)
</code>```

I have a list of students with their numbers and I have written it in file and now I need to separate them on different txt files by their similar number.

答:
If the Marks are in 3 digits always then one can do this:-

```<code>for i in student:
    f = i[-3:] #accessing the last 3 letters/digits of the string for filename
    with open("%s.txt" % f, "w") as myfile:
        myfile.write(c)
</code>```

However, if you want to display Marks and Name clearly you may want to try this:

```<code>student = ['Ted 904', 'John 904', 'Dan 905', 'Peter 905', 'Michael 906']
df = pd.DataFrame(student, columns=['String'])
df = df['String'].str.split(" ", n = 1, expand = True)
df.columns = ['Name', 'Marks']
for m in df['Marks']:
    y = df.loc[df['Marks'] == m]
    f = open("%s.txt" % m, "w")
    f.write(str(y))
</code>```

Body:
student = ['Ted 904', 'John 904', 'Dan 905', 'Peter 905', 'Michael 906']
with open('a.txt', "w") as myfile:
        for c in student:
                myfile.write("%s\n" % c)

I have a list of students with their numbers and I have written it in file and now I need to separate them on different txt files by their similar number.

Body:
If the Marks are in 3 digits always then one can do this:-

for i in student:
    f = i[-3:] #accessing the last 3 letters/digits of the string for filename
    with open("%s.txt" % f, "w") as myfile:
        myfile.write(c)

However, if you want to display Marks and Name clearly you may want to try this:

student = ['Ted 904', 'John 904', 'Dan 905', 'Peter 905', 'Michael 906']
df = pd.DataFrame(student, columns=['String'])
df = df['String'].str.split(" ", n = 1, expand = True)
df.columns = ['Name', 'Marks']
for m in df['Marks']:
    y = df.loc[df['Marks'] == m]
    f = open("%s.txt" % m, "w")
    f.write(str(y))


问:
Azure DevOps public project access logs
We have made an Azure DevOps project public and are wondering if it is possible to see audit logs for public/anonymous users. I can see a complete log history for authenticated users but cannot see anything for public users.
Any ideas?

Thanks.

答:
Unfortunately, there is no such audit log. Audit logs contain many changes that occur throughout an Azure DevOps organization. Changes occur when a user or service identity within the organization edits the state of an artifact. While a public project allows non-members of a project and users who aren't signed in read-only, anyone can view this public project only.

Since public/anonymous users can only view, but not change the project, there is no audit log.

Title: Azure DevOps public project access logs


问:
Cypress Test - Google Places Autocomplete not functioning
I am trying to use Cypress as a testing tool for an Angular website I am working on. One of the tests is for a location search, which uses the google places service to autocomplete locations. Functioning correctly, it looks like in the picture below:

However, in cypress testing, the autocomplete element does not appear, so a location cannot be chosen to proceed with the search.
The test is firing the methods that it should to make it appear, but it does not. It will appear if I manually type in the cypress browser as well.

Does anyone know what may be causing this?

答:
You can try to set the "delay" after each keypress on the "type" options object:

```<code>cy.get("input[data-name=autocomplete]")
  .type("AUTOCOMPLETE DATA", { delay: 100 })
  .type("{enter}", { delay: 100 })
</code>```

https://docs.cypress.io/api/commands/type.html#Arguments

Body:
You can try to set the "delay" after each keypress on the "type" options object:

cy.get("input[data-name=autocomplete]")
  .type("AUTOCOMPLETE DATA", { delay: 100 })
  .type("{enter}", { delay: 100 })

https://docs.cypress.io/api/commands/type.html#Arguments


问:
Is there a function to count the number of rows for a given condition?
Is there a way where I could get this desired output using mutate()? The idea is to count the number of consecutive values above 5.5 in each sequence of the Speed column. Ideally, it would also be best to get a function that could determine a "Start" and "End." E.g. in this example it would START at 5.5 and END at 5.9. </p>

```<code>Speed <- c(0.1, 0.2, 1.2, 1.5, 2.8, 5.5, 5.6, 5.7, 5.8, 5.9, 0.1, 0.2, 1.2, 1.5, 2.8, 5.5, 5.6, 5.7, 5.8, 5.9)
Number <- c(0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5)

df <- data.frame(Speed, Number)
df

     Speed Number
    1    0.1      0
    2    0.2      0
    3    1.2      0
    4    1.5      0
    5    2.8      0
    6    5.5      1
    7    5.6      2
    8    5.7      3
    9    5.8      4
    10   5.9      5
    11   0.1      0
    12   0.2      0
    13   1.2      0
    14   1.5      0
    15   2.8      0
    16   5.5      1
    17   5.6      2
    18   5.7      3
    19   5.8      4
    20   5.9      5
</code>```

答:
You need a group to demarcate your different speeds, your example is basically a repetition of the same thing, but let's say:

```<code>df %>%
mutate(group=cumsum(Speed==0.1)) %>%
group_by(group) %>%
mutate(Number=cumsum(Speed>5))

# A tibble: 20 x 3
# Groups:   group [2]
   Speed Number group
   <dbl>  <int> <int>
 1   0.1      0     1
 2   0.2      0     1
 3   1.2      0     1
 4   1.5      0     1
 5   2.8      0     1
 6   5.5      1     1
 7   5.6      2     1
 8   5.7      3     1
 9   5.8      4     1
10   5.9      5     1
11   0.1      0     2
12   0.2      0     2
13   1.2      0     2
14   1.5      0     2
15   2.8      0     2
16   5.5      1     2
17   5.6      2     2
18   5.7      3     2
19   5.8      4     2
20   5.9      5     2
</code>```

And to get min and max:

```<code>df %>%
mutate(group=cumsum(Speed==0.1)) %>%
group_by(group) %>%
mutate(Number=cumsum(Speed>5)) %>%
filter(Number>0) %>%
summarise(start=min(Speed),end=max(Speed))

# A tibble: 2 x 3
  group start   end
  <int> <dbl> <dbl>
1     1   5.5   5.9
2     2   5.5   5.9
</code>```

Body:
Is there a way where I could get this desired output using mutate()? The idea is to count the number of consecutive values above 5.5 in each sequence of the Speed column. Ideally, it would also be best to get a function that could determine a "Start" and "End." E.g. in this example it would START at 5.5 and END at 5.9.

Speed <- c(0.1, 0.2, 1.2, 1.5, 2.8, 5.5, 5.6, 5.7, 5.8, 5.9, 0.1, 0.2, 1.2, 1.5, 2.8, 5.5, 5.6, 5.7, 5.8, 5.9)
Number <- c(0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5)

df <- data.frame(Speed, Number)
df

     Speed Number
    1    0.1      0
    2    0.2      0
    3    1.2      0
    4    1.5      0
    5    2.8      0
    6    5.5      1
    7    5.6      2
    8    5.7      3
    9    5.8      4
    10   5.9      5
    11   0.1      0
    12   0.2      0
    13   1.2      0
    14   1.5      0
    15   2.8      0
    16   5.5      1
    17   5.6      2
    18   5.7      3
    19   5.8      4
    20   5.9      5

Body:
You need a group to demarcate your different speeds, your example is basically a repetition of the same thing, but let's say:

df %>%
mutate(group=cumsum(Speed==0.1)) %>%
group_by(group) %>%
mutate(Number=cumsum(Speed>5))

# A tibble: 20 x 3
# Groups:   group [2]
   Speed Number group
   <dbl>  <int> <int>
 1   0.1      0     1
 2   0.2      0     1
 3   1.2      0     1
 4   1.5      0     1
 5   2.8      0     1
 6   5.5      1     1
 7   5.6      2     1
 8   5.7      3     1
 9   5.8      4     1
10   5.9      5     1
11   0.1      0     2
12   0.2      0     2
13   1.2      0     2
14   1.5      0     2
15   2.8      0     2
16   5.5      1     2
17   5.6      2     2
18   5.7      3     2
19   5.8      4     2
20   5.9      5     2

And to get min and max:

df %>%
mutate(group=cumsum(Speed==0.1)) %>%
group_by(group) %>%
mutate(Number=cumsum(Speed>5)) %>%
filter(Number>0) %>%
summarise(start=min(Speed),end=max(Speed))

# A tibble: 2 x 3
  group start   end
  <int> <dbl> <dbl>
1     1   5.5   5.9
2     2   5.5   5.9


问:
JQuery replace async:false with promise with classes
I have a custom template class/object, combining JQuery and plain JS.

```<code>function tplObject (url) {
  this.type = "tplObject";
  this.includePath = "tpl/";
  this.url;
  this.template;
  this.output;
  this.openTpl (url);
}
tplObject.prototype = {
  openTpl: function (url) {
    if (url.split(".").length == 1) url = url + '.tpl';
    this.url = url;
    $.ajax ({
      origin: this,
      type: "GET",
      url: this.includePath + url + '?' + window.config.cacheVersion,
      async: false,
      success: function (reply) {
        this.origin.template = reply;
        this.origin.output = reply;
      }
    });
  },
...lots of functions that manipulate this.output;
  getOutput: function () {
    this._clear();
    return this.output;
  },

</code>```

I can manipulate the tpl objects, or fill one with the other, repeat fills, ect., like this:

```<code>var tpl1 = new tplObject ('tplFile');
tpl.changeVar ('from', 'to');
var tpl2 = new tplObject ('tplPart');
tpl1.fill (tpl2);
$('body').html(tpl1.getOutput());
</code>```

I have been trying different approaches using promises and waits, but I cannot get the script to wait in the main stream until the openTpl function has responded.

I would love to use fetch(), as I also use a service worker. Than the response could be cached, so I wouldn't have to reload when I want to manipulate a new version of the template.

Any help will be very welcome!

Kind regard Ingrid

答:
Making the whole function asynchonous would be alot of work. So in the mean time, I have made this old style declare-your-variables-first approach.

```<code>function fetchResources(processList) {
  return Promise.all(
    Object.keys(processList).map(function (i) {
      var obj = processList[i];
      return fetch(obj.fetchUrl)
      .then(r => r.text())
      .then(function (data) {
        obj.setData (data);
        return obj;
      })
      .catch(error => ({ error, obj }))
    })
  )
}
</code>```

The setData is called on the original object.
To be applied like so.

```<code>fetchResources ([
  tpl1 = new tplObject ('tplFile'),
  tpl2 = new tplObject ('tplPart')
]).then (function () {
  tpl1.changeVar ('from', 'to');
  tpl1.fill (tpl2);
  $('body').html(tpl1.getOutput());
});
</code>```

Body:
I have a custom template class/object, combining JQuery and plain JS.

function tplObject (url) {
  this.type = "tplObject";
  this.includePath = "tpl/";
  this.url;
  this.template;
  this.output;
  this.openTpl (url);
}
tplObject.prototype = {
  openTpl: function (url) {
    if (url.split(".").length == 1) url = url + '.tpl';
    this.url = url;
    $.ajax ({
      origin: this,
      type: "GET",
      url: this.includePath + url + '?' + window.config.cacheVersion,
      async: false,
      success: function (reply) {
        this.origin.template = reply;
        this.origin.output = reply;
      }
    });
  },
...lots of functions that manipulate this.output;
  getOutput: function () {
    this._clear();
    return this.output;
  },

I can manipulate the tpl objects, or fill one with the other, repeat fills, ect., like this:

var tpl1 = new tplObject ('tplFile');
tpl.changeVar ('from', 'to');
var tpl2 = new tplObject ('tplPart');
tpl1.fill (tpl2);
$('body').html(tpl1.getOutput());

I have been trying different approaches using promises and waits, but I cannot get the script to wait in the main stream until the openTpl function has responded.

I would love to use fetch(), as I also use a service worker. Than the response could be cached, so I wouldn't have to reload when I want to manipulate a new version of the template.

Any help will be very welcome!

Kind regard Ingrid

Body:
Making the whole function asynchonous would be alot of work. So in the mean time, I have made this old style declare-your-variables-first approach.

function fetchResources(processList) {
  return Promise.all(
    Object.keys(processList).map(function (i) {
      var obj = processList[i];
      return fetch(obj.fetchUrl)
      .then(r => r.text())
      .then(function (data) {
        obj.setData (data);
        return obj;
      })
      .catch(error => ({ error, obj }))
    })
  )
}

The setData is called on the original object.
To be applied like so.

fetchResources ([
  tpl1 = new tplObject ('tplFile'),
  tpl2 = new tplObject ('tplPart')
]).then (function () {
  tpl1.changeVar ('from', 'to');
  tpl1.fill (tpl2);
  $('body').html(tpl1.getOutput());
});


问:
jammit-s3 conflict with aws-s3
If I have both gems I get the error:

```<code>uninitialized constant AWS::S3::Connection
</code>```

I need both as I'm uploading to S3 with Paperclip and uploading my jammit assets to S3. How to solve?

答:
Try this in your Gemfile:</p>

```<code>gem 'jammit-s3', :git => "git://github.com/kmamykin/jammit-s3.git", :branch => "aws-s3"
</code>```

Title: jammit-s3 conflict with aws-s3

Body:
If I have both gems I get the error:

uninitialized constant AWS::S3::Connection

I need both as I'm uploading to S3 with Paperclip and uploading my jammit assets to S3. How to solve?

Body:
Try this in your Gemfile:

gem 'jammit-s3', :git => "git://github.com/kmamykin/jammit-s3.git", :branch => "aws-s3"