问:
How to search outlook email having string in subject line using python?
I want to count last 7 days outlook emails having subject with error types as well as server name. I am new to Python coding.Can someone please help on this?

For example:-
I have mails in my inbox as below subject line:

Check for missing backups on CP-TEST-DB2

Check deadlock on G-PROD-AUDB

There are errors in the SQL Error Log on LF-PTT-DW1

Check drive space on CP-TEST-DB1

So, I want to fetch mails with subject line 'Check for missing backups' for each server(e.g.- CP-TEST-DB2, G-PROD-AUDB) and want count on it server wise.
Like how many "Check for missing backups on" mails i have for "CP-TEST-DB2" server.
how many "Check for missing backups on" mails i have for "G-PROD-AUDB" and so on for every server.

how many "Check deadlock on" mails i have for "CP-TEST-DB2" server.
how many "Check deadlock on" mails i have for "G-PROD-AUDB" and so on for every server...
and so on for error type also.
I have 8 type of sql error alert mail for each 33 servers?

```<code>import win32com.client
import imp, sys, os, re
import datetime as dt
import time

date_time = dt.datetime.now()
print (date_time)

#list of errors
error = ['There are errors in the SQL Error Log on', 'Check for missing backups on', 'Check drive space on', 'Check memory usage on', 'Check deadlock on ']

#list of server
server = ['TEST-AUDB','TEST-AUDB','EUDB','TEST-EUDB','PROD-AUDB','PROD-EUDB']

#setup range for outlook to search emails (so we don't go through the entire inbox)
lastHourDateTime = dt.datetime.now() - dt.timedelta(days = 7)
#print (lastHourDateTime)

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.Folders.Item(2).Folders['Inbox']

messages = inbox.Items
messages.sort("[ReceivedTime]", True)
lastHourMessages = messages.Restrict("[ReceivedTime] >= '" +lastHourDateTime.strftime('%m/%d/%Y %H:%M %p')+"'")
print ("Current time: "+date_time.strftime('%m/%d/%Y %H:%M %p'))

for msg in lastHourMessages:
        subject = msg.Subject
        time = msg.ReceivedTime
        print (s1)```

```

答:
You can use the following regex expression:

```<code>([\-A-Z0-9]+)$
</code>```

which will match 1 or more of every upper case letter, number and dash until the end of the sentence. This covers all the cases you provided in your question, as can be seen here.

Next, you can use the re module, and iterate over the list of strings, searching for a match using the pattern I've mentioned above, and storing the information in a nested dictionary.

```<code>import re

# Example strings
strings = ["Check for missing backups on CP-TEST-DB2",
            "Check deadlock on CP-TEST-DB2",
            "Check deadlock on CP-TEST-DB2",
            "Check deadlock on G-PROD-AUDB",
            "There are errors in the SQL Error Log on LF-PTT-DW1",
            "Check drive space on CP-TEST-DB1"]

# Declare empty dictionary
occurrences = {}

# Iterate over all the examples
for string in strings:
    results = re.search('([\-A-Z0-9]+)$', string)
    # Get the server from the regex match
    server = results.group(0)
    # Remove the server from the string and use strip to get rid of the trailing whitespace
    instance = string.replace(server, '').strip()
    # If the server is still not in the dict, insert it manually
    if occurrences.get(server, None) is None:
        occurrences[server] = {instance: 1}
    # If the server is already in the dict, but not the instance, create the key and initial value for the instance
    elif occurrences[server].get(instance, None) is None:
        occurrences[server][instance] = 1
    # Otherwise, just increment the value for the server-instance pair
    else:
        occurrences[server].update({instance : occurrences[server].get(instance, 0) + 1})
print(occurrences)
</code>```

Hope this helps!

Body:
I want to count last 7 days outlook emails having subject with error types as well as server name. I am new to Python coding.Can someone please help on this?

For example:-
I have mails in my inbox as below subject line:

Check for missing backups on CP-TEST-DB2

Check deadlock on G-PROD-AUDB

There are errors in the SQL Error Log on LF-PTT-DW1

Check drive space on CP-TEST-DB1

So, I want to fetch mails with subject line 'Check for missing backups' for each server(e.g.- CP-TEST-DB2, G-PROD-AUDB) and want count on it server wise.
Like how many "Check for missing backups on" mails i have for "CP-TEST-DB2" server.
how many "Check for missing backups on" mails i have for "G-PROD-AUDB" and so on for every server.

how many "Check deadlock on" mails i have for "CP-TEST-DB2" server.
how many "Check deadlock on" mails i have for "G-PROD-AUDB" and so on for every server...
and so on for error type also.
I have 8 type of sql error alert mail for each 33 servers?

import win32com.client
import imp, sys, os, re
import datetime as dt
import time

date_time = dt.datetime.now()
print (date_time)

#list of errors
error = ['There are errors in the SQL Error Log on', 'Check for missing backups on', 'Check drive space on', 'Check memory usage on', 'Check deadlock on ']

#list of server
server = ['TEST-AUDB','TEST-AUDB','EUDB','TEST-EUDB','PROD-AUDB','PROD-EUDB']

#setup range for outlook to search emails (so we don't go through the entire inbox)
lastHourDateTime = dt.datetime.now() - dt.timedelta(days = 7)
#print (lastHourDateTime)

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.Folders.Item(2).Folders['Inbox']

messages = inbox.Items
messages.sort("[ReceivedTime]", True)
lastHourMessages = messages.Restrict("[ReceivedTime] >= '" +lastHourDateTime.strftime('%m/%d/%Y %H:%M %p')+"'")
print ("Current time: "+date_time.strftime('%m/%d/%Y %H:%M %p'))

for msg in lastHourMessages:
        subject = msg.Subject
        time = msg.ReceivedTime
        print (s1)```

Body:
You can use the following regex expression:

([\-A-Z0-9]+)$

which will match 1 or more of every upper case letter, number and dash until the end of the sentence. This covers all the cases you provided in your question, as can be seen here.

Next, you can use the re module, and iterate over the list of strings, searching for a match using the pattern I've mentioned above, and storing the information in a nested dictionary.

import re

# Example strings
strings = ["Check for missing backups on CP-TEST-DB2",
            "Check deadlock on CP-TEST-DB2",
            "Check deadlock on CP-TEST-DB2",
            "Check deadlock on G-PROD-AUDB",
            "There are errors in the SQL Error Log on LF-PTT-DW1",
            "Check drive space on CP-TEST-DB1"]

# Declare empty dictionary
occurrences = {}

# Iterate over all the examples
for string in strings:
    results = re.search('([\-A-Z0-9]+)$', string)
    # Get the server from the regex match
    server = results.group(0)
    # Remove the server from the string and use strip to get rid of the trailing whitespace
    instance = string.replace(server, '').strip()
    # If the server is still not in the dict, insert it manually
    if occurrences.get(server, None) is None:
        occurrences[server] = {instance: 1}
    # If the server is already in the dict, but not the instance, create the key and initial value for the instance
    elif occurrences[server].get(instance, None) is None:
        occurrences[server][instance] = 1
    # Otherwise, just increment the value for the server-instance pair
    else:
        occurrences[server].update({instance : occurrences[server].get(instance, 0) + 1})
print(occurrences)

Hope this helps!


来源: stackexchange

问:
Getting errors with os.listdir within flask and heroku
I have an application that, takes the url and returns a files corresponding to it. I wanted to push it on heroku but i get this error :
 **File "/app/server.py", line 1525, in upload1

```<code>music = os.listdir(foldername)
</code>```

FileNotFoundError: [Errno 2] No such file or directory: 'favicon.ico'**

Then i tried to add favicon.ico in all of the folders and i am getting

**File "/app/server.py", line 1525, in upload1

```<code>music = os.listdir(foldername)
</code>```

NotADirectoryError: [Errno 20] Not a directory: 'favicon.ico'**

The part where it looks to struggle is

    @app.route('/<path:foldername>')
    def upload1(foldername):
        music = os.listdir(foldername)
        print(music)
        path_to_file = music[0]

        return send_file(
        foldername+"/"+path_to_file,
        mimetype="audio/mp3",
        as_attachment=True,
        attachment_filename=path_to_file )

```

答: Ok, I feel dumb right now. the issue is that when i did heroku open i got the error instantly. But i got it because i didnt add anything after the url ( so the code would obviously not work )</p>

ContentLicense: CC BY-SA 4.0

Body:
I have an application that, takes the url and returns a files corresponding to it. I wanted to push it on heroku but i get this error :
 **File "/app/server.py", line 1525, in upload1

music = os.listdir(foldername)

FileNotFoundError: [Errno 2] No such file or directory: 'favicon.ico'**

Then i tried to add favicon.ico in all of the folders and i am getting

**File "/app/server.py", line 1525, in upload1

music = os.listdir(foldername)

NotADirectoryError: [Errno 20] Not a directory: 'favicon.ico'**

The part where it looks to struggle is

    @app.route('/<path:foldername>')
    def upload1(foldername):
        music = os.listdir(foldername)
        print(music)
        path_to_file = music[0]

        return send_file(
        foldername+"/"+path_to_file,
        mimetype="audio/mp3",
        as_attachment=True,
        attachment_filename=path_to_file )


问:
Search in front of background image redirects to home page on click
I have a header image where there is also a search field.

However, when I click on the search input I get redirected to home page because my search is inside the  tag.

How can I prevent this, when I want to make a search inside the header which has a background image.

I want the search feature NOT to go back to homepage, yet I want the background image to go back to homepage.

Here is my code:

```<code><header>
    <h1>
        <a href="/">
            <span class="texte-cache">Sel gras</span>
            <section class="section-recherche">
                <?php
                // define variables and set to empty values
                $rechercheErr = "";
                $recherche  = "";
                $rechercheValid = false;
                ?>

                <form method="get" action="../pages/recherche.php">
                    <div class="recherche">
                        <input type="search" name="recherche" id="recherche" placeholder="Rechercher..." value="<?php echo $recherche; ?>" />
                        <span class="error"> <?php echo $rechercheErr; ?></span>
                        <button title="Rechercher" class="button-recherche" id="buttonRecherche" name="submit"><i class="material-icons-white">search</i></button>
                    </div>
                </form>
            </section>
        </a>
    </h1>
    <link rel="stylesheet" type="text/css" href="/css/styles.css" media="all" />
</header>
</code>```

If there is way I can change my html so visual I can stil have this I would be very happy (see image)

Any help would be very appreciated. Also I am not allowed to use jquery, javascript.....

答:
I figured it out here is my new html

```<code><header>
    <h1>
        <a href="/">
            <span class="texte-cache">Sel gras</span>
        </a>

     <section class="section-recherche">
                <?php
                // define variables and set to empty values
                $rechercheErr = "";
                $recherche  = "";
                $rechercheValid = false;
                ?>

                <form method="get" action="../pages/recherche.php">
                    <div class="recherche">
                        <input type="search" name="recherche" id="recherche" placeholder="Rechercher..." value="<?php echo $recherche; ?>" />
                        <span class="error"> <?php echo $rechercheErr; ?></span>
                        <button title="Rechercher" class="button-recherche" id="buttonRecherche" name="submit"><i class="material-icons-white">search</i></button>
                    </div>
                </form>
            </section>

    </h1>
    <link rel="stylesheet" type="text/css" href="/css/styles.css" media="all" />

</header>
</code>```

And here is what I did in the css I gave search form a absolute position.

```<code>.section-recherche{
  position: absolute;
  top: 220px;
  padding-left: 20px;
  width: 80%;
}
</code>```

Body:
I have a header image where there is also a search field.

However, when I click on the search input I get redirected to home page because my search is inside the  tag.

How can I prevent this, when I want to make a search inside the header which has a background image.

I want the search feature NOT to go back to homepage, yet I want the background image to go back to homepage.

Here is my code:

            Sel gras

                <?php
                // define variables and set to empty values
                $rechercheErr = "";
                $recherche  = "";
                $rechercheValid = false;
                ?>

                <form method="get" action="../pages/recherche.php">

                        <input type="search" name="recherche" id="recherche" placeholder="Rechercher..." value="<?php echo $recherche; ?>" />
                         <?php echo $rechercheErr; ?>
                        <button title="Rechercher" class="button-recherche" id="buttonRecherche" name="submit">search</button>

                </form>

    <link rel="stylesheet" type="text/css" href="/css/styles.css" media="all" />

If there is way I can change my html so visual I can stil have this I would be very happy (see image)

Any help would be very appreciated. Also I am not allowed to use jquery, javascript.....

Body:
I figured it out here is my new html

<header>
    <h1>
        <a href="/">
            <span class="texte-cache">Sel gras</span>
        </a>

     <section class="section-recherche">
                <?php
                // define variables and set to empty values
                $rechercheErr = "";
                $recherche  = "";
                $rechercheValid = false;
                ?>

                <form method="get" action="../pages/recherche.php">
                    <div class="recherche">
                        <input type="search" name="recherche" id="recherche" placeholder="Rechercher..." value="<?php echo $recherche; ?>" />
                        <span class="error"> <?php echo $rechercheErr; ?></span>
                        <button title="Rechercher" class="button-recherche" id="buttonRecherche" name="submit"><i class="material-icons-white">search</i></button>
                    </div>
                </form>
            </section>

    </h1>
    <link rel="stylesheet" type="text/css" href="/css/styles.css" media="all" />

</header>

And here is what I did in the css I gave search form a absolute position.

.section-recherche{
  position: absolute;
  top: 220px;
  padding-left: 20px;
  width: 80%;
}


问:
Auto create directories after uploading with PHP
I'm creating a php site where a company will upload a lot of images. I'd like one folder to contain upto 500-1000 files and PHP automatically creates a new one if previous contains more that 1000 files.

For example, px300 has folder dir1 which stores 500 files, then a new one dir2 will be created.

Are there any existed a solutions?

答: You could use the glob function. It will return an array matching your pattern, which you could count for the amount of files.</p>

ContentLicense: CC BY-SA 3.0


问:
Git commits log information in a wrong order
I am a new in the field of Git. I tried to use git commit to log my software different versions. However, I get the following result.

```<code>60cf510 (HEAD -> master) HEAD@{0}: commit: Automatically detect whether use the fix effect to make the final prediction
791df2d HEAD@{1}: commit: release version 1.0
f9a3697 HEAD@{2}: commit: Add colmun selection in covariate and phenotype
889b11b HEAD@{3}: commit: Add preprocess (overlap, snp order, flip allele)
8c7688f HEAD@{4}: commit (initial): Fix bug in estimating delta and add flip minor allel
</code>```

The log with hash code 60cf510 is my newest submit. I think this log information should follow the 8c7688f. I am not sure what the problem is. What's more, I do not know why the commit (initial) exists. Is it because I reinitialize the git? Thank you.

The following message come from the command git log.

```<code>commit 60cf510c9b549b6a1f89fc7b3ba2f88faca7a8fa (HEAD -> master)
Author: shunkang <shunkang1997@gmail.com>
Date:   Tue Feb 18 22:57:45 2020 +0800

    Automatically detect whether use the fix effect to make the final prediction

    If there is no prediction covariate file provided, the software will only use the random effect to make the prediction. The final output result will show two columns with the same value.

commit 791df2d446ed8db87751620c48d15beac04074ce
Author: shunkang <shunkang1997@gmail.com>
Date:   Thu Nov 21 11:43:11 2019 +0800

    release version 1.0

commit f9a3697960f27648e7fbe86ad1e64072ea34888a
Author: shunkang <shunkang1997@gmail.com>
Date:   Thu Nov 21 11:10:57 2019 +0800

    Add colmun selection in covariate and phenotype

commit 889b11b7aa4c9db9a3feb3b2f6691cd64559b46b
:
</code>```

答:
Everything here looks quite normal.

We might start with these observations:

Git stores, for the most part, commits.  That is, the commit is the basic unit of Git storage.  (It's possible to break a commit into several parts, and Git sometimes does, but mostly we work with whole commits at a time.)

As each commit is created, it acquires a unique hash ID.  This hash ID is forever reserved for this commit, not only in this Git repository, but in every Git repository everywhere.  In a sense, it was reserved for this even before you made the commit, except for the fact that the commit hash ID depends on the time, down to the second, when you make the commit.

(These hash IDs are very big and unwieldy.  They have to be, to be unique like this.  No human can get them right, but that's OK: we have a computer, after all.)

Each commit holds a snapshot of all of your files.  That's the main data within a commit, but each commit also holds some metadata: some information about the commit itself.  The metadata includes the name and email address of whoever made it—as two entries, author and committer—and some date-and-time stamps, and a log message where you, or whoever, record the reason you made the commit.

A key item in this metadata, though, is that each commit stores the actual hash ID of its immediate predecessor commit or commits.  That is, each commit has some number of parent commits—usually just one—and the child commit stores the raw hash ID of its parent or parents.

Whenever we have, stored somewhere, the hash ID of a commit, we say that whatever it is that holds this hash ID points to the commit.  So if you have some hash ID H written down somewhere—on paper or on a whitebord, for instance—we might say that this points to commit H.  Since each commit stores the hash ID of its parent, each commit points to its parent.  We can draw this:

```<code>... <-F <-G <-H
</code>```

where H is some commit with some hash ID H, and it points to its parent G, which in turn points to its parent F, and so on.

If we record the last hash ID of some long chain of commits in a branch name like master, that suffices for Git to find all of those commits.  The name points to the last commit:

```<code>...--F--G--H   <-- master
</code>```

and from there, Git can work backwards: starting at H, it finds G, then F, and so on.  This repeats until Git finds the very first commit ever made, which doesn't point back any further, because it can't.

To make a new commit, we start by extracting commit H into a work area.  (All commits are 100% read-only, so we cannot change H, but we can change the stuff we copy to a work area.)  Then we edit files as usual, use git add to copy them to the index—another key item but we won't go into the details here—and use git commit to make a new commit.  Git packages up all of our files into a new snapshot, adds the metadata—our name and email address and the current date and time, for instance—and sets the parent of the new commit to be commit H.  This new commit acquires its new ID, which is too big for us to manage but we'll just call it I.  New commit I therefore points back to existing commit H.

As its final act, git commit writes the hash ID of the new commit into the current branch name.  If the current branch name is master, Git writes I's hash ID into master, so that master now points to I.  Since I points back to H, that's what we get:

```<code>...--F--G--H--I   <-- master
</code>```

The git log command starts at the end and works backwards

A regular git log—not git reflog!—starts from some ending-point commit hash ID, such as by looking inside the name master.  Whenever git log looks in a branch name, this is, by definition, the last commit in the branch.1  Then git log shows us this commit–commit I, in this case—and now git log simply moves on to the commit's parent.  So the next commit you see is the previous commit.

The log, in other words, automatically works backwards, from the end to the beginning.  This is a theme in Git: all of its internal arrows point backwards.  Git always has to start at the end and work backwards.  So git log shows the newest commit by default, because by default, it starts from your current branch name, which is the newest commit on that branch.

Note that if you use git checkout—or the new Git 2.23+ git switch—to switch to a different branch name, git log will start from that other branch name, rather than from master.  Or, if you use git checkout or git switch to switch to detached HEAD mode, in which the special name HEAD points directly to a commit, git log will default to starting from that historical commit.

1The definition of a branch name is that it holds the hash ID of the last commit.  That's what git branch -f, git reset, and so on can do: by forcing a different hash ID into a branch name, this changes which commit is the last commit.  That's also why git commit writes the new commit's hash ID into the branch name: this new commit is, by definition, the last commit, and by definition, a branch name must hold the hash ID of the last commit, so git commit keeps the two definitions working together.

When git log is more complicated

It's often important to draw the graph of commits, by drawing each commit and an arrow from it to its parent(s):

```<code>          I--J   <-- branch1
         /
...--G--H
         \
          K--L   <-- branch2
</code>```

Here we have two different branch names, each pointing to one commit—J for branch1 and L for branch2—with their one commit pointing backwards as usual, but at some point, the two branches join up in history: commits I and K both point back to commit H.

The git log command normally starts from the current branch tip and works backwards.  If we pick branch1 as our current branch, for instance, we'll see commit J first, then I, then H, then G, and so on.  If we pick branch2 as our current branch, we'll see L, then K, then H, and so on.  Note that either way, we don't see two of these commits.

We can, however, tell git log to start from both branch1 and branch2.  But git log can only show one commit at a time.  Will it show us J first, or L first?

The answer to this question is complicated.  Sometimes Git will show us J first, and sometimes it will show L first.  To pick one of the two, git log puts both commits into a priority queue.  The default priority is by committer date-and-time, so that whichever of J or L was made later is the one we'll see first.  You can give git log different sort options, which change the priority; in this case, you might see the other commit first.

Having taken one of the two commits out of the queue and shown it, git log will now put that commit's parent into the priority queue.  It will then show you the highest priority commit—whichever one that is—next.  Then it will put that commit's parent into the priority queue.  There are still two commits in this queue, so once again, which commit you see after these first two is determined by the priority queue.

Eventually, it's likely—or, depending on the flags you give git log, necessary—that git log will have shown J, I, L, and K before showing commit H.  At this point only commit H itself will be in the priority queue, so git log will now show H and put commit G in the queue.  Now G will be the only commit in the queue, so git log will show G, and put G's parent in the queue, and so on.

In other words, git log sometimes sorts commits.  It does this only when its priority queue has more than one entry in it, which happens automatically if you give it multiple starting point commits, such as J and L here.  But look what happens after we merge some commits:

```<code>          I--J
         /    \
...--G--H      M--N   <-- master
         \    /
          K--L
</code>```

Now, if we start at master and work back, git log must show N first—that's the only commit in the queue—and then M.  But commit M has two parents, so git log now puts both J and L into the queue.  Now it has two commits to show, so it picks one, based on priority.  In other words, it now sorts the commits according to the options we give it.  We're back in the same situation we had when we had two branch names, pointing to commits J and L, and told git log to show both commits / branches.

git log shows us one commit at a time, even if history is more complex

The history we'll see from git log can be misleading.  It might show us N, then M, then L and K, then IandJ`, in that order.  If we're not aware of the fact that there was a branch-and-merge, we might think that the commits were made linearly like that.

For this reason, you can have git log draw a crude text-based graph.  This graph is not always very pretty, but it will show that commits L and K are parallel to commits J and I: that they form a branch-and-merge structure in the history, as recorded in the commits.

History is commits; commits are history

Note that throughout all these processes, no commit changes.  We can view the commits one at a time, in different orders with git log --sort=... or git log --topo-order, and/or have Git draw a graph with git log --graph.  Or, we can draw our graph on a whiteboard, or on paper, or using various graph-drawing programs.  But whatever we do, the commits themselves never change.  These commits are the history in your repository.  Their connections exist from the moment you make the commits: child commits point back to their parents.  Merge commits are commits with two (or more) parents.  Branches "fork" when a parent has two or more children.

You can always add more commits to the graph.  Git finds commits by using branch names, which by definition are the last commit in that branch.  You can always add new branch names, and you can delete branch names as well.  If you delete the only name that allows you to find some commit—for instance, if you have:

```<code>...--o--o--o--o--...--o  <-- master
         \
          H   <-- branch
</code>```

and you delete the name branch—that one particular commit, in this case H, becomes hard, or maybe impossible, to find.  However, Git has other ways to find commits.  For instance, tag names can point to commits.  Git also keeps a log of previous values of particular branch and other names.  This log, called a reflog, could allow you to find commit H.

Some operations, such as git rebase, work by copying an existing series of commits to new and improved commits, then moving a branch name.  Since the name holds the hash ID of the last commit, if we copy the commits and then move the name, it looks like we somehow changed the commits:

```<code>...--o--o--o--o--...--o  <-- master
         \
          H--I--J   <-- branch
</code>```

becomes:

```<code>...--o--o--o--o--...--o  <-- master
         \             \
          H--I--J       H'-I'-J'  <-- branch
</code>```

where H' is the copy of H, I' is the copy of I, and J' is the copy of J.  We didn't actually change the commits though.  The originals are still there, in the repository.  You just can't find them easily, because we start with the name branch to find commit I' now, and work backwards from there.

(The reflog for the name branch holds the hash ID of commit J.  If we decide we wish to "undo" the rebase operation, we can force the name branch to remember J again, instead of J'.  Then the reflog for branch will hold the hash ID of commit J'.  Since reflogs hold multiple entries, we'll end up with multiple reflog entries holding J and/or J'.  The reflog entries eventually expire though, so eventually we'll forget commit J entirely, as long as the name branch points only to J'.  A branch name can only point to one commit, and in fact, must point to one commit at all times.)

Body:
I am a new in the field of Git. I tried to use git commit to log my software different versions. However, I get the following result.

60cf510 (HEAD -> master) HEAD@{0}: commit: Automatically detect whether use the fix effect to make the final prediction
791df2d HEAD@{1}: commit: release version 1.0
f9a3697 HEAD@{2}: commit: Add colmun selection in covariate and phenotype
889b11b HEAD@{3}: commit: Add preprocess (overlap, snp order, flip allele)
8c7688f HEAD@{4}: commit (initial): Fix bug in estimating delta and add flip minor allel

The log with hash code 60cf510 is my newest submit. I think this log information should follow the 8c7688f. I am not sure what the problem is. What's more, I do not know why the commit (initial) exists. Is it because I reinitialize the git? Thank you.

The following message come from the command git log.

commit 60cf510c9b549b6a1f89fc7b3ba2f88faca7a8fa (HEAD -> master)
Author: shunkang <shunkang1997@gmail.com>
Date:   Tue Feb 18 22:57:45 2020 +0800

    Automatically detect whether use the fix effect to make the final prediction

    If there is no prediction covariate file provided, the software will only use the random effect to make the prediction. The final output result will show two columns with the same value.

commit 791df2d446ed8db87751620c48d15beac04074ce
Author: shunkang <shunkang1997@gmail.com>
Date:   Thu Nov 21 11:43:11 2019 +0800

    release version 1.0

commit f9a3697960f27648e7fbe86ad1e64072ea34888a
Author: shunkang <shunkang1997@gmail.com>
Date:   Thu Nov 21 11:10:57 2019 +0800

    Add colmun selection in covariate and phenotype

commit 889b11b7aa4c9db9a3feb3b2f6691cd64559b46b
:

Body:
Everything here looks quite normal.

We might start with these observations:

Git stores, for the most part, commits.  That is, the commit is the basic unit of Git storage.  (It's possible to break a commit into several parts, and Git sometimes does, but mostly we work with whole commits at a time.)

As each commit is created, it acquires a unique hash ID.  This hash ID is forever reserved for this commit, not only in this Git repository, but in every Git repository everywhere.  In a sense, it was reserved for this even before you made the commit, except for the fact that the commit hash ID depends on the time, down to the second, when you make the commit.

(These hash IDs are very big and unwieldy.  They have to be, to be unique like this.  No human can get them right, but that's OK: we have a computer, after all.)

Each commit holds a snapshot of all of your files.  That's the main data within a commit, but each commit also holds some metadata: some information about the commit itself.  The metadata includes the name and email address of whoever made it—as two entries, author and committer—and some date-and-time stamps, and a log message where you, or whoever, record the reason you made the commit.

A key item in this metadata, though, is that each commit stores the actual hash ID of its immediate predecessor commit or commits.  That is, each commit has some number of parent commits—usually just one—and the child commit stores the raw hash ID of its parent or parents.

Whenever we have, stored somewhere, the hash ID of a commit, we say that whatever it is that holds this hash ID points to the commit.  So if you have some hash ID H written down somewhere—on paper or on a whitebord, for instance—we might say that this points to commit H.  Since each commit stores the hash ID of its parent, each commit points to its parent.  We can draw this:

... <-F <-G <-H

where H is some commit with some hash ID H, and it points to its parent G, which in turn points to its parent F, and so on.

If we record the last hash ID of some long chain of commits in a branch name like master, that suffices for Git to find all of those commits.  The name points to the last commit:

...--F--G--H   <-- master

and from there, Git can work backwards: starting at H, it finds G, then F, and so on.  This repeats until Git finds the very first commit ever made, which doesn't point back any further, because it can't.

To make a new commit, we start by extracting commit H into a work area.  (All commits are 100% read-only, so we cannot change H, but we can change the stuff we copy to a work area.)  Then we edit files as usual, use git add to copy them to the index—another key item but we won't go into the details here—and use git commit to make a new commit.  Git packages up all of our files into a new snapshot, adds the metadata—our name and email address and the current date and time, for instance—and sets the parent of the new commit to be commit H.  This new commit acquires its new ID, which is too big for us to manage but we'll just call it I.  New commit I therefore points back to existing commit H.

As its final act, git commit writes the hash ID of the new commit into the current branch name.  If the current branch name is master, Git writes I's hash ID into master, so that master now points to I.  Since I points back to H, that's what we get:

...--F--G--H--I   <-- master

The git log command starts at the end and works backwards

A regular git log—not git reflog!—starts from some ending-point commit hash ID, such as by looking inside the name master.  Whenever git log looks in a branch name, this is, by definition, the last commit in the branch.1  Then git log shows us this commit–commit I, in this case—and now git log simply moves on to the commit's parent.  So the next commit you see is the previous commit.

The log, in other words, automatically works backwards, from the end to the beginning.  This is a theme in Git: all of its internal arrows point backwards.  Git always has to start at the end and work backwards.  So git log shows the newest commit by default, because by default, it starts from your current branch name, which is the newest commit on that branch.

Note that if you use git checkout—or the new Git 2.23+ git switch—to switch to a different branch name, git log will start from that other branch name, rather than from master.  Or, if you use git checkout or git switch to switch to detached HEAD mode, in which the special name HEAD points directly to a commit, git log will default to starting from that historical commit.

1The definition of a branch name is that it holds the hash ID of the last commit.  That's what git branch -f, git reset, and so on can do: by forcing a different hash ID into a branch name, this changes which commit is the last commit.  That's also why git commit writes the new commit's hash ID into the branch name: this new commit is, by definition, the last commit, and by definition, a branch name must hold the hash ID of the last commit, so git commit keeps the two definitions working together.

When git log is more complicated

It's often important to draw the graph of commits, by drawing each commit and an arrow from it to its parent(s):

          I--J   <-- branch1
         /
...--G--H
         \
          K--L   <-- branch2

Here we have two different branch names, each pointing to one commit—J for branch1 and L for branch2—with their one commit pointing backwards as usual, but at some point, the two branches join up in history: commits I and K both point back to commit H.

The git log command normally starts from the current branch tip and works backwards.  If we pick branch1 as our current branch, for instance, we'll see commit J first, then I, then H, then G, and so on.  If we pick branch2 as our current branch, we'll see L, then K, then H, and so on.  Note that either way, we don't see two of these commits.

We can, however, tell git log to start from both branch1 and branch2.  But git log can only show one commit at a time.  Will it show us J first, or L first?

The answer to this question is complicated.  Sometimes Git will show us J first, and sometimes it will show L first.  To pick one of the two, git log puts both commits into a priority queue.  The default priority is by committer date-and-time, so that whichever of J or L was made later is the one we'll see first.  You can give git log different sort options, which change the priority; in this case, you might see the other commit first.

Having taken one of the two commits out of the queue and shown it, git log will now put that commit's parent into the priority queue.  It will then show you the highest priority commit—whichever one that is—next.  Then it will put that commit's parent into the priority queue.  There are still two commits in this queue, so once again, which commit you see after these first two is determined by the priority queue.

Eventually, it's likely—or, depending on the flags you give git log, necessary—that git log will have shown J, I, L, and K before showing commit H.  At this point only commit H itself will be in the priority queue, so git log will now show H and put commit G in the queue.  Now G will be the only commit in the queue, so git log will show G, and put G's parent in the queue, and so on.

In other words, git log sometimes sorts commits.  It does this only when its priority queue has more than one entry in it, which happens automatically if you give it multiple starting point commits, such as J and L here.  But look what happens after we merge some commits:

          I--J
         /    \
...--G--H      M--N   <-- master
         \    /
          K--L

Now, if we start at master and work back, git log must show N first—that's the only commit in the queue—and then M.  But commit M has two parents, so git log now puts both J and L into the queue.  Now it has two commits to show, so it picks one, based on priority.  In other words, it now sorts the commits according to the options we give it.  We're back in the same situation we had when we had two branch names, pointing to commits J and L, and told git log to show both commits / branches.

git log shows us one commit at a time, even if history is more complex

The history we'll see from git log can be misleading.  It might show us N, then M, then L and K, then IandJ`, in that order.  If we're not aware of the fact that there was a branch-and-merge, we might think that the commits were made linearly like that.

For this reason, you can have git log draw a crude text-based graph.  This graph is not always very pretty, but it will show that commits L and K are parallel to commits J and I: that they form a branch-and-merge structure in the history, as recorded in the commits.

History is commits; commits are history

Note that throughout all these processes, no commit changes.  We can view the commits one at a time, in different orders with git log --sort=... or git log --topo-order, and/or have Git draw a graph with git log --graph.  Or, we can draw our graph on a whiteboard, or on paper, or using various graph-drawing programs.  But whatever we do, the commits themselves never change.  These commits are the history in your repository.  Their connections exist from the moment you make the commits: child commits point back to their parents.  Merge commits are commits with two (or more) parents.  Branches "fork" when a parent has two or more children.

You can always add more commits to the graph.  Git finds commits by using branch names, which by definition are the last commit in that branch.  You can always add new branch names, and you can delete branch names as well.  If you delete the only name that allows you to find some commit—for instance, if you have:

...--o--o--o--o--...--o  <-- master
         \
          H   <-- branch

and you delete the name branch—that one particular commit, in this case H, becomes hard, or maybe impossible, to find.  However, Git has other ways to find commits.  For instance, tag names can point to commits.  Git also keeps a log of previous values of particular branch and other names.  This log, called a reflog, could allow you to find commit H.

Some operations, such as git rebase, work by copying an existing series of commits to new and improved commits, then moving a branch name.  Since the name holds the hash ID of the last commit, if we copy the commits and then move the name, it looks like we somehow changed the commits:

...--o--o--o--o--...--o  <-- master
         \
          H--I--J   <-- branch

becomes:

...--o--o--o--o--...--o  <-- master
         \             \
          H--I--J       H'-I'-J'  <-- branch

where H' is the copy of H, I' is the copy of I, and J' is the copy of J.  We didn't actually change the commits though.  The originals are still there, in the repository.  You just can't find them easily, because we start with the name branch to find commit I' now, and work backwards from there.

(The reflog for the name branch holds the hash ID of commit J.  If we decide we wish to "undo" the rebase operation, we can force the name branch to remember J again, instead of J'.  Then the reflog for branch will hold the hash ID of commit J'.  Since reflogs hold multiple entries, we'll end up with multiple reflog entries holding J and/or J'.  The reflog entries eventually expire though, so eventually we'll forget commit J entirely, as long as the name branch points only to J'.  A branch name can only point to one commit, and in fact, must point to one commit at all times.)


问:
how to update value of key in json type field on PostgreSQL
I am running postgresql 9.6 version. I am storing data in json type field.

```<code>insert into testable (name, jsonvalues)
values("Jacky", "{'has_attachment': True, 'flag':'True'")
</code>```

I want to update "flag" to "False".

What query i have to use?

答:
Here is one way to do it:

```<code>update testable
set jsonvalues = jsonb_set(jsonvalues::jsonb, '{flag}', '"False"')::json
where name = 'Jacky'
</code>```

Demo on DB Fiddle:

```
name  | jsonvalues
:---- | :------------------------------------------
Jacky | {"flag": "False", "has_attachment": "True"}
```

Note that your original insert query is not valid Postgres syntax. You need single quotes around the values, and double quotes within the JSON, so that should be:

```<code>insert into testable (name, jsonvalues) values(
    'Jacky',
    '{"has_attachment": "True", "flag":"True" }'
)
</code>```

Body:
I am running postgresql 9.6 version. I am storing data in json type field.

insert into testable (name, jsonvalues)
values("Jacky", "{'has_attachment': True, 'flag':'True'")

I want to update "flag" to "False".

What query i have to use?

Body:
Here is one way to do it:

update testable
set jsonvalues = jsonb_set(jsonvalues::jsonb, '{flag}', '"False"')::json
where name = 'Jacky'

Demo on DB Fiddle:

name  | jsonvalues
:---- | :------------------------------------------
Jacky | {"flag": "False", "has_attachment": "True"}

Note that your original insert query is not valid Postgres syntax. You need single quotes around the values, and double quotes within the JSON, so that should be:

insert into testable (name, jsonvalues) values(
    'Jacky',
    '{"has_attachment": "True", "flag":"True" }'
)


问:
CompletableFuture.runAsync vs array of CompletableFuture
I found this code in a project:

```<code>int threadCount = 10;
CompletableFuture<?>[] futures = new CompletableFuture<?>[threadCount];
for (int i = 0; i < threadCount; i++) {
    futures[i] = CompletableFuture.runAsync(() -> { process.run(queue); });
}
// Wait all futures
CompletableFuture.allOf(futures).join();
</code>```

What's the difference with doing this?

```<code>ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
CompletableFuture.runAsync(() -> { process.run(queue); }, threadPool );
</code>```

Thanks for your explanation.

答:
```<code>int threadCount = 10;
CompletableFuture<?>[] futures = new CompletableFuture<?>[threadCount];
for (int i = 0; i < threadCount; i++) {
    futures[i] = CompletableFuture.runAsync(() -> { process.run(queue); });
}
// Wait all futures
CompletableFuture.allOf(futures).join();
</code>```

In this case, you creates set of completable futures which are result of executing asynchronous code in common ForkJoin pool. Then process waits until all futures are completed.

```<code>ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
CompletableFuture.runAsync(() -> { process.run(queue); }, threadPool );
</code>```

In this case, you are executing code in specified thread pool.

The differences between these code blocks

They are executed in different thread pools (first in common ForkJoin which is default for completable futures, second in specified thread pool)

In first case you are waiting for set of tasks to be completed, in second - you just running task asynchronously

Body:
I found this code in a project:

int threadCount = 10;
CompletableFuture<?>[] futures = new CompletableFuture<?>[threadCount];
for (int i = 0; i < threadCount; i++) {
    futures[i] = CompletableFuture.runAsync(() -> { process.run(queue); });
}
// Wait all futures
CompletableFuture.allOf(futures).join();

What's the difference with doing this?

ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
CompletableFuture.runAsync(() -> { process.run(queue); }, threadPool );

Thanks for your explanation.

Body:
int threadCount = 10;
CompletableFuture<?>[] futures = new CompletableFuture<?>[threadCount];
for (int i = 0; i < threadCount; i++) {
    futures[i] = CompletableFuture.runAsync(() -> { process.run(queue); });
}
// Wait all futures
CompletableFuture.allOf(futures).join();

In this case, you creates set of completable futures which are result of executing asynchronous code in common ForkJoin pool. Then process waits until all futures are completed.

ExecutorService threadPool = Executors.newFixedThreadPool(threadCount);
CompletableFuture.runAsync(() -> { process.run(queue); }, threadPool );

In this case, you are executing code in specified thread pool.

The differences between these code blocks

They are executed in different thread pools (first in common ForkJoin which is default for completable futures, second in specified thread pool)

In first case you are waiting for set of tasks to be completed, in second - you just running task asynchronously


问:
Why would a websocket created with pywebsocket be closed automatically?
I want to test websocket with pywebsocket, after some configurations following some instructions I found on the Internet, I finally got it run.

Then I want to try the echo example: http://code.google.com/p/pywebsocket/source/browse/trunk/src/example/console.html

the websocket is connected successfully, and I can do those send and receive things, however, after about 10 seconds since the websocket was established, the websocket was closed automatically. Every time it works like this. I tested it with Chromium 11 on Ubuntu 11.04 with apache. Any ideas?

答: I've found the solution by myself, modify <code>/etc/apache2/mods-enabled/reqtimeout.conf</code> to change the timeout time to 60 seconds. </p>

Body: I've found the solution by myself, modify /etc/apache2/mods-enabled/reqtimeout.conf to change the timeout time to 60 seconds.


问:
Jenkins and Github trigger PUSH from specific branch
I set up the Github webhook in Jenkins and I created a job with the following configuration:

However, every time I push something from any branch, the job build a new version (using the branch which I specified).

I set up the job by reading some related questions on Stackoverflow but all those questions are quite old and without a clear solution:

GitHub WebHooks triggered globally instead of per branch

Trigger Jenkins job on GitHub PUSH to specific branch

Is it possible to trigger Push only from a specific branch?

答:
Finally I did it by using Multibranch Pipeline.

In Branch Sources:

Add credentials and repository URL.

In Behaviours add: Discover
branches: all branches.

Filter by name (with regular expression): for example, ^master|dev|release.$*

In Build Configuration add the path to the Jenkinsfile.

So the job will scan for all the branches of the repository that match with the regular expression.


问:
How to redirect Google Custom Search Engine results to results.php page?
I created a Google CSE and the search box is on the home page of the site. When a user searches, it should redirect them to results.php with the results, however, it redirects them to a cse.google.com/randomurl instead.

It is set up to have the two page format so there should be no problems. I have tried adding an action to my form but no luck.

```<code><form class="form-inline" action="results.php" method="POST">
  <div class="md-form my-0">
    <script async src="https://cse.google.com/cse.js?cx=983049830948390:lxzkzf8ljowm"></script>
    <div class="gcse-searchbox-only"></div>
  </div>
</form>
</code>```

*I modified my custom search engine URL in this question for anonymity purposes.

答:
The documentation shows it like this:

```<code><div class="gcse-searchbox-only" data-resultsUrl="YOUR_RESULTS_PAGE_URL"></div>
</code>```

You have:

```<code><div class="gcse-searchbox-only"></div>
</code>```

Body:
I created a Google CSE and the search box is on the home page of the site. When a user searches, it should redirect them to results.php with the results, however, it redirects them to a cse.google.com/randomurl instead.

It is set up to have the two page format so there should be no problems. I have tried adding an action to my form but no luck.

<form class="form-inline" action="results.php" method="POST">

</form>

*I modified my custom search engine URL in this question for anonymity purposes.

Body:
The documentation shows it like this:

<div class="gcse-searchbox-only" data-resultsUrl="YOUR_RESULTS_PAGE_URL"></div>

You have:

<div class="gcse-searchbox-only"></div>


问:
How can I filter information ordering by two different factors on SQL?
I have the three following tables:

```<code>create table Person (

    id int,
    popularity int,
    primary key (id)
);

create table Movie (

    id int,
    year int,
    primary key (id)
);

create table Person_Movie (

    id_person int,
    id_movie int,
    primary key (id_person, id_movie),
    foreign key (id_person) references Person (id_person),
    foreign key (id_movie) references Movie (id_movie)
);
</code>```

I want to execute a SELECT to check which person has the higher number of popularity BUT has but has participated in less movies.

How can I do this?

To check the most popular person I'd execute this:

```<code>select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by popularity;
</code>```

And, if I am correct, to check the person that has participated in less movies I'd execute this:

```<code>select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by count(M.id);
</code>```

But, how can I filter the two cases in one SELECT?

Thanks in advance.

EDIT

I'm using MySQL.

Also I'll provide an example of what I'm trying to get:

Table Person

```<code>id      popularity
-------------------
1          50
2          35
3          120
4          45
</code>```

Table Movie

```<code>id        year
----------------
1         1999
2         2014
3         1969
4         1977
5         2019
</code>```

Table Person_Movie

```<code>id_person       id_movie
--------------------------
    1              1
    2              4
    2              5
    3              3
    4              1
    4              2
</code>```

So, given this example, the output I would like to get is:

```<code>id_person
----------
    3
</code>```

Because both persons with id 1 and 3 have participated in just ONE movie, but person with id 3 has the higher number of popularity.

答:
It sounds like you want to give precedence to the number of movies as the first expression in the ORDER BY, and then use popularity to break ties. Here's a query with an ORDER BY clause that accomplishes that:

```<code>SELECT TOP 1 id
FROM Person
ORDER BY (SELECT COUNT(*) FROM dbo.Person_Movie WHERE id_person = Person.id) ASC,
    popularity DESC
</code>```

Here's a fiddle based on your sample data.

Body:
I have the three following tables:

create table Person (

    id int,
    popularity int,
    primary key (id)
);

create table Movie (

    id int,
    year int,
    primary key (id)
);

create table Person_Movie (

    id_person int,
    id_movie int,
    primary key (id_person, id_movie),
    foreign key (id_person) references Person (id_person),
    foreign key (id_movie) references Movie (id_movie)
);

I want to execute a SELECT to check which person has the higher number of popularity BUT has but has participated in less movies.

How can I do this?

To check the most popular person I'd execute this:

select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by popularity;

And, if I am correct, to check the person that has participated in less movies I'd execute this:

select P.id from Person as P, Movie as M, Person_Movie as PM
where P.id = PM.id and PM.id = M.id
group by (P.id)
order by count(M.id);

But, how can I filter the two cases in one SELECT?

Thanks in advance.

EDIT

I'm using MySQL.

Also I'll provide an example of what I'm trying to get:

Table Person

id      popularity
-------------------
1          50
2          35
3          120
4          45

Table Movie

id        year
----------------
1         1999
2         2014
3         1969
4         1977
5         2019

Table Person_Movie

id_person       id_movie
--------------------------
    1              1
    2              4
    2              5
    3              3
    4              1
    4              2

So, given this example, the output I would like to get is:

id_person
----------
    3

Because both persons with id 1 and 3 have participated in just ONE movie, but person with id 3 has the higher number of popularity.

Body:
It sounds like you want to give precedence to the number of movies as the first expression in the ORDER BY, and then use popularity to break ties. Here's a query with an ORDER BY clause that accomplishes that:

SELECT TOP 1 id
FROM Person
ORDER BY (SELECT COUNT(*) FROM dbo.Person_Movie WHERE id_person = Person.id) ASC,
    popularity DESC

Here's a fiddle based on your sample data.


问:
Commit hooks not printing any error message if script exists with code 0
My pre-commit is calling a perl script commit_log.pl.The script is doing so many pre-checks.Now I am trying to send out a mail after commit approval.We are not able to set up post-commit hooks due to some permission issues.So I am trying to call the send mail in the pre-commit script itself.

In my commit_log.pl if the exit code is zero ,even printf is not working.

If exit code is 1 everything is working fine

pre-commit:

```<code>log=`$SVNLOOK log -t "$TXN" "$REPOS"`
author=`$SVNLOOK author -t "$TXN" "$REPOS"`
CHANGED=`$SVNLOOK changed -t "$TXN" "$REPOS"`

/usr/bin/perl /isource/svnroot/fgw_ins/hooks/user/commit_log.pl "$log" "$author" "$CHANGED" "$0" 1>&2

if [ "$?" -eq "1" ];
then
        exit 1
else
        exit 0
fi

# if does not match..fail...
exit 1
---------------------------------------------------------------------------------
commit_log.pl
------------------------

}
   else
                {
                        print("Commit approved\n");#this printf itself is not working
                        `python $path/send_mail.py $comment $committed_filepath`;
                        exit 0;
                }
</code>```

答:
Can't add much more to Avi's answer: STDOUT is swallowed by the hook. You will NEVER see STDOUT. STDERR is only seen by the client if the hook script returns a non-zero exitcode -- which usually means the hook failed, and in a pre-commit hook prevents the commit.

If you need to send mail out after a commit, and you can't use a post-commit hook, I suggest you use a continuous build system like Jenkins. You can have Jenkins watch your repository, and when it sees a new revision, send out email to those involved.

Jenkins is a continuous build system which can do a build after every commit, but there's no reason why you need to do a build (except it is usually a good idea anyway). Jenkins can be setup to do any action post commit, so you could have Jenkins simply email those involved.

Yes, it's a bit of an overkill having an entire system like Jenkins just to send out email. Why not simply write your own script? However, you can download, install, and configure Jenkins in an hour or two. It'll take you longer just to layout what you think needs to be done.

Besides, once you have Jenkins, you'll find plenty of other uses for it.

Body:
My pre-commit is calling a perl script commit_log.pl.The script is doing so many pre-checks.Now I am trying to send out a mail after commit approval.We are not able to set up post-commit hooks due to some permission issues.So I am trying to call the send mail in the pre-commit script itself.

In my commit_log.pl if the exit code is zero ,even printf is not working.

If exit code is 1 everything is working fine

pre-commit:

log=`$SVNLOOK log -t "$TXN" "$REPOS"`
author=`$SVNLOOK author -t "$TXN" "$REPOS"`
CHANGED=`$SVNLOOK changed -t "$TXN" "$REPOS"`

/usr/bin/perl /isource/svnroot/fgw_ins/hooks/user/commit_log.pl "$log" "$author" "$CHANGED" "$0" 1>&2

if [ "$?" -eq "1" ];
then
        exit 1
else
        exit 0
fi

# if does not match..fail...
exit 1
---------------------------------------------------------------------------------
commit_log.pl
------------------------

}
   else
                {
                        print("Commit approved\n");#this printf itself is not working
                        `python $path/send_mail.py $comment $committed_filepath`;
                        exit 0;
                }


问:
Why is this C++ deque code 'less efficient' when I demodularize it?
This is a problem I faced when studying solutions to this problem on HackerRank.
It basically boils down to the following: given an array A and an integer K, the problem asks you to find the maximum of each contiguous subarray of A with size K.
There is some additional stuff (for each test case, this problem occurs T times, and one must read from input to obtain A), but that's the gist of it.

The site checks whether your answer is sufficiently efficient, and even if your code produces the correct output in the end, the submission may fail due to timeout.
Now, when your first get to the code area, there is some predefined code for you:

```<code>#include <iostream>
#include <deque>
using namespace std;

void printKMax(int arr[], int n, int k){
    //Write your code here.
}

int main(){

    int t;
    cin >> t;
    while(t>0) {
        int n,k;
        cin >> n >> k;
        int i;
        int arr[n];
        for(i=0;i<n;i++)
            cin >> arr[i];
        printKMax(arr, n, k);
        t--;
    }
    return 0;
}
</code>```

All fine and dandy, the site already handles input for your benefit, and points you towards a modular approach.
All you have to do is actually solve the contiguous subarray problem;
I did it with the following function, which passes all test cases:

```<code>void printKMax(int arr[], int n, int k){
    // Queue will store up to k elements (moving window)
    // Elements stored will be indices of the array. Indices allow to compare with loop iterator for removal of oldest element as window moves
    // Most recent elements are pushed to the back (so they take longer to be popped)
    std::deque<int> Q(k);

    // Iterate over the first window
    int i;
    for (i = 0; i < k; ++i) {
        // A new element (arr[i]) to be added at the back invalidates all elements added before it that are no greater (if they are smaller, they cannot be a maximum; if they are equal, the new element is more recent). Those elements are popped
        // This guarantees that the values corresponding to Q's indices will be increasing (strictly) from back to front. In particular, the front will be the maximum
        while ((!Q.empty()) && arr[i] >= arr[Q.back()])
            Q.pop_back();
        Q.push_back(i);
    }

    // Iterate, letting the window move
    for (; i < n; ++i) {
        // Print the largest element (window has not moved yet), followed by a space
        cout << arr[Q.front()] << " ";

        // Use indices to determine if oldest element has gone out of the window
        if (Q.front() <= i - k) Q.pop_front();

        // Add new element, like before
        while ((!Q.empty()) && arr[i] >= arr[Q.back()])
            Q.pop_back();
        Q.push_back(i);
    }

    // Print the maximum element of last window, and end the line
    cout << arr[Q.front()] << endl;
}
</code>```

However, looking back on it, I thought I could do (slightly?) better.
For each test case, the input handling in main loops n times to fill the array arr, and then printKMax in turn also loops n times to create and slide the moving window.
I thought I could combine these into a single loop, which I guess should be more efficient.
I did it with the following code, which is basically the same as before but with printKMax incorporated into the main.
I'll omit comments this time.

```<code>int main(){

    int t;
    cin >> t;
    while(t>0) {
        int i = 0, n, k;
        cin >> n >> k;
        int arr[n];

        std::deque<int> Q(k);

        for (; i < k; ++i) {
            cin >> arr[i];
            while ((!Q.empty()) && arr[i] >= arr[Q.back()])
                Q.pop_back();
            Q.push_back(i);
        }

        for (; i < n; ++i) {
            cout << arr[Q.front()] << " ";

            if (Q.front() <= i - k) Q.pop_front();

            cin >> arr[i];
            while ((!Q.empty()) && arr[i] >= arr[Q.back()])
                Q.pop_back();
            Q.push_back(i);
        }

        cout << arr[Q.front()] << endl;

        t--;
        }
    return 0;
}
</code>```

This time, however, the code fails all but the simplest of test cases, in each case due to time limit constraints.

I understand that in practice modularization is good, but at this point my interest is more 'academic' than anything else.
Is there something I'm missing about the actual program, or is this something related to how things are run behind the scenes that I'm unaware of?

EDIT: As suggested by PaulMcKenzie, I've used g++ to run both versions of the program, using one of the failed test cases as input.
Both ran fine and produced the same output, but the one with printKMax ran in 3.97s while the one without ran in 5.44s. It takes about 37% longe.

答:
One reason the "de-modularized" version is slow is because you have more I/O in the loop. From the C++ standard:

Reading an object designated by a volatile glvalue (6.10), modifying an object, calling a library I/O function, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment.

After calling I/O function the code must re-load objects from memory (unless the object didn't have to be stored in memory at all, like local variables whose address hasn't leaked). Note, that any function whose definition isn't available at compile time is considered to call I/O functions.

To improve the de-modularized version performance, do not do any I/O in it. Rather store the results into another array int results[k]; and print that array later.

Another issue is that by default std::cin and std::cout are in sync_with_stdio:

In practice, this means that the synchronized C++ streams are unbuffered, and each I/O operation on a C++ stream is immediately applied to the corresponding C stream's buffer.

Try calling std::cin.sync_with_stdio(false); and std::cout.sync_with_stdio(false); - that makes C++ I/O much faster.

Body:
This is a problem I faced when studying solutions to this problem on HackerRank.
It basically boils down to the following: given an array A and an integer K, the problem asks you to find the maximum of each contiguous subarray of A with size K.
There is some additional stuff (for each test case, this problem occurs T times, and one must read from input to obtain A), but that's the gist of it.

The site checks whether your answer is sufficiently efficient, and even if your code produces the correct output in the end, the submission may fail due to timeout.
Now, when your first get to the code area, there is some predefined code for you:

#include <iostream>
#include <deque>
using namespace std;

void printKMax(int arr[], int n, int k){
    //Write your code here.
}

int main(){

    int t;
    cin >> t;
    while(t>0) {
        int n,k;
        cin >> n >> k;
        int i;
        int arr[n];
        for(i=0;i<n;i++)
            cin >> arr[i];
        printKMax(arr, n, k);
        t--;
    }
    return 0;
}

All fine and dandy, the site already handles input for your benefit, and points you towards a modular approach.
All you have to do is actually solve the contiguous subarray problem;
I did it with the following function, which passes all test cases:

void printKMax(int arr[], int n, int k){
    // Queue will store up to k elements (moving window)
    // Elements stored will be indices of the array. Indices allow to compare with loop iterator for removal of oldest element as window moves
    // Most recent elements are pushed to the back (so they take longer to be popped)
    std::deque<int> Q(k);

    // Iterate over the first window
    int i;
    for (i = 0; i < k; ++i) {
        // A new element (arr[i]) to be added at the back invalidates all elements added before it that are no greater (if they are smaller, they cannot be a maximum; if they are equal, the new element is more recent). Those elements are popped
        // This guarantees that the values corresponding to Q's indices will be increasing (strictly) from back to front. In particular, the front will be the maximum
        while ((!Q.empty()) && arr[i] >= arr[Q.back()])
            Q.pop_back();
        Q.push_back(i);
    }

    // Iterate, letting the window move
    for (; i < n; ++i) {
        // Print the largest element (window has not moved yet), followed by a space
        cout << arr[Q.front()] << " ";

        // Use indices to determine if oldest element has gone out of the window
        if (Q.front() <= i - k) Q.pop_front();

        // Add new element, like before
        while ((!Q.empty()) && arr[i] >= arr[Q.back()])
            Q.pop_back();
        Q.push_back(i);
    }

    // Print the maximum element of last window, and end the line
    cout << arr[Q.front()] << endl;
}

However, looking back on it, I thought I could do (slightly?) better.
For each test case, the input handling in main loops n times to fill the array arr, and then printKMax in turn also loops n times to create and slide the moving window.
I thought I could combine these into a single loop, which I guess should be more efficient.
I did it with the following code, which is basically the same as before but with printKMax incorporated into the main.
I'll omit comments this time.

int main(){

    int t;
    cin >> t;
    while(t>0) {
        int i = 0, n, k;
        cin >> n >> k;
        int arr[n];

        std::deque<int> Q(k);

        for (; i < k; ++i) {
            cin >> arr[i];
            while ((!Q.empty()) && arr[i] >= arr[Q.back()])
                Q.pop_back();
            Q.push_back(i);
        }

        for (; i < n; ++i) {
            cout << arr[Q.front()] << " ";

            if (Q.front() <= i - k) Q.pop_front();

            cin >> arr[i];
            while ((!Q.empty()) && arr[i] >= arr[Q.back()])
                Q.pop_back();
            Q.push_back(i);
        }

        cout << arr[Q.front()] << endl;

        t--;
        }
    return 0;
}

This time, however, the code fails all but the simplest of test cases, in each case due to time limit constraints.

I understand that in practice modularization is good, but at this point my interest is more 'academic' than anything else.
Is there something I'm missing about the actual program, or is this something related to how things are run behind the scenes that I'm unaware of?

EDIT: As suggested by PaulMcKenzie, I've used g++ to run both versions of the program, using one of the failed test cases as input.
Both ran fine and produced the same output, but the one with printKMax ran in 3.97s while the one without ran in 5.44s. It takes about 37% longe.


问:
Code For Jquery AM PM Picker
I am familier with the Jquery date picker (jsfiddle). But I want to create an AM/PM picker based on Jquery so when the user clicks on the button it will show TIME like:(12:56:AM), (01:12:PM).  How can I implement that functionality? Can anyone help me with links/jsFiddle/etc.</p>

答: As Vic said, Any+Time(TM) should meet your needs nicely.  The time picker appears when you click on the field, or there are some tips for attaching it to a button.  It supports countless formats, including date+time combined.  If you have any problems, simply request help using the Contact link on the website.</p>

Title: Code For Jquery AM PM Picker