问:
What is the point of a 16-bit wide character?
I am reading the book "C in a Nutshell". It compares the two ways to represent non-Latin characters: Wide characters vs Multibyte characters. It says wide characters use the same bit width for every character in a character set (emphasis mine). Then, it introduces the type wchar_t and, after the C11 standard, types char16_t and char32_t.

My question is, in the world of unicode, how useful can char16_t be? A character encoded by UTF-16 can be anywhere from 2 bytes to 4 bytes, so a char16_t cannot reliably represent it, if one follows the rule that, in wide characters, a character always takes the same bit width.

I understand that not everything in a standard may be "useful", and the C standard does not dictate the encoding, so maybe char16_t is just there for someone to use. But, am I correct that, in terms of dealing with Unicode, char16_t is not that useful?

答:
UTF-16 is a pretty bad encoding, but we didn't know that when Unicode was first envisaged. Back then, 16 bits was enough to store any assigned code point, and UTF-8 with its many desirable properties had not been invented.

Consequently systems that were being built from that time with Unicode support from the ground up — Windows NT and Java, for example — based their string storage types on UTF-16. Those systems, and others that interoperate with them, demand that you use strings with 16-bit code unit semantics to access their APIs.

When you need to talk to one of those systems, a fixed char16_t that definitely represents 16-bit code units, and not full code points, is indeed useful.

a char16_t cannot reliably represent it, if one follows the rule that, in wide characters, a character always takes the same bit width.

That's not a real rule. char16_t (and equally wchar_t on platforms where they are the same type) certainly can be (and usually is) used to store UTF-16 code units, with astral plane characters represented by two (surrogate) code units.


来源: stackexchange

问:
Why is passenger hitting my index page so aggressively
I just moved my apache/mongrel setups to use passenger and I started noticing my index page is getting hit pretty aggressively (approx 5000 hits a day)

I chucked in some logging and it turns out the ip address (REMOTE_ADDR) is showing up as "::1" for these hits.

Has anyone seen this kind of activity? There must be a reason for it. Is there any setting I forgot to configure or set?

EDIT

Thanks Gavin, it looks like this is the dummy connection. Now the question is how I go about disabling it, Passenger conflicts with mod rewrite

I just posted a question on the passenger news group (may take a few mins to show up), will update this as soon as I hear back.

UPDATE 2

These 3 lines in my Apache configuration solve the issue:

```<code>RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
RewriteRule .* - [F,L]
</code>```

I am trying to find out if this belongs in passenger or is a bug local to my setup.

答:
See http://wiki.apache.org/httpd/InternalDummyConnection.

When the Apache HTTP Server manages its child processes, it needs a way to wake up processes that are listening for new connections. To do this, it sends a simple HTTP request back to itself.

You can filter them using mod_rewrite, SetEnvIf or a regular expression on the User-Agent (look for "internal dummy connection").

ContentLicense: CC BY-SA 2.5

Body:
I just moved my apache/mongrel setups to use passenger and I started noticing my index page is getting hit pretty aggressively (approx 5000 hits a day)

I chucked in some logging and it turns out the ip address (REMOTE_ADDR) is showing up as "::1" for these hits.

Has anyone seen this kind of activity? There must be a reason for it. Is there any setting I forgot to configure or set?

EDIT

Thanks Gavin, it looks like this is the dummy connection. Now the question is how I go about disabling it, Passenger conflicts with mod rewrite

I just posted a question on the passenger news group (may take a few mins to show up), will update this as soon as I hear back.

UPDATE 2

These 3 lines in my Apache configuration solve the issue:

RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
RewriteRule .* - [F,L]

I am trying to find out if this belongs in passenger or is a bug local to my setup.

OwnerDisplayName: Gavin Brown


问:
Prevent robots from coping images from a website
I have a website created in PHP technology and i want to prevent robots from coping images from the website.What is the best way to prevent robots from coping images from a website?

Please make sure it doesn't harm SEO.
Please make sure this does not influence spyders and crawlers from indexing the site.

答:
You can configure your robots.txt to allow certain robots, but not others:

E.g.:

```<code>User-Agent: *
Disallow: /images

User-Agent: Googlebot-Image
Disallow:
</code>```

This is just an example.  You can also allow other well-behaved robots.

But that does nothing about badly behaved robots that just ignore robots.txt.  there's really no solution for them, though authentication can help a little (you can throttle image access by account).

Body:
You can configure your robots.txt to allow certain robots, but not others:

E.g.:

User-Agent: *
Disallow: /images

User-Agent: Googlebot-Image
Disallow:

This is just an example.  You can also allow other well-behaved robots.

But that does nothing about badly behaved robots that just ignore robots.txt.  there's really no solution for them, though authentication can help a little (you can throttle image access by account).


问:
How to run a custom mongodb query in spring-boot
I have a spring-boot application and I am trying to run this below query using it.

```<code>db.userActivity.findAndModify(
{
   query: { 'appId' : 1234, 'status' : 0},
   update: { $inc: { 'status': 1 } }
});
</code>```

I did try something like this but it didn't work

```<code>public interface UserActivityRepository extends MongoRepository<UserActivity, String> {

    /**
     * Find all documents in the database
     * @param appId
     * @param status
     * @return
     */
    @Query("{ 'appId' : ?0, 'status' : ?1}")
    public List<UserActivity> findAllDocuments(long appId, int status);

    /**
     * Find all documents by appId whose state is unread
     * and marked them read after reading
     * @param appId
     * @return
     */
    @Query("db.userActivity.findAndModify({ query: { 'appId' : ?0, 'status' : ?1}, update: { $inc: { 'status': 1 } } })")
    public List<UserActivity> findAndUpdateAllUnreadDocuments(long appId, int status);
}
</code>```

Could you please tell what I am doing wrong?

答: @Query annotation used for customization of queries only. Use findAllDocuments function and implement you update logic. This is the full example: Spring Boot + Spring Data MongoDB example

ContentLicense: CC BY-SA 3.0

Body:
I have a spring-boot application and I am trying to run this below query using it.

db.userActivity.findAndModify(
{
   query: { 'appId' : 1234, 'status' : 0},
   update: { $inc: { 'status': 1 } }
});

I did try something like this but it didn't work

public interface UserActivityRepository extends MongoRepository<UserActivity, String> {

    /**
     * Find all documents in the database
     * @param appId
     * @param status
     * @return
     */
    @Query("{ 'appId' : ?0, 'status' : ?1}")
    public List<UserActivity> findAllDocuments(long appId, int status);

    /**
     * Find all documents by appId whose state is unread
     * and marked them read after reading
     * @param appId
     * @return
     */
    @Query("db.userActivity.findAndModify({ query: { 'appId' : ?0, 'status' : ?1}, update: { $inc: { 'status': 1 } } })")
    public List<UserActivity> findAndUpdateAllUnreadDocuments(long appId, int status);
}

Could you please tell what I am doing wrong?


问:
NSIS example of auto-update the installer itself?
I am looking for a NSIS example that is able to update itself with the latest version of the installer.

The logic is simple: check if the publish URL is newer than the current executable and download it and recall itself with the same parameters.

Mainly that's would me something like "wget --timestamp URL" but so far I wasn't able to find any NSIS file download extension that is able to download a file only if is newer.

答:
Here's something I wrote that might be of help to you. I have not tested this thoroughly but it did work on the first couple tests I ran. This is just an example I threw together for a project I'm working on. Hope it's of use to you. =)

VersionCompare Function

```<code>;=#
;= Taken and modified from:
;= http://nsis.sourceforge.net/VersionCompare
Function VersionCompare
    !define VersionCompare `!insertmacro _VersionCompare`
    !macro _VersionCompare _VER1 _VER2 _RESULT
        Push `${_VER1}`
        Push `${_VER2}`
        Call VersionCompare
        Pop ${_RESULT}
    !macroend
    Exch $1
    Exch
    Exch $0
    Exch
    Push $2
    Push $3
    Push $4
    Push $5
    Push $6
    Push $7
    BEGIN:
    StrCpy $2 -1
    IntOp $2 $2 + 1
    StrCpy $3 $0 1 $2
    StrCmp $3 '' +2
    StrCmp $3 '.' 0 -3
    StrCpy $4 $0 $2
    IntOp $2 $2 + 1
    StrCpy $0 $0 '' $2
    StrCpy $2 -1
    IntOp $2 $2 + 1
    StrCpy $3 $1 1 $2
    StrCmp $3 '' +2
    StrCmp $3 '.' 0 -3
    StrCpy $5 $1 $2
    IntOp $2 $2 + 1
    StrCpy $1 $1 '' $2
    StrCmp $4$5 '' EQUAL
    StrCpy $6 -1
    IntOp $6 $6 + 1
    StrCpy $3 $4 1 $6
    StrCmp $3 '0' -2
    StrCmp $3 '' 0 +2
    StrCpy $4 0
    StrCpy $7 -1
    IntOp $7 $7 + 1
    StrCpy $3 $5 1 $7
    StrCmp $3 '0' -2
    StrCmp $3 '' 0 +2
    StrCpy $5 0
    StrCmp $4 0 0 +2
    StrCmp $5 0 BEGIN NEWER2
    StrCmp $5 0 NEWER1
    IntCmp $6 $7 0 NEWER1 NEWER2
    StrCpy $4 '1$4'
    StrCpy $5 '1$5'
    IntCmp $4 $5 BEGIN NEWER2 NEWER1
    EQUAL:
    StrCpy $0 0
    Goto FINISH
    NEWER1:
    StrCpy $0 1
    Goto FINISH
    NEWER2:
    StrCpy $0 2
    FINISH:
    Pop $7
    Pop $6
    Pop $5
    Pop $4
    Pop $3
    Pop $2
    Pop $1
    Exch $0
FunctionEnd
</code>```

UpdateCheck Function

```<code>;=#
;= Author: demon.devin
;= http://softables.tk/
Function UpdateCheck
    !define UpdateCheck `!insertmacro _UpdateCheck`
    !macro _UpdateCheck _NAME _LINK _URL _VERSION
        Push `${_URL}`
        Push `${_VERSION}`
        Call UpdateCheck
        Pop `${_NAME}`
        Pop `${_LINK}`
    !macroend
    Exch $1
    Exch
    Exch $0
    Push $0
    Push $1
    DetailPrint "Current Version: $1"
    GetTempFileName $R1
    NSISdl::download $0 $R1
    ReadINIStr $R0 "$R1" "PAFInfo" "Version"
    DetailPrint "Latest Version: $R0"
    ${VersionCompare} $1 $R0 $R4
    ${If} $R4 == 0
    ${OrIf} $R4 == 1
        ReadINIStr $R3 "$R1" "PAFInfo" "Name"
        StrCpy $File `$R3`
        StrCpy $R2 ""
        StrCpy $Link ``
    ${Else}
        ReadINIStr $R2 "$R1" "PAFInfo" "DownloadLink"
        StrCpy $Link `$R2`
        ReadINIStr $R3 "$R1" "PAFInfo" "Filename"
        StrCpy $File `$R3`
    ${EndIf}
    SetDetailsPrint none
    Delete $R1
    SetDetailsPrint lastused
    Pop $1
    Pop $0
    Exch $R2
    Exch
    Exch $R3
FunctionEnd
</code>```

WGetDownload Function

```<code>;=#
;= Author: demon.devin
;= http://softables.tk/
Function WGetDownload
    !define WGetDownload "!insertmacro _WGetDownload"
    !macro _WGetDownload _RETURN _TEMPFILE _URL _FILENAME
        Push ${_URL}
        Push ${_FILENAME}
        Call WGetDownload
        Pop ${_TEMPFILE}
        Pop ${_RETURN}
    !macroend
    Exch $1
    Exch
    Exch $2
    Push $1
    Push $2
    !define WGET     `$PLUGINSDIR\wget.exe`
    !define WGETCMD  `"${WGET}" --html-extension --referer="http://www.google.com" --user-agent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6" -T 10 --no-check-certificate "$Link" --output-document=$File`
    MessageBox MB_OK|MB_USERICON|MB_TOPMOST "Package: $File$\r$\nLink: $Link$\r$\n$\r$\nClick OK to start download."
    DetailPrint "Downloading: $Link"
    SetOutPath `$PLUGINSDIR`
    File `${NSISDIR}\Contrib\7zip\wget.exe`
    WGET:
    SetOutPath `$PLUGINSDIR`
    ExecDos::Exec /TOSTACK `${WGETCMD}`
    Pop $0
    Pop $1
    ${If} $0 = 1
        StrCmp $2 1 +3
        StrCpy $2 1
        Goto WGET
        Goto FAIL
    ${EndIf}
    ${If} ${FileExists} "$PLUGINSDIR\$File"
        ClearErrors
        StrCpy $R5 true
        StrCpy $R7 "$PLUGINSDIR\$File"
        ${GetSize} "$PLUGINSDIR" "/M=$File /S=0K" $0 $1 $2
        IfErrors 0 +2
        StrCpy $0 $0 * 1024
        IntCmp $0 100 +3 0 +3
        IntCmp $0 0 +2 +2 0
        IntOp $0 103 + 0
        IntOp $0 $0 * 10
        IntOp $0 $0 / 1024
        StrCpy $1 "$0" "" -1
        IntCmp $0 9 +3 +3 0
        StrCpy $0 "$0" -1 ""
        Goto +2
        StrCpy $0 "0"
        MessageBox MB_OK|MB_USERICON|MB_TOPMOST "Your file $File was successfully downloaded! ($0.$1 MiB)"
        Goto DONE
    ${Else}
        FAIL:
        StrCpy $R5 "Your file $File has failed to download using the WGet utility!"
        Goto CANCEL
    ${EndIf}
    CANCEL:
    MessageBox MB_OK|MB_ICONSTOP|MB_TOPMOST "ERROR!$\r$\n$\r$\n$R5"
    StrCpy $R5 false
    StrCpy $R7 ""
    SetErrors
    DONE:
    Pop $2
    Pop $1
    Exch $R5
    Exch
    Exch $R7
FunctionEnd
</code>```

OpenWebPage Macro

```<code>;=#
;= Author: demon.devin
;= http://softables.tk/
!define OpenWebPage '!insertmacro "_OpenWebPage"'
!macro _OpenWebPage _URL
    ExecShell open "${_URL}"
!macroend
</code>```

EXAMPLE USAGE:

```<code>;=#
;= Author: demon.devin
;= More NSIS help:
;= http://softables.tk/docs
Section "MAIN"
    ClearErrors
    MessageBox MB_USERICON|MB_YESNO|MB_TOPMOST `Would you like to check for any possible upgrades?` IDYES CHECK IDNO NOCHECK
    NOCHECK:
    DetailPrint "What?! How can you improve if you don't check for upgrades?"
    Goto DONE
    CHECK:
    DetailPrint "Checking for new version..."
    ${UpdateCheck} $0 $1 "http://softables.tk/repository/docs/manifests.ini" "6.25.11.0"
    StrCmp $1 "" 0 +5
    DetailPrint "You have the most recent version..."
    MessageBox MB_USERICON|MB_OK|MB_TOPMOST `$0 is up to date!`
    DetailPrint "Continuing with the rest of the operation..."
    Goto DONE
    DetailPrint "There's a new version available..."
    MessageBox MB_ICONEXCLAMATION|MB_YESNO|MB_TOPMOST "New version of $File available.$\r$\nDownload now?" IDYES YES IDNO NO
    NO:
    DetailPrint "Fine! Stick with the old stuff. See if I care..."
    Goto DONE
    YES:
    DetailPrint "Great! Downloading new updates now..."
    ${WGetDownload} $R0 $R1 "$Link" "$File"
    ${If} $R0 == true
    ${AndIf} $R1 != ""
        DetailPrint "Downloaded: $R1"
        DetailPrint "Awesome! The download was successful..."
        CopyFiles /SILENT `$R1` `$INSTDIR\WGET\$R1`
        DetailPrint "Extracting the contents now..."
        File '/oname=$PLUGINSDIR\7z.dll' `${NSISDIR}\Contrib\7zip\7z.dll`
        File '/oname=$PLUGINSDIR\7z.exe' `${NSISDIR}\Contrib\7zip\7z.exe`
        ExecDos::Exec /TOSTACK `"$PLUGINSDIR\7z.exe" x "$R1" -o"$INSTDIR" -aoa -y` "" ""
        Pop $0
        DetailPrint "All done! Cleaning up temporary files..."
        Delete `$R1`
        DetailPrint "Finished. Enjoy..."
    ${Else}
        DetailPrint "Something went wrong! The download was unsuccessful..."
        MessageBox MB_ICONEXCLAMATION|MB_YESNO|MB_TOPMOST "You can manually download the upgrades by visiting:$\r$\n$Link$\r$\n$\r$\nGo there now?" IDYES WEB IDNO DONE
        WEB:
        DetailPrint "Launching web page now... "
        SetDetailsPrint none
        ${OpenWebPage} "$Link"
        SetDetailsPrint lastused
    ${EndIf}
    DONE:
    DetailPrint "Moving right along..."
SectionEnd
</code>```

Body:
Here's something I wrote that might be of help to you. I have not tested this thoroughly but it did work on the first couple tests I ran. This is just an example I threw together for a project I'm working on. Hope it's of use to you. =)

VersionCompare Function

;=#
;= Taken and modified from:
;= http://nsis.sourceforge.net/VersionCompare
Function VersionCompare
    !define VersionCompare `!insertmacro _VersionCompare`
    !macro _VersionCompare _VER1 _VER2 _RESULT
        Push `${_VER1}`
        Push `${_VER2}`
        Call VersionCompare
        Pop ${_RESULT}
    !macroend
    Exch $1
    Exch
    Exch $0
    Exch
    Push $2
    Push $3
    Push $4
    Push $5
    Push $6
    Push $7
    BEGIN:
    StrCpy $2 -1
    IntOp $2 $2 + 1
    StrCpy $3 $0 1 $2
    StrCmp $3 '' +2
    StrCmp $3 '.' 0 -3
    StrCpy $4 $0 $2
    IntOp $2 $2 + 1
    StrCpy $0 $0 '' $2
    StrCpy $2 -1
    IntOp $2 $2 + 1
    StrCpy $3 $1 1 $2
    StrCmp $3 '' +2
    StrCmp $3 '.' 0 -3
    StrCpy $5 $1 $2
    IntOp $2 $2 + 1
    StrCpy $1 $1 '' $2
    StrCmp $4$5 '' EQUAL
    StrCpy $6 -1
    IntOp $6 $6 + 1
    StrCpy $3 $4 1 $6
    StrCmp $3 '0' -2
    StrCmp $3 '' 0 +2
    StrCpy $4 0
    StrCpy $7 -1
    IntOp $7 $7 + 1
    StrCpy $3 $5 1 $7
    StrCmp $3 '0' -2
    StrCmp $3 '' 0 +2
    StrCpy $5 0
    StrCmp $4 0 0 +2
    StrCmp $5 0 BEGIN NEWER2
    StrCmp $5 0 NEWER1
    IntCmp $6 $7 0 NEWER1 NEWER2
    StrCpy $4 '1$4'
    StrCpy $5 '1$5'
    IntCmp $4 $5 BEGIN NEWER2 NEWER1
    EQUAL:
    StrCpy $0 0
    Goto FINISH
    NEWER1:
    StrCpy $0 1
    Goto FINISH
    NEWER2:
    StrCpy $0 2
    FINISH:
    Pop $7
    Pop $6
    Pop $5
    Pop $4
    Pop $3
    Pop $2
    Pop $1
    Exch $0
FunctionEnd

UpdateCheck Function

;=#
;= Author: demon.devin
;= http://softables.tk/
Function UpdateCheck
    !define UpdateCheck `!insertmacro _UpdateCheck`
    !macro _UpdateCheck _NAME _LINK _URL _VERSION
        Push `${_URL}`
        Push `${_VERSION}`
        Call UpdateCheck
        Pop `${_NAME}`
        Pop `${_LINK}`
    !macroend
    Exch $1
    Exch
    Exch $0
    Push $0
    Push $1
    DetailPrint "Current Version: $1"
    GetTempFileName $R1
    NSISdl::download $0 $R1
    ReadINIStr $R0 "$R1" "PAFInfo" "Version"
    DetailPrint "Latest Version: $R0"
    ${VersionCompare} $1 $R0 $R4
    ${If} $R4 == 0
    ${OrIf} $R4 == 1
        ReadINIStr $R3 "$R1" "PAFInfo" "Name"
        StrCpy $File `$R3`
        StrCpy $R2 ""
        StrCpy $Link ``
    ${Else}
        ReadINIStr $R2 "$R1" "PAFInfo" "DownloadLink"
        StrCpy $Link `$R2`
        ReadINIStr $R3 "$R1" "PAFInfo" "Filename"
        StrCpy $File `$R3`
    ${EndIf}
    SetDetailsPrint none
    Delete $R1
    SetDetailsPrint lastused
    Pop $1
    Pop $0
    Exch $R2
    Exch
    Exch $R3
FunctionEnd

WGetDownload Function

;=#
;= Author: demon.devin
;= http://softables.tk/
Function WGetDownload
    !define WGetDownload "!insertmacro _WGetDownload"
    !macro _WGetDownload _RETURN _TEMPFILE _URL _FILENAME
        Push ${_URL}
        Push ${_FILENAME}
        Call WGetDownload
        Pop ${_TEMPFILE}
        Pop ${_RETURN}
    !macroend
    Exch $1
    Exch
    Exch $2
    Push $1
    Push $2
    !define WGET     `$PLUGINSDIR\wget.exe`
    !define WGETCMD  `"${WGET}" --html-extension --referer="http://www.google.com" --user-agent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6" -T 10 --no-check-certificate "$Link" --output-document=$File`
    MessageBox MB_OK|MB_USERICON|MB_TOPMOST "Package: $File$\r$\nLink: $Link$\r$\n$\r$\nClick OK to start download."
    DetailPrint "Downloading: $Link"
    SetOutPath `$PLUGINSDIR`
    File `${NSISDIR}\Contrib\7zip\wget.exe`
    WGET:
    SetOutPath `$PLUGINSDIR`
    ExecDos::Exec /TOSTACK `${WGETCMD}`
    Pop $0
    Pop $1
    ${If} $0 = 1
        StrCmp $2 1 +3
        StrCpy $2 1
        Goto WGET
        Goto FAIL
    ${EndIf}
    ${If} ${FileExists} "$PLUGINSDIR\$File"
        ClearErrors
        StrCpy $R5 true
        StrCpy $R7 "$PLUGINSDIR\$File"
        ${GetSize} "$PLUGINSDIR" "/M=$File /S=0K" $0 $1 $2
        IfErrors 0 +2
        StrCpy $0 $0 * 1024
        IntCmp $0 100 +3 0 +3
        IntCmp $0 0 +2 +2 0
        IntOp $0 103 + 0
        IntOp $0 $0 * 10
        IntOp $0 $0 / 1024
        StrCpy $1 "$0" "" -1
        IntCmp $0 9 +3 +3 0
        StrCpy $0 "$0" -1 ""
        Goto +2
        StrCpy $0 "0"
        MessageBox MB_OK|MB_USERICON|MB_TOPMOST "Your file $File was successfully downloaded! ($0.$1 MiB)"
        Goto DONE
    ${Else}
        FAIL:
        StrCpy $R5 "Your file $File has failed to download using the WGet utility!"
        Goto CANCEL
    ${EndIf}
    CANCEL:
    MessageBox MB_OK|MB_ICONSTOP|MB_TOPMOST "ERROR!$\r$\n$\r$\n$R5"
    StrCpy $R5 false
    StrCpy $R7 ""
    SetErrors
    DONE:
    Pop $2
    Pop $1
    Exch $R5
    Exch
    Exch $R7
FunctionEnd

OpenWebPage Macro

;=#
;= Author: demon.devin
;= http://softables.tk/
!define OpenWebPage '!insertmacro "_OpenWebPage"'
!macro _OpenWebPage _URL
    ExecShell open "${_URL}"
!macroend

EXAMPLE USAGE:

;=#
;= Author: demon.devin
;= More NSIS help:
;= http://softables.tk/docs
Section "MAIN"
    ClearErrors
    MessageBox MB_USERICON|MB_YESNO|MB_TOPMOST `Would you like to check for any possible upgrades?` IDYES CHECK IDNO NOCHECK
    NOCHECK:
    DetailPrint "What?! How can you improve if you don't check for upgrades?"
    Goto DONE
    CHECK:
    DetailPrint "Checking for new version..."
    ${UpdateCheck} $0 $1 "http://softables.tk/repository/docs/manifests.ini" "6.25.11.0"
    StrCmp $1 "" 0 +5
    DetailPrint "You have the most recent version..."
    MessageBox MB_USERICON|MB_OK|MB_TOPMOST `$0 is up to date!`
    DetailPrint "Continuing with the rest of the operation..."
    Goto DONE
    DetailPrint "There's a new version available..."
    MessageBox MB_ICONEXCLAMATION|MB_YESNO|MB_TOPMOST "New version of $File available.$\r$\nDownload now?" IDYES YES IDNO NO
    NO:
    DetailPrint "Fine! Stick with the old stuff. See if I care..."
    Goto DONE
    YES:
    DetailPrint "Great! Downloading new updates now..."
    ${WGetDownload} $R0 $R1 "$Link" "$File"
    ${If} $R0 == true
    ${AndIf} $R1 != ""
        DetailPrint "Downloaded: $R1"
        DetailPrint "Awesome! The download was successful..."
        CopyFiles /SILENT `$R1` `$INSTDIR\WGET\$R1`
        DetailPrint "Extracting the contents now..."
        File '/oname=$PLUGINSDIR\7z.dll' `${NSISDIR}\Contrib\7zip\7z.dll`
        File '/oname=$PLUGINSDIR\7z.exe' `${NSISDIR}\Contrib\7zip\7z.exe`
        ExecDos::Exec /TOSTACK `"$PLUGINSDIR\7z.exe" x "$R1" -o"$INSTDIR" -aoa -y` "" ""
        Pop $0
        DetailPrint "All done! Cleaning up temporary files..."
        Delete `$R1`
        DetailPrint "Finished. Enjoy..."
    ${Else}
        DetailPrint "Something went wrong! The download was unsuccessful..."
        MessageBox MB_ICONEXCLAMATION|MB_YESNO|MB_TOPMOST "You can manually download the upgrades by visiting:$\r$\n$Link$\r$\n$\r$\nGo there now?" IDYES WEB IDNO DONE
        WEB:
        DetailPrint "Launching web page now... "
        SetDetailsPrint none
        ${OpenWebPage} "$Link"
        SetDetailsPrint lastused
    ${EndIf}
    DONE:
    DetailPrint "Moving right along..."
SectionEnd


问:
How can I list posts in a feed by the most recently created?
I use Onymos for my backend. When I pull my data from onymos it gives me an "arrange by" property where I can specify "createdTime" as the value, however, this doesn't carry over to my template for some reason. I don't think there is an order by directive in angular anymore from my googling. So I'm not sure how else I can order this in my template.
My service passes an array to a callback function which fires in the contstructor of the main TS page.
I put a bounty on this because the first solution someone provided didn't work for me.. kept causing errors.

HOME.HTML

```<code><ion-card id="card" *ngFor="let event of listOfEvents" >

    <ion-row id="row1">
        <ion-col>
           <span class="showDetails">Date:</span>
           {{getFormattedTime(event.eventTime, 'MM-dd-yyyy')}}
        </ion-col>
        <ion-col>
            <span class="showDetails">Time:</span>
            {{getFormattedTime(event.eventTime, 'HH:MM')}}
        </ion-col>
        <ion-col>
            <span class="showDetails">Venue:</span>
            {{event.venue}}
        </ion-col>
    </ion-row>

</ion-card>
</code>```

MyService.TS

```<code>getPosts (selectedCity, successCallback, failureCallback) {

        OnymosUtil.getData(

            '/events/' + selectedCity,
            function getPostsSuccess (listOfEventsObject){
                successCallback(listOfEventsObject);
            },//close function getPostSuccess
            function getPostsFailure (error) {
                failureCallback(error);
            },
            {
                orderByField: 'createdTime', //OrderByField not working
                limitToFirst: 100
        });

    }//end getPosts
</code>```

HOME.TS

```<code>export class Home {

    listOfEvents: Array<any> = [];
    postEvent: any;

    constructor (public navCtrl: NavController,
                 public popoverCtrl: PopoverController,
                 public getPostSrvc: getPostsService) {

        this.listOfEvents = [];
        let that = this;

        this.getPostSrvc.getPosts(
           this.selectedCity,
           function getPostsSuccess (listOfEventsObject) {
                for (var i in listOfEventsObject) {
                    that.listOfEvents.push(listOfEventsObject[i]);
                }
           },
           function getPostsFailure (error) {
             console.log('ERROR : home.ts : Failed retrieving Posts - ' + error);
            });
    }//close constructor
}//close class
</code>```

答:
Just sort it client side:</p>

```<code>function successCallback (listOfEventsObject) {

    for (var x in listOfEventsObject) {
        that.listOfEvents.push(listOfEventsObject[x]);
    }
    // sort
    that.listOfEvents = that.listOfEvents.sort(function(a, b) {
        return a.createdTime - b.createdTime;
        // or vice versa
        // or any other way you wish to sort
    });

}
</code>```

Body:
I use Onymos for my backend. When I pull my data from onymos it gives me an "arrange by" property where I can specify "createdTime" as the value, however, this doesn't carry over to my template for some reason. I don't think there is an order by directive in angular anymore from my googling. So I'm not sure how else I can order this in my template.
My service passes an array to a callback function which fires in the contstructor of the main TS page.
I put a bounty on this because the first solution someone provided didn't work for me.. kept causing errors.

HOME.HTML

<ion-card id="card" *ngFor="let event of listOfEvents" >

    <ion-row id="row1">
        <ion-col>
           Date:
           {{getFormattedTime(event.eventTime, 'MM-dd-yyyy')}}
        </ion-col>
        <ion-col>
            Time:
            {{getFormattedTime(event.eventTime, 'HH:MM')}}
        </ion-col>
        <ion-col>
            Venue:
            {{event.venue}}
        </ion-col>
    </ion-row>

</ion-card>

MyService.TS

getPosts (selectedCity, successCallback, failureCallback) {

        OnymosUtil.getData(

            '/events/' + selectedCity,
            function getPostsSuccess (listOfEventsObject){
                successCallback(listOfEventsObject);
            },//close function getPostSuccess
            function getPostsFailure (error) {
                failureCallback(error);
            },
            {
                orderByField: 'createdTime', //OrderByField not working
                limitToFirst: 100
        });

    }//end getPosts

HOME.TS

export class Home {

    listOfEvents: Array<any> = [];
    postEvent: any;

    constructor (public navCtrl: NavController,
                 public popoverCtrl: PopoverController,
                 public getPostSrvc: getPostsService) {

        this.listOfEvents = [];
        let that = this;

        this.getPostSrvc.getPosts(
           this.selectedCity,
           function getPostsSuccess (listOfEventsObject) {
                for (var i in listOfEventsObject) {
                    that.listOfEvents.push(listOfEventsObject[i]);
                }
           },
           function getPostsFailure (error) {
             console.log('ERROR : home.ts : Failed retrieving Posts - ' + error);
            });
    }//close constructor
}//close class

Body:
Just sort it client side:

function successCallback (listOfEventsObject) {

    for (var x in listOfEventsObject) {
        that.listOfEvents.push(listOfEventsObject[x]);
    }
    // sort
    that.listOfEvents = that.listOfEvents.sort(function(a, b) {
        return a.createdTime - b.createdTime;
        // or vice versa
        // or any other way you wish to sort
    });

}


问:
Creating a dictionary of dictionaries from a text file
I'm reading data from a file that looks like this...

```<code>ID; 34556
hi; 8
lo; 16
threshold; 90
ID; 54365
hi; 0.03
lo; 8
threshold; 50
......
</code>```

So far I have this...

```<code>d = {}
with open ('filename.txt', 'r') as f:
    for l in f.readlines():
        split = l.split(';')
        key = 'dictionary_key'
        if 'id' in split[0]:
           d.setdefault(key, {}).setdefault('id', split[1])
        if 'threshold' in split[0]:
            d.setdefault(key, {}).setdefault('thresh', split[1])
        if 'hi' in split[0]:
            d.setdefault(key, {}).setdefault('hi', split[1])
        if 'lo' in split[0]:
            d.setdefault(key, {}).setdefault('lo', split[1])
</code>```

But when I do this my output is only this...

```<code>{'dictionary_key': {'hi': '8', 'lo': '16', 'id': '34556', 'thresh': '90'}}
</code>```

and I can seem to create the nested dictionary for the entirety of the file.

Originally I was trying to have the id be the key and everything else fall into the nested dictionary like so...

```<code>{'34556': {'hi' : '8', 'lo' : '16', 'thresh' :90}}
</code>```

but couldn't figure out how to.  What am I doing wrong?

答:
You aren't updating the dictionary key (or creating new dictionaries for each level), try something like this?

```<code>import json

str = """
ID; 34556
hi; 8
lo; 16
threshold; 90
ID; 54365
hi; 0.03
lo; 8
threshold; 50
"""

data = {}
id = None
for line in str.split('\n'):
    try:
        key, value = line.split('; ')
        if key == "ID":
            id = value
            data[id] = {}
        elif id is not None:
            data[id][key] = value

    except Exception as e:
        print(e, 'skipping line:', line)

print(json.dumps(data, indent=4))
</code>```

output:

```<code>{
    "34556": {
        "lo": "16",
        "hi": "8",
        "threshold": "90"
    },
    "54365": {
        "lo": "8",
        "hi": "0.03",
        "threshold": "50 "
    }
}
</code>```

Body:
I'm reading data from a file that looks like this...

ID; 34556
hi; 8
lo; 16
threshold; 90
ID; 54365
hi; 0.03
lo; 8
threshold; 50
......

So far I have this...

d = {}
with open ('filename.txt', 'r') as f:
    for l in f.readlines():
        split = l.split(';')
        key = 'dictionary_key'
        if 'id' in split[0]:
           d.setdefault(key, {}).setdefault('id', split[1])
        if 'threshold' in split[0]:
            d.setdefault(key, {}).setdefault('thresh', split[1])
        if 'hi' in split[0]:
            d.setdefault(key, {}).setdefault('hi', split[1])
        if 'lo' in split[0]:
            d.setdefault(key, {}).setdefault('lo', split[1])

But when I do this my output is only this...

{'dictionary_key': {'hi': '8', 'lo': '16', 'id': '34556', 'thresh': '90'}}

and I can seem to create the nested dictionary for the entirety of the file.

Originally I was trying to have the id be the key and everything else fall into the nested dictionary like so...

{'34556': {'hi' : '8', 'lo' : '16', 'thresh' :90}}

but couldn't figure out how to.  What am I doing wrong?

Body:
You aren't updating the dictionary key (or creating new dictionaries for each level), try something like this?

import json

str = """
ID; 34556
hi; 8
lo; 16
threshold; 90
ID; 54365
hi; 0.03
lo; 8
threshold; 50
"""

data = {}
id = None
for line in str.split('\n'):
    try:
        key, value = line.split('; ')
        if key == "ID":
            id = value
            data[id] = {}
        elif id is not None:
            data[id][key] = value

    except Exception as e:
        print(e, 'skipping line:', line)

print(json.dumps(data, indent=4))

output:

{
    "34556": {
        "lo": "16",
        "hi": "8",
        "threshold": "90"
    },
    "54365": {
        "lo": "8",
        "hi": "0.03",
        "threshold": "50 "
    }
}


问:
C# Sort by boolean equality to static string, followed by sort on integer number ascending
I have a List<Data> myList where

```<code>public class Data
{
    public string Classifier;
    public int Code;
}
</code>```

and I want to sort it

By whether or not a data's Classifier is equal to some static string, we'll just call it @"Alpha" for now (non-equals first, equals second)

By Code, ascending.

So the input data

```<code>    {
      "Beta", 6
      "Alpha", 4
      "Lambda", 2
      "Beta", 1
      "Alpha", 5
    }
</code>```

would result in

```<code>    {
      "Beta", 1
      "Lambda", 2
      "Beta", 6
      "Alpha", 4
      "Alpha", 5
    }
</code>```

Specifically, I want the alpha's to settle to the bottom of the list in ascending numerical order.

I'm not sure how to implement a .Sort Comparison<Data> instance to support this, and .OrderBy doesn't seem to fit the problem.  Any thoughts?

答:
Actually, I think OrderBy/ThenBy combo would work here:

var result = myList.OrderBy(d => d.Classifier == "Alpha").ThenBy(d => d.Code);

Body:
I have a List<Data> myList where

public class Data
{
    public string Classifier;
    public int Code;
}

and I want to sort it

By whether or not a data's Classifier is equal to some static string, we'll just call it @"Alpha" for now (non-equals first, equals second)

By Code, ascending.

So the input data

    {
      "Beta", 6
      "Alpha", 4
      "Lambda", 2
      "Beta", 1
      "Alpha", 5
    }

would result in

    {
      "Beta", 1
      "Lambda", 2
      "Beta", 6
      "Alpha", 4
      "Alpha", 5
    }

Specifically, I want the alpha's to settle to the bottom of the list in ascending numerical order.

I'm not sure how to implement a .Sort Comparison<Data> instance to support this, and .OrderBy doesn't seem to fit the problem.  Any thoughts?


问:
Custom Vision API
I want to count number of people on below image,
I believe it could be possible with Microsoft vision api or custom vision api but right now I'm not able to login on microsoft cognitive service.

Can anyone please confirm, Is it possible or not with MS cognitive services ?

答: Counting objects within images is currently not supported for any of the Vision API's provided through Microsoft Cognitive Services.  </p>

Title: Custom Vision API


问:
Sleep in JQuery?
greetings all
i want to make JQuery sleep/wait for a second between two functions

```<code>$('#div1').hide();
//sleep or wait or for a sec
$("#div2").show();
</code>```

how to do so ?

答:
For your specific function .show() isn't queued, but there's an easy trick to make it queued so you can use .delay(), like this:

```<code>$('#div1').hide();
$("#div2").delay(1000).show(0);
</code>```

By giving it a 0 duration argument, it's now an instant, but queued animation.  Underneath this uses setTimeout(), so it's basically the same behavior as:

```<code>$('#div1').hide();
setTimeout(function() { $("#div2").show(); }, 1000);
</code>```

Title: Sleep in JQuery?

Body:
greetings all
i want to make JQuery sleep/wait for a second between two functions

$('#div1').hide();
//sleep or wait or for a sec
$("#div2").show();

how to do so ?

Body:
For your specific function .show() isn't queued, but there's an easy trick to make it queued so you can use .delay(), like this:

$('#div1').hide();
$("#div2").delay(1000).show(0);

By giving it a 0 duration argument, it's now an instant, but queued animation.  Underneath this uses setTimeout(), so it's basically the same behavior as:

$('#div1').hide();
setTimeout(function() { $("#div2").show(); }, 1000);


问:
JSON fails in Javascript but POSTMAN works
This works from postman but the Javascript fails everytime!
Any know what I've done wrong?

The code sample comes from here https://westus.dev.cognitive.microsoft.com/docs/services/58994a073d9e04097c7ba6fe/operations/58994a073d9e041ad42d9ba9

```<code>    $(function() {
        var params = {
        };
        $.ajax({
            url: "https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/dfb79d2e-4f4d-4201-8511-b9d7ab08bcb1/generateAnswer?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", key);
            },
            type : "POST",
            data : {"question" : "Hi"}
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function (jqXHR, textStatus, error) {
        alert("Post error: " + error);
    });
});
</code>```

--Console Log ---

POST XHR
  https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/dfb79d2e-4f4d-4201-8511-b9d7ab08bcb1/generateAnswer [HTTP/1.1 400 Bad Request 377ms] Headers Params POST Response Call
  Stack
  ErrorObjectCode"BadArgument"Message"[{"Key":"query","Value":[""]}]"
  {"Error":{"Code":"BadArgument","Message":"[{\"Key\":\"query\",\"Value\":[\"\"]}]"}}

答:
After a lot of trial and error, I was able to make it work; just for the record
  the Microsoft documentation on the subject, is not working.

```<code>    $.ajax({
        url: "https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/dfb79d2e-4f4d-4201-8511-b9d7ab08bcb1/generateAnswer",
        beforeSend: function(xhrObj){
            // Request headers
            xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","theKey");
        },
        type : "POST",
        data : {"question": "Hi"},
        dataType: "json",
        crossDomain: true
    })
    .done(function(data) {
        alert("success");
    })
    .fail(function (jqXHR, textStatus, error) {
        console.log(jqXHR);
    });
</code>```

JSFiddle demo

Body:
This works from postman but the Javascript fails everytime!
Any know what I've done wrong?

The code sample comes from here https://westus.dev.cognitive.microsoft.com/docs/services/58994a073d9e04097c7ba6fe/operations/58994a073d9e041ad42d9ba9

    $(function() {
        var params = {
        };
        $.ajax({
            url: "https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/dfb79d2e-4f4d-4201-8511-b9d7ab08bcb1/generateAnswer?" + $.param(params),
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", key);
            },
            type : "POST",
            data : {"question" : "Hi"}
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function (jqXHR, textStatus, error) {
        alert("Post error: " + error);
    });
});

--Console Log ---

POST XHR
  https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/dfb79d2e-4f4d-4201-8511-b9d7ab08bcb1/generateAnswer [HTTP/1.1 400 Bad Request 377ms] Headers Params POST Response Call
  Stack
  ErrorObjectCode"BadArgument"Message"[{"Key":"query","Value":[""]}]"
  {"Error":{"Code":"BadArgument","Message":"[{\"Key\":\"query\",\"Value\":[\"\"]}]"}}

Body:
After a lot of trial and error, I was able to make it work; just for the record
  the Microsoft documentation on the subject, is not working.

    $.ajax({
        url: "https://westus.api.cognitive.microsoft.com/qnamaker/v2.0/knowledgebases/dfb79d2e-4f4d-4201-8511-b9d7ab08bcb1/generateAnswer",
        beforeSend: function(xhrObj){
            // Request headers
            xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","theKey");
        },
        type : "POST",
        data : {"question": "Hi"},
        dataType: "json",
        crossDomain: true
    })
    .done(function(data) {
        alert("success");
    })
    .fail(function (jqXHR, textStatus, error) {
        console.log(jqXHR);
    });

JSFiddle demo


问:
how to fix different font size shown for input fields in chrome and firefox
i am noticing in my web app that the same input form font size, currently set to 17px, reads smaller on chrome compared to firefox. i've attached a screenshot.

is there a more elegant method to resolve this than simply using

```<code>/*chrome*/
input {
 font-size:17px;
}
/*firefox*/
@-moz-document url-prefix() {
   input {
     font-size:15px;/*reduce font size to match what is seen in chrome*/
   }
}
</code>```

答:
I don't know what font you're using (or platform (Mac vs Win makes a difference too) , but some browsers render fonts using CLEARTYPE subpixel rendering, some use QUARTZ subpixel rendering (making appearance differ), then others use standard antialias-ing.

A good way around this is to use font-smoothing css in your html or body css:

```<code>html {
    font-family: /*yourfont*/;
    -webkit-font-smoothing: antialiased;
}
</code>```

Read more about it and see more examples on Max Voltar's website

Also note that using em is preferable to using px for measuring your font. Large font sizes are especially harmed by pixelation if you don't use font smoothing, so in order to keep accessible text especially, it's better to use ems (this way you can still use large type sizes).

Body:
i am noticing in my web app that the same input form font size, currently set to 17px, reads smaller on chrome compared to firefox. i've attached a screenshot.

is there a more elegant method to resolve this than simply using

/*chrome*/
input {
 font-size:17px;
}
/*firefox*/
@-moz-document url-prefix() {
   input {
     font-size:15px;/*reduce font size to match what is seen in chrome*/
   }
}

Body:
I don't know what font you're using (or platform (Mac vs Win makes a difference too) , but some browsers render fonts using CLEARTYPE subpixel rendering, some use QUARTZ subpixel rendering (making appearance differ), then others use standard antialias-ing.

A good way around this is to use font-smoothing css in your html or body css:

html {
    font-family: /*yourfont*/;
    -webkit-font-smoothing: antialiased;
}

Read more about it and see more examples on Max Voltar's website

Also note that using em is preferable to using px for measuring your font. Large font sizes are especially harmed by pixelation if you don't use font smoothing, so in order to keep accessible text especially, it's better to use ems (this way you can still use large type sizes).


问:
Low Accuracy in Implementing naive Bayes classifier
I have code for naive Bayes classifier that implement the concept of the naive Bayes, but the accuracy that this algorithm gives me is about 48% and it much lower than MATLAB build-in function for Naive Bayes (84%). Can anybody help me where is the problem?
here is my code:</p>

```<code>    function [conf, confMat] =  NaiveBayesClassifier(train, test)

Att_cnt = size(train, 2) - 1;

% training set
x = train(:, 1:Att_cnt);
y = train(:, Att_cnt+1);
% test set
u = test(:, 1:Att_cnt);
v = test(:, Att_cnt+1);

yu = unique(y);
nc = length(yu); % number of classes
ni = size(x,2); % independent variables
ns = length(v); % test set

% compute class probability
for i = 1 : nc
    fy(i) = sum(double(y==yu(i)))/length(y);
end

% normal distribution
% parameters from training set
[mu, sigma] = MLE(train);

% probability for test set
for j = 1 : ns
    fu = normcdf(ones(nc,1)*u(j,:), mu, sigma);
    P(j,:)= fy.*prod(fu,2)';
end

% get predicted output for test set
[pv0, id] = max(P,[],2);
for i = 1 : length(id)
    pv(i,1) = yu(id(i));
end

% compare predicted output with actual output from test data
confMat = confusionmat(v,pv);
conf = sum(pv==v)/length(pv);

end
</code>```

答:
I just solve it. instead of this line

```<code>fu = normcdf(ones(nc,1)*u(j,:), mu, sigma);
</code>```

i have to write

```<code>fu = normpdf(ones(nc,1)*u(j,:), mu, sigma);
</code>```

so the accuracy is the same as matlab build in function.

Body:
I have code for naive Bayes classifier that implement the concept of the naive Bayes, but the accuracy that this algorithm gives me is about 48% and it much lower than MATLAB build-in function for Naive Bayes (84%). Can anybody help me where is the problem?
here is my code:

    function [conf, confMat] =  NaiveBayesClassifier(train, test)

Att_cnt = size(train, 2) - 1;

% training set
x = train(:, 1:Att_cnt);
y = train(:, Att_cnt+1);
% test set
u = test(:, 1:Att_cnt);
v = test(:, Att_cnt+1);

yu = unique(y);
nc = length(yu); % number of classes
ni = size(x,2); % independent variables
ns = length(v); % test set

% compute class probability
for i = 1 : nc
    fy(i) = sum(double(y==yu(i)))/length(y);
end

% normal distribution
% parameters from training set
[mu, sigma] = MLE(train);

% probability for test set
for j = 1 : ns
    fu = normcdf(ones(nc,1)*u(j,:), mu, sigma);
    P(j,:)= fy.*prod(fu,2)';
end

% get predicted output for test set
[pv0, id] = max(P,[],2);
for i = 1 : length(id)
    pv(i,1) = yu(id(i));
end

% compare predicted output with actual output from test data
confMat = confusionmat(v,pv);
conf = sum(pv==v)/length(pv);

end

Body:
I just solve it. instead of this line

fu = normcdf(ones(nc,1)*u(j,:), mu, sigma);

i have to write

fu = normpdf(ones(nc,1)*u(j,:), mu, sigma);

so the accuracy is the same as matlab build in function.


答:
As far as I can see from the expected output, is not really sorted by the word, You could implement a bubble sort comparing the world position but insted of switching the word position, switch the whole registry.

Then the same process for the numbers, limiting the word

```<code>lambda, 2
beta, 1
beta, 6
alfa, 4
alfa, 5
</code>```

Note grouping by word, or you could just do a bubble sort for the numbers and switch position to the whole registry.

Title: C# Sort by boolean equality to static string, followed by sort on integer number ascending

Body:
As far as I can see from the expected output, is not really sorted by the word, You could implement a bubble sort comparing the world position but insted of switching the word position, switch the whole registry.

Then the same process for the numbers, limiting the word

lambda, 2
beta, 1
beta, 6
alfa, 4
alfa, 5

Note grouping by word, or you could just do a bubble sort for the numbers and switch position to the whole registry.


问:
C# How to create Date and Time Range?
I have a program which processes a log text file, retrieves the date time, converts the date time to the system's DateTime format.

However the program does not seem to recognized the various date time range that is selected. The program should retrieve the records between the date and time selected by the user.

The problem would probably be due to the sequencing of the codes?

May someone please advise on the codes? Thanks!

The Codes:

```<code>            String timeDate2 = result1.ToString("MM/dd/yyyy HH:mm:ss");

            Console.WriteLine("The last written time to the registry was : " + timeDate2);

            TimeSpan.TryParse("12/02/2010 16:04:17", out t1);
            TimeSpan.TryParse("12/09/2010 05:12:42", out t2);
            TimeSpan.TryParse(timeDate2, out t3);

            if ((t3 >= t1 && t3 <= t2) == true)    // Is t3 between t1 and t2?
            {
                foreach (String k in lines.Skip(12))
                {
                    Console.WriteLine(k);
                }
             x = 1;
            }

            else
            {
                x = 2;
            }

            Console.WriteLine("============================================================");

        }

        if (x == 2)
        {
            Console.WriteLine("There is no selected days within the log files!");
        }
</code>```

答:
```<code>TimeSpan.TryParse("12/02/2010 16:04:17", out t1);
TimeSpan.TryParse("12/09/2010 05:12:42", out t2);
TimeSpan.TryParse(timeDate2, out t3);
</code>```

TimeSpan normally dont' have a date because its a Time Span, thus how many days, hours and minutes. Not a date. TimeSpan is a Time definition between to dates.
More info on the MSDN page

Fix it to DateTime.TryParse

(And check what the values of t1/t2/t3 are after parsing)

Title: C# How to create Date and Time Range?

Body:
I have a program which processes a log text file, retrieves the date time, converts the date time to the system's DateTime format.

However the program does not seem to recognized the various date time range that is selected. The program should retrieve the records between the date and time selected by the user.

The problem would probably be due to the sequencing of the codes?

May someone please advise on the codes? Thanks!

The Codes:

            String timeDate2 = result1.ToString("MM/dd/yyyy HH:mm:ss");

            Console.WriteLine("The last written time to the registry was : " + timeDate2);

            TimeSpan.TryParse("12/02/2010 16:04:17", out t1);
            TimeSpan.TryParse("12/09/2010 05:12:42", out t2);
            TimeSpan.TryParse(timeDate2, out t3);

            if ((t3 >= t1 && t3 <= t2) == true)    // Is t3 between t1 and t2?
            {
                foreach (String k in lines.Skip(12))
                {
                    Console.WriteLine(k);
                }
             x = 1;
            }

            else
            {
                x = 2;
            }

            Console.WriteLine("============================================================");

        }

        if (x == 2)
        {
            Console.WriteLine("There is no selected days within the log files!");
        }

Body:
TimeSpan.TryParse("12/02/2010 16:04:17", out t1);
TimeSpan.TryParse("12/09/2010 05:12:42", out t2);
TimeSpan.TryParse(timeDate2, out t3);

TimeSpan normally dont' have a date because its a Time Span, thus how many days, hours and minutes. Not a date. TimeSpan is a Time definition between to dates.
More info on the MSDN page

Fix it to DateTime.TryParse

(And check what the values of t1/t2/t3 are after parsing)


问:
Is JavaScript execution deferred until CSSOM is built or not?
The answer to this question has been clear to me ever since I read/learned  about CSSOM, until today. I can't seem to be able to find the initial article, but it explained quite clear, with examples, that JavaScript execution is deferred until CSSOM is built from all
  -->

```

<p>Ok, so let's make sure. Let's replace the <code><style></code> with </p>

```<link rel="stylesheet" type="text/css" href="test.php" />
```

<p>... and make <code>test.php</code> hang for a few seconds:</p>

<pre class="lang-php prettyprint-override"><code><?php
sleep(10);
header('Content-Type: text/css');
?>

/* adding styles here would be futile */
</code>```

If I am right (and js execution is deferred until CSSOM is built), the page hangs blank for 10 seconds, before building CSSOM and before executing the

答:
This quote is true, but it means that if you place your style sheet first, and a script after it, the script will not execute until the style sheet is downloaded and parsed. See this example:

test.php:

```<code><?php
sleep(5);
header('Content-Type: text/css');
echo 'body {background-color: red;}';
</code>```

index.html:

```<code><link rel="stylesheet" href="test.php">
<script>console.log('done');</script>
</code>```

The console.log call won't be executed until background color changes to red.

This leads to the conclusion that building CSSOM isn't done once for all style sheets, but it's a gradual process – when browser encounters a style sheet, it downloads it, parses, and moves next. Also probably browser first makes a list of all CSS resources and adds them to the download queue, even before executing any scripts. That would explain why the request is made even though the link tag is commented by a script.

Body:
The answer to this question has been clear to me ever since I read/learned  about CSSOM, until today. I can't seem to be able to find the initial article, but it explained quite clear, with examples, that JavaScript execution is deferred until CSSOM is built from all
  -->

Ok, so let's make sure. Let's replace the

Body:
This quote is true, but it means that if you place your style sheet first, and a script after it, the script will not execute until the style sheet is downloaded and parsed. See this example:

test.php:

<?php
sleep(5);
header('Content-Type: text/css');
echo 'body {background-color: red;}';

index.html:

<link rel="stylesheet" href="test.php">
<script>console.log('done');</script>

The console.log call won't be executed until background color changes to red.

This leads to the conclusion that building CSSOM isn't done once for all style sheets, but it's a gradual process – when browser encounters a style sheet, it downloads it, parses, and moves next. Also probably browser first makes a list of all CSS resources and adds them to the download queue, even before executing any scripts. That would explain why the request is made even though the link tag is commented by a script.


问:
What happen if '&' operator is not included in scanf while taking input?
hii everyone i want to ask a question that what happen if '&' operator is not included in scanf.

```<code> #include <stdio.h>
 int main()
 {
     int x;
     scanf("%d", x);
   /* than what type of value will scanf store in x if there is
       not address of operator. */
     printf("%d", x);
     return 0;
  }
</code>```

either program crash or some garbage value prints out. I m little bit confused.

答:
When you call scanf with the %d conversion specifier, the corresponding argument needs to be an expression that evaluates to the location of an integer object into which scanf will write the input value: ```<code>scanf( "%d", <em>location-expression</em> );</code>```

location-expression can take on multiple forms.  To read into a single scalar object like x, you could use the expression &x.

```<code>scanf( "%d", &x ); // &x evaluates to the location of x
</code>```

Or, you could use a pointer variable that's initialized to point to x:

```<code>int *p = &x;      // p stores the address of x
scanf( "%d", p ); // scanf writes to x *through* p; p == &x
</code>```

The expression p is equivalent to the expression &x in this case.  We don't use the & operator on p, because we want write to the address stored in p, not the address of p.

When you write

```<code>scanf( "%d", x );
</code>```

you're telling scanf to store input to the address stored in x.  There are several problems with that:

x is not explicitly initialized to anything; its value is indeterminate;

Because of 1, the odds that x contains a value that corresponds to a valid pointer value (that is, the location of an object in your program) are extremely low;

The type of the expression x is int, but %d expects its corresponding argument to have type int * - any modern compiler should yell at you.

Body:
hii everyone i want to ask a question that what happen if '&' operator is not included in scanf.

 #include <stdio.h>
 int main()
 {
     int x;
     scanf("%d", x);
   /* than what type of value will scanf store in x if there is
       not address of operator. */
     printf("%d", x);
     return 0;
  }

either program crash or some garbage value prints out. I m little bit confused.

Body:
When you call scanf with the %d conversion specifier, the corresponding argument needs to be an expression that evaluates to the location of an integer object into which scanf will write the input value:
scanf( "%d", location-expression );

location-expression can take on multiple forms.  To read into a single scalar object like x, you could use the expression &x.

scanf( "%d", &x ); // &x evaluates to the location of x

Or, you could use a pointer variable that's initialized to point to x:

int *p = &x;      // p stores the address of x
scanf( "%d", p ); // scanf writes to x *through* p; p == &x

The expression p is equivalent to the expression &x in this case.  We don't use the & operator on p, because we want write to the address stored in p, not the address of p.

When you write

scanf( "%d", x );

you're telling scanf to store input to the address stored in x.  There are several problems with that:

x is not explicitly initialized to anything; its value is indeterminate;

Because of 1, the odds that x contains a value that corresponds to a valid pointer value (that is, the location of an object in your program) are extremely low;

The type of the expression x is int, but %d expects its corresponding argument to have type int * - any modern compiler should yell at you.


问:
How to execute main1 when I have main1, main2, and main?
```<code>#include <stdio.h>
#include <string.h>

int main1(void)
{
   printf("Came to main1.\n");
}

int main2(void)
{
   printf("Came to main2.\n");
}

int main(void)
{
   printf("Came to main. \n");
}
</code>```

I have main1, main2, and main. I want to see main1 output, but every time I execute the program, I can only see main output

答:
You can do this with some preprocessor trickery:

```<code>#include <stdio.h>
#include <string.h>

#ifdef MAIN1

int main(void)
{
   printf("Came to main1.\n");
   return 0;
}

#elif defined MAIN2

int main(void)
{
   printf("Came to main2.\n");
   return 0;
}

#else

int main(void)
{
   printf("Came to main. \n");
   return 0;
}

#endif
</code>```

Then you define MAIN1 or MAIN2 as needed:

[dbush@centos72 ~]$ gcc -o x1 x1.c
[dbush@centos72 ~]$ ./x1
Came to main.
[dbush@centos72 ~]$ gcc -D MAIN1 -o x1 x1.c
[dbush@centos72 ~]$ ./x1
Came to main1.
[dbush@centos72 ~]$ gcc -D MAIN2 -o x1 x1.c
[dbush@centos72 ~]$ ./x1
Came to main2.
[dbush@centos72 ~]$
```

Body:
#include <stdio.h>
#include <string.h>

int main1(void)
{
   printf("Came to main1.\n");
}

int main2(void)
{
   printf("Came to main2.\n");
}

int main(void)
{
   printf("Came to main. \n");
}

I have main1, main2, and main. I want to see main1 output, but every time I execute the program, I can only see main output

Body:
You can do this with some preprocessor trickery:

#include <stdio.h>
#include <string.h>

#ifdef MAIN1

int main(void)
{
   printf("Came to main1.\n");
   return 0;
}

#elif defined MAIN2

int main(void)
{
   printf("Came to main2.\n");
   return 0;
}

#else

int main(void)
{
   printf("Came to main. \n");
   return 0;
}

#endif

Then you define MAIN1 or MAIN2 as needed:

[dbush@centos72 ~]$ gcc -o x1 x1.c
[dbush@centos72 ~]$ ./x1
Came to main.
[dbush@centos72 ~]$ gcc -D MAIN1 -o x1 x1.c
[dbush@centos72 ~]$ ./x1
Came to main1.
[dbush@centos72 ~]$ gcc -D MAIN2 -o x1 x1.c
[dbush@centos72 ~]$ ./x1
Came to main2.
[dbush@centos72 ~]$


问:
While loops in Python 3
I'm having some problems with some code for a menu system. What I have so far isn't completed but I'm having a problem with it. It works fine with the account.leeman' but I can never get 'administrator' to work, and it always rolls back to the beginning. I've looked at the code for a while now but I can't figure out why this is and why it doesn't ever continue. The 'add' part of the code can be ignored as it isn't a problem yet, although if you can see any way in improving it, please let me know

So this is what I have:

```<code>usernames=["m.leeman","administrator"]
passwords=["pA55w0rd","password"]
while True:
    count=0
    add_or_enter=input("Would you like to Enter a username or Add a new one?: ").lower()
    if add_or_enter=="enter":
        username=input("Please enter username: ")
        while (count+1)!=(len(usernames)):
            #problem somewhere here
            if username==usernames[count]:
                print("Username accepted")
                password=input("Please enter password: ")
                if password==passwords[count]:
                    print("Welcome "+str(username))
                    print("Continue here")
                else:
                    print("Incorrect password")
            else:
                count+=1
                if count==len(usernames):
                    print("User does not exit")
                else:
                    ()
                    #should run again after this
    elif add_or_enter=="add":
        new_user=input("Enter a new username: ")
        if (new_user=="add") or (new_user==usernames[count]):
            print("Username unavailiable")
        else:
            count=+1
            if count==len(usernames)-1:
                usernames.append(new_user)
                new_password=input("Enter a password for this user: ")
                passwords.append(new_password)
                print("User "+new_user+" successfully created")
</code>```

Any replies will be very helpful. Thanks.

答:
Lets take a look at this line of code:

```<code>while (count+1)!=(len(usernames)):
</code>```

On the first loop, count is 0 so 0+1 != 2 and the loop executes. Their inputted name "administrator" won't match "m.leeman" so count is increased by one and the loop will execute again.

This time, count = 1. So count + 1 = 2, which happens to be the length of usernames. The loop doesn't execute and the admin account is not found.

The solution? Remove the + 1

```<code>while count != len(usernames):
</code>```

Hope this helps

Title: While loops in Python 3

Body:
I'm having some problems with some code for a menu system. What I have so far isn't completed but I'm having a problem with it. It works fine with the account.leeman' but I can never get 'administrator' to work, and it always rolls back to the beginning. I've looked at the code for a while now but I can't figure out why this is and why it doesn't ever continue. The 'add' part of the code can be ignored as it isn't a problem yet, although if you can see any way in improving it, please let me know

So this is what I have:

usernames=["m.leeman","administrator"]
passwords=["pA55w0rd","password"]
while True:
    count=0
    add_or_enter=input("Would you like to Enter a username or Add a new one?: ").lower()
    if add_or_enter=="enter":
        username=input("Please enter username: ")
        while (count+1)!=(len(usernames)):
            #problem somewhere here
            if username==usernames[count]:
                print("Username accepted")
                password=input("Please enter password: ")
                if password==passwords[count]:
                    print("Welcome "+str(username))
                    print("Continue here")
                else:
                    print("Incorrect password")
            else:
                count+=1
                if count==len(usernames):
                    print("User does not exit")
                else:
                    ()
                    #should run again after this
    elif add_or_enter=="add":
        new_user=input("Enter a new username: ")
        if (new_user=="add") or (new_user==usernames[count]):
            print("Username unavailiable")
        else:
            count=+1
            if count==len(usernames)-1:
                usernames.append(new_user)
                new_password=input("Enter a password for this user: ")
                passwords.append(new_password)
                print("User "+new_user+" successfully created")

Any replies will be very helpful. Thanks.

Body:
Lets take a look at this line of code:

while (count+1)!=(len(usernames)):

On the first loop, count is 0 so 0+1 != 2 and the loop executes. Their inputted name "administrator" won't match "m.leeman" so count is increased by one and the loop will execute again.

This time, count = 1. So count + 1 = 2, which happens to be the length of usernames. The loop doesn't execute and the admin account is not found.

The solution? Remove the + 1

while count != len(usernames):

Hope this helps


问:
Pentaho behave slowly on insert/update with PostgreSQL
Pentaho behaves slowly on insert/update with PostgreSQL, which is because jdbc driver will not accept prepared statements.

After 2 million row Pentaho / PostgreSQL performance almost become 1 per 1 second. Post me an alternative solution with example.

Below is my Create Table script

```<code>CREATE TABLE fact_model
(
  model_id integer NOT NULL,
  source integer NOT NULL,
  group_sk integer NOT NULL,
  user_sk integer NOT NULL,
  order_kind character varying(255),
  model_no character varying(255),
  CONSTRAINT pf_fact_receipt PRIMARY KEY (source, model_id)
)
WITH (
  OIDS=TRUE
)

ALTER TABLE fact_model
  ADD CONSTRAINT pf_fact_receipt PRIMARY KEY(source, model_id);
</code>```

Guys, it is crazy replies I am getting, My expected intention was to help other, There are various step we can try. like follows.

Insert / Update which is slow

Upsert after PostgreSQL after 9.5 using SQL step

Update then error handled to a table output when we expect higher Update

Insert then error handled to Update when we expect higher Insert

Merge join split insert and update direct to appropriate step which makes one single

I believe there are always Lot more to figure out beyond my experience which I believe this post will sort out., So the expectation is better input than stated above.

答:
You also need the composite(primary) KEY in reversed order (assuming that its two elements are also FKs to dimension tables) This will cause a composite index to be created.

```<code>CREATE TABLE fact_model
( model_id integer NOT NULL     -- REFERENCES ...
  , source integer NOT NULL     -- REFERENCES ...
  , group_sk integer NOT NULL   -- REFERENCES ...
  , user_sk integer NOT NULL    -- REFERENCES ...
  , order_kind character varying(255)
  , model_no character varying(255)
  , CONSTRAINT pf_fact_receipt PRIMARY KEY (source, model_id)
  , CONSTRAINT pf_fact_receipt_rev UNIQUE (model_id, source) -- <<--HERE
  );

VACUUM ANALYZE fact_model;

\d fact_model
</code>```

Body:
Pentaho behaves slowly on insert/update with PostgreSQL, which is because jdbc driver will not accept prepared statements.

After 2 million row Pentaho / PostgreSQL performance almost become 1 per 1 second. Post me an alternative solution with example.

Below is my Create Table script

CREATE TABLE fact_model
(
  model_id integer NOT NULL,
  source integer NOT NULL,
  group_sk integer NOT NULL,
  user_sk integer NOT NULL,
  order_kind character varying(255),
  model_no character varying(255),
  CONSTRAINT pf_fact_receipt PRIMARY KEY (source, model_id)
)
WITH (
  OIDS=TRUE
)

ALTER TABLE fact_model
  ADD CONSTRAINT pf_fact_receipt PRIMARY KEY(source, model_id);

Guys, it is crazy replies I am getting, My expected intention was to help other, There are various step we can try. like follows.

Insert / Update which is slow

Upsert after PostgreSQL after 9.5 using SQL step

Update then error handled to a table output when we expect higher Update

Insert then error handled to Update when we expect higher Insert

Merge join split insert and update direct to appropriate step which makes one single

I believe there are always Lot more to figure out beyond my experience which I believe this post will sort out., So the expectation is better input than stated above.

Body:
You also need the composite(primary) KEY in reversed order (assuming that its two elements are also FKs to dimension tables) This will cause a composite index to be created.

CREATE TABLE fact_model
( model_id integer NOT NULL     -- REFERENCES ...
  , source integer NOT NULL     -- REFERENCES ...
  , group_sk integer NOT NULL   -- REFERENCES ...
  , user_sk integer NOT NULL    -- REFERENCES ...
  , order_kind character varying(255)
  , model_no character varying(255)
  , CONSTRAINT pf_fact_receipt PRIMARY KEY (source, model_id)
  , CONSTRAINT pf_fact_receipt_rev UNIQUE (model_id, source) -- <<--HERE
  );

VACUUM ANALYZE fact_model;

\d fact_model


问:
Issue with PHP file upload
PHP is a language that I know very little of, and today I've been given a task part of which involves uploading a file with PHP because, I think, the easiest way to make an unimportant interface is making it with HTML. I wrote some code but when I open it on my browser - even before I hit submit - an error message appears, saying:

Notice: Undefined index: resume in C:\wamp\www\cv_base\index.php on line 39

The code is following:

<!DOCTYPE html>

        <title>::Welcome to Resume Base::</title>
        <link rel="stylesheet" type="text/css" href="style/main.css" />

Add A Resume

            <form action="" method="POST">
                <input type="text" name="firstname" id="id_firstname" maxlength="20" placeholder="First Name" required="required" />
                <input type="text" name="lastname" id="id_lasttname" maxlength="20" placeholder="Last Name" required="required" />
                <input type="text" name="paternal" id="id_paternal" maxlength="20" placeholder="Paternal Name" required="required" />
                <select name="category">
                    <option selected disabled>Choose Category...</option>
                    <option value="IT & Computers">IT & Computers</option>
                    <option value="Design">Design</option>
                    <option value="Services">Services</option>
                    <option value="Agriculture & Industry">Agriculture & Industry</option>
                    <option value="Finance">Finance</option>
                    <option value="Marketing & Sales">Marketing & Sales</option>
                    <option value="Administrative">Administrative</option>
                    <option value="Medical">Medical</option>
                    <option value="Science & Education">Science & Education</option>
                    <option value="Law">Law</option>
                    <option value="Other">Other</option>
                </select>
                <input type="file" name="resume" id="id_resume" required="required" />
                <input type="submit" name="submit" id="id_submit" value="Apply!" />
            </form>
            [Search]

<?php
require_once "connection.php";

$targetDir = "resumes/";
$targetFile = $targetDir . basename($_FILES["resume"]["name"]);
$uploadFinish = 1;
$fileType = pathinfo($targetFile, PATHINFO_EXTENSION);

if (isset($_POST["submit"])) {
    $fname = $_POST["firstname"];
    $lname = $_POST["lastname"];
    $pname = $_POST["paternal"];
    $cat = $_POST["category"];
    if ($fileType != "doc" && $fileType != "docx" && $fileType != "odt" && $fileType != "pdf") {
        echo "Invalid file format!";
        $uploadFinish = 0;
    } elseif ($_FILES["resume"]["size"] > 500000) {
        echo "File too large! Choose another file.";
        $uploadFinish = 0;
    } elseif (file_exists ($targetFile)) {
        echo "File already exists! Choose another file or rename file.";
        $uploadFinish = 0;
    } else {
        $uploadFinish = 1;
    }

    if ($uploadFinish == 0) {
        echo "File not uploaded!";
    } else {
        if (move_uploaded_file($_FILES["resume"]["tmp_name"], $targetFile)) {
            echo "The file " . basename($_FILES["resume"]["name"]) . " uploaded.";
            $stmt = $conn->prepare("INSERT INTO applicants VALUES (?, ?, ?, ?, ?)");
            $stmt->execute(array($fname, $lname, $pname, $cat, $targetFile));
        } else {
            echo "Error uploading file!";
        }
    }
}
?>```

I have taken the lines 38-41 and 64-65 from the Internet, but they seem to be the part where the problem occurs. Please, help!

UPDATE: Thanks, mates! I finally finished the project thanks to you!

答:
There's a few issues.

First of all, you are running the PHP code when the user is just loading the page. You should wrap the logic to handle the upload in something like this.

```<code>if (!empty($_POST)) {
    // Do stuff here
}
</code>```

Your form will need the attribute enctype="multipart/form-data" to handle files.

It's clearly poorly organized code. This is a one off so you probably don't care, but if you find yourself writing PHP more frequently, consider using functions, frameworks, and other concepts to make your projects much easier.

Finally, there's huge security holes. Make sure the form isn't available to the internet or you may have more serious issues on your hands.

Title: Issue with PHP file upload

Body:
PHP is a language that I know very little of, and today I've been given a task part of which involves uploading a file with PHP because, I think, the easiest way to make an unimportant interface is making it with HTML. I wrote some code but when I open it on my browser - even before I hit submit - an error message appears, saying:

Notice: Undefined index: resume in C:\wamp\www\cv_base\index.php on line 39

The code is following:

<!DOCTYPE html>

        <title>::Welcome to Resume Base::</title>
        <link rel="stylesheet" type="text/css" href="style/main.css" />

Add A Resume

            <form action="" method="POST">
                <input type="text" name="firstname" id="id_firstname" maxlength="20" placeholder="First Name" required="required" />
                <input type="text" name="lastname" id="id_lasttname" maxlength="20" placeholder="Last Name" required="required" />
                <input type="text" name="paternal" id="id_paternal" maxlength="20" placeholder="Paternal Name" required="required" />
                <select name="category">
                    <option selected disabled>Choose Category...</option>
                    <option value="IT & Computers">IT & Computers</option>
                    <option value="Design">Design</option>
                    <option value="Services">Services</option>
                    <option value="Agriculture & Industry">Agriculture & Industry</option>
                    <option value="Finance">Finance</option>
                    <option value="Marketing & Sales">Marketing & Sales</option>
                    <option value="Administrative">Administrative</option>
                    <option value="Medical">Medical</option>
                    <option value="Science & Education">Science & Education</option>
                    <option value="Law">Law</option>
                    <option value="Other">Other</option>
                </select>
                <input type="file" name="resume" id="id_resume" required="required" />
                <input type="submit" name="submit" id="id_submit" value="Apply!" />
            </form>
            [Search]

<?php
require_once "connection.php";

$targetDir = "resumes/";
$targetFile = $targetDir . basename($_FILES["resume"]["name"]);
$uploadFinish = 1;
$fileType = pathinfo($targetFile, PATHINFO_EXTENSION);

if (isset($_POST["submit"])) {
    $fname = $_POST["firstname"];
    $lname = $_POST["lastname"];
    $pname = $_POST["paternal"];
    $cat = $_POST["category"];
    if ($fileType != "doc" && $fileType != "docx" && $fileType != "odt" && $fileType != "pdf") {
        echo "Invalid file format!";
        $uploadFinish = 0;
    } elseif ($_FILES["resume"]["size"] > 500000) {
        echo "File too large! Choose another file.";
        $uploadFinish = 0;
    } elseif (file_exists ($targetFile)) {
        echo "File already exists! Choose another file or rename file.";
        $uploadFinish = 0;
    } else {
        $uploadFinish = 1;
    }

    if ($uploadFinish == 0) {
        echo "File not uploaded!";
    } else {
        if (move_uploaded_file($_FILES["resume"]["tmp_name"], $targetFile)) {
            echo "The file " . basename($_FILES["resume"]["name"]) . " uploaded.";
            $stmt = $conn->prepare("INSERT INTO applicants VALUES (?, ?, ?, ?, ?)");
            $stmt->execute(array($fname, $lname, $pname, $cat, $targetFile));
        } else {
            echo "Error uploading file!";
        }
    }
}
?>

I have taken the lines 38-41 and 64-65 from the Internet, but they seem to be the part where the problem occurs. Please, help!

UPDATE: Thanks, mates! I finally finished the project thanks to you!

Body:
There's a few issues.

First of all, you are running the PHP code when the user is just loading the page. You should wrap the logic to handle the upload in something like this.

if (!empty($_POST)) {
    // Do stuff here
}

Your form will need the attribute enctype="multipart/form-data" to handle files.

It's clearly poorly organized code. This is a one off so you probably don't care, but if you find yourself writing PHP more frequently, consider using functions, frameworks, and other concepts to make your projects much easier.

Finally, there's huge security holes. Make sure the form isn't available to the internet or you may have more serious issues on your hands.


问:
react MapboxGeocoder is not defined no-undef
Everything was alright but suddenly I got this error. I have googled many times but no solution. Can anybody help me out, please?

Code I have used

```<code>import React, { Component } from 'react';
import MapboxGl from 'mapbox-gl/dist/mapbox-gl';
import '../App.css';

class MapContent extends Component {

    componentDidMount() {
        MapboxGl.accessToken = ACCESS_TOKEN;

        var map = new MapboxGl.Map({
            container: this.Mapcontainer,
            style: 'mapbox://styles/mapbox/streets-v9',
            center: [-74.50, 40], // starting position
            zoom: 9 // starting zoom
        });

        var geocoder = new MapboxGeocoder({
            accessToken: MapboxGl.accessToken
        });

        map.addControl(geocoder);
    }

    render() {
        return (
            <div className='MapContent' ref={(x) => { this.Mapcontainer = x }}>
            </div>
        )
    }
}

export default MapContent;
</code>```

答:
Got the answer. I must install '@mapbox/mapbox-gl-geocoder'. Just type

npm install @mapbox/mapbox-gl-geocoder --save

MapboxGeocoder will work well then.

Body:
Everything was alright but suddenly I got this error. I have googled many times but no solution. Can anybody help me out, please?

Code I have used

import React, { Component } from 'react';
import MapboxGl from 'mapbox-gl/dist/mapbox-gl';
import '../App.css';

class MapContent extends Component {

    componentDidMount() {
        MapboxGl.accessToken = ACCESS_TOKEN;

        var map = new MapboxGl.Map({
            container: this.Mapcontainer,
            style: 'mapbox://styles/mapbox/streets-v9',
            center: [-74.50, 40], // starting position
            zoom: 9 // starting zoom
        });

        var geocoder = new MapboxGeocoder({
            accessToken: MapboxGl.accessToken
        });

        map.addControl(geocoder);
    }

    render() {
        return (

 { this.Mapcontainer = x }}>

        )
    }
}

export default MapContent;


问:
How to write Ng-repeat for below cloudant Nested loop response to my HTML Table..?

//
    {
       "data":{
          "total_rows":3,
          "offset":0,
          "rows":[
             {
                "id":"093b21d31878c8cbed02b89ea020c988",
                "key":"093b21d31878c8cbed02b89ea020c988",
                "value":{  },

                "doc":{
                   "_id":"093b21d31878c8cbed02b89ea020c988",
                   "_rev":"1-29e2996bce09fd8fcf826871b325302f",
                   "slot":"1",
                   "out_time_stamp":"none",
                   "color":"red",
                   "s.no":35,
                   "vehicle_make":"audi",
                   "vehicle_Make_Model":"Audi A5",
                   "number_plate":"1AU890",
                   "type":"bike",
                   "In_time_stamp":"2-25-21"
                }
             },
             {  },
             {  }
          ]
       },
       "status":200,
       "config":{
          "method":"GET",
          "transformRequest":[
             null
          ],
          "transformResponse":[
             null
          ],
          "username":"****",
          "password":"*****",
          "url":"https://####.cloudant.com/parking_logs/_all_docs?include_docs=true&conflicts=true",
          "headers":{
             "Accept":"application/json, text/plain, */*"
          },
          "cached":false
       },
       "statusText":"OK"
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--sample html table --!>
      <table class="table table-no-border m-0">
                                      </thead>
                                        <tr style="color:#232527;">
                                          <th> #No </th>
                                          <th> Vehicle Type </th>
                                          <th> Vehicle Model </th>
                                          <th> Vehicle color </th>
                                          <th> Vehicle Number</th>
               <th> Level</th>
                                          <th> Slot Occupied</th>
               <th> In Time Stamp </th>
               <th> Out Time Stamp </th>
                                        </tr>
             </thead>
              <tbody>
                                        <tr ng-repeat="x in records">
                                          <td >{{ x.sno}}</td>
                                          <td> {{x.type}} </td>
               <td> {{ x.vehicle_make}} </td>
                                          <td> {{x.color}}</td>
                                          <td> {{x.number_plate}}</td>
                                          <td>{{x.vehicle_Make_Model}}</td>
                                          <td> {{x.slot}}</td>
               <td> {{x.In_time_stamp}}</td>
               <td> {{x.out_time_stamp}}</td>
                                        </tr>
              </tbody>
                       </table></code>```

答:
After resolving the promise, pull out the rows from the response. Something like this:

```<code>.....function(success) {
$scope.records = success.data.rows;
.......
</code>```

In your template iterate through the records and bind the values., below

```<code><tr ng-repeat="x in records">
  <td >{{ x.doc.sno }}</td>
   .........
  <td> {{ x.doc.color }}</td>
</code>```

This should resolve your issue. Let me know if it doesn't work

Body:
After resolving the promise, pull out the rows from the response. Something like this:

.....function(success) {
$scope.records = success.data.rows;
.......

In your template iterate through the records and bind the values., below

<tr ng-repeat="x in records">
  <td >{{ x.doc.sno }}</td>
   .........
  <td> {{ x.doc.color }}</td>

This should resolve your issue. Let me know if it doesn't work


答:
"undefined index" indicates you're attempting to access a part of a hashmap that doesn't exist. Line 39 is this:

```<code>$targetFile = $targetDir . basename($_FILES["resume"]["name"]);
</code>```

Here you're accessing the $_FILES variable and trying to get the "resume" index of that hashmap. That index does not exist, thereby causing your error.

Title: Issue with PHP file upload

Body:
"undefined index" indicates you're attempting to access a part of a hashmap that doesn't exist. Line 39 is this:

$targetFile = $targetDir . basename($_FILES["resume"]["name"]);

Here you're accessing the $_FILES variable and trying to get the "resume" index of that hashmap. That index does not exist, thereby causing your error.


问:
Finding significant peaks with MATLAB's findpeaks()
I'm using MATLAB's findpeaks function to quickly identify peaks in data:

You'll notice the peak on the second negative-sloping section, magnified here:

This peak is a known artifact of the measurement, and I'd like to exclude it. I have many such data, some with the artifact and some without, so I'd like an automated way to exclude them when encountered. What settings do I need to adjust in findpeaks to remove these pseudo-peaks? I've experimented with 'MinPeakProminence', 'Threshold', and 'MinPeakWidth' to no avail. Although it may not be obvious from the pictures, this data has thousands of data points, so the nearest neighbors of any point are very similar (look at the x-axis scale).

答: If you have R2014b or later, try checking out the MinPeakProminence name-value pair.  This can help you select peaks that are more prominent (a relative measure of how much they stand out) as opposed to selecting them by absolute value.


问:
Issue with VueJS updated function
I have the following method that I need to run on route load. I have tried calling it from updated but it's not working. I have included the ESLint error as well.

```<code>methods: {
  getDeals (key, cb) {
    this.dealsRel.child(key).on('child_added', snap => {
      let dealRef = this.dealsRef.child(snap.key)
      dealRef.once('value', cb)
    })
  }
},
updated: {
  getDeals (this.finalItem, snap => {
    var snapVal = snap.val()
    this.deals.push(snapVal)
    console.log(this.deals)
  })
}
</code>```

And the ESLint error.

```<code>Parsing error: Unexpected token

  31 |   },
  32 |   updated: {
  33 |     getDeals (this.finalItem, snap => {
     |               ^
  34 |       var snapVal = snap.val()
  35 |       this.deals.push(snapVal)
</code>```

I'm sure that this is just me formatting this wrong. But not sure how to make this work.

答: The updated hook should be a function, not an object.

Title: Issue with VueJS updated function

Body:
I have the following method that I need to run on route load. I have tried calling it from updated but it's not working. I have included the ESLint error as well.

methods: {
  getDeals (key, cb) {
    this.dealsRel.child(key).on('child_added', snap => {
      let dealRef = this.dealsRef.child(snap.key)
      dealRef.once('value', cb)
    })
  }
},
updated: {
  getDeals (this.finalItem, snap => {
    var snapVal = snap.val()
    this.deals.push(snapVal)
    console.log(this.deals)
  })
}

And the ESLint error.

Parsing error: Unexpected token

  31 |   },
  32 |   updated: {
  33 |     getDeals (this.finalItem, snap => {
     |               ^
  34 |       var snapVal = snap.val()
  35 |       this.deals.push(snapVal)

I'm sure that this is just me formatting this wrong. But not sure how to make this work.


问:
Mouse-over objects not possible in HTML export of Enterprise Architect
I need help with mouse over content of the HTML export from Enterprise Architect. I would like the HTML output from Enterprise Architect to also contain the 'Notes' of the element when I mouse over them. Currently this is not possible with the standard HTML export from Enterprise Architect.
Actually there is no way to see the contents and tags of the element if it has a composite child structure except for you have to find it in the side window like project browser and then click the individual object from there.
Please let me know if there are some ways I can achieve these.

Cheers!
Neha

答:
I don't think the mouseover option is possible since the actual clickable areas are not related to the elements, they just redirect to the elements page.

But when clicking on an element on the HTML model, it should show you its details :notes, attributes, diagram, etc...(If it shows you the diagram, rest of the content should be below it)


问:
Symfony3 registering exception listener
I have a Stripe exception wrapper for all of the exceptions that Stripe might throw based on certain cases. I'm trying to register an event listener for that exception being thrown, but it doesn't seem like the listener is ever fired.

Instead of returning the event in a json response, the exception throws a 500 and renders the stack trace. Is there something that I'm missing?

```<code>// AppBundle/Exceptions/StripePaymentException.php
namespace AppBundle\Exceptions;

use Exception;

class StripePaymentException extends Exception {

    public $response;
    public $message;

    public function __construct($message, $response, $code = 0, Exception $previous = null)
    {
        parent::__construct($message, $code);

        $this->message = $message;
        $this->response = $response;
    }

    public function getResponse()
    {
        return $this->$response;
    }

}

// AppBundle/EventListener/StripePaymentExceptionListener.php
namespace AppBundle\EventListener;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

class StripePaymentExceptionListener
{
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();
        $data = $exception->getResponse();
        $response = new JsonResponse($data);
        $event->setResponse($response);
    }
}

// services.yml
app.stripe_payment_exception_listener:
class: AppBundle\EventListener\StripePaymentExceptionListener
    tags:
        - { name: kernel.event_listener, event: kernel.exception, priority: 200 }
</code>```

答:
It could be the priority setting on your custom listener. If you have another listener that is being fired before then this will never actually be what returns the Exception.

You could change the priority here:

```<code>// services.yml
app.stripe_payment_exception_listener:
class: AppBundle\EventListener\StripePaymentExceptionListener
    tags:
        - { name: kernel.event_listener, event: kernel.exception, priority: 1 }
</code>```

Or alternatively you could alter your "standard" ExceptionListener to fork based on the type of exception caught:

```<code>if(instanceof $exception STRIPE_EXCEPTION_CLASS)
    $data = $exception->getResponse();
    $response = new JsonResponse($data);
    $event->setResponse($response);
}
else {
    //"normal" behavior here
}
</code>```

... or based on the type of Accept Header

```<code>//if you're accepting json, return json
if( $accept->has('application/json') ) {
    $response = new Response(json_encode($data, JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
    $response->headers->set('Content-Type', 'application/json; charset=utf-8');
    $event->setResponse($response);
}
//if accepting xml, return xml..
elseif( $request->isXmlHttpRequest() ) {
    $xml = new \SimpleXMLElement('<exception/>');
    $data = array_flip($data);
    array_walk_recursive($data, array ($xml, 'addChild'));
    $response = new Response($xml->asXML());
    $response->headers->set('Content-Type', 'text/xml; charset=utf-8');
    $event->setResponse($response);
}
</code>```

Title: Symfony3 registering exception listener

Body:
I have a Stripe exception wrapper for all of the exceptions that Stripe might throw based on certain cases. I'm trying to register an event listener for that exception being thrown, but it doesn't seem like the listener is ever fired.

Instead of returning the event in a json response, the exception throws a 500 and renders the stack trace. Is there something that I'm missing?

// AppBundle/Exceptions/StripePaymentException.php
namespace AppBundle\Exceptions;

use Exception;

class StripePaymentException extends Exception {

    public $response;
    public $message;

    public function __construct($message, $response, $code = 0, Exception $previous = null)
    {
        parent::__construct($message, $code);

        $this->message = $message;
        $this->response = $response;
    }

    public function getResponse()
    {
        return $this->$response;
    }

}

// AppBundle/EventListener/StripePaymentExceptionListener.php
namespace AppBundle\EventListener;

use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

class StripePaymentExceptionListener
{
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();
        $data = $exception->getResponse();
        $response = new JsonResponse($data);
        $event->setResponse($response);
    }
}

// services.yml
app.stripe_payment_exception_listener:
class: AppBundle\EventListener\StripePaymentExceptionListener
    tags:
        - { name: kernel.event_listener, event: kernel.exception, priority: 200 }

Body:
It could be the priority setting on your custom listener. If you have another listener that is being fired before then this will never actually be what returns the Exception.

You could change the priority here:

// services.yml
app.stripe_payment_exception_listener:
class: AppBundle\EventListener\StripePaymentExceptionListener
    tags:
        - { name: kernel.event_listener, event: kernel.exception, priority: 1 }

Or alternatively you could alter your "standard" ExceptionListener to fork based on the type of exception caught:

if(instanceof $exception STRIPE_EXCEPTION_CLASS)
    $data = $exception->getResponse();
    $response = new JsonResponse($data);
    $event->setResponse($response);
}
else {
    //"normal" behavior here
}

... or based on the type of Accept Header

//if you're accepting json, return json
if( $accept->has('application/json') ) {
    $response = new Response(json_encode($data, JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
    $response->headers->set('Content-Type', 'application/json; charset=utf-8');
    $event->setResponse($response);
}
//if accepting xml, return xml..
elseif( $request->isXmlHttpRequest() ) {
    $xml = new \SimpleXMLElement('<exception/>');
    $data = array_flip($data);
    array_walk_recursive($data, array ($xml, 'addChild'));
    $response = new Response($xml->asXML());
    $response->headers->set('Content-Type', 'text/xml; charset=utf-8');
    $event->setResponse($response);
}


答:
Your script assumes that $_FILES['resume'] exists, but it will only exist if the form has been properly submitted.

These four lines:

```<code>$targetDir = "resumes/";
$targetFile = $targetDir . basename($_FILES["resume"]["name"]);
$uploadFinish = 1;
$fileType = pathinfo($targetFile, PATHINFO_EXTENSION);
</code>```

Need to move into the if (isset($_POST["submit"])) { conditional with everything else that depends on the form being submitted.

Title: Issue with PHP file upload

Body:
Your script assumes that $_FILES['resume'] exists, but it will only exist if the form has been properly submitted.

These four lines:

$targetDir = "resumes/";
$targetFile = $targetDir . basename($_FILES["resume"]["name"]);
$uploadFinish = 1;
$fileType = pathinfo($targetFile, PATHINFO_EXTENSION);

Need to move into the if (isset($_POST["submit"])) { conditional with everything else that depends on the form being submitted.


问:
How to access google cloud instances from kubernetes containers
I have k8s cluster in Google Cloud and frontend/api containers there.
In addition to that I have ElasticSearch cluster (es1,es2) in Google Cloud but not under k8s.

I can access api container by name 'api' from container 'frontend'.
I can access es1 from es2 by name 'es1'.

What is a right way to access es cluster by names like es1,es2 from containers api/frontend ?

Thanks!

答: Create the Kubernetes Cluster (GKE) in the same network/subnetwork like your instances, then you can connect the internal Ip´s of your GCE instances from your k8s pods.</p>