问:
Problem with OSM Map OpenLayers 5 : the map won't show
The OSM map won't show anymore with Openlayers 5
I tried to added from ol.source.OSM() but a grey map shown.</p>

```<code>  var map3 = new ol.Map({
      layers:  new ol.layer.Tile({
        source: new ol.source.OSM()
      }) ,
    target: 'map-id3',
    view: new ol.View({
      center:ol.proj.fromLonLat([10.74,34.77]),
      zoom:12
    })

  });
</code>```

答:
layers must be an array

```<code>  layers: [ new ol.layer.Tile({
    source: new ol.source.OSM()
  }) ],
</code>```

Body:
The OSM map won't show anymore with Openlayers 5
I tried to added from ol.source.OSM() but a grey map shown.

  var map3 = new ol.Map({
      layers:  new ol.layer.Tile({
        source: new ol.source.OSM()
      }) ,
    target: 'map-id3',
    view: new ol.View({
      center:ol.proj.fromLonLat([10.74,34.77]),
      zoom:12
    })

  });

Body:
layers must be an array

  layers: [ new ol.layer.Tile({
    source: new ol.source.OSM()
  }) ],


来源: stackexchange

问:
How to make Jmeter recognize "localhost" URL?
How to do performance testing of localhost url which is accessible only to my computer?

I am able to do performance testing using jmeter for live websites like google etc but jmeter is not able to detect local url.
URL of application-192.168.121.20:8001

2. Output of View Results Tree listener- ALL failed http alerts                                                       Description of screenshot of HTTP Request sampler- added only server name i.e URL –

答:
Get your ip addres using ipconfig (windows)

Think your URL is - http://192.168.8.149:3000/api/user/showTeams

Use Server Name or IP -192.168.8.149
Use Port Number - 3000
Use Protocol - http
Use Path - api/user/showTeams

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Separate columns by their strings if they are different
I have a data frame, and I want to spli their columns if they contain different strings or words.

I am tryng different methods in R and it is not working

My data frame looks like this:

```<code>df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"), y = c("TAP1", "TAP2", "TAP2", "TAP3" ))
</code>```

And, for example, I am trying with the first column this:

```<code>df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"))
df %>% separate(x, c("TAP1", "TAP2"), extra = "drop", fill = "right")
</code>```

but is not working

I am having the next output:

```<code>TAP1 TAP2
1 <NA> <NA>
2 TAP1 <NA>
3 TAP1 <NA>
4 TAP2 <NA>
</code>```

My expected output is:

```<code> TAP1 TAP2
1 <NA> <NA>
2 TAP1 <NA>
3 TAP1 <NA>
4 <NA> TAP2
</code>```

And I would like to do the same for all columns in the complete data frame where I have different combinations of words like TAP1, TAP2, TAP3 ... etc.

In this example, the final table taking in to account column x and y would be.

```<code> df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"), y = c("TAP1", "TAP2",   "TAP2", "TAP3" ))

  TAP1 TAP2 TAP1.1 TAP2.2 TAP3.3
1 <NA> <NA> TAP1   <NA>   <NA>
2 TAP1 <NA> <NA>   TAP2   <NA>
3 TAP1 <NA> <NA>   TAP2   <NA>
4 <NA> TAP2 <NA>   <NA>   TAP3
</code>```

答:
We can do this with spread

```<code>library(tidyverse)
df %>%
   mutate(n = row_number()) %>%
   group_by(x) %>%
   mutate(rn = row_number(), y = x) %>%
   spread(y, x) %>%
   select(TAP1, TAP2)
# A tibble: 4 x 2
#  TAP1  TAP2
#  <fct> <fct>
#1 <NA>  <NA>
#2 TAP1  <NA>
#3 TAP1  <NA>
#4 <NA>  TAP2
</code>```

With multiple columns, we can gather and spread

```<code>rownames_to_column(df, 'rn') %>%
   gather(key, val, -rn) %>%
   mutate(val1 = val) %>%
   unite(val, val,key) %>%
   group_by(val) %>%    # not really need for this example
   mutate(ind = row_number()) %>% # not needed here though
   spread(val, val1) %>%
   select(starts_with("TAP"))
# A tibble: 4 x 5
# TAP1_x TAP1_y TAP2_x TAP2_y TAP3_y
#  <chr>  <chr>  <chr>  <chr>  <chr>
#1 <NA>   TAP1   <NA>   <NA>   <NA>
#2 TAP1   <NA>   <NA>   TAP2   <NA>
#3 TAP1   <NA>   <NA>   TAP2   <NA>
#4 <NA>   <NA>   TAP2   <NA>   TAP3
</code>```

Body:
I have a data frame, and I want to spli their columns if they contain different strings or words.

I am tryng different methods in R and it is not working

My data frame looks like this:

df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"), y = c("TAP1", "TAP2", "TAP2", "TAP3" ))

And, for example, I am trying with the first column this:

df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"))
df %>% separate(x, c("TAP1", "TAP2"), extra = "drop", fill = "right")

but is not working

I am having the next output:

TAP1 TAP2
1 <NA> <NA>
2 TAP1 <NA>
3 TAP1 <NA>
4 TAP2 <NA>

My expected output is:

 TAP1 TAP2
1 <NA> <NA>
2 TAP1 <NA>
3 TAP1 <NA>
4 <NA> TAP2

And I would like to do the same for all columns in the complete data frame where I have different combinations of words like TAP1, TAP2, TAP3 ... etc.

In this example, the final table taking in to account column x and y would be.

 df <- data.frame(x = c(NA, "TAP1", "TAP1", "TAP2"), y = c("TAP1", "TAP2",   "TAP2", "TAP3" ))

  TAP1 TAP2 TAP1.1 TAP2.2 TAP3.3
1 <NA> <NA> TAP1   <NA>   <NA>
2 TAP1 <NA> <NA>   TAP2   <NA>
3 TAP1 <NA> <NA>   TAP2   <NA>
4 <NA> TAP2 <NA>   <NA>   TAP3

Body:
We can do this with spread

library(tidyverse)
df %>%
   mutate(n = row_number()) %>%
   group_by(x) %>%
   mutate(rn = row_number(), y = x) %>%
   spread(y, x) %>%
   select(TAP1, TAP2)
# A tibble: 4 x 2
#  TAP1  TAP2
#  <fct> <fct>
#1 <NA>  <NA>
#2 TAP1  <NA>
#3 TAP1  <NA>
#4 <NA>  TAP2

With multiple columns, we can gather and spread

rownames_to_column(df, 'rn') %>%
   gather(key, val, -rn) %>%
   mutate(val1 = val) %>%
   unite(val, val,key) %>%
   group_by(val) %>%    # not really need for this example
   mutate(ind = row_number()) %>% # not needed here though
   spread(val, val1) %>%
   select(starts_with("TAP"))
# A tibble: 4 x 5
# TAP1_x TAP1_y TAP2_x TAP2_y TAP3_y
#  <chr>  <chr>  <chr>  <chr>  <chr>
#1 <NA>   TAP1   <NA>   <NA>   <NA>
#2 TAP1   <NA>   <NA>   TAP2   <NA>
#3 TAP1   <NA>   <NA>   TAP2   <NA>
#4 <NA>   <NA>   TAP2   <NA>   TAP3


问:
how to play video in asp.net with thumbnail support?
friends,

i am using asp.net 2.0
my requirement is  when form is loaded it should show thumbnail of video in that control first and then on play button click streaming should start.

any one guide me is this possible or not ?
any help would be appreciated.

答:
i ended up this problem by using youtubescript library.
youtube provide video gallery script for asp.net and other languages as well.</p>

ContentLicense: CC BY-SA 2.5


问:
Make Python wait until to_sql has finished
I'm using to_sql to export my dataframe into a SQL Server table however I want to delay the execution of the next line of python code until the insertion has been completed.

I have a OKish understanding of database connections but I'm a bit of a noob when trying to understand how python and sql server communicate.

```<code>engine = db.create_engine('mssql+pyodbc://username:password@ServerName/Database?driver=SQL+Server+Native+Client+11.0')

df.to_sql('Table', engine, schema = 'dbo', if_exists='append',index=False)

#Don't execute this until all the records have been added
print("All my records have been added to SQL")
</code>```

Any help would be greatly appreciated.

Thanks

答: Finally got it working as wasn't using autocommit = true</p>

Body:
I'm using to_sql to export my dataframe into a SQL Server table however I want to delay the execution of the next line of python code until the insertion has been completed.

I have a OKish understanding of database connections but I'm a bit of a noob when trying to understand how python and sql server communicate.

engine = db.create_engine('mssql+pyodbc://username:password@ServerName/Database?driver=SQL+Server+Native+Client+11.0')

df.to_sql('Table', engine, schema = 'dbo', if_exists='append',index=False)

#Don't execute this until all the records have been added
print("All my records have been added to SQL")

Any help would be greatly appreciated.

Thanks


问:
http-server with localhost:3000 gives ERR_INVALID_REDIRECT
I have installed http-server using the following command:

npm i -g http-server

Upon running the server I get the response saying Running on 127.0.0.1:8080

My call looks like this:

http-server -a 0.0.0.0 -c-1

If I go to 127.0.0.1:8080 or 10.1.1.72:8080 I get:

This page is not working.

127.0.0.1:8080 sent an invalid response

ERR_INVALID_REDIRECT

I have googled and searched everywhere with no answer as to what actually solves this. I'm not using XAMPP or IIS just a blank node server.

Node.js: 11.12.0

npm: 6.7.0

OS: Windows 10

I have checked my host files, there is nothing relevant there. I have no idea what would be causing this. I don't use .htaccess files or Web.config files either.

Notes

If I go to localhost:8080/index.html I can get to my app. This isn't supposed to work like that though.

答: pass url "0.0.0.0" when you are creating server and then try.</p>


问:
Is there a better way to change button display in javascript/Vue?
After writing so many if else, I feel very tired. I'm using Vue. The following code are written in the script section of the vue file. I get a json from file, and then read the values in json, then set what button should be display based on employee level and on application status. Is there a better way to change the button display status in Vue?

```<code>if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
        (this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")) ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        (this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")) ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")
    ) {
      this.pullDisplay = true;
    } else {
      this.pullDisplay = false;
    };

    if (
      this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising"
    ) {
      this.cancelDisplay = true;
    } else {
      this.cancelDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending")
    ) {
      this.saveDisplay = true;
    } else {
      this.saveDisplay = false;
    };

    if (
      this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising"
    ) {
      this.reviseDisplay = true;
    } else {
      this.reviseDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending")
    ) {
      this.sendDisplay = true;
    } else {
      this.sendDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking")
    ) {
      this.approvalDisplay = true;
    } else {
      this.approvalDisplay = false;
    };
</code>```

And also there are a few ones need three conditions:

```<code>    if (
      this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].requestCategory ==
        "External Request" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus ==
        "Pending"
    ) {
      this.returnDisplay = true;
    } else {
      this.returnDisplay = false;
    }
</code>```

答:
Going with a configuration based approach will make your code much more easy to edit and to read.</p>

```<code>const levels = {
  '1': {
    pullDisplayStatus: ['Checking', 'Pending', 'Approved'],
    cancelDisplayStatus: ['Revising'],
    saveDisplayStatus: ['Revising'],
    reviseDisplayStatus: ['Revising'],
    sendDisplayStatus: [],
    approvalDisplayStatus: [],
  },
  '2': {
    pullDisplayStatus: ['Pending', 'Approved'],
    cancelDisplayStatus: [],
    saveDisplayStatus: ['Checking'],
    reviseDisplayStatus: [],
    sendDisplayStatus: ['Checking'],
    approvalDisplayStatus: ['Checking'],
  },
  '3': {
    pullDisplayStatus: ['Approved'],
    cancelDisplayStatus: [],
    saveDisplayStatus: ['Pending'],
    reviseDisplayStatus: [],
    sendDisplayStatus: ['Pending'],
    approvalDisplayStatus: ['Pending'],
  },
}

const jsonForGlobal = this.GLOBAL2.jsonForGlobal;
const currentStatus = jsonForGlobal.detail[this.detailId].currentStatus;
const level = levels[jsonForGlobal.employeeLevel];
this.pullDisplay = level.pullDisplayStatus.indexOf(currentStatus) > -1;
this.cancelDisplay = level.cancelDisplayStatus.indexOf(currentStatus) > -1;
this.saveDisplay = level.cancelDisplayStatus.indexOf(currentStatus) > -1;
this.reviseDisplay = level.reviseDisplayStatus.indexOf(currentStatus) > -1;
this.sendDisplay = level.reviseDisplayStatus.indexOf(currentStatus) > -1;
</code>```

Body:
After writing so many if else, I feel very tired. I'm using Vue. The following code are written in the script section of the vue file. I get a json from file, and then read the values in json, then set what button should be display based on employee level and on application status. Is there a better way to change the button display status in Vue?

if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
        (this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")) ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        (this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending" ||
          this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")) ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Approved")
    ) {
      this.pullDisplay = true;
    } else {
      this.pullDisplay = false;
    };

    if (
      this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising"
    ) {
      this.cancelDisplay = true;
    } else {
      this.cancelDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending")
    ) {
      this.saveDisplay = true;
    } else {
      this.saveDisplay = false;
    };

    if (
      this.GLOBAL2.jsonForGlobal.employeeLevel == "1" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Revising"
    ) {
      this.reviseDisplay = true;
    } else {
      this.reviseDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending")
    ) {
      this.sendDisplay = true;
    } else {
      this.sendDisplay = false;
    };

    if (
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Pending") ||
      (this.GLOBAL2.jsonForGlobal.employeeLevel == "2" &&
        this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus == "Checking")
    ) {
      this.approvalDisplay = true;
    } else {
      this.approvalDisplay = false;
    };

And also there are a few ones need three conditions:

    if (
      this.GLOBAL2.jsonForGlobal.employeeLevel == "3" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].requestCategory ==
        "External Request" &&
      this.GLOBAL2.jsonForGlobal.detail[this.detailId].currentStatus ==
        "Pending"
    ) {
      this.returnDisplay = true;
    } else {
      this.returnDisplay = false;
    }

Body:
Going with a configuration based approach will make your code much more easy to edit and to read.

const levels = {
  '1': {
    pullDisplayStatus: ['Checking', 'Pending', 'Approved'],
    cancelDisplayStatus: ['Revising'],
    saveDisplayStatus: ['Revising'],
    reviseDisplayStatus: ['Revising'],
    sendDisplayStatus: [],
    approvalDisplayStatus: [],
  },
  '2': {
    pullDisplayStatus: ['Pending', 'Approved'],
    cancelDisplayStatus: [],
    saveDisplayStatus: ['Checking'],
    reviseDisplayStatus: [],
    sendDisplayStatus: ['Checking'],
    approvalDisplayStatus: ['Checking'],
  },
  '3': {
    pullDisplayStatus: ['Approved'],
    cancelDisplayStatus: [],
    saveDisplayStatus: ['Pending'],
    reviseDisplayStatus: [],
    sendDisplayStatus: ['Pending'],
    approvalDisplayStatus: ['Pending'],
  },
}

const jsonForGlobal = this.GLOBAL2.jsonForGlobal;
const currentStatus = jsonForGlobal.detail[this.detailId].currentStatus;
const level = levels[jsonForGlobal.employeeLevel];
this.pullDisplay = level.pullDisplayStatus.indexOf(currentStatus) > -1;
this.cancelDisplay = level.cancelDisplayStatus.indexOf(currentStatus) > -1;
this.saveDisplay = level.cancelDisplayStatus.indexOf(currentStatus) > -1;
this.reviseDisplay = level.reviseDisplayStatus.indexOf(currentStatus) > -1;
this.sendDisplay = level.reviseDisplayStatus.indexOf(currentStatus) > -1;


问:
Vim and Ctags tips and tricks
I have just installed Ctags (to help with C++ development) with my Vim (or rather gVim), and would like to find out your favorite commands, macros, shortcuts, tips that go along with it...

Share your best arsenal. What other Vim add-ons you would recommend for C++ on Vim development?

EDIT What other add-on you would use in conjunction with Ctags?

EDIT2 What version of gVim you use with tags? Does it make a difference?

EDIT3 How do you enhance your programming experience for both big and small projects?

答: The command I am using most is C-] which jumps to the definition of the function under the cursor. You can use it more often to follow more calls. After that, C-o will bring you back one level, C-i goes deeper again.</p>

OwnerDisplayName: Sasha

LastEditorDisplayName: Sasha

Title: Vim and Ctags tips and tricks

OwnerDisplayName: Raim


问:
C++ Heap Corruption
I haven't done any C++ in a while, but decided to finish a big project I was working on for someone. I am getting the following error message now though...

HEAP CORRUPTION DETECTED: after Normal Block (#1761) at 0x17DEB940.
CRT Detected that the application wrote to memory after end of heap buffer.

I have been stepping through all of the functions I thought might have caused it but I am at a loss. Is there any way using the more advanced debugging features to hunt this down?

答:
Try using AppVerifier with normal pageheap enabled. If you then attach a debugger to the process and have a heap corruption with some luck it will break at the point where the memory block gets corrupted (by a block write overrun or underrun). With a little effort you can also get a callstack of the code that allocated every heap block, something that can also help to track down the error.

Tracking these errors can be tricky though, for detailed information check the Advanced Windows Debugging book which has a whole chapter devoted to the subject.

Title: C++ Heap Corruption


问:
Get position with variable and then modify specific object in mongodb
How can I make this query use my variable instead of the hard coded 0?</p>

```<code>let pos = 0;

{$set: {'answers.0.acknowledged': data}}
</code>```

答:
You can use ES6 String Interpolation and Computed Property Names to build the key for $set:

let pos = 0;
let data = 'some data';
let q = {$set: {[`answers.${pos}.acknowledged`]: data}}
console.log(q);```

Body:
How can I make this query use my variable instead of the hard coded 0?

let pos = 0;

{$set: {'answers.0.acknowledged': data}}


问:
Artifactory - hide the "last downloaded" info
We are using the Artifactory tool to distribute gradle files and other artifacts to customers, secured by a per customer login.
However, if those customers get Webapp access (which they need to for example change their passwords) they can see all repositories and artifacts they have (read) access to, including WHO last downloaded the file. </p>

<p>Is there any way of changing this, besides building our own password change site? </p>

答:
Right now there is no way to remove the "Last Downloaded" information from the JFrog Artifactory screen. If that is a requirement you have, you can always reach out to the JFrog support team to have them log an enhancement request.

As an alternative, if you really want to use Artifactory for this use case, you might want to consider giving each customer their own repository and only giving them access to that repo. Artifactory stores files only once. The first time a file is uploaded, Artifactory calculates a checksum and stores the file accordingly (including putting a record in a database). If files are uploaded again, or copied to multiple destinations, only the database is updated to create a record mapping the file's checksum to its new location as well. On the positive side, you've got the artifacts stored once and your customers only see their own repo. On the down side, you'll end up with many more repos in Artifactory.

Body:
We are using the Artifactory tool to distribute gradle files and other artifacts to customers, secured by a per customer login.
However, if those customers get Webapp access (which they need to for example change their passwords) they can see all repositories and artifacts they have (read) access to, including WHO last downloaded the file.

Is there any way of changing this, besides building our own password change site?


问:
Add method inside command using dispatchCommand
I am trying to insert method that provides a random string out of an array and execute it in a Minecraft command.

The error

It says that java: 'void' type not allowed here when adding + operator inbetween the strings with the method randomKey().

I develope the plugin inside IntelliJ.

```<code>public class events implements Listener{

    public static void main(String[] args)
    {
        randomKey();
    }

    public static void randomKey(){
        String[] crates ={"Basic", "Classic", "Crazy", "Galactic"};
        Random random = new Random();
        int RandomNumber = random.nextInt(crates.length);
        System.out.println(crates[RandomNumber]);
    }

    @EventHandler
    public  void keyGiver(BlockBreakEvent event ){

        //get block type grass

        Block block = event.getBlock();
        Material material  = block.getType();

        Player player = event.getPlayer();

        if(material.equals(Material.GRASS)){

            getServer().dispatchCommand(getServer().getConsoleSender(), "cc give Physical"+randomKey()+" 1 " + player.getName() + " ");
        }

    }```
```

答:
you have to return something in order to use a function in an expression,
this is the fix which I recommend base on your code :</p>

```<code>public static String randomKey(){
    String[] crates ={"Basic", "Classic", "Crazy", "Galactic"};
    Random random = new Random();
    int RandomNumber = random.nextInt(crates.length);
    System.out.println(crates[RandomNumber]);
    return crates[RandomNumber];
}
</code>```

Body:
I am trying to insert method that provides a random string out of an array and execute it in a Minecraft command.

The error

It says that java: 'void' type not allowed here when adding + operator inbetween the strings with the method randomKey().

I develope the plugin inside IntelliJ.

public class events implements Listener{

    public static void main(String[] args)
    {
        randomKey();
    }

    public static void randomKey(){
        String[] crates ={"Basic", "Classic", "Crazy", "Galactic"};
        Random random = new Random();
        int RandomNumber = random.nextInt(crates.length);
        System.out.println(crates[RandomNumber]);
    }

    @EventHandler
    public  void keyGiver(BlockBreakEvent event ){

        //get block type grass

        Block block = event.getBlock();
        Material material  = block.getType();

        Player player = event.getPlayer();

        if(material.equals(Material.GRASS)){

            getServer().dispatchCommand(getServer().getConsoleSender(), "cc give Physical"+randomKey()+" 1 " + player.getName() + " ");
        }

    }```

Body:
you have to return something in order to use a function in an expression,
this is the fix which I recommend base on your code :

public static String randomKey(){
    String[] crates ={"Basic", "Classic", "Crazy", "Galactic"};
    Random random = new Random();
    int RandomNumber = random.nextInt(crates.length);
    System.out.println(crates[RandomNumber]);
    return crates[RandomNumber];
}


问:
Copy some data from a database and keep referential integrity
The requirement is to extract some data from an active database (159 tables at the moment) into another database, such that the copied data has full referential integrity, whilst the data is in flux (it is a live database). This is not about dumping the entire database (approaching 50GB), just extracting some rows that we have identified from the whole database into a separate database.

We currently create a new DB based upon our initial schema and subsequent DDL migrations and repeatables (views, stored procedures, etc.), and then
copy the appropriate rows. This normally takes more than 10 minutes, but less than 1 hour, depending upon the size of the set to be extracted.

Is there a way to tell mysql that I want ignore any transactions committed after I start running the extract, be they new rows added, rows deleted, or rows updated, but any other connection to the database just carries on working as normal, as if I wasn't making any requests.

What I don't want to have happen is I copy data from table 1 and by the time I get to table 159, table 1 has changed and a row in table 159 refers to that new row in table 1.

答:
Use mysqldump --single-transaction. This starts a repeatable-read transaction before it starts dumping data, so any concurrent transactions that happen while you are dumping data don't affect the data dumped by your transaction.

Re your updated question:

You can do your own custom queries in a transaction.

Start a transaction in repeatable-read mode before you begin running queries for your extraction. You can run many queries against many tables, and all the data you extract will be exactly what was currently committed as of the moment you started that transaction.

You might like to read https://dev.mysql.com/doc/refman/8.0/en/innodb-transaction-isolation-levels.html


问:
Google App Script and PropertiesService.getUserProperties()
I use the google app script in my google spreadsheet document.

The settings of each user of my spreadsheet doc is saved in:

```<code>var userProperties = PropertiesService.getUserProperties();.
</code>```

To save the settings I use

```<code>PropertiesService.getUserProperties()setProperties({some properties}, true)
</code>```

The problem is the first user saves his settings and another users get the settings of the first user using PropertiesService.getUserProperties()
But they should not, they should get own settings.

Do you have any idea how it is possible?

答:
In fact as the support answered me, it is not a bug. I had wrong user properties on handling triggering event.

User properties are private to the user executing the script. However, when you setup an installable onEdit trigger, the code always runs as the user that setup the trigger:

"... runs with the authorization of the user who created the trigger, even if another user with edit access opens the spreadsheet."
https://developers.google.com/apps-script/guides/triggers/installable
Since the code always runs as the same user, it's always accessing the same user properties. In general it's not possible to get the identity of a user if they haven't authorized the script.

Body:
I use the google app script in my google spreadsheet document.

The settings of each user of my spreadsheet doc is saved in:

var userProperties = PropertiesService.getUserProperties();.

To save the settings I use

PropertiesService.getUserProperties()setProperties({some properties}, true)

The problem is the first user saves his settings and another users get the settings of the first user using PropertiesService.getUserProperties()
But they should not, they should get own settings.

Do you have any idea how it is possible?


问:
Why is NAudio creating a WAV file that's twice the size it should be?
I'm using this fairly standard code sample to mix multiple WAV files into one output file (Dispose calls omitted for clarity):

public static void MixAudioFiles(IEnumerable<FileObject> input, FileObject output)
{
    var mixer = new WaveMixerStream32 { AutoStop = true };

    foreach (var file in input)
    {
        var reader = new WaveFileReader(file.FullName);

        mixer.AddInputStream(new WaveChannel32(reader));
    }

    WaveFileWriter.CreateWaveFile(output.FullName, new Wave32To16Stream(mixer));
}
```

But the output file is always twice the size of the input file, despite the use of Wave32To16Stream.

What am I missing here?

答:
Thanks, Mark, that pointed me in the right direction. For anyone else with this issue, here's the working code:

```<code>    public static void MixAudioFiles(IEnumerable<string> input, string output)
    {
        var wf = new WaveFormat(16000, 1);

        var mixer = new NAudio.Wave.SampleProviders.MixingSampleProvider(WaveFormat.CreateIeeeFloatWaveFormat(wf.SampleRate, wf.Channels));

        foreach (var file in input)
        {
            var reader = new WaveFileReader(file);

            mixer.AddMixerInput(reader);
        }

        //write the mix file
        WaveFileWriter.CreateWaveFile16(output, mixer);
}
</code>```

Note that I've omitted the Dispose calls. Make sure to add these to prevent resource leaks.

Body:
I'm using this fairly standard code sample to mix multiple WAV files into one output file (Dispose calls omitted for clarity):

public static void MixAudioFiles(IEnumerable<FileObject> input, FileObject output)
{
    var mixer = new WaveMixerStream32 { AutoStop = true };

    foreach (var file in input)
    {
        var reader = new WaveFileReader(file.FullName);

        mixer.AddInputStream(new WaveChannel32(reader));
    }

    WaveFileWriter.CreateWaveFile(output.FullName, new Wave32To16Stream(mixer));
}

But the output file is always twice the size of the input file, despite the use of Wave32To16Stream.

What am I missing here?

Body:
Thanks, Mark, that pointed me in the right direction. For anyone else with this issue, here's the working code:

    public static void MixAudioFiles(IEnumerable<string> input, string output)
    {
        var wf = new WaveFormat(16000, 1);

        var mixer = new NAudio.Wave.SampleProviders.MixingSampleProvider(WaveFormat.CreateIeeeFloatWaveFormat(wf.SampleRate, wf.Channels));

        foreach (var file in input)
        {
            var reader = new WaveFileReader(file);

            mixer.AddMixerInput(reader);
        }

        //write the mix file
        WaveFileWriter.CreateWaveFile16(output, mixer);
}

Note that I've omitted the Dispose calls. Make sure to add these to prevent resource leaks.


问:
Why is it not the same?
I newbie in scala and I have two pieces of code:

```<code>private val uploadImageTypeValidator = validator[(UploadImageRequest, DriverSession)] { case (r, s) =>
    val sessionType = SessionType.fromValue(s.`type`)
    r.`type` is sessionImageTypeValidators(sessionType)
  }
</code>```

and

```<code> private val uploadImageTypeValidator = validator[(UploadImageRequest, DriverSession)] { case (r, s) =>
    r.`type` is sessionImageTypeValidators(SessionType.fromValue(s.`type`))
  }
</code>```

I've just copy SessionType.fromValue(s.type) into func call.

Getting error:

```<code>Error:(53, 5) not found: value r
    r.`type` is sessionImageTypeValidators(SessionType.fromValue(s.`type`))
Error:(53, 66) not found: value s
    r.`type` is sessionImageTypeValidators(SessionType.fromValue(s.`type`))
</code>```

Why the second code does not compile? It Works only with val

答:
This is because of macros written by developers of Accord validation library.

With scalacOptions += "-Ymacro-debug-lite" in build.sbt the first piece of code

```<code>private val uploadImageTypeValidator0 = validator[(UploadImageRequest, DriverSession)] { case (r, s) =>
  val sessionType = SessionType.fromValue(s.`type`)
  r.`type` is sessionImageTypeValidators(sessionType)
}
</code>```

produces

```<code>Warning:scalac: performing macro expansion com.wix.accord.dsl.`package`.validator[(App.UploadImageRequest, App.DriverSession)](((x0$1: (App.UploadImageRequest, App.DriverSession)) => x0$1 match {
  case (_1: App.UploadImageRequest, _2: App.DriverSession)(App.UploadImageRequest, App.DriverSession)((r @ _), (s @ _)) => {
    val sessionType: App.SessionType = App.this.SessionType.fromValue(s.`type`);
    {
      com.wix.accord.dsl.`package`.Contextualizer[String](r.`type`).is(App.this.sessionImageTypeValidators(sessionType));
      ()
    }
  }
})) at source-/media/data/Projects/accord_validation_demo/src/main/scala/App.scala,line-6,offset=164
Warning:scalac:
Warning:scalac: new com.wix.accord.transform.ValidationTransform.TransformedValidator(new com.wix.accord.combinators.Conditional[(App.UploadImageRequest, App.DriverSession)](Seq(), None))
Apply(Select(New(Select(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("transform")), TermName("ValidationTransform")), TypeName("TransformedValidator"))), termNames.CONSTRUCTOR), List(Apply(Select(New(AppliedTypeTree(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("combinators")), TypeName("Conditional")), List(TypeTree()))), termNames.CONSTRUCTOR), List(Apply(Ident(TermName("Seq")), List()), Ident(TermName("None"))))))
</code>```

But the second piece of code

```<code>private val uploadImageTypeValidator = validator[(UploadImageRequest, DriverSession)] { case (r, s) =>
  r.`type` is sessionImageTypeValidators(SessionType.fromValue(s.`type`))
}
</code>```

produces

```<code>Warning:scalac: performing macro expansion com.wix.accord.dsl.`package`.validator[(App.UploadImageRequest, App.DriverSession)](((x0$1: (App.UploadImageRequest, App.DriverSession)) => x0$1 match {
  case (_1: App.UploadImageRequest, _2: App.DriverSession)(App.UploadImageRequest, App.DriverSession)((r @ _), (s @ _)) => {
    com.wix.accord.dsl.`package`.Contextualizer[String](r.`type`).is(App.this.sessionImageTypeValidators(App.this.SessionType.fromValue(s.`type`)));
    ()
  }
})) at source-/media/data/Projects/accord_validation_demo/src/main/scala/App.scala,line-11,offset=392
Warning:scalac:
Warning:scalac: new com.wix.accord.transform.ValidationTransform.TransformedValidator(new com.wix.accord.combinators.Conditional[(App.UploadImageRequest, App.DriverSession)](Seq(((x0$1: (App.UploadImageRequest, App.DriverSession)) => x0$1 match {
  case (_1: App.UploadImageRequest, _2: App.DriverSession)(App.UploadImageRequest, App.DriverSession)((r @ _), (s @ _)) => true
  case _ => false
}).$minus$greater({
  final class $anon extends com.wix.accord.Validator[(App.UploadImageRequest, App.DriverSession)] {
    def <init>() = {
      super.<init>();
      ()
    };
    import com.wix.accord.DescriptionBuilders._;
    def apply(x0$1: (App.UploadImageRequest, App.DriverSession)) = {
      val validation$0 = com.wix.accord.dsl.`package`.Contextualizer[String](r.`type`).is(App.this.sessionImageTypeValidators(App.this.SessionType.fromValue(s.`type`)));
      val path$0 = {
        <synthetic> <artifact> val x$1 = com.wix.accord.Descriptions.PatternMatch(on = com.wix.accord.Descriptions.Path(), value = x0$1, guard = scala.None);
        com.wix.accord.Descriptions.Path(com.wix.accord.Descriptions.Generic("r.`type`")).$plus$colon(x$1)
      };
      validation$0(r.`type`).prepend(path$0)
    }
  };
  new $anon()
})), None))
Apply(Select(New(Select(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("transform")), TermName("ValidationTransform")), TypeName("TransformedValidator"))), termNames.CONSTRUCTOR), List(Apply(Select(New(AppliedTypeTree(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("combinators")), TypeName("Conditional")), List(TypeTree()))), termNames.CONSTRUCTOR), List(Apply(Ident(TermName("Seq")), List(Apply(Select(Function(List(ValDef(Modifiers(PARAM | SYNTHETIC), TermName("x0$1"), TypeTree(), EmptyTree)), Match(Ident(TermName("x0$1")), List(CaseDef(Apply(TypeTree().setOriginal(Select(Ident(scala), scala.Tuple2)), List(Bind(TermName("r"), Ident(termNames.WILDCARD)), Bind(TermName("s"), Ident(termNames.WILDCARD)))), EmptyTree, Literal(Constant(true))), CaseDef(Ident(termNames.WILDCARD), EmptyTree, Literal(Constant(false)))))), TermName("$minus$greater")), List(Block(List(ClassDef(Modifiers(FINAL), TypeName("$anon"), List(), Template(List(AppliedTypeTree(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TypeName("Validator")), List(TypeTree()))), noSelfType, List(DefDef(Modifiers(), termNames.CONSTRUCTOR, List(), List(List()), TypeTree(), Block(List(pendingSuperCall), Literal(Constant(())))), Import(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("DescriptionBuilders")), List(ImportSelector(termNames.WILDCARD, -1, null, -1))), DefDef(Modifiers(), TermName("apply"), List(), List(List(ValDef(Modifiers(PARAM | SYNTHETIC), TermName("x0$1"), TypeTree(), EmptyTree))), TypeTree(), Block(List(ValDef(Modifiers(), TermName("validation$0"), TypeTree(), Apply(Select(Apply(TypeApply(Select(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("dsl")), termNames.PACKAGE), TermName("Contextualizer")), List(TypeTree())), List(Select(Ident(TermName("r")), TermName("type")))), TermName("is")), List(Apply(Select(This(TypeName("App")), TermName("sessionImageTypeValidators")), List(Apply(Select(Select(This(TypeName("App")), TermName("SessionType")), TermName("fromValue")), List(Select(Ident(TermName("s")), TermName("type"))))))))), ValDef(Modifiers(), TermName("path$0"), TypeTree(), Block(List(ValDef(Modifiers(SYNTHETIC | ARTIFACT), TermName("x$1"), TypeTree(), Apply(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("Descriptions")), TermName("PatternMatch")), List(AssignOrNamedArg(Ident(TermName("on")), Apply(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("Descriptions")), TermName("Path")), List())), AssignOrNamedArg(Ident(TermName("value")), Ident(TermName("x0$1"))), AssignOrNamedArg(Ident(TermName("guard")), Select(Ident(TermName("scala")), TermName("None"))))))), Apply(Select(Apply(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("Descriptions")), TermName("Path")), List(Apply(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("Descriptions")), TermName("Generic")), List(Literal(Constant("r.`type`")))))), TermName("$plus$colon")), List(Ident(TermName("x$1"))))))), Apply(Select(Apply(Ident(TermName("validation$0")), List(Select(Ident(TermName("r")), TermName("type")))), TermName("prepend")), List(Ident(TermName("path$0")))))))))), Apply(Select(New(Ident(TypeName("$anon"))), termNames.CONSTRUCTOR), List())))))), Ident(TermName("None"))))))
</code>```

Here

```<code>val validation$0 = com.wix.accord.dsl.Contextualizer[String](r.`type`).is(App.this.sessionImageTypeValidators(App.this.SessionType.fromValue(s.`type`)));
</code>```

you can see r, s out of their scope.

So the thing is that Accord macros have bugs. They don't expect code like the second piece but expect code like the first piece.

Title: Why is it not the same?

Body:
I newbie in scala and I have two pieces of code:

private val uploadImageTypeValidator = validator[(UploadImageRequest, DriverSession)] { case (r, s) =>
    val sessionType = SessionType.fromValue(s.`type`)
    r.`type` is sessionImageTypeValidators(sessionType)
  }

and

 private val uploadImageTypeValidator = validator[(UploadImageRequest, DriverSession)] { case (r, s) =>
    r.`type` is sessionImageTypeValidators(SessionType.fromValue(s.`type`))
  }

I've just copy SessionType.fromValue(s.type) into func call.

Getting error:

Error:(53, 5) not found: value r
    r.`type` is sessionImageTypeValidators(SessionType.fromValue(s.`type`))
Error:(53, 66) not found: value s
    r.`type` is sessionImageTypeValidators(SessionType.fromValue(s.`type`))

Why the second code does not compile? It Works only with val

Body:
This is because of macros written by developers of Accord validation library.

With scalacOptions += "-Ymacro-debug-lite" in build.sbt the first piece of code

private val uploadImageTypeValidator0 = validator[(UploadImageRequest, DriverSession)] { case (r, s) =>
  val sessionType = SessionType.fromValue(s.`type`)
  r.`type` is sessionImageTypeValidators(sessionType)
}

produces

Warning:scalac: performing macro expansion com.wix.accord.dsl.`package`.validator[(App.UploadImageRequest, App.DriverSession)](((x0$1: (App.UploadImageRequest, App.DriverSession)) => x0$1 match {
  case (_1: App.UploadImageRequest, _2: App.DriverSession)(App.UploadImageRequest, App.DriverSession)((r @ _), (s @ _)) => {
    val sessionType: App.SessionType = App.this.SessionType.fromValue(s.`type`);
    {
      com.wix.accord.dsl.`package`.Contextualizer[String](r.`type`).is(App.this.sessionImageTypeValidators(sessionType));
      ()
    }
  }
})) at source-/media/data/Projects/accord_validation_demo/src/main/scala/App.scala,line-6,offset=164
Warning:scalac:
Warning:scalac: new com.wix.accord.transform.ValidationTransform.TransformedValidator(new com.wix.accord.combinators.Conditional[(App.UploadImageRequest, App.DriverSession)](Seq(), None))
Apply(Select(New(Select(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("transform")), TermName("ValidationTransform")), TypeName("TransformedValidator"))), termNames.CONSTRUCTOR), List(Apply(Select(New(AppliedTypeTree(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("combinators")), TypeName("Conditional")), List(TypeTree()))), termNames.CONSTRUCTOR), List(Apply(Ident(TermName("Seq")), List()), Ident(TermName("None"))))))

But the second piece of code

private val uploadImageTypeValidator = validator[(UploadImageRequest, DriverSession)] { case (r, s) =>
  r.`type` is sessionImageTypeValidators(SessionType.fromValue(s.`type`))
}

produces

Warning:scalac: performing macro expansion com.wix.accord.dsl.`package`.validator[(App.UploadImageRequest, App.DriverSession)](((x0$1: (App.UploadImageRequest, App.DriverSession)) => x0$1 match {
  case (_1: App.UploadImageRequest, _2: App.DriverSession)(App.UploadImageRequest, App.DriverSession)((r @ _), (s @ _)) => {
    com.wix.accord.dsl.`package`.Contextualizer[String](r.`type`).is(App.this.sessionImageTypeValidators(App.this.SessionType.fromValue(s.`type`)));
    ()
  }
})) at source-/media/data/Projects/accord_validation_demo/src/main/scala/App.scala,line-11,offset=392
Warning:scalac:
Warning:scalac: new com.wix.accord.transform.ValidationTransform.TransformedValidator(new com.wix.accord.combinators.Conditional[(App.UploadImageRequest, App.DriverSession)](Seq(((x0$1: (App.UploadImageRequest, App.DriverSession)) => x0$1 match {
  case (_1: App.UploadImageRequest, _2: App.DriverSession)(App.UploadImageRequest, App.DriverSession)((r @ _), (s @ _)) => true
  case _ => false
}).$minus$greater({
  final class $anon extends com.wix.accord.Validator[(App.UploadImageRequest, App.DriverSession)] {
    def <init>() = {
      super.<init>();
      ()
    };
    import com.wix.accord.DescriptionBuilders._;
    def apply(x0$1: (App.UploadImageRequest, App.DriverSession)) = {
      val validation$0 = com.wix.accord.dsl.`package`.Contextualizer[String](r.`type`).is(App.this.sessionImageTypeValidators(App.this.SessionType.fromValue(s.`type`)));
      val path$0 = {
        <synthetic> <artifact> val x$1 = com.wix.accord.Descriptions.PatternMatch(on = com.wix.accord.Descriptions.Path(), value = x0$1, guard = scala.None);
        com.wix.accord.Descriptions.Path(com.wix.accord.Descriptions.Generic("r.`type`")).$plus$colon(x$1)
      };
      validation$0(r.`type`).prepend(path$0)
    }
  };
  new $anon()
})), None))
Apply(Select(New(Select(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("transform")), TermName("ValidationTransform")), TypeName("TransformedValidator"))), termNames.CONSTRUCTOR), List(Apply(Select(New(AppliedTypeTree(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("combinators")), TypeName("Conditional")), List(TypeTree()))), termNames.CONSTRUCTOR), List(Apply(Ident(TermName("Seq")), List(Apply(Select(Function(List(ValDef(Modifiers(PARAM | SYNTHETIC), TermName("x0$1"), TypeTree(), EmptyTree)), Match(Ident(TermName("x0$1")), List(CaseDef(Apply(TypeTree().setOriginal(Select(Ident(scala), scala.Tuple2)), List(Bind(TermName("r"), Ident(termNames.WILDCARD)), Bind(TermName("s"), Ident(termNames.WILDCARD)))), EmptyTree, Literal(Constant(true))), CaseDef(Ident(termNames.WILDCARD), EmptyTree, Literal(Constant(false)))))), TermName("$minus$greater")), List(Block(List(ClassDef(Modifiers(FINAL), TypeName("$anon"), List(), Template(List(AppliedTypeTree(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TypeName("Validator")), List(TypeTree()))), noSelfType, List(DefDef(Modifiers(), termNames.CONSTRUCTOR, List(), List(List()), TypeTree(), Block(List(pendingSuperCall), Literal(Constant(())))), Import(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("DescriptionBuilders")), List(ImportSelector(termNames.WILDCARD, -1, null, -1))), DefDef(Modifiers(), TermName("apply"), List(), List(List(ValDef(Modifiers(PARAM | SYNTHETIC), TermName("x0$1"), TypeTree(), EmptyTree))), TypeTree(), Block(List(ValDef(Modifiers(), TermName("validation$0"), TypeTree(), Apply(Select(Apply(TypeApply(Select(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("dsl")), termNames.PACKAGE), TermName("Contextualizer")), List(TypeTree())), List(Select(Ident(TermName("r")), TermName("type")))), TermName("is")), List(Apply(Select(This(TypeName("App")), TermName("sessionImageTypeValidators")), List(Apply(Select(Select(This(TypeName("App")), TermName("SessionType")), TermName("fromValue")), List(Select(Ident(TermName("s")), TermName("type"))))))))), ValDef(Modifiers(), TermName("path$0"), TypeTree(), Block(List(ValDef(Modifiers(SYNTHETIC | ARTIFACT), TermName("x$1"), TypeTree(), Apply(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("Descriptions")), TermName("PatternMatch")), List(AssignOrNamedArg(Ident(TermName("on")), Apply(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("Descriptions")), TermName("Path")), List())), AssignOrNamedArg(Ident(TermName("value")), Ident(TermName("x0$1"))), AssignOrNamedArg(Ident(TermName("guard")), Select(Ident(TermName("scala")), TermName("None"))))))), Apply(Select(Apply(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("Descriptions")), TermName("Path")), List(Apply(Select(Select(Select(Select(Ident(TermName("com")), TermName("wix")), TermName("accord")), TermName("Descriptions")), TermName("Generic")), List(Literal(Constant("r.`type`")))))), TermName("$plus$colon")), List(Ident(TermName("x$1"))))))), Apply(Select(Apply(Ident(TermName("validation$0")), List(Select(Ident(TermName("r")), TermName("type")))), TermName("prepend")), List(Ident(TermName("path$0")))))))))), Apply(Select(New(Ident(TypeName("$anon"))), termNames.CONSTRUCTOR), List())))))), Ident(TermName("None"))))))

Here

val validation$0 = com.wix.accord.dsl.Contextualizer[String](r.`type`).is(App.this.sessionImageTypeValidators(App.this.SessionType.fromValue(s.`type`)));

you can see r, s out of their scope.

So the thing is that Accord macros have bugs. They don't expect code like the second piece but expect code like the first piece.


问:
How to find neighboring records in the SQL table in terms of month and year?
Please help me to optimize my SQL query.

I have a table with the fields: date, commodity_id, exp_month_id, exp_year, price, where the first 4 fields are the primary key. The months are designated with the alphabet-ordered letters: e.g. F (for Jan), G (for Feb.), H (for March), etc. Thus the letter of more distant from Jan. month will be larger than the letter of the less distant month (F < G < H < ...). Some commodity_ids have all 12 months in the table, some only 5 or 3, which are constant for all years.

I need to calculate the difference between prices (gradient) of the neighboring records in terms of exp_month_id, exp_year. As the first step, I want to define for every couple (exp_month_id, exp_year) the valid couple (next_month_id, next_year). The main problem here, that if the current exp_month_id is the last in the year, then next_year = exp_year + 1 and next_month_id should be the first one in the year.

I have written the following query to do the job:

WITH trading_months AS (
    SELECT DISTINCT commodity_id,
                    exp_month_id
      FROM futures
     ORDER BY exp_month_id
)
SELECT DISTINCT f.commodity_id,
                f.exp_month_id,
                f.exp_year,
                (
                WITH [temp] AS (
                        SELECT exp_month_id
                          FROM trading_months
                         WHERE commodity_id = f.commodity_id
                    )
                    SELECT exp_month_id
                      FROM [temp]
                     WHERE exp_month_id > f.exp_month_id
                    UNION ALL
                    SELECT exp_month_id
                      FROM [temp]
                     LIMIT 1
                )
                AS next_month_id,
                (
                    SELECT CASE WHEN EXISTS (
                                   SELECT commodity_id,
                                          exp_month_id
                                     FROM trading_months
                                    WHERE commodity_id = f.commodity_id AND
                                          exp_month_id > f.exp_month_id
                                    LIMIT 1
                               )
                           THEN f.exp_year ELSE f.exp_year + 1 END
                )
                AS next_year
  FROM futures AS f
```

This query serves as a base for a dynamic table (view) which is subsequently used for calculating the gradient. However, the execution of this query takes more than one second and thus the whole process takes minutes. I wonder if you could help me optimizing the query.

答:
Note: The following requires Sqlite 3.25 or newer for window function support:

Lack of sample data (Preferably as a CREATE TABLE and INSERT statements for easy importing) and expected results makes it hard to test, but if your end goal is computing the difference in prices between expiration dates (Making your question a bit of an XY problem, maybe something like:

```<code>SELECT date, commodity_id, price, exp_year, exp_month_id
     , price - lag(price, 1) OVER (PARTITION BY commodity_id ORDER BY exp_year, exp_month_id) AS "change from last price"
FROM futures;
</code>```

Body:
Please help me to optimize my SQL query.

I have a table with the fields: date, commodity_id, exp_month_id, exp_year, price, where the first 4 fields are the primary key. The months are designated with the alphabet-ordered letters: e.g. F (for Jan), G (for Feb.), H (for March), etc. Thus the letter of more distant from Jan. month will be larger than the letter of the less distant month (F < G < H < ...). Some commodity_ids have all 12 months in the table, some only 5 or 3, which are constant for all years.

I need to calculate the difference between prices (gradient) of the neighboring records in terms of exp_month_id, exp_year. As the first step, I want to define for every couple (exp_month_id, exp_year) the valid couple (next_month_id, next_year). The main problem here, that if the current exp_month_id is the last in the year, then next_year = exp_year + 1 and next_month_id should be the first one in the year.

I have written the following query to do the job:

WITH trading_months AS (
    SELECT DISTINCT commodity_id,
                    exp_month_id
      FROM futures
     ORDER BY exp_month_id
)
SELECT DISTINCT f.commodity_id,
                f.exp_month_id,
                f.exp_year,
                (
                WITH [temp] AS (
                        SELECT exp_month_id
                          FROM trading_months
                         WHERE commodity_id = f.commodity_id
                    )
                    SELECT exp_month_id
                      FROM [temp]
                     WHERE exp_month_id > f.exp_month_id
                    UNION ALL
                    SELECT exp_month_id
                      FROM [temp]
                     LIMIT 1
                )
                AS next_month_id,
                (
                    SELECT CASE WHEN EXISTS (
                                   SELECT commodity_id,
                                          exp_month_id
                                     FROM trading_months
                                    WHERE commodity_id = f.commodity_id AND
                                          exp_month_id > f.exp_month_id
                                    LIMIT 1
                               )
                           THEN f.exp_year ELSE f.exp_year + 1 END
                )
                AS next_year
  FROM futures AS f

This query serves as a base for a dynamic table (view) which is subsequently used for calculating the gradient. However, the execution of this query takes more than one second and thus the whole process takes minutes. I wonder if you could help me optimizing the query.

Body:
Note: The following requires Sqlite 3.25 or newer for window function support:

Lack of sample data (Preferably as a CREATE TABLE and INSERT statements for easy importing) and expected results makes it hard to test, but if your end goal is computing the difference in prices between expiration dates (Making your question a bit of an XY problem, maybe something like:

SELECT date, commodity_id, price, exp_year, exp_month_id
     , price - lag(price, 1) OVER (PARTITION BY commodity_id ORDER BY exp_year, exp_month_id) AS "change from last price"
FROM futures;


问:
Extract Pattern Matches / Remove Everything From Line Except Pattern
I'm currently using grep to try to extract specific text from each line of a file. It's successfully extracting the matches, however, I would like it to retain any lines that don't have matches (leave them as a blank line).

This is what I've tried so far (to get the name of the city on each line):

```<code>grep -o -P '(?<="city":").*?(?=")' input.txt
</code>```

Example input:

```<code>email":"addictedtotlick7@gmail.com","last_name":"THOMPSON","first_name":"ERIN",,"__v":0,,,,"state":"NY","city":"north tonawanda"}
first_name":"chris","last_name":"caul",,"email":"dawgzn@mail.com",,,,"__v":0}
email":"lesliebo993@hotmail.com",,"first_name":"LESLIE","last_name":"RAMBO",,"city":"DOTHAN","state":"AL",,,"__v":0,
email":"malala@yahoo.com",,,"state":"GA","city":"NORCROSS",,"last_name":"KEO","first_name":"CATHY",,"__v":0,
email":"kdela@gmail.com",,"state":"FL","city":"HOLLYWOOD",,"last_name":"DE LA CRUZ","first_name":"KIDA",,"__v":0,
</code>```

Desired output:

```<code>north tonawanda

DOTHAN
NORCROSS
HOLLYWOOD
</code>```

Happy to try something in SED too if it's easier, but would prefer to avoid AWK as I have to work with big files, not sure I have enough RAM.

答:
You can try Perl</p>

```<code>$ perl -nle ' if(/"city":"(.*?)"/) { print $1 } else { print "" } ' input.txt
north tonawanda

DOTHAN
NORCROSS
HOLLYWOOD

$
</code>```

Body:
I'm currently using grep to try to extract specific text from each line of a file. It's successfully extracting the matches, however, I would like it to retain any lines that don't have matches (leave them as a blank line).

This is what I've tried so far (to get the name of the city on each line):

grep -o -P '(?<="city":").*?(?=")' input.txt

Example input:

email":"addictedtotlick7@gmail.com","last_name":"THOMPSON","first_name":"ERIN",,"__v":0,,,,"state":"NY","city":"north tonawanda"}
first_name":"chris","last_name":"caul",,"email":"dawgzn@mail.com",,,,"__v":0}
email":"lesliebo993@hotmail.com",,"first_name":"LESLIE","last_name":"RAMBO",,"city":"DOTHAN","state":"AL",,,"__v":0,
email":"malala@yahoo.com",,,"state":"GA","city":"NORCROSS",,"last_name":"KEO","first_name":"CATHY",,"__v":0,
email":"kdela@gmail.com",,"state":"FL","city":"HOLLYWOOD",,"last_name":"DE LA CRUZ","first_name":"KIDA",,"__v":0,

Desired output:

north tonawanda

DOTHAN
NORCROSS
HOLLYWOOD

Happy to try something in SED too if it's easier, but would prefer to avoid AWK as I have to work with big files, not sure I have enough RAM.

Body:
You can try Perl

$ perl -nle ' if(/"city":"(.*?)"/) { print $1 } else { print "" } ' input.txt
north tonawanda

DOTHAN
NORCROSS
HOLLYWOOD

$


问:
Getting permission denied issue after adding Maven bin to PATH variable, unable to add to PATH in root mode as well
I followed the steps mentioned in https://dzone.com/articles/installing-maven.

I am able to echo my mvn bin -

```<code>SandeepanNath:~ sandeepan.nath$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/bin:/opt/apache-maven/bin
</code>```

However, I am unable to run mvn commands still. I get permission denied -

```<code>SandeepanNath:~ sandeepan.nath$ mvn -v
-bash: /opt/apache-maven/bin/mvn: Permission denied
</code>```

If I try running after sudo, I again get command not found -

```<code>SandeepanNath:~ root# mvn -v
-sh: mvn: command not found
</code>```

I checked I don't have mvn path defined in $PATH variable in root mode. Do I need to add it here as well? I cannot find the .bash_profile for root though.

答: Your user needs to have execute rights on the /opt/apache-maven/bin/mvn

Body:
I followed the steps mentioned in https://dzone.com/articles/installing-maven.

I am able to echo my mvn bin -

SandeepanNath:~ sandeepan.nath$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/bin:/opt/apache-maven/bin

However, I am unable to run mvn commands still. I get permission denied -

SandeepanNath:~ sandeepan.nath$ mvn -v
-bash: /opt/apache-maven/bin/mvn: Permission denied

If I try running after sudo, I again get command not found -

SandeepanNath:~ root# mvn -v
-sh: mvn: command not found

I checked I don't have mvn path defined in $PATH variable in root mode. Do I need to add it here as well? I cannot find the .bash_profile for root though.


问:
Contains function in pandas dataframe column (AttributeError: 'str' object has no attribute 'str'
I'm trying to search in string in dataframe column by using contains

1.

```<code>for idx, row in df.iterrows():
  if(row['name'].str.contains('abc')):
</code>```

the above code throw this error

```<code>AttributeError: 'str' object has no attribute 'str'
</code>```

2.

```<code>for idx, row in df.iterrows():
      if(row['name'].contains('abc')):
</code>```

and the second code throw this error

```<code>AttributeError: 'str' object has no attribute 'contains'
</code>```

答: row['Name'] will return a string not a pandas series so you can't use .str.contains Instead of looping row by row you can apply it to the whole column df['row'].str.contains('abc') This will return a series of type bool.

Body:
I'm trying to search in string in dataframe column by using contains

1.

for idx, row in df.iterrows():
  if(row['name'].str.contains('abc')):

the above code throw this error

AttributeError: 'str' object has no attribute 'str'

2.

for idx, row in df.iterrows():
      if(row['name'].contains('abc')):

and the second code throw this error

AttributeError: 'str' object has no attribute 'contains'


问:
How to check if all lessons have been viewed
I want to define a method (complete) that returns true if a user has watched all lessons of a course. Right now the method only returns false even if all the lessons are viewed.

User model:

```<code>has_many :enrolments, dependent: :destroy
has_many :courses, through: :enrolments
has_many :views
has_many :lessons, through: :views

def enrol(course)
  courses << course
end

def enrolled?(course)
  courses.include?(course)
end

def view(lesson)
  lessons << lesson
end

def viewed?(lesson)
  lessons.include?(lesson)
end

def complete(course)
  if self.viewed?(course.lessons.all)
    return true
  else
    return false
  end
end
</code>```

Lesson Model:

```<code>belongs_to :course
has_one_attached :file
default_scope -> { order(created_at: :desc) }
has_many :views
has_many :users, through: :views
</code>```

Course Model:

```<code>belongs_to :company
has_many :lessons, dependent: :destroy
default_scope -> { order(created_at: :desc) }
has_many :enrolments, dependent: :destroy
has_many :users, through: :enrolments
</code>```

View Model:

```<code>belongs_to :user
belongs_to :lesson
</code>```

答:
Your viewed? checks only for a single lesson, but you're passing a relation there.

For this case it's sufficient to compare arrays with lessons ids:

def complete(course)
  lessons.where(course: course).ids.sort == course.lessons.ids.sort
end
```

Body:
I want to define a method (complete) that returns true if a user has watched all lessons of a course. Right now the method only returns false even if all the lessons are viewed.

User model:

has_many :enrolments, dependent: :destroy
has_many :courses, through: :enrolments
has_many :views
has_many :lessons, through: :views

def enrol(course)
  courses << course
end

def enrolled?(course)
  courses.include?(course)
end

def view(lesson)
  lessons << lesson
end

def viewed?(lesson)
  lessons.include?(lesson)
end

def complete(course)
  if self.viewed?(course.lessons.all)
    return true
  else
    return false
  end
end

Lesson Model:

belongs_to :course
has_one_attached :file
default_scope -> { order(created_at: :desc) }
has_many :views
has_many :users, through: :views

Course Model:

belongs_to :company
has_many :lessons, dependent: :destroy
default_scope -> { order(created_at: :desc) }
has_many :enrolments, dependent: :destroy
has_many :users, through: :enrolments

View Model:

belongs_to :user
belongs_to :lesson


问:
Why is the code in the thread executed twice?
As indicated in the title, why is the following code executed twice (2x Test in the console) and how to fix it?

```<code>type
  TSelfThread = class(TThread)
    procedure Execute; override;
end;

procedure TSelfThread.Execute;
begin
  Writeln('Test');
end;

var
  SelfThread : TSelfThread;
begin
  try
    SelfThread := TSelfThread.Create(False);
  except
    on E: Exception do
      Writeln('Error');
  end;
end.
</code>```

答:
The only possible explanation for this behaviour is the bug in your code where you fail to wait for the thread to complete before terminating the process.

Change the code to be like this:

```<code>SelfThread := TSelfThread.Create(False);
SelfThread.WaitFor;
</code>```

Body:
As indicated in the title, why is the following code executed twice (2x Test in the console) and how to fix it?

type
  TSelfThread = class(TThread)
    procedure Execute; override;
end;

procedure TSelfThread.Execute;
begin
  Writeln('Test');
end;

var
  SelfThread : TSelfThread;
begin
  try
    SelfThread := TSelfThread.Create(False);
  except
    on E: Exception do
      Writeln('Error');
  end;
end.

Body:
The only possible explanation for this behaviour is the bug in your code where you fail to wait for the thread to complete before terminating the process.

Change the code to be like this:

SelfThread := TSelfThread.Create(False);
SelfThread.WaitFor;


问:
Login using PHP to protect from downloading a file
Can I use PHP to protect someone from downloading a file unless he enters a username and password just like the sample image?

sample: http://up.iranblog.com/images/f1ufuir6kl8srq4ww4.jpg

答:
If you want to protect filedownload you could go with the following code. All files in the file folder will be protected. This is an extremly basic example and has a lot of flaws, but it might point you in the right direction.

.htaccess

```<code>RewriteRule ^/file/(.*)   /handleFiles.php?path=$1  [L]
</code>```

handleFiles.php

```<code><?
$auth = 0;
if (!isset($PHP_AUTH_USER))
{
    header('WWW-Authenticate: Basic realm="Login"');
    header('HTTP/1.0 401 Unauthorized');
    print "you need to login";
    exit;
}
else
{
    if ($PHP_AUTH_USER == "UserName" and $PHP_AUTH_PW == "Password")
    {
        $auth=1;
        $file = implode('', file('/file/'.$path);
        print $file;
        exit;
    }
    else
    {
        header('WWW-Authenticate: Basic realm="Login"');
        header('HTTP/1.0 401 Unauthorized');
        print "you need to login";
        exit;
    }
}

if ($auth==0) {
    print "you need to login";
    exit;
}
</code>```

?>

Body:
If you want to protect filedownload you could go with the following code. All files in the file folder will be protected. This is an extremly basic example and has a lot of flaws, but it might point you in the right direction.

.htaccess

RewriteRule ^/file/(.*)   /handleFiles.php?path=$1  [L]

handleFiles.php

<?
$auth = 0;
if (!isset($PHP_AUTH_USER))
{
    header('WWW-Authenticate: Basic realm="Login"');
    header('HTTP/1.0 401 Unauthorized');
    print "you need to login";
    exit;
}
else
{
    if ($PHP_AUTH_USER == "UserName" and $PHP_AUTH_PW == "Password")
    {
        $auth=1;
        $file = implode('', file('/file/'.$path);
        print $file;
        exit;
    }
    else
    {
        header('WWW-Authenticate: Basic realm="Login"');
        header('HTTP/1.0 401 Unauthorized');
        print "you need to login";
        exit;
    }
}

if ($auth==0) {
    print "you need to login";
    exit;
}

?>


问:
MySQL: How to add depended records to view
I have two tables:

goods

```<code>id parent_id name
1  null      main_part
2  1         add_part1
3  1         add_part2
4  1         add_part3
</code>```

orders

```<code>id good_id  count
1  1        5
</code>```

I want to get a view as :

orders_view

```<code>id  good_id count
1   1        5
2   2        5
3   3        5
4   4        5
</code>```

How to do in MySQL?

答:
If your relation is a single level  you could try joining the subquery for the union with the orders  </p>

```<code>select  t1.id, t1.id good_id,  o.count
from  (
    select id id_master, id
    from goods
    where parent_id is null
    union all
    select parent_id, id
    where  parent_id is not  null
) t
inner join  orders_view o on o.good_id = t1.id_master
</code>```

Body:
I have two tables:

goods

id parent_id name
1  null      main_part
2  1         add_part1
3  1         add_part2
4  1         add_part3

orders

id good_id  count
1  1        5

I want to get a view as :

orders_view

id  good_id count
1   1        5
2   2        5
3   3        5
4   4        5

How to do in MySQL?

Body:
If your relation is a single level  you could try joining the subquery for the union with the orders

select  t1.id, t1.id good_id,  o.count
from  (
    select id id_master, id
    from goods
    where parent_id is null
    union all
    select parent_id, id
    where  parent_id is not  null
) t
inner join  orders_view o on o.good_id = t1.id_master


问:
How to pass data from a master array to multiple arrays in PHP
I have an array with subarrays, each subarray has 'type' (int) and a 'datetime'. I need to loop trought the array and create new arrays (or objects) with groups of these subarrays in a special way: every 'type' could be [0-3] 0 means startdate and 3 means enddate (1 and 2 are in between for other purposes). Every new array with these subarrays should start with 0 and end with 3.

Im not using any framework, only PHP5 and jQuery. The master array comes from a loop I made from a SQL query with GROUP_CONCAT. I just passed the concat fields to a master array but I need to regroup the subarrays to create some type of registries.

Here is the array I got with subarrays. They are already sorted by datetime, every type '0' means "start date / start new registry" and '3' means "end date / end registry".

```<code>$array = [
["tipo"=>0,"fechahora"=>"2019-05-26 09:35:30"],
["tipo"=>1,"fechahora"=>"2019-05-26 10:30:15"],
["tipo"=>2,"fechahora"=>"2019-05-26 10:43:12"],
["tipo"=>3,"fechahora"=>"2019-05-26 14:30:26"],
["tipo"=>0,"fechahora"=>"2019-05-26 15:35:22"],
["tipo"=>3,"fechahora"=>"2019-05-26 16:35:31"],
["tipo"=>0,"fechahora"=>"2019-05-27 08:31:57"],
["tipo"=>1,"fechahora"=>"2019-05-27 10:27:22"],
["tipo"=>2,"fechahora"=>"2019-05-27 10:38:31"],
["tipo"=>3,"fechahora"=>"2019-05-27 14:20:38"],
["tipo"=>0,"fechahora"=>"2019-05-28 09:39:42"],
["tipo"=>1,"fechahora"=>"2019-05-28 11:43:08"],
["tipo"=>2,"fechahora"=>"2019-05-28 11:53:19"],
["tipo"=>3,"fechahora"=>"2019-05-28 14:43:31"],
["tipo"=>0,"fechahora"=>"2019-05-29 10:30:22"],
["tipo"=>3,"fechahora"=>"2019-05-29 14:38:46"]
];
</code>```

I need to create a new array with subarrays or objects by registry, a registry is an element who have startdate (type 0), somedates in between (type 1,2) and a enddate (type 3). Its important The next subarray have the startdate more current than the older subarray enddate. Every "tipo"+"fechahora" array have more fields (signature, address, etc) so I need to keep these as subarrays:

```<code>$newarray = [
    'registry0' => [
            "startdate"=> ["tipo"=>0,"fechahora"=>"2019-05-26 09:35:30"],
            "pauses"=> [
                ["tipo"=>1,"fechahora"=>"2019-05-26 10:30:15"],
                ["tipo"=>2,"fechahora"=>"2019-05-26 10:43:12"]
            ],
            "enddate" => ["tipo"=>3,"fechahora"=>"2019-05-26 14:30:26"]
        ],
    'registry1' => [
            "startdate"=> ["tipo"=>0,"fechahora"=>"2019-05-26 15:35:22"],
            "pauses"=> [],
            "enddate" => ["tipo"=>3,"fechahora"=>"2019-05-26 16:35:31"]
        ],
    'registry2' => [
            "startdate"=> ["tipo"=>0,"fechahora"=>"2019-05-27 08:31:57"],
            "pauses"=> [
                ["tipo"=>1,"fechahora"=>"2019-05-27 10:27:22"],
                ["tipo"=>2,"fechahora"=>"2019-05-27 10:38:31"]
            ],
            "enddate" => ["tipo"=>3,"fechahora"=>"2019-05-27 14:20:38"]
    ]
];
</code>```

I could use arrays or objects, I dont know hot to develop a loop to regroup arrays like this (starting at one field value and ending with another and so on). I dont even know if there is a simpler way. Any help would be appreciated.

If this could help: I need the registries this way to put into an HTML table, each registry in a row.

EDIT:

Iknow I have to use a loop but I dont know how to "get first element with type 0, create an array, include element, include all other element until type 3, close array, create new array and so on..."

In some code:

```<code>$newarray = [];
foreach($array as $element) {
if ($element["tipo"]==0) {
  //new subarray
  //include this in subarray
}
// include all "tipos" 1,2 in subarray
if ($element["tipo"]==3) {
  //include this in subarray
  //finish subarray
}
//incude subarray in $newarray
}
return $newarray;
</code>```

I dont know how to continue.

答:
It is just a case of looping over each of the original array values and creating an entry in a temporary array ($temp in this case) with any values according to type.  Then when a type 3 is found, adding this to the $newarray...

```<code>$newarray = [];
$temp = [];
$count = 0;
foreach ( $array as $entry )    {
    if ( $entry['tipo'] == 0 )  {
        $temp = [ 'startdate' => $entry ];
    }
    else if ( $entry['tipo'] == 3 ) {
        $temp["enddate"] = $entry;
        $newarray["registry".$count++] = $temp;
    }
    else    {
        $temp["pauses"][] = $entry;
    }
}
</code>```

Body:
I have an array with subarrays, each subarray has 'type' (int) and a 'datetime'. I need to loop trought the array and create new arrays (or objects) with groups of these subarrays in a special way: every 'type' could be [0-3] 0 means startdate and 3 means enddate (1 and 2 are in between for other purposes). Every new array with these subarrays should start with 0 and end with 3.

Im not using any framework, only PHP5 and jQuery. The master array comes from a loop I made from a SQL query with GROUP_CONCAT. I just passed the concat fields to a master array but I need to regroup the subarrays to create some type of registries.

Here is the array I got with subarrays. They are already sorted by datetime, every type '0' means "start date / start new registry" and '3' means "end date / end registry".

$array = [
["tipo"=>0,"fechahora"=>"2019-05-26 09:35:30"],
["tipo"=>1,"fechahora"=>"2019-05-26 10:30:15"],
["tipo"=>2,"fechahora"=>"2019-05-26 10:43:12"],
["tipo"=>3,"fechahora"=>"2019-05-26 14:30:26"],
["tipo"=>0,"fechahora"=>"2019-05-26 15:35:22"],
["tipo"=>3,"fechahora"=>"2019-05-26 16:35:31"],
["tipo"=>0,"fechahora"=>"2019-05-27 08:31:57"],
["tipo"=>1,"fechahora"=>"2019-05-27 10:27:22"],
["tipo"=>2,"fechahora"=>"2019-05-27 10:38:31"],
["tipo"=>3,"fechahora"=>"2019-05-27 14:20:38"],
["tipo"=>0,"fechahora"=>"2019-05-28 09:39:42"],
["tipo"=>1,"fechahora"=>"2019-05-28 11:43:08"],
["tipo"=>2,"fechahora"=>"2019-05-28 11:53:19"],
["tipo"=>3,"fechahora"=>"2019-05-28 14:43:31"],
["tipo"=>0,"fechahora"=>"2019-05-29 10:30:22"],
["tipo"=>3,"fechahora"=>"2019-05-29 14:38:46"]
];

I need to create a new array with subarrays or objects by registry, a registry is an element who have startdate (type 0), somedates in between (type 1,2) and a enddate (type 3). Its important The next subarray have the startdate more current than the older subarray enddate. Every "tipo"+"fechahora" array have more fields (signature, address, etc) so I need to keep these as subarrays:

$newarray = [
    'registry0' => [
            "startdate"=> ["tipo"=>0,"fechahora"=>"2019-05-26 09:35:30"],
            "pauses"=> [
                ["tipo"=>1,"fechahora"=>"2019-05-26 10:30:15"],
                ["tipo"=>2,"fechahora"=>"2019-05-26 10:43:12"]
            ],
            "enddate" => ["tipo"=>3,"fechahora"=>"2019-05-26 14:30:26"]
        ],
    'registry1' => [
            "startdate"=> ["tipo"=>0,"fechahora"=>"2019-05-26 15:35:22"],
            "pauses"=> [],
            "enddate" => ["tipo"=>3,"fechahora"=>"2019-05-26 16:35:31"]
        ],
    'registry2' => [
            "startdate"=> ["tipo"=>0,"fechahora"=>"2019-05-27 08:31:57"],
            "pauses"=> [
                ["tipo"=>1,"fechahora"=>"2019-05-27 10:27:22"],
                ["tipo"=>2,"fechahora"=>"2019-05-27 10:38:31"]
            ],
            "enddate" => ["tipo"=>3,"fechahora"=>"2019-05-27 14:20:38"]
    ]
];

I could use arrays or objects, I dont know hot to develop a loop to regroup arrays like this (starting at one field value and ending with another and so on). I dont even know if there is a simpler way. Any help would be appreciated.

If this could help: I need the registries this way to put into an HTML table, each registry in a row.

EDIT:

Iknow I have to use a loop but I dont know how to "get first element with type 0, create an array, include element, include all other element until type 3, close array, create new array and so on..."

In some code:

$newarray = [];
foreach($array as $element) {
if ($element["tipo"]==0) {
  //new subarray
  //include this in subarray
}
// include all "tipos" 1,2 in subarray
if ($element["tipo"]==3) {
  //include this in subarray
  //finish subarray
}
//incude subarray in $newarray
}
return $newarray;

I dont know how to continue.

Body:
It is just a case of looping over each of the original array values and creating an entry in a temporary array ($temp in this case) with any values according to type.  Then when a type 3 is found, adding this to the $newarray...

$newarray = [];
$temp = [];
$count = 0;
foreach ( $array as $entry )    {
    if ( $entry['tipo'] == 0 )  {
        $temp = [ 'startdate' => $entry ];
    }
    else if ( $entry['tipo'] == 3 ) {
        $temp["enddate"] = $entry;
        $newarray["registry".$count++] = $temp;
    }
    else    {
        $temp["pauses"][] = $entry;
    }
}


问:
wrapping text disappearing after giving overflow hidden
to fix the wrapping issue of this text ---> testing the be Bhere I am here I am here I am here I am here I
                am testing the be Bhere I am here I am here I am here I am here
                I am 12 34 56 78 90 123 456 7778 88889 9999 999690909090

I used overflow: "hidden" in the class right_box.

wrapping text got fixed.

but when i decrease the screen size I am seeing some of the texts are getting hidden.

I googled and found line height will fix it,

so I gave it in the two classes  sportsCardHeaderItemHeadingValue and right_box

but still its not fixing.

can you tell me how to fix it.

providing code snippet and sandbox below.

https://codesandbox.io/s/material-demo-e89n0

sportsCardHeaderItemHeadingValue: {
    fontWeight: "bold",
    fontSize: 20,
    color: "#263238",

    wordWrap: "break-word",
    lineHeight: 1.2
  },

 right_box: {
    border: "1px solid #000",
    // padding: 5,
    // background: '#ff0',
    marginTop: 8,
    marginRight: 8,
    float: "left",
    //  width: 150,
    height: 55,
    overflow: "hidden",
    lineHeight: 1.2
  },

              0
Sports

                testing the be Bhere I am here I am here I am here I am here I
                am testing the be Bhere I am here I am here I am here I am here
                I am 12 34 56 78 90 123 456 7778 88889 9999 999690909090

```

答:
There is a height set on right_box so it can't grow height-wise to fit content.  Also, when resizing the view to then restrict the width, it then overflows the content. When you add the CSS rule overflow:hidden; to right_box it then hides the overflow and you can't see it.

I commented out the height and overflow rules (approx lines 424-425) and now you can see the element expands to fill width and the height grows to fit content.

```<code>right_box: {
  border: '1px solid #000',
  // padding: 5,
  // background: '#ff0',
  marginTop: 8,
  marginRight: 8,
  float: 'left',
  //  width: 150,
  // height: 55, // don't restrict height
  // overflow: "hidden", // element can grow now so don't need to hide overflow
  lineHeight: 1.2,
},
</code>```

codesandbox

Body:
There is a height set on right_box so it can't grow height-wise to fit content.  Also, when resizing the view to then restrict the width, it then overflows the content. When you add the CSS rule overflow:hidden; to right_box it then hides the overflow and you can't see it.

I commented out the height and overflow rules (approx lines 424-425) and now you can see the element expands to fill width and the height grows to fit content.

right_box: {
  border: '1px solid #000',
  // padding: 5,
  // background: '#ff0',
  marginTop: 8,
  marginRight: 8,
  float: 'left',
  //  width: 150,
  // height: 55, // don't restrict height
  // overflow: "hidden", // element can grow now so don't need to hide overflow
  lineHeight: 1.2,
},

codesandbox


问:
Flyway and gradle kotlin dsl
I'm migrating from Gradle to Gradle Kotlin DSL, and I have a question.
Have

```<code>flyway {
    url = System.getenv ('DB_URL')
    user = System.getenv ('DB_USER')
    password = System.getenv ('DB_PASSWORD')
    baselineOnMigrate = true
    locations = ["filesystem: resources / db / migration"]
}
</code>```

In Gradle.

How would you look in Kotlin DSL?

答:
The code in the block is almost exactly the same in Kotlin as in Groovy, with two exceptions for what you have above:

Use double-quotes instead of single-quotes for the strings.

Use arrayOf instead of [...] for the array for the locations property.

In other words it would look as follows:

```<code>flyway {
    url = System.getenv("DB_URL")
    user = System.getenv("DB_USER")
    password = System.getenv("DB_PASSWORD")
    baselineOnMigrate = true
    locations = arrayOf("filesystem: resources / db / migration")
}
</code>```

Bear in mind that for the build file to understand the flyway function (and for the IDE to give you intellisense for what options are available in the block, etc.) you need to apply the Flyway plugin using the Gradle Plugins DSL, as follows at the top of your build.gradle.kts file:

```<code>plugins {
    id("org.flywaydb.flyway") version "5.2.4"
}
</code>```

Title: Flyway and gradle kotlin dsl

Body:
I'm migrating from Gradle to Gradle Kotlin DSL, and I have a question.
Have

flyway {
    url = System.getenv ('DB_URL')
    user = System.getenv ('DB_USER')
    password = System.getenv ('DB_PASSWORD')
    baselineOnMigrate = true
    locations = ["filesystem: resources / db / migration"]
}

In Gradle.

How would you look in Kotlin DSL?

Body:
The code in the block is almost exactly the same in Kotlin as in Groovy, with two exceptions for what you have above:

Use double-quotes instead of single-quotes for the strings.

Use arrayOf instead of [...] for the array for the locations property.

In other words it would look as follows:

flyway {
    url = System.getenv("DB_URL")
    user = System.getenv("DB_USER")
    password = System.getenv("DB_PASSWORD")
    baselineOnMigrate = true
    locations = arrayOf("filesystem: resources / db / migration")
}

Bear in mind that for the build file to understand the flyway function (and for the IDE to give you intellisense for what options are available in the block, etc.) you need to apply the Flyway plugin using the Gradle Plugins DSL, as follows at the top of your build.gradle.kts file:

plugins {
    id("org.flywaydb.flyway") version "5.2.4"
}


问:
python __init__ method in inherited class
I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an __init__ type method which does not override the __init__ method of the parent class?

I have written the code below purely to illustrate my question (hence the poor naming of attributes etc).

```<code>class initialclass():
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'

class inheritedclass(initialclass):
    def __new__(self):
        self.attr3 = 'three'

    def somemethod(self):
        print 'the method'

a = inheritedclass()

for each in a.__dict__:
    print each

#I would like the output to be:
attr1
attr2
attr3
</code>```

Thank you

答:
Just call the parent's __init__ using super:

```<code>class inheritedclass(initialclass):
    def __new__(self):
        self.attr3 = 'three'
        super(initialclass, self).__init__()
</code>```

I strongly advise to follow Python's naming conventions and start a class with a Capital letter, e.g. InheritedClass and InitialClass. This helps quickly distinguish classes from methods and variables.

Body:
I would like to give a daughter class some extra attributes without having to explicitly call a new method. So is there a way of giving the inherited class an __init__ type method which does not override the __init__ method of the parent class?

I have written the code below purely to illustrate my question (hence the poor naming of attributes etc).

class initialclass():
    def __init__(self):
        self.attr1 = 'one'
        self.attr2 = 'two'

class inheritedclass(initialclass):
    def __new__(self):
        self.attr3 = 'three'

    def somemethod(self):
        print 'the method'

a = inheritedclass()

for each in a.__dict__:
    print each

#I would like the output to be:
attr1
attr2
attr3

Thank you

Body:
Just call the parent's __init__ using super:

class inheritedclass(initialclass):
    def __new__(self):
        self.attr3 = 'three'
        super(initialclass, self).__init__()

I strongly advise to follow Python's naming conventions and start a class with a Capital letter, e.g. InheritedClass and InitialClass. This helps quickly distinguish classes from methods and variables.


问:
Problem with rotated yticklabels using pgfplot
I am using "yticklabel style={rotate=90}" to rotate the ytick labels in a pgfplot by 90°. The text of the labels is not properly horizontally aligned.

In the following example "Grouped" is not aligned with the other labels (especially, because it contains a "p").

Image :

I am running out of "style" options to fix this, any idea how to get these values horizontally aligned? Thanks!

Edit:

Minimal example (please note, that my actual code uses labels to address columns in CSV files):

```<code>\documentclass{article}
% translate with >> pdflatex -shell-escape <file>

% This file is an extract of the PGFPLOTS manual, copyright by Christian Feuersaenger.
%
% Feel free to use it as long as you cite the pgfplots manual properly.
%
% See
%   http://pgfplots.sourceforge.net/pgfplots.pdf
% for the complete manual.
%
% Any required input files (for <plot table> or <plot file> or the table package) can be downloaded
% at
% http://www.ctan.org/tex-archive/graphics/pgf/contrib/pgfplots/doc/latex/
% and
% http://www.ctan.org/tex-archive/graphics/pgf/contrib/pgfplots/doc/latex/plotdata/

\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\pagestyle{empty}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
    xbar, xmin=0,
    width=12cm, height=5.5cm, enlarge y limits=0.5,
    xlabel={\#participants},
    symbolic y coords={Flat,Grouped},
    ytick=data,
    nodes near coords, nodes near coords align={horizontal},
    yticklabel style={rotate=90},
    ]
    \addplot coordinates {(3,Flat) (7,Grouped)};
  \end{axis}
\end{tikzpicture}
\end{document}
</code>```

答:
With yticklabel style={rotate=90,anchor=base,yshift=0.2cm}:

```<code>\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\pagestyle{empty}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
    xbar, xmin=0,
    width=12cm, height=5.5cm, enlarge y limits=0.5,
    xlabel={\#participants},
    symbolic y coords={Flat,Grouped},
    ytick=data,
    nodes near coords, nodes near coords align={horizontal},
    yticklabel style={rotate=90,anchor=base,yshift=0.2cm},
    ]
    \addplot coordinates {(3,{Flat}) (7,Grouped)};
  \end{axis}
\end{tikzpicture}
\end{document}
</code>```

(the red line is just to see that the baselines are aligned)

Body:
I am using "yticklabel style={rotate=90}" to rotate the ytick labels in a pgfplot by 90°. The text of the labels is not properly horizontally aligned.

In the following example "Grouped" is not aligned with the other labels (especially, because it contains a "p").

Image :

I am running out of "style" options to fix this, any idea how to get these values horizontally aligned? Thanks!

Edit:

Minimal example (please note, that my actual code uses labels to address columns in CSV files):

\documentclass{article}
% translate with >> pdflatex -shell-escape <file>

% This file is an extract of the PGFPLOTS manual, copyright by Christian Feuersaenger.
%
% Feel free to use it as long as you cite the pgfplots manual properly.
%
% See
%   http://pgfplots.sourceforge.net/pgfplots.pdf
% for the complete manual.
%
% Any required input files (for <plot table> or <plot file> or the table package) can be downloaded
% at
% http://www.ctan.org/tex-archive/graphics/pgf/contrib/pgfplots/doc/latex/
% and
% http://www.ctan.org/tex-archive/graphics/pgf/contrib/pgfplots/doc/latex/plotdata/

\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\pagestyle{empty}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
    xbar, xmin=0,
    width=12cm, height=5.5cm, enlarge y limits=0.5,
    xlabel={\#participants},
    symbolic y coords={Flat,Grouped},
    ytick=data,
    nodes near coords, nodes near coords align={horizontal},
    yticklabel style={rotate=90},
    ]
    \addplot coordinates {(3,Flat) (7,Grouped)};
  \end{axis}
\end{tikzpicture}
\end{document}

Body:
With yticklabel style={rotate=90,anchor=base,yshift=0.2cm}:

\documentclass{article}
\usepackage{pgfplots}
\pgfplotsset{compat=newest}

\pagestyle{empty}

\begin{document}
\begin{tikzpicture}
  \begin{axis}[
    xbar, xmin=0,
    width=12cm, height=5.5cm, enlarge y limits=0.5,
    xlabel={\#participants},
    symbolic y coords={Flat,Grouped},
    ytick=data,
    nodes near coords, nodes near coords align={horizontal},
    yticklabel style={rotate=90,anchor=base,yshift=0.2cm},
    ]
    \addplot coordinates {(3,{Flat}) (7,Grouped)};
  \end{axis}
\end{tikzpicture}
\end{document}

(the red line is just to see that the baselines are aligned)