问:
Regular expression for dataframe column
I would like to take out only the date part of my dataframe column which has data like

```<code>$83,00010/7/2016       10/7/2016  # is the date here
$721,0002/7/2015       2/7/2015  # is the date here
$3,00012/12/2015       12/12/2015  # is the date here
</code>```

I tried patterns like

```<code>^(?!,\d{3}) and (\$[,\d{3}]*\,\d{3})
</code>```

but I am not able to exactly pick just the date part.

答:
This is slightly complicated, let's start with a simple expression, then we would expand it. I'm hoping that we would have , in our money part, then we might try:

```<code>,\d{3}(\d{1,2}\/.+?\/\d{4})
</code>```

DEMO

or

```<code>([1-3]?\d\/.+?\/\d{4})
</code>```

DEMO

Test

```<code># coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"([1-3]?\d\/.+?\/\d{4})"

test_str = ("$83,00010/7/2016 ----> 10/7/2016 is the date here,\n"
    "$721,0002/7/2015 ----> 2/7/2015 is the date here,\n"
    "$3,00012/12/2015  -----> 12/12/2015 is the date here")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
</code>```

RegEx Circuit

jex.im visualizes regular expressions:

Title: Regular expression for dataframe column

Body:
I would like to take out only the date part of my dataframe column which has data like

$83,00010/7/2016       10/7/2016  # is the date here
$721,0002/7/2015       2/7/2015  # is the date here
$3,00012/12/2015       12/12/2015  # is the date here

I tried patterns like

^(?!,\d{3}) and (\$[,\d{3}]*\,\d{3})

but I am not able to exactly pick just the date part.

Body:
This is slightly complicated, let's start with a simple expression, then we would expand it. I'm hoping that we would have , in our money part, then we might try:

,\d{3}(\d{1,2}\/.+?\/\d{4})

DEMO

or

([1-3]?\d\/.+?\/\d{4})

DEMO

Test

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"([1-3]?\d\/.+?\/\d{4})"

test_str = ("$83,00010/7/2016 ----> 10/7/2016 is the date here,\n"
    "$721,0002/7/2015 ----> 2/7/2015 is the date here,\n"
    "$3,00012/12/2015  -----> 12/12/2015 is the date here")

matches = re.finditer(regex, test_str, re.MULTILINE)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

RegEx Circuit

jex.im visualizes regular expressions:


来源: stackexchange

问:
Precompilation and startup times on ASP.Net
I am developping a (relatively small) website in ASP.Net 2.0. I am also using nAnt to perform some easy tweaking on my project before delivering executables. In its current state, the website is "precompiled" using

aspnet_compiler.exe -nologo -v ${Appname} -u ${target}

I have noticed that after the IIS pool is restarted (after a idle shutdown or a recycle), the application takes up to 20 seconds before it is back online (and Application_start is reached).

I don't have the same issue when I am debugging directly within Visual Studio (it takes 2 seconds to start) so I am wondering if the aspnet_compiler is really such a good idea.

I couldn't find much on MSDN. How do you compile your websites for production?

答:
@Simon:

The project is a Web Application. Websites are then slower to startup (I had no idea it had an incidence, beside the different code organization)?

I checked, and while I edit the web.config after aspnet_compiler is called, I don't touch the debug value (I will however check the website is not faster to startup if I don't touch the web.config, just to make sure)

(And I will definitely have a look at ngen, I was not aware of that tool.)

OwnerDisplayName: lucasbfr

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: ScottCher


问:
PHP join help with two tables
I am just learning php as I go along, and I'm completely lost here.  I've never really used join before, and I think I need to here, but I don't know.  I'm not expecting anyone to do it for me but if you could just point me in the right direction it would be amazing, I've tried reading up on joins but there are like 20 different methods and I'm just lost.

Basically, I hand coded a forum, and it works fine but is not efficient.

I have board_posts (for posts) and board_forums (for forums, the categories as well as the sections).

The part I'm redoing is how I get the information for the last post for the index page. The way I set it up is that to avoid using joins, I have it store the info for latest post in the table for board_forums, so say there is a section called "Off Topic" there I would have a field for "forum_lastpost_username/userid/posttitle/posttime" which I woudl update when a user posts etc.  But this is bad, I'm trying to grab it all dynamically and get rid of those fields.

Right now my query is just like:

```<code>`SELECT * FROM board_forums WHERE forum_parent='$forum_id''
</code>```

And then I have the stuff where I grab the info for that forum (name, description, etc) and all the data for the last post is there:

```<code>    $last_thread_title = $forumrow["forum_lastpost_title"];
    $last_thread_time = $forumrow["forum_lastpost_time"];
    $lastpost_username = $forumrow["forum_lastpost_username"];
    $lastpost_threadid = $forumrow["forum_lastpost_threadid"];
</code>```

But I need to get rid of that, and get it from board_posts. The way it's set up in board_posts is that if it's a thread, post_parentpost is NULL, if it's a reply, then that field has the id of the thread (first post of the topic).  So, I need to grab the latest post_date, see which user posted that, THEN see if parentpost is NULL (if it's null then the last post is a new thread, so I can get all the info of the title and user there, but if it's not, then I need to get the info (title, id) of the first post in that thread (which can be found by seeing what post_parentpost is, looking up that ID and getting the title from it.

Does that make any sense? If so please help me out :(

Any help is greatly appreciated!!!!

答:
It looks like you've already done the right thing.

If you were to join, you'd do it like this:

```<code>SELECT * FROM board_forums
JOIN board_posts ON board_posts.forum_id = board_forums.id
WHERE forum_parent = '$forum_id'
</code>```

The problem with that, is that it gets you every post, which is not useful (and very slow). What you would want to do is something like this

```<code>SELECT * FROM board_forums
JOIN board_posts ON board_posts.forum_id = board_forums.id ORDER BY board_posts.id desc LIMIT 1
WHERE forum_parent = '$forum_id'
</code>```

except SQL doesn't work like that. You can't order or limit on a join (or do many other useful things like that), so you have to fetch every row and then scan them in code (which sucks).

In short, don't worry. Use joins for the actual case where you do want to load all forums and all posts in one hit.

OwnerDisplayName: Vadim

LastEditorDisplayName: Vadim

Title: PHP join help with two tables

Body:
I am just learning php as I go along, and I'm completely lost here.  I've never really used join before, and I think I need to here, but I don't know.  I'm not expecting anyone to do it for me but if you could just point me in the right direction it would be amazing, I've tried reading up on joins but there are like 20 different methods and I'm just lost.

Basically, I hand coded a forum, and it works fine but is not efficient.

I have board_posts (for posts) and board_forums (for forums, the categories as well as the sections).

The part I'm redoing is how I get the information for the last post for the index page. The way I set it up is that to avoid using joins, I have it store the info for latest post in the table for board_forums, so say there is a section called "Off Topic" there I would have a field for "forum_lastpost_username/userid/posttitle/posttime" which I woudl update when a user posts etc.  But this is bad, I'm trying to grab it all dynamically and get rid of those fields.

Right now my query is just like:

`SELECT * FROM board_forums WHERE forum_parent='$forum_id''

And then I have the stuff where I grab the info for that forum (name, description, etc) and all the data for the last post is there:

    $last_thread_title = $forumrow["forum_lastpost_title"];
    $last_thread_time = $forumrow["forum_lastpost_time"];
    $lastpost_username = $forumrow["forum_lastpost_username"];
    $lastpost_threadid = $forumrow["forum_lastpost_threadid"];

But I need to get rid of that, and get it from board_posts. The way it's set up in board_posts is that if it's a thread, post_parentpost is NULL, if it's a reply, then that field has the id of the thread (first post of the topic).  So, I need to grab the latest post_date, see which user posted that, THEN see if parentpost is NULL (if it's null then the last post is a new thread, so I can get all the info of the title and user there, but if it's not, then I need to get the info (title, id) of the first post in that thread (which can be found by seeing what post_parentpost is, looking up that ID and getting the title from it.

Does that make any sense? If so please help me out :(

Any help is greatly appreciated!!!!

Body:
It looks like you've already done the right thing.

If you were to join, you'd do it like this:

SELECT * FROM board_forums
JOIN board_posts ON board_posts.forum_id = board_forums.id
WHERE forum_parent = '$forum_id'

The problem with that, is that it gets you every post, which is not useful (and very slow). What you would want to do is something like this

SELECT * FROM board_forums
JOIN board_posts ON board_posts.forum_id = board_forums.id ORDER BY board_posts.id desc LIMIT 1
WHERE forum_parent = '$forum_id'

except SQL doesn't work like that. You can't order or limit on a join (or do many other useful things like that), so you have to fetch every row and then scan them in code (which sucks).

In short, don't worry. Use joins for the actual case where you do want to load all forums and all posts in one hit.

OwnerDisplayName: Orion Edwards


问:
Moment JS start and end of given month
I need to calculate a JS date given year=2014 and month=9 (September 2014).

I tried this:

```<code>var moment = require('moment');
var startDate = moment( year+'-'+month+'-'+01 + ' 00:00:00' );
            var endDate = startDate.endOf('month');
            console.log(startDate.toDate());
            console.log(endDate.toDate());
</code>```

Both of logs show:

```<code>Tue Sep 30 2014 23:59:59 GMT+0200 (CEST)
Tue Sep 30 2014 23:59:59 GMT+0200 (CEST)
</code>```

End date is correct but... why the start date is not?

答:
Try the following code:</p>

```<code>moment(startDate).startOf('months')
moment(startDate).endOf('months')
</code>```

ContentLicense: CC BY-SA 3.0

Title: Moment JS start and end of given month

Body:
I need to calculate a JS date given year=2014 and month=9 (September 2014).

I tried this:

var moment = require('moment');
var startDate = moment( year+'-'+month+'-'+01 + ' 00:00:00' );
            var endDate = startDate.endOf('month');
            console.log(startDate.toDate());
            console.log(endDate.toDate());

Both of logs show:

Tue Sep 30 2014 23:59:59 GMT+0200 (CEST)
Tue Sep 30 2014 23:59:59 GMT+0200 (CEST)

End date is correct but... why the start date is not?

Body:
Try the following code:

moment(startDate).startOf('months')
moment(startDate).endOf('months')

ContentLicense: CC BY-SA 4.0


问:
Pandas: Faster way to do complex column transposition with pivot function
Simply put, I need to convert the following input dataframe to the output below.

After a few hours struggling to figure out how, by combining multiple previous stackoverflow questions, I could transform dataframe, but it takes so much time for large dataframe to convert since I use pivot and apply method.

```<code>import numpy as np
import pandas as pd
df = pd.DataFrame({"id":[1,2,3,4,5],
                  "day":pd.Timestamp('20190529'),
                  "subject":"math,english,economics",
                  "score":pd.Categorical(["68,62,49","58,72,87","28,32,46","48,72,66","46,25,93"]),
                  "Department":pd.Categorical(["Economics","Computer Science","Sociology","Business","Math"])})

---Input DataFrame---

    id    day           subject                score       Department
0   1   2019-05-29  math,english,economics    68,62,49    Economics
1   2   2019-05-29  math,economics             58,87       Computer Science
2   3   2019-05-29  philosophy,english,business 28,32,46    Sociology
3   4   2019-05-29  physics,sociology           72,66      Business
4   5   2019-05-29  Math                          93          Math
</code>```

And output is like the one below

```<code>---Output DataFrame---

id  day         Department          Math business economics english math philosophy physics sociology
1   2019-05-29  Economics           NaN NaN 49  62  68  NaN NaN NaN
2   2019-05-29  Computer Science    NaN NaN 87  NaN 58  NaN NaN NaN
3   2019-05-29  Sociology           NaN 46  NaN 32  NaN 28  NaN NaN
4   2019-05-29  Business            NaN NaN NaN NaN NaN NaN 72  66
5   2019-05-29  Math                93  NaN NaN NaN NaN NaN NaN NaN
</code>```

And my approach is

I split subject and score columns by ','.

Explode the list of elements in subject and score columns to separate row as pandas.Series

Join each pandas.Series to make new dataframe

Pivot new dataframe created in step 3

Drop subject and score column in original dataframe

Join each dataframe made in step 4 and step 5

And my code is as follows

```<code>df["subject"] = df["subject"].str.split(",")
df["score"] = df["score"].str.split(",")

subject = df.apply(lambda x: pd.Series(x['subject']),axis=1).stack().reset_index(level=1, drop=True)
score = df.apply(lambda x: pd.Series(x['score']),axis=1).stack().reset_index(level=1, drop=True)
subject.name = 'subject'
score.name = 'score'

subject_score = pd.concat([subject, score],join='outer', axis=1)
pdf = df.drop('subject', axis=1).drop("score", axis=1).join(subject_score)

pivot = pdf.pivot(columns="subject",values="score")
concate_table = df.drop("subject",axis = 1).drop("score", axis=1)
output = concate_table.join(pivot)
</code>```

I just started learning pandas recently and I am sure this wouldn't be best way to column transposition.

If you could give me some advice how to optimize this code, I appreciate.

Thank you in advance.

答:
I would define a custom function stack_str to unpack string column to dataframe using expand=True and stack and reset_index to a series.

Apply stack_str to 2 columns of strings to make df1 of 2 columns.

Next, do pivot on df1 to make subject values as columns and scores as values. Finally, join back to df already dropped 2 columns having strings.

```<code>def stack_str(x):
        s = x.str.split(',', expand=True).stack().reset_index(level=-1, drop=True)
        return s

df1 = df[['subject', 'score']].apply(stack_list)

Out[984]:
      subject score
0        math    68
0     english    62
0   economics    49
1        math    58
1   economics    87
2  philosophy    28
2     english    32
2    business    46
3     physics    72
3   sociology    66
4        Math    93

df2 = df.drop(['subject', 'score'], axis=1).join(df1.pivot(columns='subject', values='score'))

Out[986]:
   id         day        Department Math business economics english math  \
0   1  2019-05-29         Economics  NaN      NaN        49      62   68
1   2  2019-05-29  Computer_Science  NaN      NaN        87     NaN   58
2   3  2019-05-29         Sociology  NaN       46       NaN      32  NaN
3   4  2019-05-29          Business  NaN      NaN       NaN     NaN  NaN
4   5  2019-05-29              Math   93      NaN       NaN     NaN  NaN

  philosophy physics sociology
0        NaN     NaN       NaN
1        NaN     NaN       NaN
2         28     NaN       NaN
3        NaN      72        66
4        NaN     NaN       NaN
</code>```

Body:
Simply put, I need to convert the following input dataframe to the output below.

After a few hours struggling to figure out how, by combining multiple previous stackoverflow questions, I could transform dataframe, but it takes so much time for large dataframe to convert since I use pivot and apply method.

import numpy as np
import pandas as pd
df = pd.DataFrame({"id":[1,2,3,4,5],
                  "day":pd.Timestamp('20190529'),
                  "subject":"math,english,economics",
                  "score":pd.Categorical(["68,62,49","58,72,87","28,32,46","48,72,66","46,25,93"]),
                  "Department":pd.Categorical(["Economics","Computer Science","Sociology","Business","Math"])})

---Input DataFrame---

    id    day           subject                score       Department
0   1   2019-05-29  math,english,economics    68,62,49    Economics
1   2   2019-05-29  math,economics             58,87       Computer Science
2   3   2019-05-29  philosophy,english,business 28,32,46    Sociology
3   4   2019-05-29  physics,sociology           72,66      Business
4   5   2019-05-29  Math                          93          Math

And output is like the one below

---Output DataFrame---

id  day         Department          Math business economics english math philosophy physics sociology
1   2019-05-29  Economics           NaN NaN 49  62  68  NaN NaN NaN
2   2019-05-29  Computer Science    NaN NaN 87  NaN 58  NaN NaN NaN
3   2019-05-29  Sociology           NaN 46  NaN 32  NaN 28  NaN NaN
4   2019-05-29  Business            NaN NaN NaN NaN NaN NaN 72  66
5   2019-05-29  Math                93  NaN NaN NaN NaN NaN NaN NaN

And my approach is

I split subject and score columns by ','.

Explode the list of elements in subject and score columns to separate row as pandas.Series

Join each pandas.Series to make new dataframe

Pivot new dataframe created in step 3

Drop subject and score column in original dataframe

Join each dataframe made in step 4 and step 5

And my code is as follows

df["subject"] = df["subject"].str.split(",")
df["score"] = df["score"].str.split(",")

subject = df.apply(lambda x: pd.Series(x['subject']),axis=1).stack().reset_index(level=1, drop=True)
score = df.apply(lambda x: pd.Series(x['score']),axis=1).stack().reset_index(level=1, drop=True)
subject.name = 'subject'
score.name = 'score'

subject_score = pd.concat([subject, score],join='outer', axis=1)
pdf = df.drop('subject', axis=1).drop("score", axis=1).join(subject_score)

pivot = pdf.pivot(columns="subject",values="score")
concate_table = df.drop("subject",axis = 1).drop("score", axis=1)
output = concate_table.join(pivot)

I just started learning pandas recently and I am sure this wouldn't be best way to column transposition.

If you could give me some advice how to optimize this code, I appreciate.

Thank you in advance.

Body:
I would define a custom function stack_str to unpack string column to dataframe using expand=True and stack and reset_index to a series.

Apply stack_str to 2 columns of strings to make df1 of 2 columns.

Next, do pivot on df1 to make subject values as columns and scores as values. Finally, join back to df already dropped 2 columns having strings.

def stack_str(x):
        s = x.str.split(',', expand=True).stack().reset_index(level=-1, drop=True)
        return s

df1 = df[['subject', 'score']].apply(stack_list)

Out[984]:
      subject score
0        math    68
0     english    62
0   economics    49
1        math    58
1   economics    87
2  philosophy    28
2     english    32
2    business    46
3     physics    72
3   sociology    66
4        Math    93

df2 = df.drop(['subject', 'score'], axis=1).join(df1.pivot(columns='subject', values='score'))

Out[986]:
   id         day        Department Math business economics english math  \
0   1  2019-05-29         Economics  NaN      NaN        49      62   68
1   2  2019-05-29  Computer_Science  NaN      NaN        87     NaN   58
2   3  2019-05-29         Sociology  NaN       46       NaN      32  NaN
3   4  2019-05-29          Business  NaN      NaN       NaN     NaN  NaN
4   5  2019-05-29              Math   93      NaN       NaN     NaN  NaN

  philosophy physics sociology
0        NaN     NaN       NaN
1        NaN     NaN       NaN
2         28     NaN       NaN
3        NaN      72        66
4        NaN     NaN       NaN


问:
h have aproblem when i tried to excute angular funtion from custom confirm-dialog component
I created custom angular confirm dialog component which contains two buttons
I send callback function for every button
but I faced a problem because in dialog custom control can't read main component form control.

Custom Control service

```<code>   export class ConfirmDialogService {
  private subject = new Subject<any>();
    constructor() { }
    confirmThis(message: string, siFn: () => void, noFn: () => void) {
        this.setConfirmation(message, siFn, noFn);
    }
    setConfirmation(message: string, siFn: () => void, noFn: () => void) {
        let that = this;
        this.subject.next({
            type: "confirm",
            text: message,
            siFn:
                function () {
                    that.subject.next(); //this will close the modal
                    siFn();
                },
            noFn: function () {
                that.subject.next();
                noFn();
            }
        });

    }
    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }
}
</code>```

my main component

```<code>showDialog() {
    this.confirmDialogService.confirmThis("Are you sure to delete?", function () {
      this.searchForm.get("SearchText").setValue(null); // error here can't read any form control
    }, function () {
      alert("No clicked");
    })
  }
</code>```

答:
You have to change your function declarations to arrow functions:

```<code>    setConfirmation(message: string, siFn: () => void, noFn: () => void) {
    this.subject.next({
        type: "confirm",
        text: message,
        siFn:
            () => {
                this.subject.next(); //this will close the modal
                siFn();
            },
        noFn: () => {
            this.subject.next();
            noFn();
        }
    });

}
</code>```

As you can see, I erased the:

```<code>let that = this;
</code>```

because when we use arrow functions we are keeping the class scope in this case the "ConfirmDialogService".

I recommend you read this.

Body:
I created custom angular confirm dialog component which contains two buttons
I send callback function for every button
but I faced a problem because in dialog custom control can't read main component form control.

Custom Control service

   export class ConfirmDialogService {
  private subject = new Subject<any>();
    constructor() { }
    confirmThis(message: string, siFn: () => void, noFn: () => void) {
        this.setConfirmation(message, siFn, noFn);
    }
    setConfirmation(message: string, siFn: () => void, noFn: () => void) {
        let that = this;
        this.subject.next({
            type: "confirm",
            text: message,
            siFn:
                function () {
                    that.subject.next(); //this will close the modal
                    siFn();
                },
            noFn: function () {
                that.subject.next();
                noFn();
            }
        });

    }
    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }
}

my main component

showDialog() {
    this.confirmDialogService.confirmThis("Are you sure to delete?", function () {
      this.searchForm.get("SearchText").setValue(null); // error here can't read any form control
    }, function () {
      alert("No clicked");
    })
  }

Body:
You have to change your function declarations to arrow functions:

    setConfirmation(message: string, siFn: () => void, noFn: () => void) {
    this.subject.next({
        type: "confirm",
        text: message,
        siFn:
            () => {
                this.subject.next(); //this will close the modal
                siFn();
            },
        noFn: () => {
            this.subject.next();
            noFn();
        }
    });

}

As you can see, I erased the:

let that = this;

because when we use arrow functions we are keeping the class scope in this case the "ConfirmDialogService".

I recommend you read this.


问:
Validation Plugin
I want to learn how to add validation plugin at Jira so I am following https://developer.atlassian.com/server/jira/platform/creating-workflow-extensions/? tutorials part 3. When step 3.1 I faced build failure error could anybody help me

TY

Osman

https://pasteboard.co/IgUNSjj.png

答:
Can you update your atlassian SDK to the latest version and also change the maven-jira-plugin to jira-maven-plugin for the plugin

```<code><build>
<plugins>
  <plugin>
    <groupId>com.atlassian.maven.plugins</groupId>
    <artifactId>jira-maven-plugin</artifactId>
    <version>${amps.version}</version>
</code>```

At the time of writing this answer, put the value of amps.version to 8.0.0 after upgrading your SDK.

I hope this helps you.

Title: Validation Plugin

Body:
Can you update your atlassian SDK to the latest version and also change the maven-jira-plugin to jira-maven-plugin for the plugin

<build>
<plugins>
  <plugin>
    <groupId>com.atlassian.maven.plugins</groupId>
    <artifactId>jira-maven-plugin</artifactId>
    <version>${amps.version}</version>

At the time of writing this answer, put the value of amps.version to 8.0.0 after upgrading your SDK.

I hope this helps you.


问:
Finding out what privilege is required to run a given MongoDB command
I'm running replSetReconfig on the primary of a replica set and get this error:

not authorized on admin to execute command replSetReconfig

It's not documented what privilege this command requires, so the general question is: How can I determine the privilege required to run a given MongoDB command, so that I can run the corresponding db.grantRolesToUser() command and grant the user the necessary privilege?

答:
One solution is to look through the built-in roles page for the operation you want to perform.

In this case, clusterManager provides the replSetConfigure action.


问:
Toggle and Modals are not working on Angular app
I am new to Angular and having some issues with getting Bootstrap toggle and Modal to work. BootStrap CSS files are working because the form is picking up the styling; however, I reckon JS files are not being linked properly. Please let me know what am I doing working.

I did an NPM install of BootStrap and jQuery using the Angular CLI.
Once installed, I linked the BootStrap and jQuery files to the angular.json file for the application to be able to use the libraries.

```<code>"build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/LyndaChapter1",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            **"styles": [
              **"node_modules/bootstrap/dist/css/bootstrap.css",
              "src/styles.css"**
            ],
            "scripts": [
              "node_modules/bootstrap/dist/js/bootstrap.js",
              "node_modules/jquery/dist/jquery.js"
            ],**
            "es5BrowserSupport": true
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            }
          }
        },
</code>```

Expected result: Toggle and Modals should work
Actual result: Neither are working

答:
Try adding these packages to your package.json file and run npm install --save command on Package.json file level.

/* "@ng-bootstrap/ng-bootstrap": "^4.1.0",
    "bootstrap": "^4.3.1" */

Body:
I am new to Angular and having some issues with getting Bootstrap toggle and Modal to work. BootStrap CSS files are working because the form is picking up the styling; however, I reckon JS files are not being linked properly. Please let me know what am I doing working.

I did an NPM install of BootStrap and jQuery using the Angular CLI.
Once installed, I linked the BootStrap and jQuery files to the angular.json file for the application to be able to use the libraries.

"build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/LyndaChapter1",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            **"styles": [
              **"node_modules/bootstrap/dist/css/bootstrap.css",
              "src/styles.css"**
            ],
            "scripts": [
              "node_modules/bootstrap/dist/js/bootstrap.js",
              "node_modules/jquery/dist/jquery.js"
            ],**
            "es5BrowserSupport": true
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            }
          }
        },

Expected result: Toggle and Modals should work
Actual result: Neither are working


问:
Wait for Localstorage then call api
I get settings from user inputs and store it by localstorage. I use this data in the API Call.

```<code> userlocation;
 userservice ;
 usercategory ;

 constructor(public http: HttpClient, public storage : Storage) { }

 getListings(){

 this.storage.get('area').then((userlocation) => {
  this.userlocation =  userlocation;

  console.log(this.userlocation)
 });

  this.storage.get('ser').then((userservice) => {
  this.userservice =  userservice;

  console.log(this.userlocation)
 });

  return  this.http.get(this.api_url+"?location="+ this.userlocation+
  "&ser= " + this.userservice)

 }
</code>```

the problem that the api call happens before localstorage get the data.
How I can make The api call wait for localstorage

答:
Using async and await you can resolve this.</p>

```<code>userlocation;
 userservice ;
 usercategory ;

 constructor(public http: HttpClient, public storage : Storage) { }

 async getListings(){

 await this.storage.get('area').then((userlocation) => {
  this.userlocation =  userlocation;

  console.log(this.userlocation);

    await this.storage.get('ser').then((userservice) => {
      this.userservice =  userservice;

      console.log(this.userlocation)
    });
 });

  return  this.http.get(this.api_url+"?location="+ this.userlocation+
  "&ser= " + this.userservice)

 }
</code>```

Title: Wait for Localstorage then call api

Body:
I get settings from user inputs and store it by localstorage. I use this data in the API Call.

 userlocation;
 userservice ;
 usercategory ;

 constructor(public http: HttpClient, public storage : Storage) { }

 getListings(){

 this.storage.get('area').then((userlocation) => {
  this.userlocation =  userlocation;

  console.log(this.userlocation)
 });

  this.storage.get('ser').then((userservice) => {
  this.userservice =  userservice;

  console.log(this.userlocation)
 });

  return  this.http.get(this.api_url+"?location="+ this.userlocation+
  "&ser= " + this.userservice)

 }

the problem that the api call happens before localstorage get the data.
How I can make The api call wait for localstorage

Body:
Using async and await you can resolve this.

userlocation;
 userservice ;
 usercategory ;

 constructor(public http: HttpClient, public storage : Storage) { }

 async getListings(){

 await this.storage.get('area').then((userlocation) => {
  this.userlocation =  userlocation;

  console.log(this.userlocation);

    await this.storage.get('ser').then((userservice) => {
      this.userservice =  userservice;

      console.log(this.userlocation)
    });
 });

  return  this.http.get(this.api_url+"?location="+ this.userlocation+
  "&ser= " + this.userservice)

 }


问:
MariaDB server times out client connection after 600 seconds
My MariaDB server is timing out my C++ client (using libmariadb) after 600 seconds (10 minutes) of inactivity, and I'm not sure why, because I can't find any configured timeouts that specify that number.

Here's my code, where I execute a simple SELECT query, wait 11 minutes, then run that same query again and get a "server gone" error:

#include <iostream>
#include <unistd.h>

#include <errmsg.h>
#include <mysql.h>

int main(int, char**)
{
    // connect to the database
    MYSQL* connection = mysql_init(NULL);
    my_bool reconnect = 0;
    mysql_options(connection, MYSQL_OPT_RECONNECT, &reconnect);  // don't implicitly reconnect
    mysql_real_connect(connection, "127.0.0.1", "testuser", "password",
                       "my_test_db", 3306, NULL, 0);

    // run a simple query
    mysql_query(connection, "select 5");
    mysql_free_result(mysql_store_result(connection));
    std::cout << "First query done...\n";

    // sleep for 11 minutes
    sleep(660);

    // run the query again
    if(! mysql_query(connection, "select 5"))
    {
        std::cout << "Second query succeeded after " << seconds << " seconds\n";
        mysql_free_result(mysql_store_result(connection));
    }
    else
    {
        if(mysql_errno(connection) == CR_SERVER_GONE_ERROR)
        {
            // **** this happens every time ****
            std::cout << "Server went away after " << seconds << " seconds\n";
        }
    }

    // close the connection
    mysql_close(connection);
    connection = nullptr;

    return 0;
}
```
<p>The stdout of the server process reports that it timed out my connection:</p>
```$ sudo journalctl -u mariadb
...
Jul 24 17:58:31 myhost mysqld[407]: 2018-07-24 17:58:31 139667452651264 [Warning] Aborted connection 222 to db: 'my_test_db' user: 'testuser' host: 'localhost' (Got timeout reading communication packets)
...
```
<p>Looking at a tcpdump capture, I can also see the server sending the client a TCP FIN packet, which closes the connection.</p>
<p>The reason I'm stumped is because I haven't changed any of the default timeout values, <em>none</em> of which are even 600 seconds:</p>
```MariaDB [(none)]> show variables like '%timeout%';
+-------------------------------------+----------+
| Variable_name                       | Value    |
+-------------------------------------+----------+
| connect_timeout                     | 10       |
| deadlock_timeout_long               | 50000000 |
| deadlock_timeout_short              | 10000    |
| delayed_insert_timeout              | 300      |
| innodb_flush_log_at_timeout         | 1        |
| innodb_lock_wait_timeout            | 50       |
| innodb_print_lock_wait_timeout_info | OFF      |
| innodb_rollback_on_timeout          | OFF      |
| interactive_timeout                 | 28800    |
| lock_wait_timeout                   | 31536000 |
| net_read_timeout                    | 30       |
| net_write_timeout                   | 60       |
| slave_net_timeout                   | 3600     |
| thread_pool_idle_timeout            | 60       |
| wait_timeout                        | 28800    |
+-------------------------------------+----------+
```

So why is the server timing out my connection? Based on the documentation, I would have thought it would have been because of the wait_timeout server variable, but it's left at the default of 8 hours...

BTW I'm using MariaDB 10.0 and libmariadb 2.0 (from the Ubuntu Xenial Universe repo)

Edit: here's an image of a tcpdump capture catching the disconnect. My Wireshark filter is tcp.port == 55916, so I'm looking at traffic to/from this one client connection. The FIN packet that the server sends is packet 1199, exactly 600 seconds after the previous packet (884).

答:
Galera cluster with Haproxy Load balancing. Change this parameter on haproxy
settings</p>

```<code>defaults
    timeout connect 10s
    timeout client 30s
    timeout server 30s
</code>```

Body:
My MariaDB server is timing out my C++ client (using libmariadb) after 600 seconds (10 minutes) of inactivity, and I'm not sure why, because I can't find any configured timeouts that specify that number.

Here's my code, where I execute a simple SELECT query, wait 11 minutes, then run that same query again and get a "server gone" error:

#include <iostream>
#include <unistd.h>

#include <errmsg.h>
#include <mysql.h>

int main(int, char**)
{
    // connect to the database
    MYSQL* connection = mysql_init(NULL);
    my_bool reconnect = 0;
    mysql_options(connection, MYSQL_OPT_RECONNECT, &reconnect);  // don't implicitly reconnect
    mysql_real_connect(connection, "127.0.0.1", "testuser", "password",
                       "my_test_db", 3306, NULL, 0);

    // run a simple query
    mysql_query(connection, "select 5");
    mysql_free_result(mysql_store_result(connection));
    std::cout << "First query done...\n";

    // sleep for 11 minutes
    sleep(660);

    // run the query again
    if(! mysql_query(connection, "select 5"))
    {
        std::cout << "Second query succeeded after " << seconds << " seconds\n";
        mysql_free_result(mysql_store_result(connection));
    }
    else
    {
        if(mysql_errno(connection) == CR_SERVER_GONE_ERROR)
        {
            // **** this happens every time ****
            std::cout << "Server went away after " << seconds << " seconds\n";
        }
    }

    // close the connection
    mysql_close(connection);
    connection = nullptr;

    return 0;
}

The stdout of the server process reports that it timed out my connection:

$ sudo journalctl -u mariadb
...
Jul 24 17:58:31 myhost mysqld[407]: 2018-07-24 17:58:31 139667452651264 [Warning] Aborted connection 222 to db: 'my_test_db' user: 'testuser' host: 'localhost' (Got timeout reading communication packets)
...

Looking at a tcpdump capture, I can also see the server sending the client a TCP FIN packet, which closes the connection.

The reason I'm stumped is because I haven't changed any of the default timeout values, none of which are even 600 seconds:

MariaDB [(none)]> show variables like '%timeout%';
+-------------------------------------+----------+
| Variable_name                       | Value    |
+-------------------------------------+----------+
| connect_timeout                     | 10       |
| deadlock_timeout_long               | 50000000 |
| deadlock_timeout_short              | 10000    |
| delayed_insert_timeout              | 300      |
| innodb_flush_log_at_timeout         | 1        |
| innodb_lock_wait_timeout            | 50       |
| innodb_print_lock_wait_timeout_info | OFF      |
| innodb_rollback_on_timeout          | OFF      |
| interactive_timeout                 | 28800    |
| lock_wait_timeout                   | 31536000 |
| net_read_timeout                    | 30       |
| net_write_timeout                   | 60       |
| slave_net_timeout                   | 3600     |
| thread_pool_idle_timeout            | 60       |
| wait_timeout                        | 28800    |
+-------------------------------------+----------+

So why is the server timing out my connection? Based on the documentation, I would have thought it would have been because of the wait_timeout server variable, but it's left at the default of 8 hours...

BTW I'm using MariaDB 10.0 and libmariadb 2.0 (from the Ubuntu Xenial Universe repo)

Edit: here's an image of a tcpdump capture catching the disconnect. My Wireshark filter is tcp.port == 55916, so I'm looking at traffic to/from this one client connection. The FIN packet that the server sends is packet 1199, exactly 600 seconds after the previous packet (884).

Body:
Galera cluster with Haproxy Load balancing. Change this parameter on haproxy
settings

defaults
    timeout connect 10s
    timeout client 30s
    timeout server 30s


问:
Check for value changes in variable
I have 2 components in my angular app. Component A is a header and component B sets a value that I need in component A. The problem is that component A is getting set before B so the value that I need is not being displayed when I need it. If I refresh my browser then it shows. My code will explain better.

Component A

```<code>  offerExpiry: any;

  constructor(
    public expiry: ExploreOfferService
  ) {

  }
  ngOnChanges() {
    this.expiry.event.subscribe((data) => {
      this.offerExpiry = data;
    });
  }

  <div class="col-5 right">
    <div>
      <span *ngIf="offerExpiry">{{offerExpiry?.data}} days left to respond</span>
      <img src="../../../../assets/icons/calendar(old).png">
    </div>
  </div>
</code>```

Component B

```<code>offerExpiry: any;

...

  async ngOnInit() {
    if (this._exploreService.offer) {
      ...
    } else {
      const offer = await this._exploreService.getOfferDetails();
      const date1 = new Date(offer.expiryDate);
      const date2 = new Date(offer.startDate);
      const diffTime = Math.abs(date2.getTime() - date1.getTime());
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      this.offerExpiry = diffDays;
      this._exploreService.publishExpiryDate({data: this.offerExpiry});
    }
  }
</code>```

service file

```<code>  public publishExpiryDate(data: any) {
    this._subject.next(data);
  }
</code>```

答:
When you are getting data from service do this in your service: create a subject and a method to get it subscribed in component B

```<code>private com_sub = new Subject<any>();
getData(): Observable<any> {
   return this.com_sub.asObservable();
}
</code>```

whenever you get data in from service, pass it to subject:

```<code>this.com_sub.next(data);
</code>```

In Component B, that loads earlier, subscribes that subject like :

```<code>this.yourservice.getData().subscribe(data => {
  console.log('your data here',data);
});
</code>```

Title: Check for value changes in variable

Body:
I have 2 components in my angular app. Component A is a header and component B sets a value that I need in component A. The problem is that component A is getting set before B so the value that I need is not being displayed when I need it. If I refresh my browser then it shows. My code will explain better.

Component A

  offerExpiry: any;

  constructor(
    public expiry: ExploreOfferService
  ) {

  }
  ngOnChanges() {
    this.expiry.event.subscribe((data) => {
      this.offerExpiry = data;
    });
  }

      {{offerExpiry?.data}} days left to respond

Component B

offerExpiry: any;

...

  async ngOnInit() {
    if (this._exploreService.offer) {
      ...
    } else {
      const offer = await this._exploreService.getOfferDetails();
      const date1 = new Date(offer.expiryDate);
      const date2 = new Date(offer.startDate);
      const diffTime = Math.abs(date2.getTime() - date1.getTime());
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      this.offerExpiry = diffDays;
      this._exploreService.publishExpiryDate({data: this.offerExpiry});
    }
  }

service file

  public publishExpiryDate(data: any) {
    this._subject.next(data);
  }

Body:
When you are getting data from service do this in your service: create a subject and a method to get it subscribed in component B

private com_sub = new Subject<any>();
getData(): Observable<any> {
   return this.com_sub.asObservable();
}

whenever you get data in from service, pass it to subject:

this.com_sub.next(data);

In Component B, that loads earlier, subscribes that subject like :

this.yourservice.getData().subscribe(data => {
  console.log('your data here',data);
});


问:
Why I cant use join with regex in mysql?
I want to find some invalid postal codes in my database(which has more than 5 million records) using a regex which i tested in www.regex101.com and some other regex test websites and it works fine. I also need to join the table with another one to find more details about that record. But the query doesnt work and keeps searching without ANY errors. I have used this exact regex for another query without the join and for only one table and it works. So i think its not about back references which some other developers told me.

This is the query ive tried and didnt work:

```<code>"SELECT a.Name,a.AdslTel,a.Mobile, b.CodePosty
 FROM on_customers as a, on_customers_detail as b
 WHERE a.Serial=b.CustomerRef and a.TownshipRef='1'
 AND b.CodePosty NOT REGEXP '^[13456789]{5}[1-9]([[:digit:]]){3}([1-
 9]){1}$' or b.CodePosty REGEXP '([[:digit:]])\1{5,}' "
</code>```

And this is the query that worked just fine :

```<code>"SELECT * FROM on_customers WHERE Mobile NOT REGEXP '^(09)
([[:digit:]]){9}$'
 or Mobile REGEXP '([[:digit:]])\1{5,}' "
</code>```

答:
NOT a OR b means (NOT a) OR b -- perhaps you want NOT (a OR b)?

a AND b OR c means (a AND b) OR c -- perhaps you want a AND (b OR c)?

Add parentheses, at least when you are unsure of the precedence rules.

Body:
I want to find some invalid postal codes in my database(which has more than 5 million records) using a regex which i tested in www.regex101.com and some other regex test websites and it works fine. I also need to join the table with another one to find more details about that record. But the query doesnt work and keeps searching without ANY errors. I have used this exact regex for another query without the join and for only one table and it works. So i think its not about back references which some other developers told me.

This is the query ive tried and didnt work:

"SELECT a.Name,a.AdslTel,a.Mobile, b.CodePosty
 FROM on_customers as a, on_customers_detail as b
 WHERE a.Serial=b.CustomerRef and a.TownshipRef='1'
 AND b.CodePosty NOT REGEXP '^[13456789]{5}[1-9]([[:digit:]]){3}([1-
 9]){1}$' or b.CodePosty REGEXP '([[:digit:]])\1{5,}' "

And this is the query that worked just fine :

"SELECT * FROM on_customers WHERE Mobile NOT REGEXP '^(09)
([[:digit:]]){9}$'
 or Mobile REGEXP '([[:digit:]])\1{5,}' "


问:
Disable splitpane divider movement in one particular direction
I have a vertical split pane. The top portion contains a table and the bottom portion contains a JInternalFrame that displays console.

I want to restrict the movement of the divider in the downward direction i.e the divider can be moved upwards but cannot be moved down. Is there a way to achieve this?

答: You can set the minimum size of the bottom component. </p>


问:
Can't find "User" class for Dropwizard Authentication
I'm trying to implement an authentication system in my Dropwizard application, but am unable to use the User class that all the examples I can find seem to take for granted.

I'm using the information from Dropwizard's own site, which matches various other tutorials and examples I've found online in how it implements an authenticator.

https://www.dropwizard.io/1.0.0/docs/manual/auth.html

This is the example Authenticator, which I have essentially copied:

```<code> public class ExampleAuthenticator implements Authenticator<BasicCredentials, User> {
     @Override
     public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException {
         if ("secret".equals(credentials.getPassword())) {
             return Optional.of(new User(credentials.getUsername()));
         }
         return Optional.absent();
     }
 }
</code>```

However, when I try to do this, the only way my IDE can resolve the "User" dependency is as User from the "org.jetty.eclipse.Authentication" library, which fails to compile because it does not extend the Principal class required by the Authenticator interface.

This is the relevant portion of my pom:

```<code> <properties>
    <dropwizard.version>1.3.5</dropwizard.version>
</properties>

<dependencies>

    <dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-core</artifactId>
        <version>${dropwizard.version}</version>
    </dependency>

    <dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-jdbi</artifactId>
        <version>${dropwizard.version}</version>
    </dependency>

    <dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-auth</artifactId>
        <version>${dropwizard.version}</version>
    </dependency>

</dependencies>
</code>```

The code either refuses to compile because the Jetty version of "User" doesn't fit the interface, or because it can't find any other version of "User".  Is there a dependency I'm missing?  Am I supposed to be implementing my own User class, and this just wasn't mentioned in any of the samples?

答:
You should supply your own implementation of the Principle interface class. Note the following sentence from the documentation and the second template parameter:

```<code>Authenticators implement the Authenticator<C, P extends Principal> interface, which has a single method:
</code>```

There is the dropwizard-example project where this is demonstrated:

https://github.com/dropwizard/dropwizard/blob/5c74a4894395303fad547b036859ab16535f101a/dropwizard-example/src/main/java/com/example/helloworld/auth/ExampleAuthenticator.java#L3

https://github.com/dropwizard/dropwizard/blob/5c74a4894395303fad547b036859ab16535f101a/dropwizard-example/src/main/java/com/example/helloworld/core/User.java#L6

Body:
I'm trying to implement an authentication system in my Dropwizard application, but am unable to use the User class that all the examples I can find seem to take for granted.

I'm using the information from Dropwizard's own site, which matches various other tutorials and examples I've found online in how it implements an authenticator.

https://www.dropwizard.io/1.0.0/docs/manual/auth.html

This is the example Authenticator, which I have essentially copied:

 public class ExampleAuthenticator implements Authenticator<BasicCredentials, User> {
     @Override
     public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException {
         if ("secret".equals(credentials.getPassword())) {
             return Optional.of(new User(credentials.getUsername()));
         }
         return Optional.absent();
     }
 }

However, when I try to do this, the only way my IDE can resolve the "User" dependency is as User from the "org.jetty.eclipse.Authentication" library, which fails to compile because it does not extend the Principal class required by the Authenticator interface.

This is the relevant portion of my pom:

 <properties>
    <dropwizard.version>1.3.5</dropwizard.version>
</properties>

<dependencies>

    <dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-core</artifactId>
        <version>${dropwizard.version}</version>
    </dependency>

    <dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-jdbi</artifactId>
        <version>${dropwizard.version}</version>
    </dependency>

    <dependency>
        <groupId>io.dropwizard</groupId>
        <artifactId>dropwizard-auth</artifactId>
        <version>${dropwizard.version}</version>
    </dependency>

</dependencies>

The code either refuses to compile because the Jetty version of "User" doesn't fit the interface, or because it can't find any other version of "User".  Is there a dependency I'm missing?  Am I supposed to be implementing my own User class, and this just wasn't mentioned in any of the samples?

Body:
You should supply your own implementation of the Principle interface class. Note the following sentence from the documentation and the second template parameter:

Authenticators implement the Authenticator<C, P extends Principal> interface, which has a single method:

There is the dropwizard-example project where this is demonstrated:

https://github.com/dropwizard/dropwizard/blob/5c74a4894395303fad547b036859ab16535f101a/dropwizard-example/src/main/java/com/example/helloworld/auth/ExampleAuthenticator.java#L3

https://github.com/dropwizard/dropwizard/blob/5c74a4894395303fad547b036859ab16535f101a/dropwizard-example/src/main/java/com/example/helloworld/core/User.java#L6


问:
SELECT JOIN Table Operations
In my query below, I joined tables b, c, d to a by the base_id column.
However, I need to do some operations in my SELECT statement.
Since b, c, and d are not joined to each other,

is my (a.qty - (b.qty - (c.qty + d.qty))) formula computing only those tables that have the same base_id column?

```<code>SELECT (a.qty - (b.qty - (c.qty + d.qty))) AS qc_in
  FROM receiving a
  LEFT JOIN (
     SELECT SUM(qty) AS qty, base_id
        FROM quality_control bb
       WHERE location_to = 6
         AND is_canceled = 0
       GROUP BY base_id
      ) b
         ON b.base_id = a.base_id
  LEFT JOIN (
      SELECT SUM(qty) AS qty, base_id
        FROM quality_control ba
       WHERE location_from = 6
         AND is_canceled = 0
       GROUP BY base_id
      ) c
         ON c.base_id = a.base_id
  LEFT JOIN (
     SELECT SUM(qty) AS qty, base_id
       FROM issuance
      WHERE location_from = 6
        AND is_canceled = 0
      GROUP BY base_id
      ) d
         ON d.base_id = a.base_id
 WHERE a.is_canceled = 0
</code>```

答:
I think you're confused by how joining works (if I'm reading the question correctly). If you have:

```<code>select *
from table1 a
join table2 b
    on a.Id = b.Id
join table3c
    on a.Id = c.Id
</code>```

Then yes a is joined to b, and b is joined to c, but that also means that a is joined to c. One way to think of it is as one giant in-memory table that has all of the a columns then all of the b columns and then all of the c columns in the one result.

If a.Id is 1, and you select the row from b where Id is the same (1) and then you join to c where the Id is the same as a (1), then a, b and c all have the same id.

So yes, (a.qty - (b.qty - (c.qty + d.qty))) will only be doing that calculation for rows where a, b, c and d all have the same base_id .

Title: SELECT JOIN Table Operations

Body:
In my query below, I joined tables b, c, d to a by the base_id column.
However, I need to do some operations in my SELECT statement.
Since b, c, and d are not joined to each other,

is my (a.qty - (b.qty - (c.qty + d.qty))) formula computing only those tables that have the same base_id column?

SELECT (a.qty - (b.qty - (c.qty + d.qty))) AS qc_in
  FROM receiving a
  LEFT JOIN (
     SELECT SUM(qty) AS qty, base_id
        FROM quality_control bb
       WHERE location_to = 6
         AND is_canceled = 0
       GROUP BY base_id
      ) b
         ON b.base_id = a.base_id
  LEFT JOIN (
      SELECT SUM(qty) AS qty, base_id
        FROM quality_control ba
       WHERE location_from = 6
         AND is_canceled = 0
       GROUP BY base_id
      ) c
         ON c.base_id = a.base_id
  LEFT JOIN (
     SELECT SUM(qty) AS qty, base_id
       FROM issuance
      WHERE location_from = 6
        AND is_canceled = 0
      GROUP BY base_id
      ) d
         ON d.base_id = a.base_id
 WHERE a.is_canceled = 0

Body:
I think you're confused by how joining works (if I'm reading the question correctly). If you have:

select *
from table1 a
join table2 b
    on a.Id = b.Id
join table3c
    on a.Id = c.Id

Then yes a is joined to b, and b is joined to c, but that also means that a is joined to c. One way to think of it is as one giant in-memory table that has all of the a columns then all of the b columns and then all of the c columns in the one result.

If a.Id is 1, and you select the row from b where Id is the same (1) and then you join to c where the Id is the same as a (1), then a, b and c all have the same id.

So yes, (a.qty - (b.qty - (c.qty + d.qty))) will only be doing that calculation for rows where a, b, c and d all have the same base_id .


问:
Docker - unable to run Jupyter notebook - KeyError: 'allow_remote_access'
This is my first time using Docker. I am trying to install jupyter and run an ipynb file.
I tried 2 images and ran into the same error on both:

1) python:3.6.2-slim

2) jupyter/datascience-notebook

Dockerfile:

```<code>#Use this python image
FROM python:3.6.2-slim
#Set metadata
LABEL maintainer="MyName"
#Set working directory to /app
WORKDIR /app
#Copy all files  in current directory to working directory (/app)
COPY . /app
#Install the required libraries
RUN pip --no-cache-dir install numpy pandas seaborn sklearn jupyter
#Make port 8888 available to the world outside this Container
EXPOSE 8888
#Run jupyter when container launches
CMD ["jupyter","notebook","--ip='*'","--port=8888","--no-browser","--allow-root"]
</code>```

Build:

```<code>docker build -t helloworld_container .
</code>```

Run:

```<code>docker run -p 9999:8888 helloworld_container
</code>```

I get the following error:

```<code>Traceback (most recent call last):
  File "/opt/conda/lib/python3.6/site-packages/traitlets/traitlets.py", line 528, in get
    value = obj._trait_values[self.name]
KeyError: 'allow_remote_access'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/conda/lib/python3.6/site-packages/notebook/notebookapp.py", line 869, in _default_allow_remote
    addr = ipaddress.ip_address(self.ip)
  File "/opt/conda/lib/python3.6/ipaddress.py", line 54, in ip_address
    address)
ValueError: '' does not appear to be an IPv4 or IPv6 address

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/conda/bin/jupyter-notebook", line 11, in <module>
    sys.exit(main())
  File "/opt/conda/lib/python3.6/site-packages/jupyter_core/application.py", line 266, in launch_instance
    return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/traitlets/config/application.py", line 657, in launch_instance
    app.initialize(argv)
  File "<decorator-gen-7>", line 2, in initialize
  File "/opt/conda/lib/python3.6/site-packages/traitlets/config/application.py", line 87, in catch_config_error
    return method(app, *args, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/notebook/notebookapp.py", line 1629, in initialize
    self.init_webapp()
  File "/opt/conda/lib/python3.6/site-packages/notebook/notebookapp.py", line 1379, in init_webapp
    self.jinja_environment_options,
  File "/opt/conda/lib/python3.6/site-packages/notebook/notebookapp.py", line 158, in __init__
    default_url, settings_overrides, jinja_env_options)
  File "/opt/conda/lib/python3.6/site-packages/notebook/notebookapp.py", line 251, in init_settings
    allow_remote_access=jupyter_app.allow_remote_access,
  File "/opt/conda/lib/python3.6/site-packages/traitlets/traitlets.py", line 556, in __get__
    return self.get(obj, cls)
  File "/opt/conda/lib/python3.6/site-packages/traitlets/traitlets.py", line 535, in get
    value = self._validate(obj, dynamic_default())
  File "/opt/conda/lib/python3.6/site-packages/notebook/notebookapp.py", line 872, in _default_allow_remote
    for info in socket.getaddrinfo(self.ip, self.port, 0, socket.SOCK_STREAM):
  File "/opt/conda/lib/python3.6/socket.py", line 745, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known
</code>```

I think a potential fix to this issue is to update the jupyter_notebook_config.py file. So I need to generate the file using:

```<code>jupyter notebook --generate-config
</code>```

I need to uncomment

```<code>#c.NotebookApp.ip = ‘*’
</code>```

and set it to:

```<code>c.NotebookApp.ip = ‘0.0.0.0’
</code>```

I know how to perform these steps on my machine but I do not know how to perform these steps on the image. So I generated the config file on my machine, made the changes and then copied it to the container by adding the following line to the dockerfile(and creating a new container):

```<code>COPY jupyter_notebook_config.py /config/location/jupyter_notebook_config.py
</code>```

This did not fix the issue.

For now, I have moved to a different image (tensorflow\tensorflow) that has jupyter installed but I want to know what am I doing wrong.

答:
I wanted to run Jupyter notebooks using Docker, and I faced the same problem you have reported. Fortunately, I was able to find a solution.

Note: I am using the continuumio/anaconda3 image.

Steps

Pull the image from Docker Hub

```<code>docker pull continuumio/anaconda3
</code>```

Run the following command (the one provided the documentation image doesn't work and generates the error you have reported)

```<code>docker run -i -t -p 8888:8888 continuumio/anaconda3 /bin/bash -c "/opt/conda/bin/conda install jupyter -y --quiet && mkdir /opt/notebooks && /opt/conda/bin/jupyter notebook --notebook-dir=/opt/notebooks --ip='0.0.0.0' --port=8888 --no-browser --allow-root"
</code>```

There are two crucial modifications to make this work. First, use --ip='0.0.0.0' instead of --ip='*'. Second, add --allow-root to see the notebooks running in the browser.

Adding a volume in a temporal container

If you want to create a temporal container, i.e., one that is removed once it stops running, and you want to create a volume so that you can keep, in your host, the files you created inside the container, use the following command:

```<code>docker run --volume /path/in/your/host/jupyter_notebooks:/opt/notebooks --rm -it -p 8888:8888 continuumio/anaconda3 /bin/bash -c "/opt/conda/bin/conda install jupyter -y --quiet && /opt/conda/bin/jupyter notebook --notebook-dir=/opt/notebooks --ip='0.0.0.0' --port=8888 --no-browser --allow-root"
</code>```

Body:
This is my first time using Docker. I am trying to install jupyter and run an ipynb file.
I tried 2 images and ran into the same error on both:

1) python:3.6.2-slim

2) jupyter/datascience-notebook

Dockerfile:

#Use this python image
FROM python:3.6.2-slim
#Set metadata
LABEL maintainer="MyName"
#Set working directory to /app
WORKDIR /app
#Copy all files  in current directory to working directory (/app)
COPY . /app
#Install the required libraries
RUN pip --no-cache-dir install numpy pandas seaborn sklearn jupyter
#Make port 8888 available to the world outside this Container
EXPOSE 8888
#Run jupyter when container launches
CMD ["jupyter","notebook","--ip='*'","--port=8888","--no-browser","--allow-root"]

Build:

docker build -t helloworld_container .

Run:

docker run -p 9999:8888 helloworld_container

I get the following error:

Traceback (most recent call last):
  File "/opt/conda/lib/python3.6/site-packages/traitlets/traitlets.py", line 528, in get
    value = obj._trait_values[self.name]
KeyError: 'allow_remote_access'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/conda/lib/python3.6/site-packages/notebook/notebookapp.py", line 869, in _default_allow_remote
    addr = ipaddress.ip_address(self.ip)
  File "/opt/conda/lib/python3.6/ipaddress.py", line 54, in ip_address
    address)
ValueError: '' does not appear to be an IPv4 or IPv6 address

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/conda/bin/jupyter-notebook", line 11, in <module>
    sys.exit(main())
  File "/opt/conda/lib/python3.6/site-packages/jupyter_core/application.py", line 266, in launch_instance
    return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/traitlets/config/application.py", line 657, in launch_instance
    app.initialize(argv)
  File "<decorator-gen-7>", line 2, in initialize
  File "/opt/conda/lib/python3.6/site-packages/traitlets/config/application.py", line 87, in catch_config_error
    return method(app, *args, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/notebook/notebookapp.py", line 1629, in initialize
    self.init_webapp()
  File "/opt/conda/lib/python3.6/site-packages/notebook/notebookapp.py", line 1379, in init_webapp
    self.jinja_environment_options,
  File "/opt/conda/lib/python3.6/site-packages/notebook/notebookapp.py", line 158, in __init__
    default_url, settings_overrides, jinja_env_options)
  File "/opt/conda/lib/python3.6/site-packages/notebook/notebookapp.py", line 251, in init_settings
    allow_remote_access=jupyter_app.allow_remote_access,
  File "/opt/conda/lib/python3.6/site-packages/traitlets/traitlets.py", line 556, in __get__
    return self.get(obj, cls)
  File "/opt/conda/lib/python3.6/site-packages/traitlets/traitlets.py", line 535, in get
    value = self._validate(obj, dynamic_default())
  File "/opt/conda/lib/python3.6/site-packages/notebook/notebookapp.py", line 872, in _default_allow_remote
    for info in socket.getaddrinfo(self.ip, self.port, 0, socket.SOCK_STREAM):
  File "/opt/conda/lib/python3.6/socket.py", line 745, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

I think a potential fix to this issue is to update the jupyter_notebook_config.py file. So I need to generate the file using:

jupyter notebook --generate-config

I need to uncomment

#c.NotebookApp.ip = ‘*’

and set it to:

c.NotebookApp.ip = ‘0.0.0.0’

I know how to perform these steps on my machine but I do not know how to perform these steps on the image. So I generated the config file on my machine, made the changes and then copied it to the container by adding the following line to the dockerfile(and creating a new container):

COPY jupyter_notebook_config.py /config/location/jupyter_notebook_config.py

This did not fix the issue.

For now, I have moved to a different image (tensorflow\tensorflow) that has jupyter installed but I want to know what am I doing wrong.

Body:
I wanted to run Jupyter notebooks using Docker, and I faced the same problem you have reported. Fortunately, I was able to find a solution.

Note: I am using the continuumio/anaconda3 image.

Steps

Pull the image from Docker Hub

docker pull continuumio/anaconda3

Run the following command (the one provided the documentation image doesn't work and generates the error you have reported)

docker run -i -t -p 8888:8888 continuumio/anaconda3 /bin/bash -c "/opt/conda/bin/conda install jupyter -y --quiet && mkdir /opt/notebooks && /opt/conda/bin/jupyter notebook --notebook-dir=/opt/notebooks --ip='0.0.0.0' --port=8888 --no-browser --allow-root"

There are two crucial modifications to make this work. First, use --ip='0.0.0.0' instead of --ip='*'. Second, add --allow-root to see the notebooks running in the browser.

Adding a volume in a temporal container

If you want to create a temporal container, i.e., one that is removed once it stops running, and you want to create a volume so that you can keep, in your host, the files you created inside the container, use the following command:

docker run --volume /path/in/your/host/jupyter_notebooks:/opt/notebooks --rm -it -p 8888:8888 continuumio/anaconda3 /bin/bash -c "/opt/conda/bin/conda install jupyter -y --quiet && /opt/conda/bin/jupyter notebook --notebook-dir=/opt/notebooks --ip='0.0.0.0' --port=8888 --no-browser --allow-root"


问:
Simplest method to Convert Json to Xml
I have web-service in .net. When I retrieve data from database, it returns JSON File in Android Mobile. How can I convert JSON File to XML Or text.</p>

答:
Underscore-java library has static method U.jsonToXml(string). Live example

```<code>import com.github.underscore.U;

public class MyClass {
    public static void main(String args[]) {
        String json = "{\"Price\": {"
        + "    \"LineItems\": {"
        + "        \"LineItem\": {"
        + "            \"UnitOfMeasure\": \"EACH\", \"Quantity\": 2, \"ItemID\": \"ItemID\""
        + "        }"
        + "    },"
        + "    \"Currency\": \"USD\","
        + "    \"EnterpriseCode\": \"EnterpriseCode\""
        + "}}";
        System.out.println(U.jsonToXml(json));
    }
}
</code>```

Output:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Price>
  <LineItems>
    <LineItem>
      <UnitOfMeasure>EACH</UnitOfMeasure>
      <Quantity number="true">2</Quantity>
      <ItemID>ItemID</ItemID>
    </LineItem>
  </LineItems>
  <Currency>USD</Currency>
  <EnterpriseCode>EnterpriseCode</EnterpriseCode>
</Price>
</code>```

Title: Simplest method to Convert Json to Xml

Body:
Underscore-java library has static method U.jsonToXml(string). Live example

import com.github.underscore.U;

public class MyClass {
    public static void main(String args[]) {
        String json = "{\"Price\": {"
        + "    \"LineItems\": {"
        + "        \"LineItem\": {"
        + "            \"UnitOfMeasure\": \"EACH\", \"Quantity\": 2, \"ItemID\": \"ItemID\""
        + "        }"
        + "    },"
        + "    \"Currency\": \"USD\","
        + "    \"EnterpriseCode\": \"EnterpriseCode\""
        + "}}";
        System.out.println(U.jsonToXml(json));
    }
}

Output:

<?xml version="1.0" encoding="UTF-8"?>
<Price>
  <LineItems>
    <LineItem>
      <UnitOfMeasure>EACH</UnitOfMeasure>
      <Quantity number="true">2</Quantity>
      <ItemID>ItemID</ItemID>
    </LineItem>
  </LineItems>
  <Currency>USD</Currency>
  <EnterpriseCode>EnterpriseCode</EnterpriseCode>
</Price>


问:
How to add offsetTime to UTC time to get the right ZonedDateTime?
I want to convert a UTC time to a localisedDateTime or zonedDateTime.

I have the following input: 2013-07-10 02:52:49,-44.490947,171.220966 Where the date time is UTC time zone.

I get my zoneId with latitude and longitude which gives me Pacific/Auckland.

With this, I try to get the local time at zonePacific/Auckland from the timestamp and expect as shows the following conversion the result I am looking for.

Playing around with my timeStamp I get:

2013-07-10T02:52:49+12:00[Pacific/Auckland].

But I am looking for the following output:

2013-07-10T14:52:49

I don't think that manipulating the string the change it to a number and add manually is the right answer.

I am sure that we can do this with dates but I am new to Java and after surfing for hours I have not yet found my solution.

The solutions below while they seem valid show the date 2013-07-9 and so does it in my code. So if the website shows the time im expecting why are we not getting the same result?

答:
When you capture the date time

2013-07-10T02:52:49+12:00[Pacific/Auckland]

, capture it as ZonedDateTime, so that it will have the zone as UTC+12:00.

On that use dateTime.withZoneSameInstant(ZoneId.of("UTC")); to convert the date time into UTC+0 HRS which results 2013-07-10T14:52:49

If you get above data time as a string, then you can convert it to UTC ZonedDateTime as below.

```<code>    String time = "2013-07-10T02:52:49+12:00[Pacific/Auckland]";
    ZonedDateTime zdt = ZonedDateTime.parse(time);
    ZoneId zoneId = zdt.getZone();
    System.out.println(zdt);
    System.out.println(zdt.withZoneSameInstant(zoneId).toLocalDateTime());
    zdt = zdt.withZoneSameInstant(ZoneId.of("UTC"));
    System.out.println(zdt);
</code>```

Output:

```<code>2013-07-10T02:52:49+12:00[Pacific/Auckland]
2013-07-10T02:52:49
2013-07-09T14:52:49Z[UTC]
</code>```

Body:
When you capture the date time

2013-07-10T02:52:49+12:00[Pacific/Auckland]

, capture it as ZonedDateTime, so that it will have the zone as UTC+12:00.

On that use dateTime.withZoneSameInstant(ZoneId.of("UTC")); to convert the date time into UTC+0 HRS which results 2013-07-10T14:52:49

If you get above data time as a string, then you can convert it to UTC ZonedDateTime as below.

    String time = "2013-07-10T02:52:49+12:00[Pacific/Auckland]";
    ZonedDateTime zdt = ZonedDateTime.parse(time);
    ZoneId zoneId = zdt.getZone();
    System.out.println(zdt);
    System.out.println(zdt.withZoneSameInstant(zoneId).toLocalDateTime());
    zdt = zdt.withZoneSameInstant(ZoneId.of("UTC"));
    System.out.println(zdt);

Output:

2013-07-10T02:52:49+12:00[Pacific/Auckland]
2013-07-10T02:52:49
2013-07-09T14:52:49Z[UTC]


问:
RxJava - zip list of Observable if throw exception how to get success response
I am trying to call multiple API parallel using rxjava2 in Android. it's working as per the requirement but in case of any api throws exception it fails to give the response of other API's, so is there any way to call other API who returning success response.</p>

```<code>private fun getStoreCouponData() {

    val userObservable = repo2
        .create<StoreCouponsApi>(StoreCouponsApi::class.java!!)
        .getCoupons
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())

    val eventsObservable = repo2
        .create<StoreCouponsApi>(StoreCouponsApi::class.java!!)
        .storeInfo
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())

    val combined = Observable.zip<StoreCoupons, StoreCoupons, StoreList>(userObservable, eventsObservable,
        BiFunction<StoreCoupons, StoreCoupons, StoreList> { response1, response2 -> StoreList(response1, response2) })

    combined.subscribe(object : DefaultObserver<StoreList>() {
        override fun onNext(s: StoreList) {
            for (item in s.store!!.coupons!!) {
                System.out.println(item.store)
            }
        }

        override fun onError(e: Throwable) {
           System.out.println(e)
        }

        override fun onComplete() {

        }
    })

    println(combined)

}
</code>```

答:
There is callback called onErrorResumeNext which can be used for continuing the process, when one request gets to error.

```<code>val combined = Observable.zip<StoreCoupons, StoreCoupons, StoreList>(userObservable, eventsObservable,
        BiFunction<StoreCoupons, StoreCoupons, StoreList> { response1, response2 -> StoreList(response1, response2) }).onErrorResumeNext(
// you can error separately on each requests, and you can call other requests )
</code>```

Body:
I am trying to call multiple API parallel using rxjava2 in Android. it's working as per the requirement but in case of any api throws exception it fails to give the response of other API's, so is there any way to call other API who returning success response.

private fun getStoreCouponData() {

    val userObservable = repo2
        .create<StoreCouponsApi>(StoreCouponsApi::class.java!!)
        .getCoupons
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())

    val eventsObservable = repo2
        .create<StoreCouponsApi>(StoreCouponsApi::class.java!!)
        .storeInfo
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())

    val combined = Observable.zip<StoreCoupons, StoreCoupons, StoreList>(userObservable, eventsObservable,
        BiFunction<StoreCoupons, StoreCoupons, StoreList> { response1, response2 -> StoreList(response1, response2) })

    combined.subscribe(object : DefaultObserver<StoreList>() {
        override fun onNext(s: StoreList) {
            for (item in s.store!!.coupons!!) {
                System.out.println(item.store)
            }
        }

        override fun onError(e: Throwable) {
           System.out.println(e)
        }

        override fun onComplete() {

        }
    })

    println(combined)

}

Body:
There is callback called onErrorResumeNext which can be used for continuing the process, when one request gets to error.

val combined = Observable.zip<StoreCoupons, StoreCoupons, StoreList>(userObservable, eventsObservable,
        BiFunction<StoreCoupons, StoreCoupons, StoreList> { response1, response2 -> StoreList(response1, response2) }).onErrorResumeNext(
// you can error separately on each requests, and you can call other requests )


问:
Why is Java 6 compiled class size larger than Java 5?
We are noticing that when we compile our classes on Java 6, they are consistently larger than Java 5.

I understand that there has not been a change to the byte code to date, so I assume the Java 6 compiler is throwing in more stuff. Is that all required, or is there any way to turn that off and still compile Java 6 source code?

答:
The version 6 javac is generating additional "Stack Map" attributes in the class files to make verification by the jvm easier and faster. I doubt this amounts too much size difference, you could alway use the -target 1.5 option to make it generate the same bytecode as earlier in versions.

Edit: Details on this new attribute can be found in section 4.8.4 of jsr 202

4.8.4 The StackMapTable Attribute

The stack map attribute is a variable-length attribute in the attributes table of a Code
  attribute. The name of the attribute is StackMapTable. This attribute is used during
  the process of verification by typechecking (§4.11.1).

A stack map attribute consists of zero or more stack map frames. Each stack map
  frame specifies (either explicitly or implicitly) a bytecode offset, the verification
  types (§4.11.1) for the local variables, and the verification types for the operand
  stack.


答:
ggplot removes NA values. The real issue here is the way that scale_x_datetime is setting the axis limits.

If you use geom_point, you see the complete first day:

```<code>x %>%
  ggplot(aes(date, inf)) + geom_point()
</code>```

But if you use geom_col, the expansion of the axis is different:

```<code>x %>%
  ggplot(aes(date, inf)) + geom_col()
</code>```

So one solution, if you want bars, is to adjust the expand() parameters:

```<code>x %>%
  ggplot(aes(date, inf)) + geom_col() + scale_x_datetime(expand = c(0.5, 0.5))
</code>```

Another way as you indicated is to replace NA with zero. Strictly-speaking you should not, since NA (value not known) is not the same as value = 0. It may be OK for the purposes of a chart, unless the plot uses any statistical transformations.

```<code>library(dplyr)
x %>%
  mutate(inf = ifelse(is.na(inf), 0, inf)) %>%
  ggplot(aes(date, inf)) + geom_col()
</code>```

Title: ggplot omits day with missing data

Body:
I am trying to plot data which has missing values for the first and last day. ggplot simply 'eats' that day:

ggplot()+
     geom_col(data = x, aes(x = date, y = inf),fill= "cadetblue3", size = 0.1)

How do I make R plot the whole range of date(and time)?
I have tried a small trick to assign 0 at the beginning, but that is a dirty solution.

 x$spor[1] <-0
 x$spor[nrow(x)] <-0

Any better suggestions?

Data:

x  <- structure(list(date = structure(c(1465689600, 1465693200, 1465696800,
1465700400, 1465704000, 1465707600, 1465711200, 1465714800, 1465718400,
1465722000, 1465725600, 1465729200, 1465732800, 1465736400, 1465740000,
1465743600, 1465747200, 1465750800, 1465754400, 1465758000, 1465761600,
1465765200, 1465768800, 1465772400, 1465776000, 1465779600, 1465783200,
1465786800, 1465790400, 1465794000, 1465797600, 1465801200, 1465804800,
1465808400, 1465812000, 1465815600, 1465819200, 1465822800, 1465826400,
1465830000, 1465833600, 1465837200, 1465840800, 1465844400, 1465848000,
1465851600, 1465855200, 1465858800, 1465862400, 1465866000, 1465869600,
1465873200, 1465876800, 1465880400, 1465884000, 1465887600, 1465891200,
1465894800, 1465898400, 1465902000, 1465905600, 1465909200, 1465912800,
1465916400, 1465920000, 1465923600, 1465927200, 1465930800, 1465934400,
1465938000, 1465941600, 1465945200, 1465948800, 1465952400, 1465956000,
1465959600, 1465963200, 1465966800, 1465970400, 1465974000, 1465977600,
1465981200, 1465984800, 1465988400, 1465992000, 1465995600, 1465999200,
1466002800, 1466006400, 1466010000, 1466013600, 1466017200, 1466020800,
1466024400, 1466028000, 1466031600, 1466035200, 1466038800, 1466042400,
1466046000, 1466049600, 1466053200, 1466056800, 1466060400, 1466064000,
1466067600, 1466071200, 1466074800, 1466078400, 1466082000, 1466085600,
1466089200, 1466092800, 1466096400, 1466100000, 1466103600, 1466107200,
1466110800, 1466114400, 1466118000, 1466121600, 1466125200, 1466128800,
1466132400, 1466136000, 1466139600, 1466143200, 1466146800, 1466150400,
1466154000, 1466157600, 1466161200, 1466164800, 1466168400, 1466172000,
1466175600, 1466179200, 1466182800, 1466186400, 1466190000, 1466193600,
1466197200, 1466200800, 1466204400), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), inf = c(NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 18.4313, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, 25.3237, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 22.9965,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, 11.7823, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)), class = "data.frame", row.names = 2997018:2997161)

Body:
ggplot removes NA values. The real issue here is the way that scale_x_datetime is setting the axis limits.

If you use geom_point, you see the complete first day:

x %>%
  ggplot(aes(date, inf)) + geom_point()

But if you use geom_col, the expansion of the axis is different:

x %>%
  ggplot(aes(date, inf)) + geom_col()

So one solution, if you want bars, is to adjust the expand() parameters:

x %>%
  ggplot(aes(date, inf)) + geom_col() + scale_x_datetime(expand = c(0.5, 0.5))

Another way as you indicated is to replace NA with zero. Strictly-speaking you should not, since NA (value not known) is not the same as value = 0. It may be OK for the purposes of a chart, unless the plot uses any statistical transformations.

library(dplyr)
x %>%
  mutate(inf = ifelse(is.na(inf), 0, inf)) %>%
  ggplot(aes(date, inf)) + geom_col()


问:
How to upload image with Codeigniter frame work?
I require help with Image upload code with CodeIgniter. Please refer to my code below

I did try File Upload class, but I am failing on using it on already created code for adding new Products.

This is my Form

```<code><form action="<?php echo base_url().'index.php/admin/Welcome/add_new_product'; ?>" method="POST">
  <section class="content">
    <div class="row">
      <div class="col-md-12">
        <div class="box box-info">
          <div class="box-header">
            <h3 class="box-title">Product description
              <small></small>
            </h3>

            <h1><input type="textarea" name="pd_title" placeholder="Enter Title Here" style="width:100%;"></h1>
          </div>
          <!-- /.box-header -->
          <div class="box-body pad">

                  <textarea id="editor1" name="pd_short_desc" rows="10" cols="80">
                                          This is my textarea to be replaced with CKEditor.
                  </textarea>
                </div>
                  <div class="box-body pad">
                  <label for="Image">Upload Image</label>
                  <input type="file" name="pd_img" value="" style="padding:10px;">
                </div>

                  <div class="box-body pad">
                  <h3 class="box-title">Description to right of Image</h3>
                  <textarea id="editor2" name="pd_info_right" rows="10" cols="80">
                                          This is my textarea to be replaced with CKEditor.
                  </textarea>
                </div>
                  <div class="box-body pad">
                  <h3>Product Complete Description</h3>
                  <textarea id="editor3" name="pd_desc" rows="10" cols="80">
                                          This is my textarea to be replaced with CKEditor.
                  </textarea>
                </div>

                <input type="submit" name="submit" class="btn  btn-info btn-raised ink-reaction">
            </form>
</code>```

This is my Controller

```<code>public function add_new_product()
    {
        $p = $this->model_one->add_new_product();
        redirect('admin/Welcome/view_products');
    }
</code>```

This Model should insert data in mysqli db table

```<code>public function add_new_product()
{
  $pd_title = $_POST['pd_title'];
  $pd_short_desc = $_POST['pd_short_desc'];
  $pd_image = $_POST['pd_image'];
  $pd_info_right = $_POST['pd_info_right'];
  $pd_desc = $_POST['pd_desc'];

  $sql = $this->db->query("INSERT INTO products (pd_title, pd_short_desc, pd_image, pd_info_right, pd_desc)
  VALUES('$pd_title','$pd_short_desc', '$pd_image','$pd_info_right','$pd_desc')");

  return "yes";
}
</code>```

When submit this form, Image needs to upload in uploads folder, as well insert into products table in mysqli db.

答:
Do some changes

View

Add enctype="multipart/form-data" in the <form> tag

```<code><form action="<?php echo base_url().'index.php/admin/Welcome/add_new_product'; ?>" method="POST" enctype="multipart/form-data">
</code>```

Controller

Get POST values in the controller

```<code>public function add_new_product()
{
    $data = array('pd_title' => $_POST['pd_title'], 'pd_short_desc' => $_POST['pd_short_desc'], 'pd_info_right' => $_POST['pd_info_right'], 'pd_desc' => $_POST['pd_desc']);

    $config['upload_path'] = FCPATH.'uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = 100;
    $config['max_width'] = 1024;
    $config['max_height'] = 768;

    if(isset($_FILES['pd_img']['name'])){
       $this->load->library('upload', $config);
       if(!$this->upload->do_upload('pd_img')){
           print_r($this->upload->display_errors());
       }else{
           $data['pd_image'] = $this->upload->data('file_name');
       }
    }

    $this->model_one->add_new_product($data);
    redirect('admin/Welcome/view_products');
}
</code>```

Model

```<code>public function add_new_product($data)
{
    return $this->db->insert('products', $data);
}
</code>```

Body:
I require help with Image upload code with CodeIgniter. Please refer to my code below

I did try File Upload class, but I am failing on using it on already created code for adding new Products.

This is my Form

<form action="<?php echo base_url().'index.php/admin/Welcome/add_new_product'; ?>" method="POST">

Product description

<input type="textarea" name="pd_title" placeholder="Enter Title Here" style="width:100%;">

                  <textarea id="editor1" name="pd_short_desc" rows="10" cols="80">
                                          This is my textarea to be replaced with CKEditor.
                  </textarea>

                  Upload Image
                  <input type="file" name="pd_img" value="" style="padding:10px;">

Description to right of Image

                  <textarea id="editor2" name="pd_info_right" rows="10" cols="80">
                                          This is my textarea to be replaced with CKEditor.
                  </textarea>

Product Complete Description

                  <textarea id="editor3" name="pd_desc" rows="10" cols="80">
                                          This is my textarea to be replaced with CKEditor.
                  </textarea>

                <input type="submit" name="submit" class="btn  btn-info btn-raised ink-reaction">
            </form>

This is my Controller

public function add_new_product()
    {
        $p = $this->model_one->add_new_product();
        redirect('admin/Welcome/view_products');
    }

This Model should insert data in mysqli db table

public function add_new_product()
{
  $pd_title = $_POST['pd_title'];
  $pd_short_desc = $_POST['pd_short_desc'];
  $pd_image = $_POST['pd_image'];
  $pd_info_right = $_POST['pd_info_right'];
  $pd_desc = $_POST['pd_desc'];

  $sql = $this->db->query("INSERT INTO products (pd_title, pd_short_desc, pd_image, pd_info_right, pd_desc)
  VALUES('$pd_title','$pd_short_desc', '$pd_image','$pd_info_right','$pd_desc')");

  return "yes";
}

When submit this form, Image needs to upload in uploads folder, as well insert into products table in mysqli db.

Body:
Do some changes

View

Add enctype="multipart/form-data" in the <form> tag

<form action="<?php echo base_url().'index.php/admin/Welcome/add_new_product'; ?>" method="POST" enctype="multipart/form-data">

Controller

Get POST values in the controller

public function add_new_product()
{
    $data = array('pd_title' => $_POST['pd_title'], 'pd_short_desc' => $_POST['pd_short_desc'], 'pd_info_right' => $_POST['pd_info_right'], 'pd_desc' => $_POST['pd_desc']);

    $config['upload_path'] = FCPATH.'uploads/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = 100;
    $config['max_width'] = 1024;
    $config['max_height'] = 768;

    if(isset($_FILES['pd_img']['name'])){
       $this->load->library('upload', $config);
       if(!$this->upload->do_upload('pd_img')){
           print_r($this->upload->display_errors());
       }else{
           $data['pd_image'] = $this->upload->data('file_name');
       }
    }

    $this->model_one->add_new_product($data);
    redirect('admin/Welcome/view_products');
}

Model

public function add_new_product($data)
{
    return $this->db->insert('products', $data);
}


问:
Get number of lines of code modified from GitHub repository
I have a repository on GitHub from which I have to find some statistics, then I have to process this data in a Python script. In particular, the information I have to get is the number of lines of code modified in a certain amount of days, i. e. the number of lines of code added, deleted and modified.
I tried to take a look at the bees of GitHub but unfortunately I have not found what I need, would anyone know how to advise me what to do?
Thank you.</p>

答:
You can use CLOC(“Count Lines of Code”), which will give you a breakdown of significant and insignificant lines of code by language.

```<code>cloc $(git ls-files)
</code>```

This git ls-files is same as xargs cloc.

Or another way to get number of coded line is to use...

```<code>git ls-files | xargs wc -l
</code>```

Body:
You can use CLOC(“Count Lines of Code”), which will give you a breakdown of significant and insignificant lines of code by language.

cloc $(git ls-files)

This git ls-files is same as xargs cloc.

Or another way to get number of coded line is to use...

git ls-files | xargs wc -l