问:
Filtering ID's based on specified difference in values
I am trying to filter IDs based on a specified conditions. For instance, I want to filter IDs which have a particular difference in questionnaire score from pre to post treatment. The idea is to get IDs that have improved in score, have stayed the same or have worsened. Here is a mock data set of what I'm trying to achieve:-

```<code>    ID<-c("aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","aaa","bbb","ccc")
    Condition<-c("Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Post","Post","Post","Post","Post","Post","Post","Post","Post","Pre","Pre","Pre","Post","Post", "Post")
    Score<-c(23,20,19,15,22,22,20,19,18,17,17,19,20,22,22,14,15,10,23,23,21,20,18,11)
    df<-cbind(ID,Condition,Score)
    df<-as.data.frame(df)
    df$Condition<-as.factor(df$Condition)
</code>```

The main issue here is that there are ID's who appear in the data, for both pre and post, twice.

I have tried using a dplyr solution to select the appropriate columns from the main data frame, and then use tidyverse, and the spread function to convert to wide format, because from there I can work out the differences easily enough. However, there is a particular problem that I've experienced. It wouldn't work because there are duplicate instances where an ID has appeared in the data again (for example, IDs aaa, bbb & ccc).

```<code>     df2<-df%>%
     group_by(ID)%>%
     spread(Condition, Score)
</code>```

This gets me the following error message:-

Error: Each row of output must be identified by a unique combination of keys.
  Keys are shared for 12 rows:
  * 10, 22
  * 11, 23
  * 12, 24
  * 1, 19
  * 2, 20
  * 3, 21
  Do you need to create unique ID with tibble::rowid_to_column()?

Ideally, the kind of result I would be looking for is like so:-

```<code>    #improved
    ID      Pre       Post     Difference
    aaa      23        17           -6
    bbb      20        17           -3
    ggg      20        14           -6
    hhh      19        15           -4
    iii      18        10           -8
    aaa      23        20           -3
    bbb      23        18           -5
    ccc      21        11           -10

    #no improvement
    ID      Pre       Post      Difference
    ccc      19         19          0
    eee      22         22          0
    fff      22         22          0

    #worsened
    ID      Pre       Post      Difference
    ddd      15         20          +5
</code>```

Or something to this effect. As long as it allows me to include the repeated IDs. Ideally, I would like to be able to conditionally filter further based on the magnitude of difference. So for instance, if I want to subset/filter IDs with an improved score of more than 5, or a worsened score of more than 5. Bare in mind, my actual data set will have far more IDs to work with than the example that I just made up and provided. Any help would be greatly appreciated, as always.

Thank you in advance :)

答:
An option would be to first convert the 'Score' to numeric from factor, grouped by 'ID' 'Condition', create a sequence column ('rn'), spread to 'wide' format, get the diifference of 'Post' and 'Pre'  Scores, and split by the sign of 'Difference' column to create a list of tibbles

```<code>library(tidyverse)
df %>%
   mutate(Score = as.numeric(as.character(Score))) %>%
   group_by(ID, Condition) %>%
   mutate(rn = row_number()) %>%
   spread(Condition, Score) %>%
   mutate(Difference = Post -Pre) %>%
   ungroup %>%
   select(-rn) %>%
   group_split(grp = sign(Difference), keep = FALSE)
#[[1]]
# A tibble: 8 x 4
#  ID     Post   Pre Difference
#  <fct> <dbl> <dbl>      <dbl>
#1 aaa      17    23         -6
#2 aaa      20    23         -3
#3 bbb      17    20         -3
#4 bbb      18    23         -5
#5 ccc      11    21        -10
#6 ggg      14    20         -6
#7 hhh      15    19         -4
#8 iii      10    18         -8

#[[2]]
# A tibble: 3 x 4
#  ID     Post   Pre Difference
#  <fct> <dbl> <dbl>      <dbl>
#1 ccc      19    19          0
#2 eee      22    22          0
#3 fff      22    22          0

#[[3]]
# A tibble: 1 x 4
#  ID     Post   Pre Difference
#  <fct> <dbl> <dbl>      <dbl>
#1 ddd      20    15          5
</code>```

NOTE: It is not advisable to use as.data.frame(cbind, as cbind converts to a matrix and matrix can hold only a single class, i.e.if there is a character column, all the other columns get converted to character and wrapping with as.data.frame (default option is stringsAsFactors = TRUE).

```<code>df <- data.frame(...) #directly create
</code>```

Body:
I am trying to filter IDs based on a specified conditions. For instance, I want to filter IDs which have a particular difference in questionnaire score from pre to post treatment. The idea is to get IDs that have improved in score, have stayed the same or have worsened. Here is a mock data set of what I'm trying to achieve:-

    ID<-c("aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","ddd","eee","fff","ggg","hhh","iii","aaa","bbb","ccc","aaa","bbb","ccc")
    Condition<-c("Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Pre","Post","Post","Post","Post","Post","Post","Post","Post","Post","Pre","Pre","Pre","Post","Post", "Post")
    Score<-c(23,20,19,15,22,22,20,19,18,17,17,19,20,22,22,14,15,10,23,23,21,20,18,11)
    df<-cbind(ID,Condition,Score)
    df<-as.data.frame(df)
    df$Condition<-as.factor(df$Condition)

The main issue here is that there are ID's who appear in the data, for both pre and post, twice.

I have tried using a dplyr solution to select the appropriate columns from the main data frame, and then use tidyverse, and the spread function to convert to wide format, because from there I can work out the differences easily enough. However, there is a particular problem that I've experienced. It wouldn't work because there are duplicate instances where an ID has appeared in the data again (for example, IDs aaa, bbb & ccc).

     df2<-df%>%
     group_by(ID)%>%
     spread(Condition, Score)

This gets me the following error message:-

Error: Each row of output must be identified by a unique combination of keys.
  Keys are shared for 12 rows:
  * 10, 22
  * 11, 23
  * 12, 24
  * 1, 19
  * 2, 20
  * 3, 21
  Do you need to create unique ID with tibble::rowid_to_column()?

Ideally, the kind of result I would be looking for is like so:-

    #improved
    ID      Pre       Post     Difference
    aaa      23        17           -6
    bbb      20        17           -3
    ggg      20        14           -6
    hhh      19        15           -4
    iii      18        10           -8
    aaa      23        20           -3
    bbb      23        18           -5
    ccc      21        11           -10

    #no improvement
    ID      Pre       Post      Difference
    ccc      19         19          0
    eee      22         22          0
    fff      22         22          0

    #worsened
    ID      Pre       Post      Difference
    ddd      15         20          +5

Or something to this effect. As long as it allows me to include the repeated IDs. Ideally, I would like to be able to conditionally filter further based on the magnitude of difference. So for instance, if I want to subset/filter IDs with an improved score of more than 5, or a worsened score of more than 5. Bare in mind, my actual data set will have far more IDs to work with than the example that I just made up and provided. Any help would be greatly appreciated, as always.

Thank you in advance :)

Body:
An option would be to first convert the 'Score' to numeric from factor, grouped by 'ID' 'Condition', create a sequence column ('rn'), spread to 'wide' format, get the diifference of 'Post' and 'Pre'  Scores, and split by the sign of 'Difference' column to create a list of tibbles

library(tidyverse)
df %>%
   mutate(Score = as.numeric(as.character(Score))) %>%
   group_by(ID, Condition) %>%
   mutate(rn = row_number()) %>%
   spread(Condition, Score) %>%
   mutate(Difference = Post -Pre) %>%
   ungroup %>%
   select(-rn) %>%
   group_split(grp = sign(Difference), keep = FALSE)
#[[1]]
# A tibble: 8 x 4
#  ID     Post   Pre Difference
#  <fct> <dbl> <dbl>      <dbl>
#1 aaa      17    23         -6
#2 aaa      20    23         -3
#3 bbb      17    20         -3
#4 bbb      18    23         -5
#5 ccc      11    21        -10
#6 ggg      14    20         -6
#7 hhh      15    19         -4
#8 iii      10    18         -8

#[[2]]
# A tibble: 3 x 4
#  ID     Post   Pre Difference
#  <fct> <dbl> <dbl>      <dbl>
#1 ccc      19    19          0
#2 eee      22    22          0
#3 fff      22    22          0

#[[3]]
# A tibble: 1 x 4
#  ID     Post   Pre Difference
#  <fct> <dbl> <dbl>      <dbl>
#1 ddd      20    15          5

NOTE: It is not advisable to use as.data.frame(cbind, as cbind converts to a matrix and matrix can hold only a single class, i.e.if there is a character column, all the other columns get converted to character and wrapping with as.data.frame (default option is stringsAsFactors = TRUE).

df <- data.frame(...) #directly create


来源: stackexchange

问:
What is the part "baltimore.legistar" of the URL "http://baltimore.legistar.com" called?
What is it called when a website's domain is like:

```<code>http://baltimore.legistar.com
</code>```

What is the baltimore.legistar part called?

I see this sometimes where there's a large website and they appended something else to it such as:

```<code>www.bigwebsite._____.org
</code>```

答:
I think for your webpage legistar is the main domain and baltimore is a subdomain.

Protocol - The beginning of the url with https/http

Domain name - The unique part to your URL. e.g. google in https://www.google.com/

Path name - The path to a page on your website.

See https://doepud.co.uk/blog/anatomy-of-a-url for reference.

ContentLicense: CC BY-SA 4.0

Body:
What is it called when a website's domain is like:

http://baltimore.legistar.com

What is the baltimore.legistar part called?

I see this sometimes where there's a large website and they appended something else to it such as:

www.bigwebsite._____.org


问:
How can i add more than 1mission
I have a problem I want to make an app make more than 1 mission but it makes just 1 mission.
Note that Mission is a class and
toManinActivity is an ArrayList. How can I solve it?

```<code>   Save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Name.getText().toString().isEmpty()) {
                    Name.setError("");
                } else if (Hours.getText().toString().isEmpty()) {
                    Hours.setError("");
                } else if (Minutes.getText().toString().isEmpty()) {
                    Minutes.setError("");
                } else if (AboutMission.getText().toString().isEmpty()) {
                    AboutMission.setError("");
                } else {
                    int h = Integer.parseInt(Hours.getText().toString());//The hours
                    int m = Integer.parseInt(Minutes.getText().toString());//The minutes
                    if (m >= 60) {
                        Minutes.setError("Minutes should be under 60");
                    } else if (h >= 12) {
                        Hours.setError("Hours should be under 12");
                    } else {
                        toMainActivity.add(0, new NewMission("Date" + ":" + Dates, "Name" + ":" + Name.getText().toString(), "TIme" + ":" + Hours.getText().toString() + ":" + Minutes.getText().toString() + AmPm.getSelectedItem().toString(), "About Mission" + ":" + AboutMission.getText().toString(), Integer.parseInt(importance.getSelectedItem().toString())));
                        PreferencesManager.getInstance(Main2Activity.this).putString("Name", new Gson().toJson(toMainActivity));
                        startActivity(new Intent(Main2Activity.this, MainActivity.class));
                    }
                }
            }
        });
</code>```

答:
You are adding your mission object to the first (0) index of your list meaning you will overwrite anything that was already at that index (0). Use basic add() method without an index parameter so that each new object is added at the end of the list.

```<code>toMainActivity.add(new NewMission...
</code>```

Title: How can i add more than 1mission

Body:
I have a problem I want to make an app make more than 1 mission but it makes just 1 mission.
Note that Mission is a class and
toManinActivity is an ArrayList. How can I solve it?

   Save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Name.getText().toString().isEmpty()) {
                    Name.setError("");
                } else if (Hours.getText().toString().isEmpty()) {
                    Hours.setError("");
                } else if (Minutes.getText().toString().isEmpty()) {
                    Minutes.setError("");
                } else if (AboutMission.getText().toString().isEmpty()) {
                    AboutMission.setError("");
                } else {
                    int h = Integer.parseInt(Hours.getText().toString());//The hours
                    int m = Integer.parseInt(Minutes.getText().toString());//The minutes
                    if (m >= 60) {
                        Minutes.setError("Minutes should be under 60");
                    } else if (h >= 12) {
                        Hours.setError("Hours should be under 12");
                    } else {
                        toMainActivity.add(0, new NewMission("Date" + ":" + Dates, "Name" + ":" + Name.getText().toString(), "TIme" + ":" + Hours.getText().toString() + ":" + Minutes.getText().toString() + AmPm.getSelectedItem().toString(), "About Mission" + ":" + AboutMission.getText().toString(), Integer.parseInt(importance.getSelectedItem().toString())));
                        PreferencesManager.getInstance(Main2Activity.this).putString("Name", new Gson().toJson(toMainActivity));
                        startActivity(new Intent(Main2Activity.this, MainActivity.class));
                    }
                }
            }
        });

Body:
You are adding your mission object to the first (0) index of your list meaning you will overwrite anything that was already at that index (0). Use basic add() method without an index parameter so that each new object is added at the end of the list.

toMainActivity.add(new NewMission...


问:
Android studio- "SDK tools directory is missing"
When I start Android Studio, it displays a window entitled "Downloading components" which says:
 "Android SDK was installed to: C: / Users / user / AppData / Local / android / SDK2<code>  </code> SDK tools directory is missing "
I can not fix it and I need help!!</p>

答:
If you are using Windows S.O. make sure it is in the folder:

```<code>C:\Users\**your-user-name**\AppData\Local\Android\Sdk\platform-tools
</code>```

Otherwise, open Android Studio and go to:

```<code>Tools> SDK Manager> Android SDK> SDK Tools
</code>```

Select the Android Platform-Tools and Android SDK Tools checkbox and click Apply. After download check the directory again.

Body:
When I start Android Studio, it displays a window entitled "Downloading components" which says:
 "Android SDK was installed to: C: / Users / user / AppData / Local / android / SDK2   SDK tools directory is missing "
I can not fix it and I need help!!

Body:
If you are using Windows S.O. make sure it is in the folder:

C:\Users\**your-user-name**\AppData\Local\Android\Sdk\platform-tools

Otherwise, open Android Studio and go to:

Tools> SDK Manager> Android SDK> SDK Tools

Select the Android Platform-Tools and Android SDK Tools checkbox and click Apply. After download check the directory again.


问:
adding jquery in Jhipster angular project
I am new in Jhipster and Angular, and I am struggling in adding a jquery instance in my Jhipster Angular project.

I simply need to change the theme and outlook of the default jhipster application. For that purpose I downloaded a theme which has the combination of jquery and bootstrap, therefore, I installed the jquery through npm in the jhipster project.

I can see its folder in the node_modules as well, so it is already available.

Even though I have added its link in the vendor.ts but it seems it does not get loaded. So here my vendor.ts code where I am importing jquery file

```<code>import 'jquery/dist/jquery.min.js';
</code>```

To test my jquery object I coded following in my home.component.ts file.

```<code>import { Component, OnInit } from '@angular/core';
import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { JhiEventManager } from 'ng-jhipster';
import { LoginModalService, AccountService, Account } from 'app/core';

declare var $: any;
@Component({
    selector: 'jhi-home',
    templateUrl: './home.component.html',
    styleUrls: ['home.css'],
})
export class HomeComponent implements OnInit {
    account: Account;
    modalRef: NgbModalRef;

    constructor(
        private accountService: AccountService,
        private loginModalService: LoginModalService,
        private eventManager: JhiEventManager
    ) {}

    ngOnInit() {

        alert('I am Called');

        $(document).ready(function() {
            alert('I am Called From jQuery');
        });

    }
</code>```

But it gives me an error after the page gets loaded

```<code>ERROR ReferenceError: $ is not defined
    at HomeComponent.ngOnInit
</code>```

Any tip on this matter would be highly appreciable.

EDIT: I am adding my angular.json code

```<code>{

"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
    "paperproject": {
        "root": "",
        "sourceRoot": "src/main/webapp",
        "projectType": "application",
        "architect": {}
    }

},
"defaultProject": "paper-auth",
"cli": {
    "packageManager": "npm"
},
"schematics": {
    "@schematics/angular:component": {
        "inlineStyle": true,
        "inlineTemplate": false,
        "spec": false,
        "prefix": "jhi",
        "styleExt": "css"
    },
    "@schematics/angular:directive": {
        "spec": false,
        "prefix": "jhi"
    },
    "@schematics/angular:guard": {
        "spec": false
    },
    "@schematics/angular:pipe": {
        "spec": false
    },
    "@schematics/angular:service": {
        "spec": false
    },
    "scripts": "./node_modules/jquery/dist/jquery.min.js"
}
}
</code>```

It didn't had any script attribute therefore I added script attribute But it still does not work. Jhipster wizard only creates this default angular.json file.
 I added

```<code>  "scripts": "./node_modules/jquery/dist/jquery.min.js"
</code>```

答:
try this:

npm i jquery --save

in TypeScript file:

```<code>import * as $ from 'jquery';

ngOnInit() {

    alert('I am Called');

    $(document).ready(function() {
        alert('I am Called From jQuery');
    });

}
</code>```

or

add jquery script in index.html

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</code>```

on TypeScript file:

```<code>declare var $: any;

ngOnInit() {
  alert('I am Called');

  $(document).ready(function() {
    alert('I am Called From jQuery');
  });

}
</code>```

Body:
I am new in Jhipster and Angular, and I am struggling in adding a jquery instance in my Jhipster Angular project.

I simply need to change the theme and outlook of the default jhipster application. For that purpose I downloaded a theme which has the combination of jquery and bootstrap, therefore, I installed the jquery through npm in the jhipster project.

I can see its folder in the node_modules as well, so it is already available.

Even though I have added its link in the vendor.ts but it seems it does not get loaded. So here my vendor.ts code where I am importing jquery file

import 'jquery/dist/jquery.min.js';

To test my jquery object I coded following in my home.component.ts file.

import { Component, OnInit } from '@angular/core';
import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { JhiEventManager } from 'ng-jhipster';
import { LoginModalService, AccountService, Account } from 'app/core';

declare var $: any;
@Component({
    selector: 'jhi-home',
    templateUrl: './home.component.html',
    styleUrls: ['home.css'],
})
export class HomeComponent implements OnInit {
    account: Account;
    modalRef: NgbModalRef;

    constructor(
        private accountService: AccountService,
        private loginModalService: LoginModalService,
        private eventManager: JhiEventManager
    ) {}

    ngOnInit() {

        alert('I am Called');

        $(document).ready(function() {
            alert('I am Called From jQuery');
        });

    }

But it gives me an error after the page gets loaded

ERROR ReferenceError: $ is not defined
    at HomeComponent.ngOnInit

Any tip on this matter would be highly appreciable.

EDIT: I am adding my angular.json code

{

"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
    "paperproject": {
        "root": "",
        "sourceRoot": "src/main/webapp",
        "projectType": "application",
        "architect": {}
    }

},
"defaultProject": "paper-auth",
"cli": {
    "packageManager": "npm"
},
"schematics": {
    "@schematics/angular:component": {
        "inlineStyle": true,
        "inlineTemplate": false,
        "spec": false,
        "prefix": "jhi",
        "styleExt": "css"
    },
    "@schematics/angular:directive": {
        "spec": false,
        "prefix": "jhi"
    },
    "@schematics/angular:guard": {
        "spec": false
    },
    "@schematics/angular:pipe": {
        "spec": false
    },
    "@schematics/angular:service": {
        "spec": false
    },
    "scripts": "./node_modules/jquery/dist/jquery.min.js"
}
}

It didn't had any script attribute therefore I added script attribute But it still does not work. Jhipster wizard only creates this default angular.json file.
 I added

  "scripts": "./node_modules/jquery/dist/jquery.min.js"

Body:
try this:

npm i jquery --save

in TypeScript file:

import * as $ from 'jquery';

ngOnInit() {

    alert('I am Called');

    $(document).ready(function() {
        alert('I am Called From jQuery');
    });

}

or

add jquery script in index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

on TypeScript file:

declare var $: any;

ngOnInit() {
  alert('I am Called');

  $(document).ready(function() {
    alert('I am Called From jQuery');
  });

}


问:
How to display results from two tables sharing ids?
I have built a MYSQL database with multiple tables (accounts, attachments, categories, email, mailboxes, original, settings, tag). The only two tables in concern is email and attachments.
If an email has an attachment, the email and the attachment share an id. Therefore, I want to display all results from the two tables ordered by date.

However, with the code below, only the attachments table was displayed (about 1500 instances) whereas, I want to show the 1500 instances from attachments and all 60K instances from email table

```<code>SELECT
email.from_fld,
email.subj_fld,
email.date_fld,
email.mailto,
email.body_fld,
email.numAttach,
email.attachNames,
email.attachText,
attachments.filename_fld,
attachments.encode_fld,
attachments.attach_fld,
email.id,
attachments.id AS id_0
FROM
email
JOIN attachments
ON email.id = attachments.id
ORDER BY
email.date_fld ASC
</code>```

I expect all contents of both tables displayed ordered by date

attachments table description

```<code>id  int(11) NO  MUL
type_fld    varchar(127)    NO
filename_fld    varchar(127)    NO
encode_fld  int(11) YES     0
attach_fld  longblob    NO
</code>```

email table description

```<code>id  int(11) NO  PRI     auto_increment
from_fld    varchar(255)    NO  MUL
to_fld  mediumtext  NO
subj_fld    mediumtext  NO
date_fld    datetime    NO
mailbox varchar(255)    NO
mailto  varchar(127)    NO
body_fld    longtext    NO
numAttach   int(11) NO      0
attachNames mediumtext  NO
attachText  longtext    NO
headings    mediumtext  NO
</code>```

答:
You need a LEFT join from email to attachments because there are emails without attachments.

The INNER join you use shows only the emails which have attachments.

So replace the line:

```<code>JOIN attachments
</code>```

with

```<code>LEFT JOIN attachments
</code>```

Body:
I have built a MYSQL database with multiple tables (accounts, attachments, categories, email, mailboxes, original, settings, tag). The only two tables in concern is email and attachments.
If an email has an attachment, the email and the attachment share an id. Therefore, I want to display all results from the two tables ordered by date.

However, with the code below, only the attachments table was displayed (about 1500 instances) whereas, I want to show the 1500 instances from attachments and all 60K instances from email table

SELECT
email.from_fld,
email.subj_fld,
email.date_fld,
email.mailto,
email.body_fld,
email.numAttach,
email.attachNames,
email.attachText,
attachments.filename_fld,
attachments.encode_fld,
attachments.attach_fld,
email.id,
attachments.id AS id_0
FROM
email
JOIN attachments
ON email.id = attachments.id
ORDER BY
email.date_fld ASC

I expect all contents of both tables displayed ordered by date

attachments table description

id  int(11) NO  MUL
type_fld    varchar(127)    NO
filename_fld    varchar(127)    NO
encode_fld  int(11) YES     0
attach_fld  longblob    NO

email table description

id  int(11) NO  PRI     auto_increment
from_fld    varchar(255)    NO  MUL
to_fld  mediumtext  NO
subj_fld    mediumtext  NO
date_fld    datetime    NO
mailbox varchar(255)    NO
mailto  varchar(127)    NO
body_fld    longtext    NO
numAttach   int(11) NO      0
attachNames mediumtext  NO
attachText  longtext    NO
headings    mediumtext  NO

Body:
You need a LEFT join from email to attachments because there are emails without attachments.

The INNER join you use shows only the emails which have attachments.

So replace the line:

JOIN attachments

with

LEFT JOIN attachments


问:
git diff ignore semicolon at end of line
A colleague has created a commit where his editor has appended semicolons to each line (amongst other changes).

I know that I can use the -w switch to ignore whitespace errors. Would there be some kind of git magic to make git ignore ; altogether, or even better only when at EOL ?

Something like:

```<code>git diff --ignore=; -w
</code>```

答:
The easiest way I can think of is :

create a file, with your colleague's version, where you remove the semicolons at EOL, and compare that with the file you want :

```<code>git show modifiedcommit:the/file | sed -e 's/;$//' > /tmp/theFile
git diff originalcommit:the/file /tmp/theFile
</code>```

Body:
A colleague has created a commit where his editor has appended semicolons to each line (amongst other changes).

I know that I can use the -w switch to ignore whitespace errors. Would there be some kind of git magic to make git ignore ; altogether, or even better only when at EOL ?

Something like:

git diff --ignore=; -w

Body:
The easiest way I can think of is :

create a file, with your colleague's version, where you remove the semicolons at EOL, and compare that with the file you want :

git show modifiedcommit:the/file | sed -e 's/;$//' > /tmp/theFile
git diff originalcommit:the/file /tmp/theFile


问:
Opening URL's on same browser in different tab from CSV in Python
I am trying to open a list of URLs in new tabs in a single window, but it instead opens them in new windows. Please help. This is my URL.csv

```<code>SN,Title,URL
1,Google,https://google.com
2,youtube,https://youtube.com
</code>```

```<code>import csv

from selenium import webdriver

def csv_url_reader(url_obj):
    reader = csv.DictReader(url_obj, delimiter=',')

    for line in reader:
        url = line["URL"]
        title = line["Title"]
        print(url + title)
        driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')
        driver.get(url)

if __name__ == "__main__":
    with open("URL.csv") as url_obj:
        csv_url_reader(url_obj)
</code>```

答:
To add a new tab you would use
send_keys(Keys.COMMAND + 't') for mac,
or
send_keys(Keys.CTRL + 't') for windows

Body:
I am trying to open a list of URLs in new tabs in a single window, but it instead opens them in new windows. Please help. This is my URL.csv

SN,Title,URL
1,Google,https://google.com
2,youtube,https://youtube.com

import csv

from selenium import webdriver

def csv_url_reader(url_obj):
    reader = csv.DictReader(url_obj, delimiter=',')

    for line in reader:
        url = line["URL"]
        title = line["Title"]
        print(url + title)
        driver = webdriver.Chrome(r'C:\chromedriver_win32\chromedriver')
        driver.get(url)

if __name__ == "__main__":
    with open("URL.csv") as url_obj:
        csv_url_reader(url_obj)


问:
how to retrieve array of ids from facebook, using Graph API?
This is NSString retrieve from facebook using me/friends, so I want individual images, so I can get by simply

```<code>http://graph.facebook.com/"id here"/picture
</code>```

so how can I get array of ids from my friends, have any idea?

{"data":[{"name":"Abdul Basit","id":"508238854"},{"name":"Nasar Farooqui","id":"516100136"},{"name":"Ahmad Al-Refai","id":"525085450"},{"name":"Zamzam Shk","id":"100002088918788"},{"name":"Gm Jatoi","id":"100002187305416"},{"name":"Mohd Ali Khoso","id":"100002199757555"},{"name":"Shusheela Kumari","id":"100002282658638"}]}

答:
It is JSON response...... you will need JSON parsing..... For this, either you can write your own parser..... or you can use exising one http://code.google.com/p/json-framework/

thanks.

ContentLicense: CC BY-SA 3.0

Body:
This is NSString retrieve from facebook using me/friends, so I want individual images, so I can get by simply

http://graph.facebook.com/"id here"/picture

so how can I get array of ids from my friends, have any idea?

{"data":[{"name":"Abdul Basit","id":"508238854"},{"name":"Nasar Farooqui","id":"516100136"},{"name":"Ahmad Al-Refai","id":"525085450"},{"name":"Zamzam Shk","id":"100002088918788"},{"name":"Gm Jatoi","id":"100002187305416"},{"name":"Mohd Ali Khoso","id":"100002199757555"},{"name":"Shusheela Kumari","id":"100002282658638"}]}


问:
Does the linker script always determine at what addresses code is placed
I've spent most of my time developing for microcontrollers using tools and IDEs such as Atmel Studio, and abstracted from as to what goes on behind the scenes exactly.

Let's say in this case we are executing the code directly from flash which can be the case in embedded systems.

When we develop an application and flash it to the microcontroller using provided tools from the chip vendor, is it the loader / flasher that determines at what physical address in memory will be flashed?

I understand that the linker script defines memory offsets as to where the different sections such as .data and .txt should be placed, so is it actually this that ultimately determines at what address in the mcu flash everything should go?

Lets's say now that I discover a part of flash that is not used at all and I wish to put something else there (another application even), do I modify the linker script, create a new one, or how would I write to this particular location? I haven't fully grasped this yet.

答:
Your idea is generally correct. A linker script, which is nothing more than a file with its specialized language that conveys certain information regarding memory and how they should be used, determines the layout of your program in the memory. Some linkers would accept such memory specifications via command line options as well.

Regarding your specific question, yes, you can write another firmware that occupies different memory addresses (than the first one) by modifying the second one's linker script, in particular, the starting address of the program image. This of course does not say anything about how these two pieces of firmware will run or communicate. Those are separate issues. You will also need to know the MCU's flash erasable page boundary so you can place the 2nd image in a different erasable page boundary.

In some firmware downloader / programmer, you may also be able to specify a different starting offset than what's specified in the firmware image. This is separate from the linker script process. There are a few uses for this. For example, your firmware maybe built to run from SRAM instead of directly from flash. Therefore at firmware download, it will need to be moved to a flash location, and at runtime, some kind of mechanism will be used to copy the code from the flash to SRAM where the program actually will run. There are other scenarios as well.


问:
SQL - Fill NULL values with previous value
After seeing a lot of examples, I didn't find a simple way to replace NULL values for each column with last value.

After pivot my table, I have this example:

```<code>IDS 1234,4567,7890

| 1234     |   4567    |   7890  |
|  1       |    2      |    3    |
| NULL     |    4      |    5    |
| NULL     |    6      |   NULL  |
|  8       |   NULL    |    9    |
</code>```

Result:

```<code>| 1234      |      4567      |     7890 |
|  1        |       2        |       3  |
|  1        |       4        |       5  |
|  1        |       6        |       5  |
|  8        |       6        |       9  |
</code>```

答:
We don't know your DBMS, but for most of them lag() window analytic function is used for previous records, and coalesce() function is used to substitute the null values. So, try to use :

```<code>with t1( id, col_1234, col_4567, col_7890 ) as
(
  select 1, 1   , 2  , 3    union all
  select 2, NULL, 4  , 5    union all
  select 3, NULL, 6  , NULL union all
  select 4, 8   ,NULL, 9
), t2 as
(
 select id,
        coalesce( col_1234, lag(col_1234) over (order by id) ) as col_1234,
        coalesce( col_4567, lag(col_4567) over (order by id) ) as col_4567,
        coalesce( col_7890, lag(col_7890) over (order by id) ) as col_7890
   from t1
)
select coalesce( col_1234, lag(col_1234) over (order by id) ) as col_1234,
       col_4567, col_7890
  from t2
</code>```

Demo

Body:
After seeing a lot of examples, I didn't find a simple way to replace NULL values for each column with last value.

After pivot my table, I have this example:

IDS 1234,4567,7890

| 1234     |   4567    |   7890  |
|  1       |    2      |    3    |
| NULL     |    4      |    5    |
| NULL     |    6      |   NULL  |
|  8       |   NULL    |    9    |

Result:

| 1234      |      4567      |     7890 |
|  1        |       2        |       3  |
|  1        |       4        |       5  |
|  1        |       6        |       5  |
|  8        |       6        |       9  |

Body:
We don't know your DBMS, but for most of them lag() window analytic function is used for previous records, and coalesce() function is used to substitute the null values. So, try to use :

with t1( id, col_1234, col_4567, col_7890 ) as
(
  select 1, 1   , 2  , 3    union all
  select 2, NULL, 4  , 5    union all
  select 3, NULL, 6  , NULL union all
  select 4, 8   ,NULL, 9
), t2 as
(
 select id,
        coalesce( col_1234, lag(col_1234) over (order by id) ) as col_1234,
        coalesce( col_4567, lag(col_4567) over (order by id) ) as col_4567,
        coalesce( col_7890, lag(col_7890) over (order by id) ) as col_7890
   from t1
)
select coalesce( col_1234, lag(col_1234) over (order by id) ) as col_1234,
       col_4567, col_7890
  from t2

Demo


问:
How to execute gradle task during project import in Intellij Idea
Let's assume my build.gradle file contains task generateSources which as name suggests generates additional java files. It's easy to ensure that generateSources is executed before compileJava: compileJava.dependsOn generateSources. How can I make sure generateSources is called when importing project into Intellij Idea as well?

答:
This can be done via id("org.jetbrains.gradle.plugin.idea-ext") plugin (https://github.com/JetBrains/gradle-idea-ext-plugin).

See sample code in Gradle sources: https://github.com/gradle/gradle/blob/135fb4751faf2736c231636e8a2a92d47706a3b9/buildSrc/subprojects/ide/src/main/kotlin/org/gradle/gradlebuild/ide/IdePlugin.kt#L147


问:
How to get exit code when using Python subprocess communicate method?
How do I retrieve the exit code when using Python's subprocess module and the communicate() method?

Relevant code:

```<code>import subprocess as sp
data = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE).communicate()[0]
</code>```

Should I be doing this another way?

答: exitcode = data.wait(). The child process will be blocked If it writes to standard output/error, and/or reads from standard input, and there are no peers.

Body:
How do I retrieve the exit code when using Python's subprocess module and the communicate() method?

Relevant code:

import subprocess as sp
data = sp.Popen(openRTSP + opts.split(), stdout=sp.PIPE).communicate()[0]

Should I be doing this another way?


问:
AWS EC2 vs Serverless Cost Comparison
I am currently using AWS EC2 for my workloads.

Now I want to convert the EC2 server to the Serverless Platform i.e(API Gateway and Lambda).

I have also followed different blogs and I am ready to go with the serverless. But, my one concern is on pricing.

How can I predict per month cost for the serverless according to my use of EC2? Will the EC2 Cloudwatch metrics help me to calculate the costing?

How can I make cost comparison?

答:
Firstly, there is no simple answer to your question as a simple lift and shift from a VM to Lambda is not ideal. To make the most of lambda, you need to architect your solution to be serverless. This means making use of the event-driven nature of Lambda.

Now to answer the question simply, you are charged only for the time it takes to serve a request (to the next 100ms). So if your lambda responds to the request in 70ms you pay for 100ms of execution time. If you serve the request in 210ms then you pay for 300ms.

You also pay for the memory allocated to the function on the order of GB per/month.

If you have a good logging or monitoring strategy you could check how long it takes to serve each type of request and how often they occur. If your application is fairly low-scale and is not accessed often (say all requests come within an 8 hour window) then you may end up saving money with lambda as you are only paying AWS for the time spent serving the request.

Also, it may help to read the following article on common pitfalls:
https://medium.com/@emaildelivery/serverless-pitfalls-issues-you-may-encounter-running-a-start-up-on-aws-lambda-f242b404f41c

Title: AWS EC2 vs Serverless Cost Comparison


问:
how to reduce typing for properties assignment (destructuring,...)?
How to reduce typing for:

```<code>class C {
    Constructor(a,b,c,d,e,f) {
       this.a=a;
       this.b=b;
       this.c=c;
       this.d=d;
       this.e=e;
    }
}
</code>```

for doing something like this:

```<code>class C {
    Constructor(param: [a,b,c,d,e,f]) {
       this=param;
    }
}
</code>```

but this syntax doesn't work

答:
Pass in an object instead, then use Object.assign:

class C {
  constructor(obj) {
    Object.assign(this, obj);
  }
}

const c = new C({ a: 'a', b: 'b', c: 'c', d: 'd', e: 'e' });
console.log(c);```
</div>
</div>
</p>

<p>Note that <code>constructor</code> must be lower-cased.</p>

<p>You could also use argument rest syntax, allowing you to avoid repitition when calling <code>new C</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class C {
  constructor(...args) {
    const props = ['a', 'b', 'c', 'd', 'e'];
    const obj = Object.fromEntries(
      args
        .slice(0, 5)
        .map((val, i) => [props[i], val])
    );
    Object.assign(this, obj);
  }
}

const c = new C('a', 'b', 'c', 'd', 'e');
console.log(c);</code>```

As Bergi notes, you could also call Array.prototype.entries on props for less code:

class C {
  constructor(...args) {
    const props = ['a', 'b', 'c', 'd', 'e'];
    for (const [i, prop] of props.entries()) {
      this[prop] = args[i];
    }
  }
}

const c = new C('a', 'b', 'c', 'd', 'e');
console.log(c);```

Body:
How to reduce typing for:

class C {
    Constructor(a,b,c,d,e,f) {
       this.a=a;
       this.b=b;
       this.c=c;
       this.d=d;
       this.e=e;
    }
}

for doing something like this:

class C {
    Constructor(param: [a,b,c,d,e,f]) {
       this=param;
    }
}

but this syntax doesn't work

Body:
Pass in an object instead, then use Object.assign:

class C {
  constructor(obj) {
    Object.assign(this, obj);
  }
}

const c = new C({ a: 'a', b: 'b', c: 'c', d: 'd', e: 'e' });
console.log(c);

Note that constructor must be lower-cased.

You could also use argument rest syntax, allowing you to avoid repitition when calling new C:

class C {
  constructor(...args) {
    const props = ['a', 'b', 'c', 'd', 'e'];
    const obj = Object.fromEntries(
      args
        .slice(0, 5)
        .map((val, i) => [props[i], val])
    );
    Object.assign(this, obj);
  }
}

const c = new C('a', 'b', 'c', 'd', 'e');
console.log(c);

As Bergi notes, you could also call Array.prototype.entries on props for less code:

class C {
  constructor(...args) {
    const props = ['a', 'b', 'c', 'd', 'e'];
    for (const [i, prop] of props.entries()) {
      this[prop] = args[i];
    }
  }
}

const c = new C('a', 'b', 'c', 'd', 'e');
console.log(c);


问:
sample of neural network
In the neural network code that I've written, I could not get an answer since the problem of alignment.

I wrote a neural network code (based on some other). I tried to build input and output in the right way. While I defined the class and operations correctly, I could not get an answer since the problem of alignment. Error : shapes (127,3) and (1,4) not aligned: 3 (dim 1) != 1 (dim 0)

Datafile = pd.read_excel(r"C:\\Users\Hasan\Desktop\ANN\x.xlsx") is  127x3

Target = pd.read_excel(r"C:\\Users\Hasan\Desktop\ANN\y.xlsx") is 127x1

class Neural_Network(object):

```<code>def __init__(self):
  self.inputlayer = 1

  self.w1 = np.random.randn(self.inputlayer, self.hiddenlayer)

  self.z = np.dot(Datafile, self.w1)
</code>```

I think it's because of the dimension of two matrices but even, when I changed the dimensions it did not work.
All help will be appreciated

答:
For matrix multiplication (dot product), number of columns of first matrix should be equal to number of rows of second matrix.

In your case, Datafile has 3 columns while w1 has 1 row, that's why it's giving you error because of incorrect dimensions.

For giving you example, I am assuming random matrices,

```<code>Datafile = np.random.rand(127, 3)
w1 = np.random.rand(3, 127)

z = np.dot(Datafile, w1)

print(z.shape)
</code>```

Output: (127, 127)

In this example, Datafile has 3 columns and w1 has 3 rows so in this case, dot-product will be successful.

Title: sample of neural network

Body:
In the neural network code that I've written, I could not get an answer since the problem of alignment.

I wrote a neural network code (based on some other). I tried to build input and output in the right way. While I defined the class and operations correctly, I could not get an answer since the problem of alignment. Error : shapes (127,3) and (1,4) not aligned: 3 (dim 1) != 1 (dim 0)

Datafile = pd.read_excel(r"C:\\Users\Hasan\Desktop\ANN\x.xlsx") is  127x3

Target = pd.read_excel(r"C:\\Users\Hasan\Desktop\ANN\y.xlsx") is 127x1

class Neural_Network(object):

def __init__(self):
  self.inputlayer = 1

  self.w1 = np.random.randn(self.inputlayer, self.hiddenlayer)

  self.z = np.dot(Datafile, self.w1)

I think it's because of the dimension of two matrices but even, when I changed the dimensions it did not work.
All help will be appreciated

Body:
For matrix multiplication (dot product), number of columns of first matrix should be equal to number of rows of second matrix.

In your case, Datafile has 3 columns while w1 has 1 row, that's why it's giving you error because of incorrect dimensions.

For giving you example, I am assuming random matrices,

Datafile = np.random.rand(127, 3)
w1 = np.random.rand(3, 127)

z = np.dot(Datafile, w1)

print(z.shape)

Output: (127, 127)

In this example, Datafile has 3 columns and w1 has 3 rows so in this case, dot-product will be successful.


问:
How to establish a private connection between Google app engine and compute engine?
I have a web app/Api which is currently running on a google app engine resource. As the calculations of the API are very computing intensive, i have outsourced the computational part to a managed auto-scaling google compute engine group, with a HTTP load balancer in the front end (to maintain a single IP address and balance load accross the several engines that are dynamically spawning).

Currently, i just make an HTTP call to the load balancer IP address from the app engine. As the GAE and GCE are in the same region, this however feels highly innefficient (i am aware that the app engine and compute engines are still in two physically seperated data centers). This also poses a security threat as I am constently receiving calls from random IP bots trying to exploit potential security loopholes. Additionally, i am only verfying API token validity at the app engine level, as i do not want to give user database access to the compute engine (security reasons), so this means that there is no verification beeing done between app engine and compute engine, so that the latter answers all calls that it gets.

Is there a way to establish a private connection between the app engine and cloud engine?

My goal would be to not have to open the GCE to the whole internet, bearing in mind that it is only receiving calls from one IP adress/resource

I have tried whitelisting only the app engines IP addresses, but this unforthunately is a large block of adresses, is very cumbersome to retrieve and changes dynamically. The app engine also cannot use the private IP of the compute engine/ google SQL servers.

Other creative ideas are highly welcome!

答:
It appears that Serverless VPC Access may be a potential solution.  The following is taken from the overview:

Serverless VPC Access enables you to connect from the App Engine
  standard environment and Cloud Functions directly to your VPC network.
  This connection makes it possible for your App Engine standard
  environment apps and Cloud Functions to access resources in your VPC
  network via internal (private) IP addresses. Using internal IP
  addresses improves the latency of communication between your Google
  Cloud Platform services and avoids exposing internal resources to the
  public internet.

Serverless VPC Access only allows your app or function to send
  requests to resources in your VPC network and receive responses to
  those requests. Communication in the opposite direction, where a VM
  initiates a request to an app or function, requires you to use the
  public address of the app or function.


问:
Save users activity
I am a web developer and I want to design a commercial website to sell a customer's product. Sell and buy activities are important and I need to maintain user activity information to keep the site secure.

I want to write a dynamic website. I want to control all user activity and then decide whether to save user activity information in a database. Some of site's visitors are registered users and some are anonymous. I want to save online information such as ip address, username, page name, and date/time for my registered users.

I want to know:

How do I save a user's IP address?

What more do I need to save?

答:
Saving each HTTP request details into database will work for low traffic web sites, but you will have performance issues in case of popular website, since writing to database in relatively slow operation.

Why not to use server HTTP logs instead?

All HTTP web servers create plain text log files which record remote user IP address, URL requested, etc. You can create activity report by writing your own script or using log file report tools. AWStats ( http://awstats.sourceforge.net/ ) is one of the most popular open-source tools for this.

On client side you can use Google Analytics to track user activity. It also provides means to track custom events:

```<code>_gaq.push(['_trackEvent', 'login', 'user_login', "custom data"]);
</code>```

More info at: http://code.google.com/apis/analytics/docs/tracking/asyncUsageGuide.html

This option only tracks users with JavaScript enabled, so it won't show bots, crawlers or users having analytics blocking addons installed.

ContentLicense: CC BY-SA 2.5

Title: Save users activity

Body:
Saving each HTTP request details into database will work for low traffic web sites, but you will have performance issues in case of popular website, since writing to database in relatively slow operation.

Why not to use server HTTP logs instead?

All HTTP web servers create plain text log files which record remote user IP address, URL requested, etc. You can create activity report by writing your own script or using log file report tools. AWStats ( http://awstats.sourceforge.net/ ) is one of the most popular open-source tools for this.

On client side you can use Google Analytics to track user activity. It also provides means to track custom events:

_gaq.push(['_trackEvent', 'login', 'user_login', "custom data"]);

More info at: http://code.google.com/apis/analytics/docs/tracking/asyncUsageGuide.html

This option only tracks users with JavaScript enabled, so it won't show bots, crawlers or users having analytics blocking addons installed.


问:
Keras Multi-layer Neural Network Accuracy
I've built a simplistic multi-layer NN using Keras with precipitation data in Australia.  The code takes 4 input columns: ['MinTemp', 'MaxTemp', 'Rainfall', 'WindGustSpeed'] and trains against the RainTomorrow output.

I've partitioned the data into training/test buckets, transformed all values into 0 <= n <= 1.  When I trying to run model.fit, my loss values steady at ~13.2, but my accuracy is always 0.0.  An example of logged fitting intervals are:

```<code>...
Epoch 37/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1274 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 38/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1457 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 39/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1315 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 40/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1797 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 41/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1844 - acc: 0.0000e+00 - val_loss: -16.1169 - val_acc: 0.0000e+00
Epoch 42/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.2205 - acc: 0.0000e+00 - val_loss: -16.1169 - val_acc: 0.0000e+00
Epoch 43/200
...
</code>```

How can I amend the following script, so my accuracy grows, and my predication output returns a value between 0 and 1 (0: no rain, 1: rain)?

```<code>import keras
import sklearn.model_selection
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler

labelencoder = LabelEncoder()

# read data, replace NaN with 0.0
csv_data = pd.read_csv('weatherAUS.csv', header=0)
csv_data = csv_data.replace(np.nan, 0.0, regex=True)

# Input/output columns scaled to 0<=n<=1
x = csv_data.loc[:, ['MinTemp', 'MaxTemp', 'Rainfall', 'WindGustSpeed']]
y = labelencoder.fit_transform(csv_data['RainTomorrow'])
scaler_x = MinMaxScaler(feature_range =(-1, 1))
x = scaler_x.fit_transform(x)
scaler_y = MinMaxScaler(feature_range =(-1, 1))
y = scaler_y.fit_transform([y])[0]

# Partitioned data for training/testing
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.2)

# model
model = keras.models.Sequential()
model.add( keras.layers.normalization.BatchNormalization(input_shape=tuple([x_train.shape[1]])))
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.normalization.BatchNormalization())
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.normalization.BatchNormalization())
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.core.Dense(1,   activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=["accuracy"])

callback_early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='auto')

model.fit(x_train, y_train, batch_size=1024, epochs=200, validation_data=(x_test, y_test), verbose=1, callbacks=[callback_early_stopping])

y_test = model.predict(x_test.values)
</code>```

答:
As you can see, the sigmoid activation function that you are using in your neural network output (the last  layer) range from 0 to 1.

Note that your label (y) is rescaled to -1 to 1.

I suggest you change the y range to 0 to 1 and keep the sigmoid output.

Body:
I've built a simplistic multi-layer NN using Keras with precipitation data in Australia.  The code takes 4 input columns: ['MinTemp', 'MaxTemp', 'Rainfall', 'WindGustSpeed'] and trains against the RainTomorrow output.

I've partitioned the data into training/test buckets, transformed all values into 0 <= n <= 1.  When I trying to run model.fit, my loss values steady at ~13.2, but my accuracy is always 0.0.  An example of logged fitting intervals are:

...
Epoch 37/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1274 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 38/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1457 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 39/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1315 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 40/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1797 - acc: 0.0000e+00 - val_loss: -16.1168 - val_acc: 0.0000e+00
Epoch 41/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.1844 - acc: 0.0000e+00 - val_loss: -16.1169 - val_acc: 0.0000e+00
Epoch 42/200
113754/113754 [==============================] - 0s 2us/step - loss: -13.2205 - acc: 0.0000e+00 - val_loss: -16.1169 - val_acc: 0.0000e+00
Epoch 43/200
...

How can I amend the following script, so my accuracy grows, and my predication output returns a value between 0 and 1 (0: no rain, 1: rain)?

import keras
import sklearn.model_selection
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import MinMaxScaler

labelencoder = LabelEncoder()

# read data, replace NaN with 0.0
csv_data = pd.read_csv('weatherAUS.csv', header=0)
csv_data = csv_data.replace(np.nan, 0.0, regex=True)

# Input/output columns scaled to 0<=n<=1
x = csv_data.loc[:, ['MinTemp', 'MaxTemp', 'Rainfall', 'WindGustSpeed']]
y = labelencoder.fit_transform(csv_data['RainTomorrow'])
scaler_x = MinMaxScaler(feature_range =(-1, 1))
x = scaler_x.fit_transform(x)
scaler_y = MinMaxScaler(feature_range =(-1, 1))
y = scaler_y.fit_transform([y])[0]

# Partitioned data for training/testing
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.2)

# model
model = keras.models.Sequential()
model.add( keras.layers.normalization.BatchNormalization(input_shape=tuple([x_train.shape[1]])))
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.normalization.BatchNormalization())
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.normalization.BatchNormalization())
model.add(keras.layers.core.Dense(4, activation='relu'))
model.add(keras.layers.core.Dropout(rate=0.5))
model.add(keras.layers.core.Dense(1,   activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=["accuracy"])

callback_early_stopping = keras.callbacks.EarlyStopping(monitor='val_loss', patience=10, verbose=0, mode='auto')

model.fit(x_train, y_train, batch_size=1024, epochs=200, validation_data=(x_test, y_test), verbose=1, callbacks=[callback_early_stopping])

y_test = model.predict(x_test.values)


问:
How to get dropdown list items from pandas dataframe using python flask?
I need to add the data from the pandas dataframe to dropdown list in an html document using python flask...

```<code>@app.route('/api/v1/resources/getservices', methods=['GET'])
def api_services():
    return render_template('view.html',table=df.to_html())

<!DOCTYPE html>
<html lang="en">
<head>
     <meta charset="UTF-8">
     <title>Dropdown</title>
     <h1>Services</h1>
</head>
<body>
<select name="table" method="GET" action="/">
  <option value="{{table[0]}}" selected>{{table[0]}}</option>
  {% for colour in table[1:] %}
  <option value="{{colour}}">{{colour}}</option>
  {% endfor %}
</select>
</body>
</html>
</code>```

What I am expecting is that the data from the column 'Service' in the pandas dataframe df should be added as items in the drop down list in the html file.. but whenever i am trying with the above code, drop down list is created without any items...

答:
when you call to_html() method, it will create the html table and you can't iterate over it. I don't know what was your df data, but i think this might work for you.

app.py

```<code>@app.route('/api/v1/resources/getservices', methods=['GET'])
def api_services():
    d = {'Services': ["red", "green", "blue"]}
    df = pd.DataFrame(data=d)
    return render_template('view.html', table=df)
</code>```

view.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dropdown</title>
    <h1>Services</h1>
</head>
<body>
<select name="table" method="GET" action="/">
{% for colour in table["Services"] %}
        <option value="{{ colour }}">{{ colour }}</option>
    {% endfor %}
</select>
</body>
</html>
</code>```

Body:
I need to add the data from the pandas dataframe to dropdown list in an html document using python flask...

@app.route('/api/v1/resources/getservices', methods=['GET'])
def api_services():
    return render_template('view.html',table=df.to_html())

<!DOCTYPE html>

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

Services

<select name="table" method="GET" action="/">
  <option value="{{table[0]}}" selected>{{table[0]}}</option>
  {% for colour in table[1:] %}
  <option value="{{colour}}">{{colour}}</option>
  {% endfor %}
</select>

What I am expecting is that the data from the column 'Service' in the pandas dataframe df should be added as items in the drop down list in the html file.. but whenever i am trying with the above code, drop down list is created without any items...

Body:
when you call to_html() method, it will create the html table and you can't iterate over it. I don't know what was your df data, but i think this might work for you.

app.py

@app.route('/api/v1/resources/getservices', methods=['GET'])
def api_services():
    d = {'Services': ["red", "green", "blue"]}
    df = pd.DataFrame(data=d)
    return render_template('view.html', table=df)

view.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dropdown</title>
    <h1>Services</h1>
</head>
<body>
<select name="table" method="GET" action="/">
{% for colour in table["Services"] %}
        <option value="{{ colour }}">{{ colour }}</option>
    {% endfor %}
</select>
</body>
</html>


问:
Generate Apache public key from private key
What are the steps to generate a SSL compatible public key out of a private key generated by my server hosting service provider?
Here are parts of the key, it's an RSA private key it seems.

```<code>-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAqy0rpDUVRzxHsFr4#FET5iSNVkIljgN75jQi4W7DOtAf6BWk
umcLMLIxBaQl3m7/1X93lW5EpyIa/+IqlLH0fUwMyURY6UHJ5WP/LOiV8xs2+xoJ
3LtXdMGjHEyOoSuNcJCiP4nsoYUOvxn9A37vxYnJ3Z5a9lcTQNZSorQJnxDT8cmN
y/LwcgNNVDyPwTHHxgf/V6lnuZiiaCZb5ulwSbSWaHJm7+AsXf7E2oFl3YCE7nGE
NuVM9QP0sDc44oV9qG8QZqc6wGYwSEX3YegKL0hp/2se6xwK20N/KJ5b/toWqvUt
....+G3mblRn2D==
</code>```

I do not have too much experience with this and seems I have lost the
logs how I generated the key pair for my last years certs.
Thanks!

答:
First of all don't ever give out your private key (or even part of the private key) like you have.  Especially since that private key is not encrypted with a password.

Since you have done that, I would generate a new private key.

Normally you would just generate a certificate request based on your current private key, that way you don't need to update your private key on the server just your new certificate using the openssl req command.

e.g.

openssl req -out newrequest.csr -key private.key -new

Since you should really generate a new private key, you can do instead:

openssl req -out newrequest.csr -new -newkey rsa:2048 -nodes -keyout
  private.key

Body:
What are the steps to generate a SSL compatible public key out of a private key generated by my server hosting service provider?
Here are parts of the key, it's an RSA private key it seems.

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAqy0rpDUVRzxHsFr4#FET5iSNVkIljgN75jQi4W7DOtAf6BWk
umcLMLIxBaQl3m7/1X93lW5EpyIa/+IqlLH0fUwMyURY6UHJ5WP/LOiV8xs2+xoJ
3LtXdMGjHEyOoSuNcJCiP4nsoYUOvxn9A37vxYnJ3Z5a9lcTQNZSorQJnxDT8cmN
y/LwcgNNVDyPwTHHxgf/V6lnuZiiaCZb5ulwSbSWaHJm7+AsXf7E2oFl3YCE7nGE
NuVM9QP0sDc44oV9qG8QZqc6wGYwSEX3YegKL0hp/2se6xwK20N/KJ5b/toWqvUt
....+G3mblRn2D==

I do not have too much experience with this and seems I have lost the
logs how I generated the key pair for my last years certs.
Thanks!


问:
Trunc a number and get removed value. Or cast to int?
I try to get the removed part of the math.trunc function.
Or a function supports this request.

```<code>import math
number = 1.9
newnumber, removed = math.trunc(number)
</code>```

I need the number = 1 and also the removed 0.9
So basicly i need the integer and the removed float.

Obove example will not work :/
Any suggestions ?

答:
For a starting point, use modulus 1 get the removed part.

```<code>def truncate(n):
    return math.trunc(n), n % 1
</code>```

Then you want to consider how negative numbers are handled. Do they return a positive ‘removed’ value?

This method won’t work for negative numbers, instead you can subtract the truncates number from the original:

```<code>t = math.trunc(n)
return t, n - t
</code>```

Body:
I try to get the removed part of the math.trunc function.
Or a function supports this request.

import math
number = 1.9
newnumber, removed = math.trunc(number)

I need the number = 1 and also the removed 0.9
So basicly i need the integer and the removed float.

Obove example will not work :/
Any suggestions ?

Body:
For a starting point, use modulus 1 get the removed part.

def truncate(n):
    return math.trunc(n), n % 1

Then you want to consider how negative numbers are handled. Do they return a positive ‘removed’ value?

This method won’t work for negative numbers, instead you can subtract the truncates number from the original:

t = math.trunc(n)
return t, n - t


答:
You need to keep a handle on the truncated number, and subtract it from the original number:</p>

```<code>import math
number = 1.9
truncated = math.trunc(number)
print(truncated, number - truncated)
</code>```

Title: Trunc a number and get removed value. Or cast to int?

Body:
You need to keep a handle on the truncated number, and subtract it from the original number:

import math
number = 1.9
truncated = math.trunc(number)
print(truncated, number - truncated)


问:
Keep background color after selection when in focus Microsoft Edge
I have a select form in Bootstrap 4 with dark background, when I select an option I want the background after selection to stay dark. My example works in Chrome and Firefox. But in IE and Edge the background stays white while in focus. Check my jsfiddle, any ideas?

```<code>.form-control:focus {
  background-color: #121212;
  border-color: #121212;
  outline: 0;
  box-shadow: 0 0 0 0rem rgba(0,123,255,.25);
}
</code>```

https://jsfiddle.net/cd1eyqvr/3/

答:
Check this link from offical docs:

https://getbootstrap.com/docs/4.0/getting-started/browsers-devices/

It seems the edge has problems with box shadow and you must add extra css to your stylesheet Check the links blow for more help about your problem Box shadow not working in microsoft edge

And also check this link for complete box shadow in edge solutions

https://css-tricks.com/snippets/css/css-box-shadow/

Body:
I have a select form in Bootstrap 4 with dark background, when I select an option I want the background after selection to stay dark. My example works in Chrome and Firefox. But in IE and Edge the background stays white while in focus. Check my jsfiddle, any ideas?

.form-control:focus {
  background-color: #121212;
  border-color: #121212;
  outline: 0;
  box-shadow: 0 0 0 0rem rgba(0,123,255,.25);
}

https://jsfiddle.net/cd1eyqvr/3/


问:
ERROR TypeError: _co.Get_products is not a function
here , I want to call a function of a component from its HTML template.
but it is showing error as below.
please suggest any changes to solve the error.

```<code>ERROR TypeError: _co.Get_products is not a function
at Object.eval [as handleEvent] (MapsComponent.html:49)

MapsComponent.html:49 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 9, nodeDef: {…}, elDef: {…}, elView: {…}}
</code>```

maps.component.html

```<code><button (click)="Get_products()">Function</button>
</code>```

maps.component.ts

```<code> import { Component, OnInit } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { NgForm } from '@angular/forms';
    import * as Chart from 'chart.js';
    import { Router } from '@angular/router';
    import {
      AgmCoreModule
    } from '@agm/core';
    //import { google } from 'googlemaps';
    import { MapsAPILoader } from '@agm/core';
    import { HttpClient } from '@angular/common/http';

    declare const google: any;

    interface Marker {
    lat: number;
    lng: number;
    label?: string;
    draggable?: boolean;
    }
    @Component({
      selector: 'app-maps',
      templateUrl: './maps.component.html',
      styleUrls: ['./maps.component.css']
    })
    export class MapsComponent implements OnInit {

      constructor() { }
      private products  = [];
      ngOnInit() {
    .......
        function Get_products(){
            console.log('Hello');
        }
    ......
          }

    }
</code>```

Error

答:
You should define Get_products outside of ngOnInit as a method of the MapsComponent class.

```<code>private products  = [];

constructor() { }

ngOnInit() {
    .......
}

Get_products(){
    console.log('Hello');
}
</code>```

Body:
here , I want to call a function of a component from its HTML template.
but it is showing error as below.
please suggest any changes to solve the error.

ERROR TypeError: _co.Get_products is not a function
at Object.eval [as handleEvent] (MapsComponent.html:49)

MapsComponent.html:49 ERROR CONTEXT DebugContext_ {view: {…}, nodeIndex: 9, nodeDef: {…}, elDef: {…}, elView: {…}}

maps.component.html

<button (click)="Get_products()">Function</button>

maps.component.ts

 import { Component, OnInit } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { NgForm } from '@angular/forms';
    import * as Chart from 'chart.js';
    import { Router } from '@angular/router';
    import {
      AgmCoreModule
    } from '@agm/core';
    //import { google } from 'googlemaps';
    import { MapsAPILoader } from '@agm/core';
    import { HttpClient } from '@angular/common/http';

    declare const google: any;

    interface Marker {
    lat: number;
    lng: number;
    label?: string;
    draggable?: boolean;
    }
    @Component({
      selector: 'app-maps',
      templateUrl: './maps.component.html',
      styleUrls: ['./maps.component.css']
    })
    export class MapsComponent implements OnInit {

      constructor() { }
      private products  = [];
      ngOnInit() {
    .......
        function Get_products(){
            console.log('Hello');
        }
    ......
          }

    }

Error

Body:
You should define Get_products outside of ngOnInit as a method of the MapsComponent class.

private products  = [];

constructor() { }

ngOnInit() {
    .......
}

Get_products(){
    console.log('Hello');
}


问:
Constructing a Paypal OAuth
I am trying to get an access token for Paypal's RESTful web services but unfortunately not making any headway. This is my first time dealing with REST, so please be patient with me :)

Here is what I have:

Client_id and secret as provided by Paypal for a sandbox account through the paypal developer website.

The ENDpoint: https://api.sandbox.paypal.com/v1/oauth2/token

The documentation that i am referring to is : https://developer.paypal.com/webapps/developer/docs/integration/direct/make-your-first-call/

Now the juicy part of making that API call. I am developing in PHP so I am using CURL to make the calls. something like this;

```<code>const CLIENT_ID = ****..*** ;
const SECRET = ***..***;

$base64EncodedClientID = base64_encode(self::CLIENT_ID . ":" . self::SECRET);
$headers = array("Authorization" => "Basic " . $base64EncodedClientId, "Accept" =>"*/*", "Content-type" => "multipart/form-data");
$params = array("grant_type"=>"client_credentials");
$url = "https://api.sandbox.paypal.com/v1/oauth2/token";

 $ch = curl_init();
 curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch,CURLOPT_URL, $url);
 curl_setopt($ch,CURLOPT_POST, true);
 curl_setopt($ch,CURLOPT_HEADER, $headers);
 curl_setopt($ch,CURLOPT_POSTFIELDS,$params);
 $response = curl_exec($ch);
</code>```

Pretty vanilla right? Except that I do not get the JSON response that I expect from Paypal but false. This implies that my CURL request was not prepared well, perhaps I am setting the header incorrectly or the params are incorrect. Regardless, the URL is definitely accessible since I was able to access it through command line with the same credentials and got the desired JSON response.

The one glaring problem I have with the above code is that I am providing the client_id and secret as a header option. basic sense tells me that they need to be part of the POST field data However, if you look at line 89 of this Github code https://github.com/paypal/rest-api-sdk-php/blob/master/lib/PayPal/Auth/OAuthTokenCredential.php (Paypals' official PHP REST SDK), it clearly states that the credentials are being set in the header field.

Where am I messing up ?

答:
Had the exact same problem you ran into. The issue is that PayPal accepts the content-type application/x-www-form-urlencoded. Your code is attempting to send multipart/form-data. CURL by default sends application/x-www-form-urlencoded, but you are passing your data as an array. Instead, you should be passing the data like a url encoded string since this is what application/x-www-form-urlencoded data looks like:

```<code>$params = "grant_type=client_credentials";
</code>```

Your headers have the same problem. Pass it as an array of strings instead of a dictionary. For instance:

```<code>$headers = ["Authorization Basic " . $base64EncodedClientId];
</code>```

Also, you don't need those other two headers you passed in. The 'Accept' header does nothing since you are accepting everything, and the Content-type is wrong for one, and two is defaulted to 'application/x-www-form-urlencoded' by CURL so unless you need to override that, there is no need.

Title: Constructing a Paypal OAuth

Body:
I am trying to get an access token for Paypal's RESTful web services but unfortunately not making any headway. This is my first time dealing with REST, so please be patient with me :)

Here is what I have:

Client_id and secret as provided by Paypal for a sandbox account through the paypal developer website.

The ENDpoint: https://api.sandbox.paypal.com/v1/oauth2/token

The documentation that i am referring to is : https://developer.paypal.com/webapps/developer/docs/integration/direct/make-your-first-call/

Now the juicy part of making that API call. I am developing in PHP so I am using CURL to make the calls. something like this;

const CLIENT_ID = ****..*** ;
const SECRET = ***..***;

$base64EncodedClientID = base64_encode(self::CLIENT_ID . ":" . self::SECRET);
$headers = array("Authorization" => "Basic " . $base64EncodedClientId, "Accept" =>"*/*", "Content-type" => "multipart/form-data");
$params = array("grant_type"=>"client_credentials");
$url = "https://api.sandbox.paypal.com/v1/oauth2/token";

 $ch = curl_init();
 curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch,CURLOPT_URL, $url);
 curl_setopt($ch,CURLOPT_POST, true);
 curl_setopt($ch,CURLOPT_HEADER, $headers);
 curl_setopt($ch,CURLOPT_POSTFIELDS,$params);
 $response = curl_exec($ch);

Pretty vanilla right? Except that I do not get the JSON response that I expect from Paypal but false. This implies that my CURL request was not prepared well, perhaps I am setting the header incorrectly or the params are incorrect. Regardless, the URL is definitely accessible since I was able to access it through command line with the same credentials and got the desired JSON response.

The one glaring problem I have with the above code is that I am providing the client_id and secret as a header option. basic sense tells me that they need to be part of the POST field data However, if you look at line 89 of this Github code https://github.com/paypal/rest-api-sdk-php/blob/master/lib/PayPal/Auth/OAuthTokenCredential.php (Paypals' official PHP REST SDK), it clearly states that the credentials are being set in the header field.

Where am I messing up ?

Body:
Had the exact same problem you ran into. The issue is that PayPal accepts the content-type application/x-www-form-urlencoded. Your code is attempting to send multipart/form-data. CURL by default sends application/x-www-form-urlencoded, but you are passing your data as an array. Instead, you should be passing the data like a url encoded string since this is what application/x-www-form-urlencoded data looks like:

$params = "grant_type=client_credentials";

Your headers have the same problem. Pass it as an array of strings instead of a dictionary. For instance:

$headers = ["Authorization Basic " . $base64EncodedClientId];

Also, you don't need those other two headers you passed in. The 'Accept' header does nothing since you are accepting everything, and the Content-type is wrong for one, and two is defaulted to 'application/x-www-form-urlencoded' by CURL so unless you need to override that, there is no need.


问:
Did Firebase start reporting in_app_purchase for subscriptions recently?

My Android app has integrated Firebase SDK

Firebase is linked to Google Play

I'm using subscriptions only

In the past there weren't any "in_app_purchase" events automatically reported (comparing to one-time products)

I do not report "in_app_purchase" manually from the client or server.

But I've got "in_app_purchase" recently with "subscription" (=1) parameter.

https://support.google.com/firebase/answer/7061705?hl=en lists next parameters: product_id, product_name, price, price_is_discounted, value, currency, quantity, app_version

Was there any changes in Firebase/GMS? Any blog posts/docs?

答:
Looks like Firebase did enable it recently. I'm seeing "in_app_purchase" events matching my own custom event started ~May 12.
And description was changed on https://support.google.com/firebase/answer/6317485?hl=en.

when a user completes an in-app purchase, including an initial
  subscription, that is processed by the App Store on iTunes or by
  Google Play


问:
Getting realtime output using subprocess
I am trying to write a wrapper script for a command line program (svnadmin verify) that will display a nice progress indicator for the operation.  This requires me to be able to see each line of output from the wrapped program as soon as it is output.

I figured that I'd just execute the program using subprocess.Popen, use stdout=PIPE, then read each line as it came in and act on it accordingly.  However, when I ran the following code, the output appeared to be buffered somewhere, causing it to appear in two chunks, lines 1 through 332, then 333 through 439 (the last line of output)

```<code>from subprocess import Popen, PIPE, STDOUT

p = Popen('svnadmin verify /var/svn/repos/config', stdout = PIPE,
        stderr = STDOUT, shell = True)
for line in p.stdout:
    print line.replace('\n', '')
</code>```

After looking at the documentation on subprocess a little, I discovered the bufsize parameter to Popen, so I tried setting bufsize to 1 (buffer each line) and 0 (no buffer), but neither value seemed to change the way the lines were being delivered.

At this point I was starting to grasp for straws, so I wrote the following output loop:

```<code>while True:
    try:
        print p.stdout.next().replace('\n', '')
    except StopIteration:
        break
</code>```

but got the same result.

Is it possible to get 'realtime' program output of a program executed using subprocess?  Is there some other option in Python that is forward-compatible (not exec*)?

答:
(This solution has been tested with Python 2.7.15)

You just need to sys.stdout.flush() after each line read/write:

```<code>while proc.poll() is None:
    line = proc.stdout.readline()
    sys.stdout.write(line)
    # or print(line.strip()), you still need to force the flush.
    sys.stdout.flush()
</code>```

Body:
I am trying to write a wrapper script for a command line program (svnadmin verify) that will display a nice progress indicator for the operation.  This requires me to be able to see each line of output from the wrapped program as soon as it is output.

I figured that I'd just execute the program using subprocess.Popen, use stdout=PIPE, then read each line as it came in and act on it accordingly.  However, when I ran the following code, the output appeared to be buffered somewhere, causing it to appear in two chunks, lines 1 through 332, then 333 through 439 (the last line of output)

from subprocess import Popen, PIPE, STDOUT

p = Popen('svnadmin verify /var/svn/repos/config', stdout = PIPE,
        stderr = STDOUT, shell = True)
for line in p.stdout:
    print line.replace('\n', '')

After looking at the documentation on subprocess a little, I discovered the bufsize parameter to Popen, so I tried setting bufsize to 1 (buffer each line) and 0 (no buffer), but neither value seemed to change the way the lines were being delivered.

At this point I was starting to grasp for straws, so I wrote the following output loop:

while True:
    try:
        print p.stdout.next().replace('\n', '')
    except StopIteration:
        break

but got the same result.

Is it possible to get 'realtime' program output of a program executed using subprocess?  Is there some other option in Python that is forward-compatible (not exec*)?

Body:
(This solution has been tested with Python 2.7.15)

You just need to sys.stdout.flush() after each line read/write:

while proc.poll() is None:
    line = proc.stdout.readline()
    sys.stdout.write(line)
    # or print(line.strip()), you still need to force the flush.
    sys.stdout.flush()


问:
Difference in behavior between Automation Schedule and Process All action on Processing page
I have customized the GLTran DAC to have a custom field for Tax Zone and it gets populated along with Tax Category and Tax ID if the "Create Tax Transactions" check box is selected. I have also customized the "Release" to populate this Tax Zone over to the TaxTran table.

The Journal Transactions are created by a custom processing page that reads an XML file and create the Journal Transaction document and also releases it.

Everything works fine in my local instance and also on our sandbox instance.

In production, when I process the XML files using the Processing page, everything is fine. But when I create Automation Schedule, the Journal Transactions are created with Tax Zone populated and the document is released without any error. However the Tax Zone is not populated in the TaxTran table!

I don't have the same problem with Automation Schedule in my local instance or Sandbox. All these instances are of same version of Acumatica.

```<code>public class GLTranExt : PXCacheExtension<PX.Objects.GL.GLTran>
    {
        #region UsrTaxZoneID
        [PXDBString(10)]
        [PXSelector(typeof(Search<TaxZone.taxZoneID>),
              typeof(TaxZone.taxZoneID),
              typeof(TaxZone.descr))]
        [PXUIField(DisplayName = "Tax Zone")]
        public virtual string UsrTaxZoneID { get; set; }
        public abstract class usrTaxZoneID : IBqlField { }
        #endregion
    }

public class PostGraph_Extension : PXGraphExtension<PostGraph>
    {
        public PXSelect<GLTran, Where<GLTran.batchNbr, Equal<Required<GLTran.batchNbr>>, And<GLTran.accountID, Equal<Required<GLTran.accountID>>, And<GLTran.subID, Equal<Required<GLTran.subID>>, And<GLTran.branchID, Equal<Required<GLTran.branchID>>>>>>> GLTransactions;
        public delegate void ReleaseBatchProcDelegate(Batch b, bool unholdBatch = false);
        [PXOverride]
        public void ReleaseBatchProc(Batch b, bool unholdBatch, ReleaseBatchProcDelegate baseMethod)
        {
            baseMethod(b, unholdBatch = false);
            foreach(TaxTran rec in Base.GL_GLTran_Taxes.Select(b.Module, b.BatchNbr))
            {
                GLTran glTran = GLTransactions.Select(rec.RefNbr, rec.AccountID, rec.SubID, rec.BranchID);
                GLTranExt glTranExt = PXCache<GLTran>.GetExtension<GLTranExt>(glTran);
                if (glTranExt != null)
                    rec.TaxZoneID = glTranExt.UsrTaxZoneID;
                Base.GL_GLTran_Taxes.Update(rec);
                Base.GL_GLTran_Taxes.Cache.Persist(PXDBOperation.Update);
            }
        }
}
</code>```

答:
I had the same problem, and in my case it was difference in permissions between account from which Automation Schedule was executed, and processing screen was executed. In order to fix it, I've added those lines:

```<code>using (new PXImpersonationContext(PX.Data.Update.PXInstanceHelper.ScopeUser))
{
                            using (new PXReadBranchRestrictedScope())
                            {
                            }
}
</code>```

first using makes running your code from user name admin, and second using makes your code running with permissions access to necessary branches

Body:
I have customized the GLTran DAC to have a custom field for Tax Zone and it gets populated along with Tax Category and Tax ID if the "Create Tax Transactions" check box is selected. I have also customized the "Release" to populate this Tax Zone over to the TaxTran table.

The Journal Transactions are created by a custom processing page that reads an XML file and create the Journal Transaction document and also releases it.

Everything works fine in my local instance and also on our sandbox instance.

In production, when I process the XML files using the Processing page, everything is fine. But when I create Automation Schedule, the Journal Transactions are created with Tax Zone populated and the document is released without any error. However the Tax Zone is not populated in the TaxTran table!

I don't have the same problem with Automation Schedule in my local instance or Sandbox. All these instances are of same version of Acumatica.

public class GLTranExt : PXCacheExtension<PX.Objects.GL.GLTran>
    {
        #region UsrTaxZoneID
        [PXDBString(10)]
        [PXSelector(typeof(Search<TaxZone.taxZoneID>),
              typeof(TaxZone.taxZoneID),
              typeof(TaxZone.descr))]
        [PXUIField(DisplayName = "Tax Zone")]
        public virtual string UsrTaxZoneID { get; set; }
        public abstract class usrTaxZoneID : IBqlField { }
        #endregion
    }

public class PostGraph_Extension : PXGraphExtension<PostGraph>
    {
        public PXSelect<GLTran, Where<GLTran.batchNbr, Equal<Required<GLTran.batchNbr>>, And<GLTran.accountID, Equal<Required<GLTran.accountID>>, And<GLTran.subID, Equal<Required<GLTran.subID>>, And<GLTran.branchID, Equal<Required<GLTran.branchID>>>>>>> GLTransactions;
        public delegate void ReleaseBatchProcDelegate(Batch b, bool unholdBatch = false);
        [PXOverride]
        public void ReleaseBatchProc(Batch b, bool unholdBatch, ReleaseBatchProcDelegate baseMethod)
        {
            baseMethod(b, unholdBatch = false);
            foreach(TaxTran rec in Base.GL_GLTran_Taxes.Select(b.Module, b.BatchNbr))
            {
                GLTran glTran = GLTransactions.Select(rec.RefNbr, rec.AccountID, rec.SubID, rec.BranchID);
                GLTranExt glTranExt = PXCache<GLTran>.GetExtension<GLTranExt>(glTran);
                if (glTranExt != null)
                    rec.TaxZoneID = glTranExt.UsrTaxZoneID;
                Base.GL_GLTran_Taxes.Update(rec);
                Base.GL_GLTran_Taxes.Cache.Persist(PXDBOperation.Update);
            }
        }
}

Body:
I had the same problem, and in my case it was difference in permissions between account from which Automation Schedule was executed, and processing screen was executed. In order to fix it, I've added those lines:

using (new PXImpersonationContext(PX.Data.Update.PXInstanceHelper.ScopeUser))
{
                            using (new PXReadBranchRestrictedScope())
                            {
                            }
}

first using makes running your code from user name admin, and second using makes your code running with permissions access to necessary branches


问:
digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
I'm trying to make a Python program that runs OpenSSL commands for the encryption and decryption of files.

In the command line I made:

```<code>vagrant@vagrant:~$ openssl enc -aes256 -base64 -k $(base64 alice_shared_secret.bin) -e -in plain.txt -out cipher.txt
vagrant@vagrant:~$ openssl enc -aes256 -base64 -k $(base64 bob_shared_secret.bin) -d -in cipher.txt -out plain_again.txt
</code>```

And it works.
However, if I cipher the text with my Python program, I can't decrypt.

```<code>vagrant@vagrant:~$ openssl enc -aes256 -base64 -k $(base64 bob_shared_secret.bin) -d -in cipher.txt -out plain_again.txt
bad decrypt
140321401345688:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:529:
</code>```

What is the difference between my program and the cipher of the command line?

Code:

```<code>#!/System/Library/Frameworks/Python.framework/Versions/2.6/bin/python
openssl         = '/usr/bin/openssl'
from subprocess import Popen, PIPE, STDOUT

def encrypt():
  arguments = [
    openssl,
    'enc',
    '-aes256',
    '-base64',
    '-k',
    '$(base64 alice_shared_secret.bin)',
    '-e',
    '-in',
    'plain.txt',
    '-out',
    'cipher.txt',
  ]

  execute = Popen(arguments, stdout=PIPE)
  out, err = execute.communicate()

encrypt()
</code>```

Any help?

答:
AFAIK you can't use shell string interpolation from the Popen parameters (your "$(...)" expression). Try encoding the base64 data directly and it will work fine:</p>

```<code>import base64

with open('secret.bin') as x: secret = x.read()

def encrypt():
  arguments = [
    openssl,
    'enc',
    '-aes256',
    '-base64',
    '-k',
    base64.b64encode(secret),
    '-e',
    '-in',
    'plain.txt',
    '-out',
    'cipher.txt',
  ]
</code>```

Body:
I'm trying to make a Python program that runs OpenSSL commands for the encryption and decryption of files.

In the command line I made:

vagrant@vagrant:~$ openssl enc -aes256 -base64 -k $(base64 alice_shared_secret.bin) -e -in plain.txt -out cipher.txt
vagrant@vagrant:~$ openssl enc -aes256 -base64 -k $(base64 bob_shared_secret.bin) -d -in cipher.txt -out plain_again.txt

And it works.
However, if I cipher the text with my Python program, I can't decrypt.

vagrant@vagrant:~$ openssl enc -aes256 -base64 -k $(base64 bob_shared_secret.bin) -d -in cipher.txt -out plain_again.txt
bad decrypt
140321401345688:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:529:

What is the difference between my program and the cipher of the command line?

Code:

#!/System/Library/Frameworks/Python.framework/Versions/2.6/bin/python
openssl         = '/usr/bin/openssl'
from subprocess import Popen, PIPE, STDOUT

def encrypt():
  arguments = [
    openssl,
    'enc',
    '-aes256',
    '-base64',
    '-k',
    '$(base64 alice_shared_secret.bin)',
    '-e',
    '-in',
    'plain.txt',
    '-out',
    'cipher.txt',
  ]

  execute = Popen(arguments, stdout=PIPE)
  out, err = execute.communicate()

encrypt()

Any help?

Body:
AFAIK you can't use shell string interpolation from the Popen parameters (your "$(...)" expression). Try encoding the base64 data directly and it will work fine:

import base64

with open('secret.bin') as x: secret = x.read()

def encrypt():
  arguments = [
    openssl,
    'enc',
    '-aes256',
    '-base64',
    '-k',
    base64.b64encode(secret),
    '-e',
    '-in',
    'plain.txt',
    '-out',
    'cipher.txt',
  ]


问:
adding jquery in Jhipster angular project
I am new in Jhipster and Angular, and I am struggling in adding a jquery instance in my Jhipster Angular project.

I simply need to change the theme and outlook of the default jhipster application. For that purpose I downloaded a theme which has the combination of jquery and bootstrap, therefore, I installed the jquery through npm in the jhipster project.

I can see its folder in the node_modules as well, so it is already available.

Even though I have added its link in the vendor.ts but it seems it does not get loaded. So here my vendor.ts code where I am importing jquery file

```<code>import 'jquery/dist/jquery.min.js';
</code>```

To test my jquery object I coded following in my home.component.ts file.

```<code>import { Component, OnInit } from '@angular/core';
import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { JhiEventManager } from 'ng-jhipster';
import { LoginModalService, AccountService, Account } from 'app/core';

declare var $: any;
@Component({
    selector: 'jhi-home',
    templateUrl: './home.component.html',
    styleUrls: ['home.css'],
})
export class HomeComponent implements OnInit {
    account: Account;
    modalRef: NgbModalRef;

    constructor(
        private accountService: AccountService,
        private loginModalService: LoginModalService,
        private eventManager: JhiEventManager
    ) {}

    ngOnInit() {

        alert('I am Called');

        $(document).ready(function() {
            alert('I am Called From jQuery');
        });

    }
</code>```

But it gives me an error after the page gets loaded

```<code>ERROR ReferenceError: $ is not defined
    at HomeComponent.ngOnInit
</code>```

Any tip on this matter would be highly appreciable.

EDIT: I am adding my angular.json code

```<code>{

"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
    "paperproject": {
        "root": "",
        "sourceRoot": "src/main/webapp",
        "projectType": "application",
        "architect": {}
    }

},
"defaultProject": "paper-auth",
"cli": {
    "packageManager": "npm"
},
"schematics": {
    "@schematics/angular:component": {
        "inlineStyle": true,
        "inlineTemplate": false,
        "spec": false,
        "prefix": "jhi",
        "styleExt": "css"
    },
    "@schematics/angular:directive": {
        "spec": false,
        "prefix": "jhi"
    },
    "@schematics/angular:guard": {
        "spec": false
    },
    "@schematics/angular:pipe": {
        "spec": false
    },
    "@schematics/angular:service": {
        "spec": false
    },
    "scripts": "./node_modules/jquery/dist/jquery.min.js"
}
}
</code>```

It didn't had any script attribute therefore I added script attribute But it still does not work. Jhipster wizard only creates this default angular.json file.
 I added

```<code>  "scripts": "./node_modules/jquery/dist/jquery.min.js"
</code>```

答:
jQuery writes itself to window.$ or if you use jQuery.noConflict() it will appear in window.jQuery, so you can use $ or jQuery on a website. It do not export an object.

To use jQuery in your Angular-project, implement jQuery into your scripts section of you ./angular.json for Angular 6 and 7 or in older projects (Angular 2 - 5) ./angular-cli.json.

Search for "scripts": []

and replace it with

"scripts": ["../node_modules/jquery/dist/jquery.min.js" ]

Then you have access to $ as jQuery in your code.

Body:
I am new in Jhipster and Angular, and I am struggling in adding a jquery instance in my Jhipster Angular project.

I simply need to change the theme and outlook of the default jhipster application. For that purpose I downloaded a theme which has the combination of jquery and bootstrap, therefore, I installed the jquery through npm in the jhipster project.

I can see its folder in the node_modules as well, so it is already available.

Even though I have added its link in the vendor.ts but it seems it does not get loaded. So here my vendor.ts code where I am importing jquery file

import 'jquery/dist/jquery.min.js';

To test my jquery object I coded following in my home.component.ts file.

import { Component, OnInit } from '@angular/core';
import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { JhiEventManager } from 'ng-jhipster';
import { LoginModalService, AccountService, Account } from 'app/core';

declare var $: any;
@Component({
    selector: 'jhi-home',
    templateUrl: './home.component.html',
    styleUrls: ['home.css'],
})
export class HomeComponent implements OnInit {
    account: Account;
    modalRef: NgbModalRef;

    constructor(
        private accountService: AccountService,
        private loginModalService: LoginModalService,
        private eventManager: JhiEventManager
    ) {}

    ngOnInit() {

        alert('I am Called');

        $(document).ready(function() {
            alert('I am Called From jQuery');
        });

    }

But it gives me an error after the page gets loaded

ERROR ReferenceError: $ is not defined
    at HomeComponent.ngOnInit

Any tip on this matter would be highly appreciable.

EDIT: I am adding my angular.json code

{

"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
    "paperproject": {
        "root": "",
        "sourceRoot": "src/main/webapp",
        "projectType": "application",
        "architect": {}
    }

},
"defaultProject": "paper-auth",
"cli": {
    "packageManager": "npm"
},
"schematics": {
    "@schematics/angular:component": {
        "inlineStyle": true,
        "inlineTemplate": false,
        "spec": false,
        "prefix": "jhi",
        "styleExt": "css"
    },
    "@schematics/angular:directive": {
        "spec": false,
        "prefix": "jhi"
    },
    "@schematics/angular:guard": {
        "spec": false
    },
    "@schematics/angular:pipe": {
        "spec": false
    },
    "@schematics/angular:service": {
        "spec": false
    },
    "scripts": "./node_modules/jquery/dist/jquery.min.js"
}
}

It didn't had any script attribute therefore I added script attribute But it still does not work. Jhipster wizard only creates this default angular.json file.
 I added

  "scripts": "./node_modules/jquery/dist/jquery.min.js"