问:
Windows batch script to parse CSV file and output a text file
I've seen a response on another page (Help in writing a batch script to parse CSV file and output a text file) - brilliant code BTW:

```<code>@ECHO OFF
IF "%~1"=="" GOTO :EOF
SET "filename=%~1"
SET fcount=0
SET linenum=0
FOR /F "usebackq tokens=1-10 delims=," %%a IN ("%filename%") DO ^
CALL :process "%%a" "%%b" "%%c" "%%d" "%%e" "%%f" "%%g" "%%h" "%%i" "%%j"
GOTO :EOF

:trim
SET "tmp=%~1"
:trimlead
IF NOT "%tmp:~0,1%"==" " GOTO :EOF
SET "tmp=%tmp:~1%"
GOTO trimlead

:process
SET /A linenum+=1
IF "%linenum%"=="1" GOTO picknames

SET ind=0
:display
IF "%fcount%"=="%ind%" (ECHO.&GOTO :EOF)
SET /A ind+=1
CALL :trim %1
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO !f%ind%!!tmp!
ENDLOCAL
SHIFT
GOTO display

:picknames
IF %1=="" GOTO :EOF
CALL :trim %1
SET /a fcount+=1
SET "f%fcount%=%tmp%"
SHIFT
GOTO picknames
</code>```

It works brilliantly for an example csv file I made in the format:

```<code>Header,Name,Place
one,two,three
four,five,six
</code>```

However the actual file I want to change comprises of 64 fields - so I altered the tokens=1-10 to tokens=1-64 and increased the %%a etc right up to 64 variables (the last being called %%BL for example). Now, however, when I run the batch on my 'big' csv file (with the 64 tokens) nothing happens. No errors (good) but no output! (bad). If anyone can help that would be fantastic... am soooo close to getting the whole app working if I can just nail this last bit! Or if anyone has some example code that will do similar for an indefinite number of tokens... Ultimately I want to make a string which will be something like:

```<code>field7,field12,field15,field18
</code>```

答:
When I read this problem again and the solution proposed in the most-voted answer, I thought that a much simpler way to make good use of a series of nested FOR /F commands could be developed. I started to write such a method, that would allowed to use 127 additional tokens placing they in the ASCII 128-254 characters range. However, when my program was completed I discovered that the ASCII characters in the "natural" 128..254 order could not be used for this purpose...

Then, a group of people were interested in this problem and they made a series of discoveries and developments that culminated in a method that allows to use many tokens (more than 43,000!) in a series of nested FOR /F commands. You may read a detailed description of the research and development involved in this discovery at this DosTips topic.

Finally, I used the new method to modify my program, so it now allows the processing of up to 4094 simultaneous tokens (from a text file with long lines), but in a simple way. My application consists in a Batch file, called MakeForTokens.bat, that you may run with the number of desired tokens in the parameter. For example:

```<code>MakeForTokens.bat 64
</code>```

The program generates a Batch file, called ForTokens.bat, that contain all the code necessary to manage such an amount of simultaneous tokens, including examples of how to process a file. In this way, the users just needs to insert their own file names and desired tokens in order to get a working program.

In this particular case, this would be the final ForTokens.bat file that solve the problem as stated in this question, after most descriptive comments were deleted:

```<code>@echo off & setlocal EnableDelayedExpansion & set "$numTokens=65"

Rem/For  Step 1: Define the series of auxiliary variables that will be used as FOR tokens.
call :DefineForTokens

Rem/For  Step 2:  Define an auxiliary variable that will contain the desired tokens when it is %expanded%.
call :ExpandTokensString "tokens=7,12,15,18"

Rem/For  Step 3:  Define the variable with the "delims" value that will be used in the nested FOR's.
set "delims=delims=,"

Rem/For  Step 4:  Create the macro that contain the nested FOR's.
call :CreateNestedFors

Rem/For  Step 5:  This is the main FOR /F command that process the file.
for /F "usebackq tokens=1-31* %delims%" %%%$1% in ("filename.txt") do %NestedFors% (

   Rem/For  Step 6: Process the tokens.

   Rem/For  To just show they, use the "tokens" variable defined above:
   echo %tokens%

   Rem/For  You may also process individual tokens via another FOR /F command:
   for /F "tokens=1-%tokens.len%" %%a in ("%tokens%") do (
      echo Field  #7: %%a
      echo Field #12: %%b
      echo Field #15: %%c
      echo Field #18: %%d
   )

)

goto :EOF

Support subroutines. You must not modify any code below this line.

:DefineForTokens

for /F "tokens=2 delims=:." %%p in ('chcp') do set /A "_cp=%%p, _pages=($numTokens/256+1)*2"
set "_hex= 0 1 2 3 4 5 6 7 8 9 A B C D E F"
call set "_pages=%%_hex:~0,%_pages%%%"
if %$numTokens% gtr 2048 echo Creating FOR tokens variables, please wait . . .
(
   echo FF FE
   for %%P in (%_pages%) do for %%A in (%_hex%) do for %%B in (%_hex%) do echo %%A%%B 3%%P 0D 00 0A 00
) > "%temp%\forTokens.hex.txt"
certutil.exe -decodehex -f "%temp%\forTokens.hex.txt" "%temp%\forTokens.utf-16le.bom.txt" >NUL
chcp 65001 >NUL
type "%temp%\forTokens.utf-16le.bom.txt" > "%temp%\forTokens.utf8.txt"
(for /L %%N in (0,1,%$numTokens%) do set /P "$%%N=")  < "%temp%\forTokens.utf8.txt"
chcp %_cp% >NUL
del "%temp%\forTokens.*.txt"
for %%v in (_cp _hex _pages) do set "%%v="
exit /B

:CreateNestedFors

setlocal EnableDelayedExpansion
set /A "numTokens=$numTokens-1, mod=numTokens%%31, i=numTokens/31, lim=31"
if %mod% equ 0 set "mod=31"
set "NestedFors="
for /L %%i in (32,31,%numTokens%) do (
   if !i! equ 1 set "lim=!mod!"
   set "NestedFors=!NestedFors! for /F "tokens=1-!lim!* %delims%" %%!$%%i! in ("%%!$%%i!") do"
   set /A "i-=1"
)
for /F "delims=" %%a in ("!NestedFors!") do endlocal & set "NestedFors=%%a"
exit /B

:ExpandTokensString variable=tokens definitions ...

setlocal EnableDelayedExpansion
set "var=" & set "tokens=" & set "len=0"
if "%~2" equ "" (set "params=%~1") else set "params=%*"
for %%a in (!params!) do (
   if not defined var (
      set "var=%%a"
   ) else for /F "tokens=1-3 delims=-+" %%i in ("%%a") do (
      if "%%j" equ "" (
         if %%i lss %$numTokens% set "tokens=!tokens! %%!$%%i!" & set /A len+=1
      ) else (
         if "%%k" equ "" (set "k=1") else set "k=%%k"
         if %%i leq %%j (
            for /L %%n in (%%i,!k!,%%j) do if %%n lss %$numTokens% set "tokens=!tokens! %%!$%%n!" & set /A len+=1
         ) else (
            for /L %%n in (%%i,-!k!,%%j) do if %%n lss %$numTokens% set "tokens=!tokens! %%!$%%n!" & set /A len+=1
         )
      )
   )
)
endlocal & set "%var%=%tokens%" & set "%var%.len=%len%"
exit /B
</code>```

You may download the MakeForTokens.bat application from this site.

Body:
I've seen a response on another page (Help in writing a batch script to parse CSV file and output a text file) - brilliant code BTW:

@ECHO OFF
IF "%~1"=="" GOTO :EOF
SET "filename=%~1"
SET fcount=0
SET linenum=0
FOR /F "usebackq tokens=1-10 delims=," %%a IN ("%filename%") DO ^
CALL :process "%%a" "%%b" "%%c" "%%d" "%%e" "%%f" "%%g" "%%h" "%%i" "%%j"
GOTO :EOF

:trim
SET "tmp=%~1"
:trimlead
IF NOT "%tmp:~0,1%"==" " GOTO :EOF
SET "tmp=%tmp:~1%"
GOTO trimlead

:process
SET /A linenum+=1
IF "%linenum%"=="1" GOTO picknames

SET ind=0
:display
IF "%fcount%"=="%ind%" (ECHO.&GOTO :EOF)
SET /A ind+=1
CALL :trim %1
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO !f%ind%!!tmp!
ENDLOCAL
SHIFT
GOTO display

:picknames
IF %1=="" GOTO :EOF
CALL :trim %1
SET /a fcount+=1
SET "f%fcount%=%tmp%"
SHIFT
GOTO picknames

It works brilliantly for an example csv file I made in the format:

Header,Name,Place
one,two,three
four,five,six

However the actual file I want to change comprises of 64 fields - so I altered the tokens=1-10 to tokens=1-64 and increased the %%a etc right up to 64 variables (the last being called %%BL for example). Now, however, when I run the batch on my 'big' csv file (with the 64 tokens) nothing happens. No errors (good) but no output! (bad). If anyone can help that would be fantastic... am soooo close to getting the whole app working if I can just nail this last bit! Or if anyone has some example code that will do similar for an indefinite number of tokens... Ultimately I want to make a string which will be something like:

field7,field12,field15,field18

Body:
When I read this problem again and the solution proposed in the most-voted answer, I thought that a much simpler way to make good use of a series of nested FOR /F commands could be developed. I started to write such a method, that would allowed to use 127 additional tokens placing they in the ASCII 128-254 characters range. However, when my program was completed I discovered that the ASCII characters in the "natural" 128..254 order could not be used for this purpose...

Then, a group of people were interested in this problem and they made a series of discoveries and developments that culminated in a method that allows to use many tokens (more than 43,000!) in a series of nested FOR /F commands. You may read a detailed description of the research and development involved in this discovery at this DosTips topic.

Finally, I used the new method to modify my program, so it now allows the processing of up to 4094 simultaneous tokens (from a text file with long lines), but in a simple way. My application consists in a Batch file, called MakeForTokens.bat, that you may run with the number of desired tokens in the parameter. For example:

MakeForTokens.bat 64

The program generates a Batch file, called ForTokens.bat, that contain all the code necessary to manage such an amount of simultaneous tokens, including examples of how to process a file. In this way, the users just needs to insert their own file names and desired tokens in order to get a working program.

In this particular case, this would be the final ForTokens.bat file that solve the problem as stated in this question, after most descriptive comments were deleted:

@echo off & setlocal EnableDelayedExpansion & set "$numTokens=65"

Rem/For  Step 1: Define the series of auxiliary variables that will be used as FOR tokens.
call :DefineForTokens

Rem/For  Step 2:  Define an auxiliary variable that will contain the desired tokens when it is %expanded%.
call :ExpandTokensString "tokens=7,12,15,18"

Rem/For  Step 3:  Define the variable with the "delims" value that will be used in the nested FOR's.
set "delims=delims=,"

Rem/For  Step 4:  Create the macro that contain the nested FOR's.
call :CreateNestedFors

Rem/For  Step 5:  This is the main FOR /F command that process the file.
for /F "usebackq tokens=1-31* %delims%" %%%$1% in ("filename.txt") do %NestedFors% (

   Rem/For  Step 6: Process the tokens.

   Rem/For  To just show they, use the "tokens" variable defined above:
   echo %tokens%

   Rem/For  You may also process individual tokens via another FOR /F command:
   for /F "tokens=1-%tokens.len%" %%a in ("%tokens%") do (
      echo Field  #7: %%a
      echo Field #12: %%b
      echo Field #15: %%c
      echo Field #18: %%d
   )

)

goto :EOF

Support subroutines. You must not modify any code below this line.

:DefineForTokens

for /F "tokens=2 delims=:." %%p in ('chcp') do set /A "_cp=%%p, _pages=($numTokens/256+1)*2"
set "_hex= 0 1 2 3 4 5 6 7 8 9 A B C D E F"
call set "_pages=%%_hex:~0,%_pages%%%"
if %$numTokens% gtr 2048 echo Creating FOR tokens variables, please wait . . .
(
   echo FF FE
   for %%P in (%_pages%) do for %%A in (%_hex%) do for %%B in (%_hex%) do echo %%A%%B 3%%P 0D 00 0A 00
) > "%temp%\forTokens.hex.txt"
certutil.exe -decodehex -f "%temp%\forTokens.hex.txt" "%temp%\forTokens.utf-16le.bom.txt" >NUL
chcp 65001 >NUL
type "%temp%\forTokens.utf-16le.bom.txt" > "%temp%\forTokens.utf8.txt"
(for /L %%N in (0,1,%$numTokens%) do set /P "$%%N=")  < "%temp%\forTokens.utf8.txt"
chcp %_cp% >NUL
del "%temp%\forTokens.*.txt"
for %%v in (_cp _hex _pages) do set "%%v="
exit /B

:CreateNestedFors

setlocal EnableDelayedExpansion
set /A "numTokens=$numTokens-1, mod=numTokens%%31, i=numTokens/31, lim=31"
if %mod% equ 0 set "mod=31"
set "NestedFors="
for /L %%i in (32,31,%numTokens%) do (
   if !i! equ 1 set "lim=!mod!"
   set "NestedFors=!NestedFors! for /F "tokens=1-!lim!* %delims%" %%!$%%i! in ("%%!$%%i!") do"
   set /A "i-=1"
)
for /F "delims=" %%a in ("!NestedFors!") do endlocal & set "NestedFors=%%a"
exit /B

:ExpandTokensString variable=tokens definitions ...

setlocal EnableDelayedExpansion
set "var=" & set "tokens=" & set "len=0"
if "%~2" equ "" (set "params=%~1") else set "params=%*"
for %%a in (!params!) do (
   if not defined var (
      set "var=%%a"
   ) else for /F "tokens=1-3 delims=-+" %%i in ("%%a") do (
      if "%%j" equ "" (
         if %%i lss %$numTokens% set "tokens=!tokens! %%!$%%i!" & set /A len+=1
      ) else (
         if "%%k" equ "" (set "k=1") else set "k=%%k"
         if %%i leq %%j (
            for /L %%n in (%%i,!k!,%%j) do if %%n lss %$numTokens% set "tokens=!tokens! %%!$%%n!" & set /A len+=1
         ) else (
            for /L %%n in (%%i,-!k!,%%j) do if %%n lss %$numTokens% set "tokens=!tokens! %%!$%%n!" & set /A len+=1
         )
      )
   )
)
endlocal & set "%var%=%tokens%" & set "%var%.len=%len%"
exit /B

You may download the MakeForTokens.bat application from this site.


来源: stackexchange

问:
Casting to URLError, then accessing 'code' property causes a crash
When I case an Error as URLError, then try to access its 'code' property the app is crashing. I get

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

```<code>func somFunc(things: [Thing]?,
             error: Error?) {

              let errorCopy = (error as? URLError)
              let errorCode = errorCopy?.code //Crash
}
</code>```

I can understand the casting returning nil, or the call on code returning nil. But I am not sure of the cause of the crash.

When I print errorCopy before I try to read 'code', I get:

errorCopy: Optional(Foundation.URLError(_nsError: Error
  Domain=NSURLErrorDomain Code=404 "(null)"))

答:
I still cannot explain the crash, but I found a work around. Cast the error to an NSError, then read the code property.

```<code> let errorCopy = (error as? NSError)
 let errorCode = errorCopy?.code
</code>```

Then I can use the error code without crashing:

```<code>if errorCode == URLError.cancelled.rawValue {
//Do Something
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I case an Error as URLError, then try to access its 'code' property the app is crashing. I get

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

func somFunc(things: [Thing]?,
             error: Error?) {

              let errorCopy = (error as? URLError)
              let errorCode = errorCopy?.code //Crash
}

I can understand the casting returning nil, or the call on code returning nil. But I am not sure of the cause of the crash.

When I print errorCopy before I try to read 'code', I get:

errorCopy: Optional(Foundation.URLError(_nsError: Error
  Domain=NSURLErrorDomain Code=404 "(null)"))

Body:
I still cannot explain the crash, but I found a work around. Cast the error to an NSError, then read the code property.

 let errorCopy = (error as? NSError)
 let errorCode = errorCopy?.code

Then I can use the error code without crashing:

if errorCode == URLError.cancelled.rawValue {
//Do Something
}


问:
Scrolling text in Dialog not working
I am creating a Dialog with the following code:

```<code>Dialog dlg = new Dialog();
dlg.setUIID("AboutDialog");
dlg.setTitle("About");
dlg.setScrollableY(true);
dlg.setScrollVisible(true);
dlg.setLayout(new BorderLayout());
SpanLabel spl = new SpanLabel(DialogText.aboutTxt[txtItem]);
dlg.addComponent(BorderLayout.CENTER, spl);
height = screenHorizontalSize / 9;
width = screenVerticalSize / 10;
Button close = new Button("Close");
close.addActionListener((ee) -> dlg.dispose());
dlg.addComponent(BorderLayout.SOUTH, close);
dlg.show(height, height, width, width);
</code>```

The DialogText contains several lines that need to be scrollable on low resolution devices, but the above code doesn't achieve this. What have I missed? Also tried making the SpanLabel scrollable but that didn't work.
Just moved this project from Eclipse to Netbeans (new to this). Using old GUI builder but not for this Dialog.

答:
I think I found the answer - use the show methods in Dialog as in:

```<code>Dialog dlg = new Dialog();
dlg.setUIID("AboutDialog");
String title = "About";
String txt = DialogText.aboutTxt[txtItem];
dlg.setLayout(new BorderLayout());
dlg.setScrollableY(true);
dlg.setScrollVisible(true);
dlg.show(title, txt, Dialog.TYPE_INFO, logo_icon, "", "Close");
</code>```

Needs a bit of tweaking but the scroll now works.
Apologies if I've wasted anyone's time.

Later: Unable to 'tweak' the above code, so in case it helps someone else, I finally got scrollable text in the Dialog using:

```<code>String title = DialogText.getTitleUIID(txtItem);
String txt = DialogText.dialogTxt[txtItem];

Dialog dlg = new Dialog();
dlg.setTitle(title);
dlg.setLayout(new BorderLayout());
TextArea txtArea = new TextArea(txt);
txtArea.setScrollVisible(true);
dlg.add(BorderLayout.CENTER, txtArea);
Button close = new Button("Close");
close.addActionListener((ee) -> dlg.dispose());
dlg.addComponent(BorderLayout.SOUTH, close);
dlg.showAtPosition(0, 0, 0, 0, true);
</code>```

Title: Scrolling text in Dialog not working

Body:
I am creating a Dialog with the following code:

Dialog dlg = new Dialog();
dlg.setUIID("AboutDialog");
dlg.setTitle("About");
dlg.setScrollableY(true);
dlg.setScrollVisible(true);
dlg.setLayout(new BorderLayout());
SpanLabel spl = new SpanLabel(DialogText.aboutTxt[txtItem]);
dlg.addComponent(BorderLayout.CENTER, spl);
height = screenHorizontalSize / 9;
width = screenVerticalSize / 10;
Button close = new Button("Close");
close.addActionListener((ee) -> dlg.dispose());
dlg.addComponent(BorderLayout.SOUTH, close);
dlg.show(height, height, width, width);

The DialogText contains several lines that need to be scrollable on low resolution devices, but the above code doesn't achieve this. What have I missed? Also tried making the SpanLabel scrollable but that didn't work.
Just moved this project from Eclipse to Netbeans (new to this). Using old GUI builder but not for this Dialog.

Body:
I think I found the answer - use the show methods in Dialog as in:

Dialog dlg = new Dialog();
dlg.setUIID("AboutDialog");
String title = "About";
String txt = DialogText.aboutTxt[txtItem];
dlg.setLayout(new BorderLayout());
dlg.setScrollableY(true);
dlg.setScrollVisible(true);
dlg.show(title, txt, Dialog.TYPE_INFO, logo_icon, "", "Close");

Needs a bit of tweaking but the scroll now works.
Apologies if I've wasted anyone's time.

Later: Unable to 'tweak' the above code, so in case it helps someone else, I finally got scrollable text in the Dialog using:

String title = DialogText.getTitleUIID(txtItem);
String txt = DialogText.dialogTxt[txtItem];

Dialog dlg = new Dialog();
dlg.setTitle(title);
dlg.setLayout(new BorderLayout());
TextArea txtArea = new TextArea(txt);
txtArea.setScrollVisible(true);
dlg.add(BorderLayout.CENTER, txtArea);
Button close = new Button("Close");
close.addActionListener((ee) -> dlg.dispose());
dlg.addComponent(BorderLayout.SOUTH, close);
dlg.showAtPosition(0, 0, 0, 0, true);


问:
Find if the number is Prime or show the prime factors using excel formula?
I have of integers in Col A and in col B i want to show result 'Prime' if it doesn't have further factors for the number itself. This goes like this if the number for example is 37 result will be 'Prime' and if its 44 then result will be 2x2x11. How can i do this using excel formula? Screen shot :

答:
Here is a somewhat straightforward recursive version. It is based on the idea that once you identify a factor you divide the number by that factor and then turn your attention to factoring the rest.

```<code>Function Factor(ByVal n As Long, Optional FirstTrial As Long = 2) As String
    Dim i As Long
    Dim t As Long
    Dim limit As Long
    Dim rest As String
    Dim s As String

    If n = 1 Then
        Factor = n
        Exit Function
    End If
    limit = Int(Sqr(n))
    t = FirstTrial
    Do While t <= limit
        If n Mod t = 0 Then
            rest = Factor(n / t, t)
            If rest <> "1" Then
                s = t & "x" & rest
            End If
            Factor = s
            Exit Function
        Else
            If t = 2 Then t = 3 Else t = t + 2
        End If
    Loop
    'if we get here:
    Factor = n
End Function

Function PrimeOrFactor(n As Long) As String
    Dim s As String
    s = Factor(n)
    If n = 1 Then
        PrimeOrFactor = "Neither"
    ElseIf (s) = Trim(n) Then
        PrimeOrFactor = "Prime"
    Else
        PrimeOrFactor = s
    End If
End Function
</code>```

Tested like:

```<code>Sub test()
    Dim i As Long
    For i = 1 To 20
        Cells(i, 1) = i
        Cells(i, 2) = PrimeOrFactor(i)
    Next i
End Sub
</code>```

Output:

Body:
Here is a somewhat straightforward recursive version. It is based on the idea that once you identify a factor you divide the number by that factor and then turn your attention to factoring the rest.

Function Factor(ByVal n As Long, Optional FirstTrial As Long = 2) As String
    Dim i As Long
    Dim t As Long
    Dim limit As Long
    Dim rest As String
    Dim s As String

    If n = 1 Then
        Factor = n
        Exit Function
    End If
    limit = Int(Sqr(n))
    t = FirstTrial
    Do While t <= limit
        If n Mod t = 0 Then
            rest = Factor(n / t, t)
            If rest <> "1" Then
                s = t & "x" & rest
            End If
            Factor = s
            Exit Function
        Else
            If t = 2 Then t = 3 Else t = t + 2
        End If
    Loop
    'if we get here:
    Factor = n
End Function

Function PrimeOrFactor(n As Long) As String
    Dim s As String
    s = Factor(n)
    If n = 1 Then
        PrimeOrFactor = "Neither"
    ElseIf (s) = Trim(n) Then
        PrimeOrFactor = "Prime"
    Else
        PrimeOrFactor = s
    End If
End Function

Tested like:

Sub test()
    Dim i As Long
    For i = 1 To 20
        Cells(i, 1) = i
        Cells(i, 2) = PrimeOrFactor(i)
    Next i
End Sub

Output:


答:
The problem is because you are using LEFT JOIN some of the values for usersbycourse.modulesfinished are NULL

Something you need to learn is

```<code>  NULL == something
</code>```

Is always unknown, not true, not false, just unknown.

So when you try to compare with = 1 your nulls get the ELSE but not because they aren't 1, is because is all the rest.

So if instead you change the condition to

```<code>COUNT(CASE WHEN usersbycourse.modulesfinished = 0 THEN 1 ELSE NULL)
</code>```

Only the TRUE match will get 1, the FALSE and the UNKNOW part ill get NULL and COUNT doesnt count nulls. And that is what you want.

Title: COUNT counting something on LEFT JOIN that doesn't exist. Why?

Body:
I'm having a problem.

I have this table called usersbycourse which shows this information:

+------------+-----------------+--------+-----------+-------+-----------------+-----------------+
| instanceid | shortname       | userid | firstname | logid | lastaccessdelta | modulesfinished |
+------------+-----------------+--------+-----------+-------+-----------------+-----------------+
|          2 | PJU             |     74 | Robin     |   766 |         1662246 |               0 |
|          3 | Fundgest-GRHN1A |     75 | Batman    |   867 |         1576725 |               0 |
|          3 | Fundgest-GRHN1A |     77 | Abigobeu  |  1004 |          610480 |               0 |
+------------+-----------------+--------+-----------+-------+-----------------+-----------------+

and this SQL:

SELECT
mdl_course.id,
mdl_course.shortname,
COUNT(CASE WHEN usersbycourse.modulesfinished = 1 THEN NULL ELSE 1 END) AS studentcount
FROM mdl_course LEFT JOIN usersbycourse ON mdl_course.id = usersbycourse.instanceid
GROUP BY mdl_course.id;

The results from the SQL are:

+----+-----------------+--------------+
| id | shortname       | studentcount |
+----+-----------------+--------------+
|  1 | Unity I         |            1 |
|  2 | PJU             |            1 |
|  3 | Fundgest-GRHN1A |            2 |
|  4 | asdzxc2         |            1 |
+----+-----------------+--------------+

But why? In inside SQL has no Unity I, and no asdzxc2. How do I produce a result like this:

+----+-----------------+--------------+
| id | shortname       | studentcount |
+----+-----------------+--------------+
|  1 | Unity I         |            0 |
|  2 | PJU             |            1 |
|  3 | Fundgest-GRHN1A |            2 |
|  4 | asdzxc2         |            0 |
+----+-----------------+--------------+

?

EDIT:

I want to count only rows having modulesfinished = 0

Body:
The problem is because you are using LEFT JOIN some of the values for usersbycourse.modulesfinished are NULL

Something you need to learn is

  NULL == something

Is always unknown, not true, not false, just unknown.

So when you try to compare with = 1 your nulls get the ELSE but not because they aren't 1, is because is all the rest.

So if instead you change the condition to

COUNT(CASE WHEN usersbycourse.modulesfinished = 0 THEN 1 ELSE NULL)

Only the TRUE match will get 1, the FALSE and the UNKNOW part ill get NULL and COUNT doesnt count nulls. And that is what you want.


问:
When is innodb_lock_wait_timeout ignored?
I'm having a weird case of the classic deadlock exception:

Caused by: java.sql.BatchUpdateException: Deadlock found when trying to get lock; try restarting transaction.

The code is identified and indeed, it's possible to get a deadlock. The thing is that I'm getting the exception immediately. I've set the innodb_lock_wait_timeout variable to 1 hour (3600). But still, the exception comes right away.

What exactly is happening?

答:
You are hitting a deadlock the lock_wait_timeout variable is how long a query will wait to acquire locks before timing out - not the same thing.

From the manual:
The timeout in seconds an InnoDB transaction may wait for a row lock before giving up. The default value is 50 seconds. A transaction that tries to access a row that is locked by another InnoDB transaction will hang for at most this many seconds before issuing the following error:

You'd see this if you were hitting the timeout.  You have a proper deadlock that needs fixing.
ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
How to compute a power of a power using recursion?
I've recently been looking into recursion and it's been very confusing. I'm trying to write a java program which uses recursion to generate the result of a base number to a power, which also has a height of how many exponents the base has. For example, a base of two with a power of 3 and a height of 3 will result:

(((2^3)^3)^3)

Here is my (very flawed) code:

```<code>    public static void main(String[] args) {
    System.out.println(exponentWithHeight(2, 2, 3));
}

public static int exponentWithHeight(int base, int power, int height) {
    if (power < 0 || height < 0) {
        throw new IllegalArgumentException("Check input values.");
    }
    if (power == 0) {
        return 1;
    } else {
        return (base * height * exponentWithHeight(base, power - 1, height - 1));
    }
}
</code>```

I'm really not sure how to go about getting my desired output; As I said this is really confusing and new to me. Can someone help explain how to go about doing this?

答:
Here is Another Simple and Clear Exemple using a for Loop to calculate the Power Then Calculate the Height Using The Recursion</p>

```<code>public static long exponentWithHeight(long base, long power, long height) {
            long calculatedPower;
            if (power < 0 || height < 0) {
                throw new IllegalArgumentException("Invalid Input; Check power and/or height value.");
            }
            if (power == 0) {
                return 1;
            }
            if (height > 0) {
                calculatedPower = base;
                for (int i = (int) power; i > 1; i--) {
                        calculatedPower *= base;
                }
                return exponentWithHeight(calculatedPower, power, --height);
            }

            return base;

    }
</code>```

Body:
I've recently been looking into recursion and it's been very confusing. I'm trying to write a java program which uses recursion to generate the result of a base number to a power, which also has a height of how many exponents the base has. For example, a base of two with a power of 3 and a height of 3 will result:

(((2^3)^3)^3)

Here is my (very flawed) code:

    public static void main(String[] args) {
    System.out.println(exponentWithHeight(2, 2, 3));
}

public static int exponentWithHeight(int base, int power, int height) {
    if (power < 0 || height < 0) {
        throw new IllegalArgumentException("Check input values.");
    }
    if (power == 0) {
        return 1;
    } else {
        return (base * height * exponentWithHeight(base, power - 1, height - 1));
    }
}

I'm really not sure how to go about getting my desired output; As I said this is really confusing and new to me. Can someone help explain how to go about doing this?

Body:
Here is Another Simple and Clear Exemple using a for Loop to calculate the Power Then Calculate the Height Using The Recursion

public static long exponentWithHeight(long base, long power, long height) {
            long calculatedPower;
            if (power < 0 || height < 0) {
                throw new IllegalArgumentException("Invalid Input; Check power and/or height value.");
            }
            if (power == 0) {
                return 1;
            }
            if (height > 0) {
                calculatedPower = base;
                for (int i = (int) power; i > 1; i--) {
                        calculatedPower *= base;
                }
                return exponentWithHeight(calculatedPower, power, --height);
            }

            return base;

    }


问:
Image object can only be logged to the console
I am trying to store the image object in a constructor variable but it comes up undefined, at the moment I can only log the object to the result.

I am trying to get the object data from the class method getUserImage();
but when I try storing the object in this._userImage it shows undefined. Again, only console.log(result) only works :(

```<code>Error: TypeError: Cannot read property '_userImage' of undefined
    at /home/jd/Projects/game-site/app/Http/Helpers/ImageUploader.js:23:11
    at IncomingMessage.<anonymous> (/home/jd/Projects/game-site/node_modules/cloudinary/lib/uploader.js:499:51)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:188:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
[nodemon] app crashed - waiting for file changes before starting...
</code>```

ImageUploader.js

```<code>'use strict';

const cloudinary = require('cloudinary');

class ImageUploader {

  constructor(imageObj) {
    this.imageObj = imageObj;
    this._apiKey = "key";
    this._apiSecret = "secret";
    this._url = `url here`;
    this._userImage = {}; // this is the empty object I try storing the image data into from Cloudinary
    this.config = cloudinary.config({
      cloud_name: 'cloud name here',
      api_key: this._apiKey,
      api_secret: this._apiSecret
    });
  }

  * uploadAvatar(path) {
    cloudinary.uploader.upload(path, function(result) {
      this._userImage.imgData = result;
      return console.log(this._userImage);
    });
  }

  getUserImage() {
    return this._userImage;
  }

}

module.exports = ImageUploader;
</code>```

UsersController.js

```<code>'use strict'

const Validator = require("../Helpers/ValidatorHelper.js");
const ImageUploader = require("../Helpers/ImageUploader.js");

class UsersController {

  * registerView (request, response) {
    yield response.sendView('users.register');
  }

  * register (request, response) {
    const user = request.only('display_name', 'username', 'email', 'password', 'confirm_password', 'console');
    const avatar = request.file('avatar');

    let validator = new Validator(user, avatar);
    let imageUpload = new ImageUploader(avatar);

    let avatarStatus = yield validator.validateAvatar();
    if (avatarStatus) { // is true
      yield imageUpload.uploadAvatar(avatar.file.path);
      console.log(imageUpload.getUserImage());
    } else { // is false
      // pick a random avatar
    }

    return response.status(200).json(user);

  }

}

module.exports = UsersController
</code>```

答:
Your callback is changing the scope this refers to:

```<code>* uploadAvatar(path) {
    cloudinary.uploader.upload(path, function(result) {
      // "this" is now referring to your callback function
      this._userImage.imgData = result;
      return console.log(this._userImage);
    });
  }
</code>```

Preferably, you can fix this by using an arrow function (which retains the parent scope):

```<code> * uploadAvatar(path) {
    cloudinary.uploader.upload(path, (result) => {
      this._userImage.imgData = result;
      return console.log(this._userImage);
    });
  }
</code>```

Or by capturing this prior to entering your callback:

```<code> * uploadAvatar(path) {
    const _this = this;
    cloudinary.uploader.upload(path, function(result) {
      _this._userImage.imgData = result;
      return console.log(_this._userImage);
    });
  }
</code>```

Body:
I am trying to store the image object in a constructor variable but it comes up undefined, at the moment I can only log the object to the result.

I am trying to get the object data from the class method getUserImage();
but when I try storing the object in this._userImage it shows undefined. Again, only console.log(result) only works :(

Error: TypeError: Cannot read property '_userImage' of undefined
    at /home/jd/Projects/game-site/app/Http/Helpers/ImageUploader.js:23:11
    at IncomingMessage.<anonymous> (/home/jd/Projects/game-site/node_modules/cloudinary/lib/uploader.js:499:51)
    at emitNone (events.js:91:20)
    at IncomingMessage.emit (events.js:188:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:80:11)
    at process._tickCallback (internal/process/next_tick.js:104:9)
[nodemon] app crashed - waiting for file changes before starting...

ImageUploader.js

'use strict';

const cloudinary = require('cloudinary');

class ImageUploader {

  constructor(imageObj) {
    this.imageObj = imageObj;
    this._apiKey = "key";
    this._apiSecret = "secret";
    this._url = `url here`;
    this._userImage = {}; // this is the empty object I try storing the image data into from Cloudinary
    this.config = cloudinary.config({
      cloud_name: 'cloud name here',
      api_key: this._apiKey,
      api_secret: this._apiSecret
    });
  }

  * uploadAvatar(path) {
    cloudinary.uploader.upload(path, function(result) {
      this._userImage.imgData = result;
      return console.log(this._userImage);
    });
  }

  getUserImage() {
    return this._userImage;
  }

}

module.exports = ImageUploader;

UsersController.js

'use strict'

const Validator = require("../Helpers/ValidatorHelper.js");
const ImageUploader = require("../Helpers/ImageUploader.js");

class UsersController {

  * registerView (request, response) {
    yield response.sendView('users.register');
  }

  * register (request, response) {
    const user = request.only('display_name', 'username', 'email', 'password', 'confirm_password', 'console');
    const avatar = request.file('avatar');

    let validator = new Validator(user, avatar);
    let imageUpload = new ImageUploader(avatar);

    let avatarStatus = yield validator.validateAvatar();
    if (avatarStatus) { // is true
      yield imageUpload.uploadAvatar(avatar.file.path);
      console.log(imageUpload.getUserImage());
    } else { // is false
      // pick a random avatar
    }

    return response.status(200).json(user);

  }

}

module.exports = UsersController

Body:
Your callback is changing the scope this refers to:

* uploadAvatar(path) {
    cloudinary.uploader.upload(path, function(result) {
      // "this" is now referring to your callback function
      this._userImage.imgData = result;
      return console.log(this._userImage);
    });
  }

Preferably, you can fix this by using an arrow function (which retains the parent scope):

 * uploadAvatar(path) {
    cloudinary.uploader.upload(path, (result) => {
      this._userImage.imgData = result;
      return console.log(this._userImage);
    });
  }

Or by capturing this prior to entering your callback:

 * uploadAvatar(path) {
    const _this = this;
    cloudinary.uploader.upload(path, function(result) {
      _this._userImage.imgData = result;
      return console.log(_this._userImage);
    });
  }


问:
MySQL select 10 random rows from 600K rows fast
How can I best write a query that selects 10 rows randomly from a total of 600k?</p>

答:
I improved the answer @Riedsio had. This is the most efficient query I can find on a large, uniformly distributed table with gaps (tested on getting 1000 random rows from a table that has > 2.6B rows).

```<code>(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max := (SELECT MAX(id) FROM table)) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1)
</code>```

Let me unpack what's going on.

@max := (SELECT MAX(id) FROM table)

I'm calculating and saving the max. For very large tables, there is a slight overhead for calculating MAX(id) each time you need a row

SELECT FLOOR(rand() * @max) + 1 as rand)

Gets a random id

SELECT id FROM table INNER JOIN (...) on id > rand LIMIT 1

This fills in the gaps. Basically if you randomly select a number in the gaps, it will just pick the next id. Assuming the gaps are uniformly distributed, this shouldn't be a problem.

Doing the union helps you fit everything into 1 query so you can avoid doing multiple queries. It also lets you save the overhead of calculating MAX(id). Depending on your application, this might matter a lot or very little.

Note that this gets only the ids and gets them in random order. If you want to do anything more advanced I recommend you do this:

```<code>SELECT t.id, t.name -- etc, etc
FROM table t
INNER JOIN (
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max := (SELECT MAX(id) FROM table)) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1)
) x ON x.id = t.id
ORDER BY t.id
</code>```

Body:
I improved the answer @Riedsio had. This is the most efficient query I can find on a large, uniformly distributed table with gaps (tested on getting 1000 random rows from a table that has > 2.6B rows).

(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max := (SELECT MAX(id) FROM table)) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
(SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1)

Let me unpack what's going on.

@max := (SELECT MAX(id) FROM table)

I'm calculating and saving the max. For very large tables, there is a slight overhead for calculating MAX(id) each time you need a row

SELECT FLOOR(rand() * @max) + 1 as rand)

Gets a random id

SELECT id FROM table INNER JOIN (...) on id > rand LIMIT 1

This fills in the gaps. Basically if you randomly select a number in the gaps, it will just pick the next id. Assuming the gaps are uniformly distributed, this shouldn't be a problem.

Doing the union helps you fit everything into 1 query so you can avoid doing multiple queries. It also lets you save the overhead of calculating MAX(id). Depending on your application, this might matter a lot or very little.

Note that this gets only the ids and gets them in random order. If you want to do anything more advanced I recommend you do this:

SELECT t.id, t.name -- etc, etc
FROM table t
INNER JOIN (
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max := (SELECT MAX(id) FROM table)) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1) UNION
    (SELECT id FROM table INNER JOIN (SELECT FLOOR(RAND() * @max) + 1 as rand) r on id > rand LIMIT 1)
) x ON x.id = t.id
ORDER BY t.id


问:
Program outputs wrong string
I have a program were the user inputs a drivers first name, last name, their team leader's id, phone number and area code. Then it stores the info into the database, but instead of storing the leader's id, it finds the teams id that is corresponding to the leader's id and stores it.

Example

Drivers Table

```<code>driver_id | first_name | last_name | phone | area_code | team_id
</code>```

Teams Table

```<code>team_id | leader_id | student_id
</code>```

So the program finds the team_id that corresponds to the leader_id that the user enters.

Problem

My problem is that if the leader_id doesn't exist, that means that the team doesn't exist, so the program should output this line of code header("Location: ../../../admin.php?message=Team Doesn't Exist"); ( because the table is empty ) but the program outputs this line of code header("Location: ../../../admin.php?message=Success!");, which should be outputted if the leader_id exists.

PHP CODE

```<code><?php

require '../../connect.php';

$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$leader_id = $_POST['leader_id'];
$phone = $_POST['phone'];
$area_code = $_POST['area_code'];

if(!empty($first_name) && !empty($last_name) && !empty($phone) && !empty($leader_id)) {

    if(is_numeric($leader_id) && is_numeric($phone) && is_numeric($area_code)) {

        $get_team_id = mysqli_query($link, "SELECT team_id FROM teams WHERE leader_id = $leader_id");

        if($get_team_id) {

            $result = mysqli_query($link, "INSERT INTO drivers (first_name, last_name, phone, area_code, team_id) SELECT '$first_name', '$last_name', '$phone', '$area_code', team_id FROM teams WHERE leader_id = '$leader_id'");

            if($result) {

                header("Location: ../../../admin.php?message=Success!");

            } else {

                header("Location: ../../../admin.php?message=Sorry we ran into an error");

            }

            header("Location: ../../../admin.php?message=Team Exists");

        } else {

            header("Location: ../../../admin.php?message=Team Doesn't Exist");

        }

    } else {

        header("Location: ../../../admin.php?message=Please add a number for the Leader ID, Phone Number and Area Code");

    }
} else if (empty($first_name) || empty($last_name) || empty($leader_id) || empty($phone)) {

    header("Location: ../../../admin.php?message=Please add you're input values");

}
</code>```

?>

答:
Try below code for your Condition

if(mysqli_num_rows($get_team_id)>0)

instead of

if($get_team_id)

Title: Program outputs wrong string

Body:
I have a program were the user inputs a drivers first name, last name, their team leader's id, phone number and area code. Then it stores the info into the database, but instead of storing the leader's id, it finds the teams id that is corresponding to the leader's id and stores it.

Example

Drivers Table

driver_id | first_name | last_name | phone | area_code | team_id

Teams Table

team_id | leader_id | student_id

So the program finds the team_id that corresponds to the leader_id that the user enters.

Problem

My problem is that if the leader_id doesn't exist, that means that the team doesn't exist, so the program should output this line of code header("Location: ../../../admin.php?message=Team Doesn't Exist"); ( because the table is empty ) but the program outputs this line of code header("Location: ../../../admin.php?message=Success!");, which should be outputted if the leader_id exists.

PHP CODE

<?php

require '../../connect.php';

$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$leader_id = $_POST['leader_id'];
$phone = $_POST['phone'];
$area_code = $_POST['area_code'];

if(!empty($first_name) && !empty($last_name) && !empty($phone) && !empty($leader_id)) {

    if(is_numeric($leader_id) && is_numeric($phone) && is_numeric($area_code)) {

        $get_team_id = mysqli_query($link, "SELECT team_id FROM teams WHERE leader_id = $leader_id");

        if($get_team_id) {

            $result = mysqli_query($link, "INSERT INTO drivers (first_name, last_name, phone, area_code, team_id) SELECT '$first_name', '$last_name', '$phone', '$area_code', team_id FROM teams WHERE leader_id = '$leader_id'");

            if($result) {

                header("Location: ../../../admin.php?message=Success!");

            } else {

                header("Location: ../../../admin.php?message=Sorry we ran into an error");

            }

            header("Location: ../../../admin.php?message=Team Exists");

        } else {

            header("Location: ../../../admin.php?message=Team Doesn't Exist");

        }

    } else {

        header("Location: ../../../admin.php?message=Please add a number for the Leader ID, Phone Number and Area Code");

    }
} else if (empty($first_name) || empty($last_name) || empty($leader_id) || empty($phone)) {

    header("Location: ../../../admin.php?message=Please add you're input values");

}

?>


问:
ggplot2::geom_segment. How to set multiple sizes, say c(10,12)?
I'm plotting with ggplot a data frame of different actions (A,B) not mutually exclusive and have multiple Ids.
The activities often overlap within an Id, which might cause that some are not visible.

The data

```<code>df <- data.frame(id = c("id1", "id1", "id2", "id2"), x1 = c(10, 9, 12, 12 ), x2 = c(16, 17, 15, 19), type = c("A", "B", "A", "B"))
</code>```

The codes

```<code>library("ggplot2")
</code>```

This works:

```<code>ggplot2::ggplot() +
  geom_segment(data = df, aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = 10)
</code>```

Result: overlapping B and A. How to specify different geom_segment size?

Does not work:

```<code>ggplot2::ggplot() +
  geom_segment(data = df, aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = c(10,12,10,12))
</code>```

Error: Aesthetics must be either length 1 or the same as the data (2):
  size

答:
```<code>ggplot2::ggplot() +
  geom_segment(data = df[df$type=="A", ], aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = 12)+
  geom_segment(data = df[df$type=="B", ], aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = 6)
</code>```

Body:
I'm plotting with ggplot a data frame of different actions (A,B) not mutually exclusive and have multiple Ids.
The activities often overlap within an Id, which might cause that some are not visible.

The data

df <- data.frame(id = c("id1", "id1", "id2", "id2"), x1 = c(10, 9, 12, 12 ), x2 = c(16, 17, 15, 19), type = c("A", "B", "A", "B"))

The codes

library("ggplot2")

This works:

ggplot2::ggplot() +
  geom_segment(data = df, aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = 10)

Result: overlapping B and A. How to specify different geom_segment size?

Does not work:

ggplot2::ggplot() +
  geom_segment(data = df, aes(colour = type, x = x1, xend = x2, y = id, yend = id), size = c(10,12,10,12))

Error: Aesthetics must be either length 1 or the same as the data (2):
  size


问:
Behavior of Async logger in log4j2
My log4j2.xml contains both sync and async loggers. However, when I use the async loggers I could only get the first (out of 5) log.debug statement to be printed.

Update 3/28 --
If I introduce a Thread.sleep(1) before the log.debug calls..  then I am able to get all the debug messages logged via Async logger --> Rewrite Appender --> Rolling File Appender But not sure how to achieve this without that sleep statement..

```<code><Configuration status="WARN" packages="com.loggy.test">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>

    <!--  Custom Appender Approach below -->
    <Stub name="myapp" fileName="/Users/loggy/logs/myapp.log"
                 filePattern="logs/myapp-%d{MM-dd-yyyy}.log.gz">
         <RegexFilter regex=".* special_log .*" onMatch="ACCEPT" onMismatch="DENY"/>
        <PatternLayout>
                    <pattern>%d %p %c{1.} [%t] %m%n</pattern>
          </PatternLayout>
          <TimeBasedTriggeringPolicy />
    </Stub>
    <!--  Custom Appender Approach above ends here -->

    <RollingFile name="RollingFile" fileName="/Users/loggy/logs/roll_file_app.log"
                 filePattern="logs/app-%d{MM-dd-yyyy}.log.gz">
           <PatternLayout>
                    <pattern>%d %p %c{1.} [%t] %m%n</pattern>
          </PatternLayout>
          <TimeBasedTriggeringPolicy />
    </RollingFile>

    <Rewrite name="Rewrite" ignoreExceptions = "false">
        <CookieAppenderPolicy cookieNeeded="true">
        </CookieAppenderPolicy>
        <AppenderRef ref="RollingFile"/>
    </Rewrite>
  </Appenders>
    <Loggers>
        <AsyncLogger name="com.loggy.test" level="debug" includeLocation="true">
            <AppenderRef ref="Rewrite" />
        </AsyncLogger>
    <Root level="trace">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

package com.loggy.test;

public class TestJ {
    @Inject
    public static void main(String[] args)
    {
        final Logger log4j = LogManager.getLogger(TestJ.class
                .getName());

        log4j.trace(" special_log Trace");

/* When Async logger is used, Only this line below gets printed to the Rewrite Appender and hence to the Rolling File appender */

        log4j.debug(" special_log debug published!");

    log4j.info(" special_log test info");

    log4j.debug(" sd_log test info");

   /* Following lines NEVER gets published to the rolling file appender or to the Rewrite Appender */

    log4j.debug(" special_log debug 2");

    log4j.debug(" special_log debug 3");

    log4j.debug(" special_log debug 4");

    log4j.debug(" special_log debug 5");

}
</code>```

However, if I include the <AppenderRef ref="Rewrite" /> outside the <AsyncLogger> then I get all the lines published.

Any thoughts as to what should be changed with the log4j2.xml so that I get all the appropriate lines when I use the AsyncLogger?

I also noticed that inside log4j2 package theAsyncLoggerConfig.java class the code never gets to the super.callAppenders(event);.

I am assuming that the super.callAppenders(event) has to work for the referenced appenders to be called? How can I make this line be executed via the log4j2.xml?

```<code>/**  AsyncLoggerConfig.java
 * Passes on the event to a separate thread that will call
 * {@link #asyncCallAppenders(LogEvent)}.
 */
@Override
protected void callAppenders(final LogEvent event) {
    // populate lazily initialized fields
    event.getSource();

event.getThreadName();

// pass on the event to a separate thread
if (!helper.callAppendersFromAnotherThread(event)) {
    super.callAppenders(event);
}
}
</code>```

答: Looks like this is due to application's shutdown event shutting down the async log threads that haven't finished writing. Same issue as described here - [shutdown hook called too early] https://issues.apache.org/jira/browse/LOG4J2-658. </p>

Title: Behavior of Async logger in log4j2

Body:
My log4j2.xml contains both sync and async loggers. However, when I use the async loggers I could only get the first (out of 5) log.debug statement to be printed.

Update 3/28 --
If I introduce a Thread.sleep(1) before the log.debug calls..  then I am able to get all the debug messages logged via Async logger --> Rewrite Appender --> Rolling File Appender But not sure how to achieve this without that sleep statement..

<Configuration status="WARN" packages="com.loggy.test">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>

    <Stub name="myapp" fileName="/Users/loggy/logs/myapp.log"
                 filePattern="logs/myapp-%d{MM-dd-yyyy}.log.gz">
         <RegexFilter regex=".* special_log .*" onMatch="ACCEPT" onMismatch="DENY"/>
        <PatternLayout>
                    <pattern>%d %p %c{1.} [%t] %m%n</pattern>
          </PatternLayout>
          <TimeBasedTriggeringPolicy />
    </Stub>

    <RollingFile name="RollingFile" fileName="/Users/loggy/logs/roll_file_app.log"
                 filePattern="logs/app-%d{MM-dd-yyyy}.log.gz">
           <PatternLayout>
                    <pattern>%d %p %c{1.} [%t] %m%n</pattern>
          </PatternLayout>
          <TimeBasedTriggeringPolicy />
    </RollingFile>

    <Rewrite name="Rewrite" ignoreExceptions = "false">
        <CookieAppenderPolicy cookieNeeded="true">
        </CookieAppenderPolicy>
        <AppenderRef ref="RollingFile"/>
    </Rewrite>
  </Appenders>
    <Loggers>
        <AsyncLogger name="com.loggy.test" level="debug" includeLocation="true">
            <AppenderRef ref="Rewrite" />
        </AsyncLogger>
    <Root level="trace">
      <AppenderRef ref="Console"/>
    </Root>
  </Loggers>
</Configuration>

package com.loggy.test;

public class TestJ {
    @Inject
    public static void main(String[] args)
    {
        final Logger log4j = LogManager.getLogger(TestJ.class
                .getName());

        log4j.trace(" special_log Trace");

/* When Async logger is used, Only this line below gets printed to the Rewrite Appender and hence to the Rolling File appender */

        log4j.debug(" special_log debug published!");

    log4j.info(" special_log test info");

    log4j.debug(" sd_log test info");

   /* Following lines NEVER gets published to the rolling file appender or to the Rewrite Appender */

    log4j.debug(" special_log debug 2");

    log4j.debug(" special_log debug 3");

    log4j.debug(" special_log debug 4");

    log4j.debug(" special_log debug 5");

}

However, if I include the <AppenderRef ref="Rewrite" /> outside the <AsyncLogger> then I get all the lines published.

Any thoughts as to what should be changed with the log4j2.xml so that I get all the appropriate lines when I use the AsyncLogger?

I also noticed that inside log4j2 package theAsyncLoggerConfig.java class the code never gets to the super.callAppenders(event);.

I am assuming that the super.callAppenders(event) has to work for the referenced appenders to be called? How can I make this line be executed via the log4j2.xml?

/**  AsyncLoggerConfig.java
 * Passes on the event to a separate thread that will call
 * {@link #asyncCallAppenders(LogEvent)}.
 */
@Override
protected void callAppenders(final LogEvent event) {
    // populate lazily initialized fields
    event.getSource();

event.getThreadName();

// pass on the event to a separate thread
if (!helper.callAppendersFromAnotherThread(event)) {
    super.callAppenders(event);
}
}


问:
Git format-patch to be svn compatible?
Is there any way to get a patch created with git format-patch to be svn compatible so that I can submit it to an svn repo?

I'm working off an svn repo on github and want to submit my changes back to the main repo. I need to create a patch to do this, however the patch cannot be applied since git formats that patch differently then svn. Is there some secret I haven't discovered yet?

UPDATE: Although currently there exists no script or native git way to do this, I did managed to find a post from earlier this year about how to manually accomplish this. I have followed the instructions and had success getting my git patches to work with svn.

If someone could take a stab at writing a script to accomplish this and contribute to the git project, I'm everyone would be much appreciated.

http://kerneltrap.org/mailarchive/git/2008/1/15/570308/thread#mid-570308

答:
Here's a helper script for making a diff against the the latest svn changeset and the given commit:
http://www.mail-archive.com/dev@trafficserver.apache.org/msg00864.html</p>

```<code>#!/bin/sh
#
# git-svn-diff
# Generate an SVN-compatible diff against the tip of the tracking branch
TRACKING_BRANCH=`git config --get svn-remote.svn.fetch | sed -e 's/.*:refs\/remotes\///'`
REV=`git svn find-rev $(git rev-list --date-order --max-count=1 $TRACKING_BRANCH)`
git diff --no-prefix $(git rev-list --date-order --max-count=1 $TRACKING_BRANCH) $* |
sed -e "s/^+++ .*/&    (working copy)/" -e "s/^--- .*/&    (revision $REV)/" \
-e "s/^diff --git [^[:space:]]*/Index:/" \
-e "s/^index.*/===================================================================/"
</code>```

Title: Git format-patch to be svn compatible?

Body:
Here's a helper script for making a diff against the the latest svn changeset and the given commit:
http://www.mail-archive.com/dev@trafficserver.apache.org/msg00864.html

#!/bin/sh
#
# git-svn-diff
# Generate an SVN-compatible diff against the tip of the tracking branch
TRACKING_BRANCH=`git config --get svn-remote.svn.fetch | sed -e 's/.*:refs\/remotes\///'`
REV=`git svn find-rev $(git rev-list --date-order --max-count=1 $TRACKING_BRANCH)`
git diff --no-prefix $(git rev-list --date-order --max-count=1 $TRACKING_BRANCH) $* |
sed -e "s/^+++ .*/&    (working copy)/" -e "s/^--- .*/&    (revision $REV)/" \
-e "s/^diff --git [^[:space:]]*/Index:/" \
-e "s/^index.*/===================================================================/"


问:
len() of a numpy array in python
If I use len(np.array([[2,3,1,0], [2,3,1,0], [3,2,1,1]])), I get back 3.

Why is there no argument for len() about which axis I want the length of in multidimensional arrays? This is alarming.  Is there an alternative?

答:
Easy. Use .shape.

```<code>>>> nparray.shape
(5, 6) #Returns a tuple of array dimensions.
</code>```

Title: len() of a numpy array in python

Body:
Easy. Use .shape.

>>> nparray.shape
(5, 6) #Returns a tuple of array dimensions.


问:
Visual studio code extension: How can I add error markers to files in the explorer?
I have written a validator for my vscode extension, which uses a DiagnosticCollection to set errors for files. This works and the errors are shown when a file is opened.

I would now like to mark files in the explorer, so that it is easy to find files with errors. Here is an example]of how it looks in Eclipse:

Is it possible to do this in a vscode extension? Is there already an extension doing this?

答:
Unfortunately, you can't do that.

There is an open issue asking something related to Git, but not as open as you want. Maybe using the API described in this another issue you could create a new panel with the marked files.

It is still experimental, BTW...


问:
Vue directive to access the Vue instance?
How do you access the Vue instance from a directive?

I have this HTML

```<code><div id='vueApp' v-init='my initial data from server-side'>
</code>```

and this script

```<code>var app = new Vue({
    el: '#vueApp',
    data: {
        myData: null
    }
});

Vue.directive('init', function(el, binding) {
    app.myData = binding.value;
});
</code>```

It throws this error:

Failed to resolve directive: init

答:
Your particular error is because the directive is created after the Vue.

For this particular directive, you could access the Vue through vnode.context.

```<code>Vue.directive('init', {
  bind(el, binding, vnode){
    vnode.context.myData = binding.expression;
  }
});

const app = new Vue({
    el: '#vueApp',
    data: {
        myData: null
    }
});
</code>```

Example.

You might also consider using vnode.context.$root.

Post Comment Edit

You could also just do this:

```<code>const initialData = {
    someData: "Hello Vue!"
};

const app = new Vue({
    el: '#vueApp',
    data: {
        myData: intialData
    }
});
</code>```

Body:
How do you access the Vue instance from a directive?

I have this HTML

and this script

var app = new Vue({
    el: '#vueApp',
    data: {
        myData: null
    }
});

Vue.directive('init', function(el, binding) {
    app.myData = binding.value;
});

It throws this error:

Failed to resolve directive: init

Body:
Your particular error is because the directive is created after the Vue.

For this particular directive, you could access the Vue through vnode.context.

Vue.directive('init', {
  bind(el, binding, vnode){
    vnode.context.myData = binding.expression;
  }
});

const app = new Vue({
    el: '#vueApp',
    data: {
        myData: null
    }
});

Example.

You might also consider using vnode.context.$root.

Post Comment Edit

You could also just do this:

const initialData = {
    someData: "Hello Vue!"
};

const app = new Vue({
    el: '#vueApp',
    data: {
        myData: intialData
    }
});


问:
Upload file with tags through OwnCloud or NextCloud API
I have a database of files that are already tagged. Now, I would like to upload these files to an OwnCloud or NextCloud Server and pass on my already existing tags so that they show up as tags in the respective system. I wasnt able yet to find a way how I could do that in the documentation, does anyone have an idea how I could do it?

Thanks!

答:
I just made available the source code of the (remote) file tagging micro-service for Nextcloud on github (https://github.com/julianthome/taggy). The implementation consists of two parts: 1) the taggy client for uploading files to the Nextcloud server, and for invoking the taggy server; 2) the taggy server for adding specified tags to uploaded files.

I will polish the code further within the next days. I am also planning to add SSL support which is important because username and password are currently transmitted unencrypted to the taggy server. The server uses these credentials in order to check whether the user can be properly authenticated before tagging any files.

Please let me know if you have other ideas, suggestions or feedback ;)

Kind regards


问:
What is the easy way to display menu after clicked on Icon in mobile device?
I have to display a menu on a mobile device. When the user clicked on menubar icon than menu will display with the full background color on screen and cross sign will appear. after clicked on cross sign menu will close. I tried some code which is not working properly. I need easy and best answer. Would help me in this?

$(function() {
  var menuVisible = false;
  $('#menuBtn').click(function() {
  $("#main-list").slideDown();
  //manu bar will hide after clicked
  $('#menuBtn').css({'display': 'none'});

  //cross sign will displya after clicked menu bar
  $('#menu-close-sign').css({'display': 'block' });
  $('#menuBtn').click(function() {
  $("#main-list").show();
  $('#menu-close-sign').show();
  $('#menu').css({'background-color': '#F4FAFF', 'height': '100%'});
  $('#menuBtn').hide();
  });

  $('#menu-close-sign').click(function() {
  $("#main-list").hide();
  $('#menu-close-sign').hide();
  $('#menuBtn').show();
  $('#menu').css({'background-color': '#fff', 'height': '50px'});
  // $(".right_side").slideUp();
  });

  if (menuVisible) {
  $('.right_side').css({'display': 'none' });
  menuVisible = false;
  return;
  }
  $('.right_side').css({'display': 'block'});
  $('.menu').css({'background-color': '#F4FAFF', 'height': '100%'});
  menuVisible = true;
  });
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
    margin: 0;
    padding: 0;
   }
  #menu
  {
   background-color: #fff;
   height: 70px;
   z-index: 999;
   webkit-box-shadow: 0 3px 4px rgba(0, 0, 0, 0.24);
  -moz-box-shadow: 0 3px 4px rgba(0, 0, 0, 0.24);
  box-shadow: 0 3px 4px rgba(0, 0, 0, 0.24);
  }
  .menu-section
  {
   padding: 0 30px;
  }
  .menu-left-side
  {
   float: left;
  }

  .icon-bar-menu, #menu-close-sign
  {
  display: none;
  }
  .menu-right-side
  {
   float: right;
   margin: 22px;
  }

  ul#main-list{
  list-style: none;
  text-transform: uppercase;

  }

  ul#main-list li{
   float: left;
   margin: 0 20px;
  }

  ul#main-list li a{
   color: #212F3D;

  }

  ul#main-list li a:hover
  {
   color: #ffb902;
  }

  @media only screen and (max-width: 600px) {
  .menu-left-side
  {
  float:none;
  padding: 0;
  margin: 0;
  }

  .icon-bar-menu
  {
  position: absolute;
  right: 10px;
  top: 9px;
  padding: 10px 20px;
  cursor: pointer;
  display: block;
  }
  .icon-bar-menu i{
  font-size: 25px;
  color: #000;
  }

  .menu-right-side
  {
  margin:20px 0;
  }
  ul#main-list
  {
  padding:0;
  }

  ul#main-list li, .menu-right-side
  {
  float:none;
  }
  ul#main-list li
  {
  margin:20px 0;
  }
  #menu
  {
  height:100%;
  width: 100%;
  background-color: #64d0e7 !important;
  }

  ul#main-list li a
  {
  color:#000;
  }
  #menu-close-sign
  {
  display:none;
  }
  }</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>

logo

 home

about

services

news

contact

```

答:
You can simplify your Javascript if you separate the menu icon from the navigation div. On clicking the menu icon, the entire navigation div will show/hide. You can then use media queries to show/hide the mobile icon depending on the screen size.

You will need to tweak the CSS in order to get the close icon in the same position as the menu icon, but that should be fairly easy.

https://codepen.io/cassyj122/pen/NpOXbV

HTML

```<code><script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="container">
  <!--menu-->
  <span id="menuBtn"><i class="fa fa-bars" aria-hidden="true"></i></span>
  <div id="menu">
    <div class="menu-section">
      <div class="menu-left-side">
        <div class="logo-section">
          <a href="index.php"><h2>logo</h2></a>
        </div>
        <!--logo-section-->
      </div>
      <!--menu-left-side-->
      <div class="menu-right-side">
        <div class="icon-bar-menu">
          <span id="menu-close-sign"><i class="fa fa-times" aria-hidden="true"></i></span>
        </div>
        <ul id="main-list">
          <li> <a href="index.php">home</a></li>
          <li><a href="about.php">about</a></li>
          <li><a href="services.php">services</a></li>
          <li><a href="news.php">news</a></li>
          <li><a href="contactus.php">contact</a></li>
        </ul>
        <!--main-list-->

      </div>
      <!--menu-right-side-->
    </div>
    <!--menu-section-->
  </div>
  <!--menu-->
</div>

#menu {
  background-color: #64d0e7;
  width: 100%;
}

#menuBtn {
  position: absolute;
  font-size: 25px;
  top: 0;
  right: 0;
  display: none;
  z-index: -1;
}

#menu-close-sign {
  position: absolute;
  top: 0;
  display: none;
  left: 0;
}

#container {
  width: 100%;
  position: relative;
}

body {
  margin: 0;
  padding: 0;
}
</code>```

CSS

```<code>#menu {
  background-color: #fff;
  height: 70px;
  z-index: 999;
  webkit-box-shadow: 0 3px 4px rgba(0, 0, 0, 0.24);
  -moz-box-shadow: 0 3px 4px rgba(0, 0, 0, 0.24);
  box-shadow: 0 3px 4px rgba(0, 0, 0, 0.24);
}

.menu-section {
  padding: 0 30px;
}

.menu-left-side {
  float: left;
}

.menu-right-side {
  float: right;
  margin: 22px;
}

ul#main-list {
  list-style: none;
  text-transform: uppercase;
}

ul#main-list li {
  float: left;
  margin: 0 20px;
}

ul#main-list li a {
  color: #212F3D;
}

ul#main-list li a:hover {
  color: #ffb902;
}

@media only screen and (max-width: 600px) {
  #menuBtn {
    display: block;
  }
  #menu-close-sign {
    display: block;
  }
  #menu {
    display: none;
  }
  .menu-left-side {
    float: none;
    padding: 0;
    margin: 0;
  }
  .icon-bar-menu {
    position: absolute;
    right: 10px;
    top: 9px;
    padding: 10px 20px;
    cursor: pointer;
    display: block;
  }
  .icon-bar-menu i {
    font-size: 25px;
    color: #000;
  }
  .menu-right-side {
    margin: 20px 0;
  }
  ul#main-list {
    padding: 0;
  }
  ul#main-list li,
  .menu-right-side {
    float: none;
  }
  ul#main-list li {
    margin: 20px 0;
  }
  #menu {
    height: 100%;
    width: 100%;
    background-color: #64d0e7 !important;
  }
  ul#main-list li a {
    color: #000;
  }
}
</code>```

Javascript

```<code>$(function() {
  $('#menuBtn').click(function() {
    $('#menu').show();
  });
  $('#menu-close-sign').click(function() {
    $('#menu').hide();
  });

});

$(window).resize(function() {
  if ($(window).width() > 600) {
    $('#menu').show();
  } else {
    $('#menu').hide();
  }
});
</code>```

Body:
I have to display a menu on a mobile device. When the user clicked on menubar icon than menu will display with the full background color on screen and cross sign will appear. after clicked on cross sign menu will close. I tried some code which is not working properly. I need easy and best answer. Would help me in this?

$(function() {
  var menuVisible = false;
  $('#menuBtn').click(function() {
  $("#main-list").slideDown();
  //manu bar will hide after clicked
  $('#menuBtn').css({'display': 'none'});

  //cross sign will displya after clicked menu bar
  $('#menu-close-sign').css({'display': 'block' });
  $('#menuBtn').click(function() {
  $("#main-list").show();
  $('#menu-close-sign').show();
  $('#menu').css({'background-color': '#F4FAFF', 'height': '100%'});
  $('#menuBtn').hide();
  });

  $('#menu-close-sign').click(function() {
  $("#main-list").hide();
  $('#menu-close-sign').hide();
  $('#menuBtn').show();
  $('#menu').css({'background-color': '#fff', 'height': '50px'});
  // $(".right_side").slideUp();
  });

  if (menuVisible) {
  $('.right_side').css({'display': 'none' });
  menuVisible = false;
  return;
  }
  $('.right_side').css({'display': 'block'});
  $('.menu').css({'background-color': '#F4FAFF', 'height': '100%'});
  menuVisible = true;
  });
  });

body{
    margin: 0;
    padding: 0;
   }
  #menu
  {
   background-color: #fff;
   height: 70px;
   z-index: 999;
   webkit-box-shadow: 0 3px 4px rgba(0, 0, 0, 0.24);
  -moz-box-shadow: 0 3px 4px rgba(0, 0, 0, 0.24);
  box-shadow: 0 3px 4px rgba(0, 0, 0, 0.24);
  }
  .menu-section
  {
   padding: 0 30px;
  }
  .menu-left-side
  {
   float: left;
  }

  .icon-bar-menu, #menu-close-sign
  {
  display: none;
  }
  .menu-right-side
  {
   float: right;
   margin: 22px;
  }

  ul#main-list{
  list-style: none;
  text-transform: uppercase;

  }

  ul#main-list li{
   float: left;
   margin: 0 20px;
  }

  ul#main-list li a{
   color: #212F3D;

  }

  ul#main-list li a:hover
  {
   color: #ffb902;
  }

  @media only screen and (max-width: 600px) {
  .menu-left-side
  {
  float:none;
  padding: 0;
  margin: 0;
  }

  .icon-bar-menu
  {
  position: absolute;
  right: 10px;
  top: 9px;
  padding: 10px 20px;
  cursor: pointer;
  display: block;
  }
  .icon-bar-menu i{
  font-size: 25px;
  color: #000;
  }

  .menu-right-side
  {
  margin:20px 0;
  }
  ul#main-list
  {
  padding:0;
  }

  ul#main-list li, .menu-right-side
  {
  float:none;
  }
  ul#main-list li
  {
  margin:20px 0;
  }
  #menu
  {
  height:100%;
  width: 100%;
  background-color: #64d0e7 !important;
  }

  ul#main-list li a
  {
  color:#000;
  }
  #menu-close-sign
  {
  display:none;
  }
  }

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>

logo

 home

about

services

news

contact

Body:
You can simplify your Javascript if you separate the menu icon from the navigation div. On clicking the menu icon, the entire navigation div will show/hide. You can then use media queries to show/hide the mobile icon depending on the screen size.

You will need to tweak the CSS in order to get the close icon in the same position as the menu icon, but that should be fairly easy.

https://codepen.io/cassyj122/pen/NpOXbV

HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="container">
  <!--menu-->
  <span id="menuBtn"><i class="fa fa-bars" aria-hidden="true"></i></span>
  <div id="menu">
    <div class="menu-section">
      <div class="menu-left-side">
        <div class="logo-section">
          <a href="index.php"><h2>logo</h2></a>
        </div>
        <!--logo-section-->
      </div>
      <!--menu-left-side-->
      <div class="menu-right-side">
        <div class="icon-bar-menu">
          <span id="menu-close-sign"><i class="fa fa-times" aria-hidden="true"></i></span>
        </div>
        <ul id="main-list">
          <li> <a href="index.php">home</a></li>
          <li><a href="about.php">about</a></li>
          <li><a href="services.php">services</a></li>
          <li><a href="news.php">news</a></li>
          <li><a href="contactus.php">contact</a></li>
        </ul>
        <!--main-list-->

      </div>
      <!--menu-right-side-->
    </div>
    <!--menu-section-->
  </div>
  <!--menu-->
</div>

#menu {
  background-color: #64d0e7;
  width: 100%;
}

#menuBtn {
  position: absolute;
  font-size: 25px;
  top: 0;
  right: 0;
  display: none;
  z-index: -1;
}

#menu-close-sign {
  position: absolute;
  top: 0;
  display: none;
  left: 0;
}

#container {
  width: 100%;
  position: relative;
}

body {
  margin: 0;
  padding: 0;
}

CSS

#menu {
  background-color: #fff;
  height: 70px;
  z-index: 999;
  webkit-box-shadow: 0 3px 4px rgba(0, 0, 0, 0.24);
  -moz-box-shadow: 0 3px 4px rgba(0, 0, 0, 0.24);
  box-shadow: 0 3px 4px rgba(0, 0, 0, 0.24);
}

.menu-section {
  padding: 0 30px;
}

.menu-left-side {
  float: left;
}

.menu-right-side {
  float: right;
  margin: 22px;
}

ul#main-list {
  list-style: none;
  text-transform: uppercase;
}

ul#main-list li {
  float: left;
  margin: 0 20px;
}

ul#main-list li a {
  color: #212F3D;
}

ul#main-list li a:hover {
  color: #ffb902;
}

@media only screen and (max-width: 600px) {
  #menuBtn {
    display: block;
  }
  #menu-close-sign {
    display: block;
  }
  #menu {
    display: none;
  }
  .menu-left-side {
    float: none;
    padding: 0;
    margin: 0;
  }
  .icon-bar-menu {
    position: absolute;
    right: 10px;
    top: 9px;
    padding: 10px 20px;
    cursor: pointer;
    display: block;
  }
  .icon-bar-menu i {
    font-size: 25px;
    color: #000;
  }
  .menu-right-side {
    margin: 20px 0;
  }
  ul#main-list {
    padding: 0;
  }
  ul#main-list li,
  .menu-right-side {
    float: none;
  }
  ul#main-list li {
    margin: 20px 0;
  }
  #menu {
    height: 100%;
    width: 100%;
    background-color: #64d0e7 !important;
  }
  ul#main-list li a {
    color: #000;
  }
}

Javascript

$(function() {
  $('#menuBtn').click(function() {
    $('#menu').show();
  });
  $('#menu-close-sign').click(function() {
    $('#menu').hide();
  });

});

$(window).resize(function() {
  if ($(window).width() > 600) {
    $('#menu').show();
  } else {
    $('#menu').hide();
  }
});


问:
Create HCK and HLK tests for .inf file drivers required?
We have an hardware device that is used by many customers. We support windows 7 - 10 OS's. With this device, a driver and software is included. The device is is built in China, they eventually use a Cypress USB driver. The .inf file can be found below. The Chinese company then adds some references for their own device inside the .inf file, which magically makes it work, in combination with their software.

My background is not C++ or any hardware related development. Now we have customers receiving code 52 error when the driver is installed and plugged in.

Windows cannot verify the digital signature for this file. A recent hardware or software change might have installed a file that is signed incorrectly or damaged, or that might be malicious software from an unknown source.

So after a lot of googling it seems like the Chinese company didn't keep up with the latest standards for drivers. Newer devices have secure boot enabled which blocks drivers that are not signed correctly.

Now I am wondering a few things:

Would getting my driver though the various HCK/HLK/WLK test be required? My driver is simply a .inf file, .sys file and a generated .cat file.

Would generating a .cab file with makecab be sufficient?

Is my driver actually a kernel mode driver or user mode driver?

This will of course be tested: but would signing the cat file with an EV certificate solve this problem already?

Getting though the HCK and HLK test seems a lot of work for a simple .inf file. While the guidelines are pretty clear, I am not entirely sure if there are specific things I don't need to do in my scenario.

.inf file code:

```<code>; Installation INF for the Cypress Generic USB Driver for Windows 2000
; Processor support for x86 based platforms.
;
; (c) Copyright 2011 Cypress Semiconductor Corporation
;

[Version]
Signature="$WINDOWS NT$"
Class=USB
ClassGUID={36FC9E60-C465-11CF-8056-444553540000}
provider=%CYUSB_Provider%
CatalogFile=CYUSB.cat
DriverVer=10/17/2011,3.4.7.000

[SourceDisksNames]
1=%CYUSB_Install%,,,

[SourceDisksFiles]
CYUSB.sys = 1

[DestinationDirs]
CYUSB.Files.Ext = 10,System32\Drivers

[ControlFlags]
ExcludeFromSelect = *

[Manufacturer]
%CYUSB_Provider%=Device,NT,NTx86,NTamd64

;for all platforms
[Device]
;%VID_XXXX&PID_XXXX.DeviceDesc%=CyUsb, USB\VID_XXXX&PID_XXXX

;for windows 2000 non intel platforms
[Device.NT]
;%VID_XXXX&PID_XXXX.DeviceDesc%=CyUsb, USB\VID_XXXX&PID_XXXX

;for x86 platforms
[Device.NTx86]
;%VID_XXXX&PID_XXXX.DeviceDesc%=CyUsb, USB\VID_XXXX&PID_XXXX

;for x64 platforms
[Device.NTamd64]
;%VID_XXXX&PID_XXXX.DeviceDesc%=CyUsb, USB\VID_XXXX&PID_XXXX

[CYUSB]
CopyFiles=CYUSB.Files.Ext
AddReg=CyUsb.AddReg

[CYUSB.HW]
AddReg=CYUSB.AddReg.Guid

[CYUSB.Services]
Addservice = CYUSB,2,CYUSB.AddService

[CYUSB.NT]
CopyFiles=CYUSB.Files.Ext
AddReg=CyUsb.AddReg

[CYUSB.NT.HW]
AddReg=CYUSB.AddReg.Guid

[CYUSB.NT.Services]
Addservice = CYUSB,2,CYUSB.AddService

[CYUSB.NTx86]
CopyFiles=CYUSB.Files.Ext
AddReg=CyUsb.AddReg

[CYUSB.NTx86.HW]
AddReg=CYUSB.AddReg.Guid

[CYUSB.NTx86.Services]
Addservice = CYUSB,2,CYUSB.AddService

[CYUSB.NTamd64]
CopyFiles=CYUSB.Files.Ext
AddReg=CyUsb.AddReg

[CYUSB.NTamd64.HW]
AddReg=CYUSB.AddReg.Guid

[CYUSB.NTamd64.Services]
Addservice = CYUSB,2,CYUSB.AddService

[CYUSB.AddReg]
; Deprecating - do not use in new apps to identify a CYUSB driver
HKR,,DevLoader,,*ntkern
HKR,,NTMPDriver,,CYUSB.sys
; You may optionally include a check for DriverBase in your application to check for a CYUSB driver
HKR,,DriverBase,,CYUSB.sys
HKR,"Parameters","MaximumTransferSize",0x10001,4096
HKR,"Parameters","DebugLevel",0x10001,2
HKR,,FriendlyName,,%CYUSB_Description%

[CYUSB.AddService]
DisplayName    = %CYUSB_Description%
ServiceType    = 1                  ; SERVICE_KERNEL_DRIVER
StartType      = 3                  ; SERVICE_DEMAND_START
ErrorControl   = 1                  ; SERVICE_ERROR_NORMAL
ServiceBinary  = %10%\System32\Drivers\CYUSB.sys
AddReg         = CYUSB.AddReg
LoadOrderGroup = Base

[CYUSB.Files.Ext]
CYUSB.sys

[CYUSB.AddReg.Guid]
HKR,,DriverGUID,,%CYUSB.GUID%

[Strings]
CYUSB_Provider    = "Cypress"
CYUSB_Company     = "Cypress Semiconductor Corporation"
CYUSB_Description = "Cypress Generic USB Driver"
CYUSB_DisplayName = "Cypress USB Generic"
CYUSB_Install     = "Cypress CYUSB Driver Installation Disk"
VID_XXXX&PID_XXXX.DeviceDesc="Cypress USB Generic Driver (3.4.7.000)"
CYUSB.GUID="{AE18AA60-7F6A-11d4-97DD-00010229B959}"
CYUSB_Unused      = "."
</code>```

答:
Microsoft keeps adding hurdles, you might have to sign it in their dev portal now and you need a EV cert. to sign up. There is also a difference between a clean install and a upgrade when it comes to the enforcement of secure boot!

I would recommend that you read/join the OSR mailing list, it has multiple threads dealing with the struggles of Windows 10 & SHA2 signing.

Their blog might also be useful.

Body:
We have an hardware device that is used by many customers. We support windows 7 - 10 OS's. With this device, a driver and software is included. The device is is built in China, they eventually use a Cypress USB driver. The .inf file can be found below. The Chinese company then adds some references for their own device inside the .inf file, which magically makes it work, in combination with their software.

My background is not C++ or any hardware related development. Now we have customers receiving code 52 error when the driver is installed and plugged in.

Windows cannot verify the digital signature for this file. A recent hardware or software change might have installed a file that is signed incorrectly or damaged, or that might be malicious software from an unknown source.

So after a lot of googling it seems like the Chinese company didn't keep up with the latest standards for drivers. Newer devices have secure boot enabled which blocks drivers that are not signed correctly.

Now I am wondering a few things:

Would getting my driver though the various HCK/HLK/WLK test be required? My driver is simply a .inf file, .sys file and a generated .cat file.

Would generating a .cab file with makecab be sufficient?

Is my driver actually a kernel mode driver or user mode driver?

This will of course be tested: but would signing the cat file with an EV certificate solve this problem already?

Getting though the HCK and HLK test seems a lot of work for a simple .inf file. While the guidelines are pretty clear, I am not entirely sure if there are specific things I don't need to do in my scenario.

.inf file code:

; Installation INF for the Cypress Generic USB Driver for Windows 2000
; Processor support for x86 based platforms.
;
; (c) Copyright 2011 Cypress Semiconductor Corporation
;

[Version]
Signature="$WINDOWS NT$"
Class=USB
ClassGUID={36FC9E60-C465-11CF-8056-444553540000}
provider=%CYUSB_Provider%
CatalogFile=CYUSB.cat
DriverVer=10/17/2011,3.4.7.000

[SourceDisksNames]
1=%CYUSB_Install%,,,

[SourceDisksFiles]
CYUSB.sys = 1

[DestinationDirs]
CYUSB.Files.Ext = 10,System32\Drivers

[ControlFlags]
ExcludeFromSelect = *

[Manufacturer]
%CYUSB_Provider%=Device,NT,NTx86,NTamd64

;for all platforms
[Device]
;%VID_XXXX&PID_XXXX.DeviceDesc%=CyUsb, USB\VID_XXXX&PID_XXXX

;for windows 2000 non intel platforms
[Device.NT]
;%VID_XXXX&PID_XXXX.DeviceDesc%=CyUsb, USB\VID_XXXX&PID_XXXX

;for x86 platforms
[Device.NTx86]
;%VID_XXXX&PID_XXXX.DeviceDesc%=CyUsb, USB\VID_XXXX&PID_XXXX

;for x64 platforms
[Device.NTamd64]
;%VID_XXXX&PID_XXXX.DeviceDesc%=CyUsb, USB\VID_XXXX&PID_XXXX

[CYUSB]
CopyFiles=CYUSB.Files.Ext
AddReg=CyUsb.AddReg

[CYUSB.HW]
AddReg=CYUSB.AddReg.Guid

[CYUSB.Services]
Addservice = CYUSB,2,CYUSB.AddService

[CYUSB.NT]
CopyFiles=CYUSB.Files.Ext
AddReg=CyUsb.AddReg

[CYUSB.NT.HW]
AddReg=CYUSB.AddReg.Guid

[CYUSB.NT.Services]
Addservice = CYUSB,2,CYUSB.AddService

[CYUSB.NTx86]
CopyFiles=CYUSB.Files.Ext
AddReg=CyUsb.AddReg

[CYUSB.NTx86.HW]
AddReg=CYUSB.AddReg.Guid

[CYUSB.NTx86.Services]
Addservice = CYUSB,2,CYUSB.AddService

[CYUSB.NTamd64]
CopyFiles=CYUSB.Files.Ext
AddReg=CyUsb.AddReg

[CYUSB.NTamd64.HW]
AddReg=CYUSB.AddReg.Guid

[CYUSB.NTamd64.Services]
Addservice = CYUSB,2,CYUSB.AddService

[CYUSB.AddReg]
; Deprecating - do not use in new apps to identify a CYUSB driver
HKR,,DevLoader,,*ntkern
HKR,,NTMPDriver,,CYUSB.sys
; You may optionally include a check for DriverBase in your application to check for a CYUSB driver
HKR,,DriverBase,,CYUSB.sys
HKR,"Parameters","MaximumTransferSize",0x10001,4096
HKR,"Parameters","DebugLevel",0x10001,2
HKR,,FriendlyName,,%CYUSB_Description%

[CYUSB.AddService]
DisplayName    = %CYUSB_Description%
ServiceType    = 1                  ; SERVICE_KERNEL_DRIVER
StartType      = 3                  ; SERVICE_DEMAND_START
ErrorControl   = 1                  ; SERVICE_ERROR_NORMAL
ServiceBinary  = %10%\System32\Drivers\CYUSB.sys
AddReg         = CYUSB.AddReg
LoadOrderGroup = Base

[CYUSB.Files.Ext]
CYUSB.sys

[CYUSB.AddReg.Guid]
HKR,,DriverGUID,,%CYUSB.GUID%

[Strings]
CYUSB_Provider    = "Cypress"
CYUSB_Company     = "Cypress Semiconductor Corporation"
CYUSB_Description = "Cypress Generic USB Driver"
CYUSB_DisplayName = "Cypress USB Generic"
CYUSB_Install     = "Cypress CYUSB Driver Installation Disk"
VID_XXXX&PID_XXXX.DeviceDesc="Cypress USB Generic Driver (3.4.7.000)"
CYUSB.GUID="{AE18AA60-7F6A-11d4-97DD-00010229B959}"
CYUSB_Unused      = "."


问:
How to use group_by variable as an exclusion value with dplyr?
Let's say I have the following data frame:

```<code>(dat  = data_frame(v1 = c(rep("a", 3), rep("b", 3), rep("c", 4)), v2 = 1:10))
# A tibble: 10 × 2
#       v1    v2
#    <chr> <int>
# 1      a     1
# 2      a     2
# 3      a     3
# 4      b     4
# 5      b     5
# 6      b     6
# 7      c     7
# 8      c     8
# 9      c     9
# 10     c    10
</code>```

What I want to be able to do is compute a sum for each group (i.e. "a", "b", and "c") that is equal to the sum of v2 where v1 is not equal to the grouping value. So it should look like this:

```<code># A tibble: 3 × 2
#      v1   sum
#   <chr> <int>
# 1     a    49
# 2     b    40
# 3     c    21
</code>```

Based on what I've been seeing online, this looks like a job for do, but I can't wrap my head around how to achieve this. I thought it would look something like this:

```<code>x %>%
  group_by(v1) %>%
  do(data.frame(sum=sum(.$v2[x$v1 != unique(.$v1)])))
</code>```

But this just gives me a dataframe with sum equal to NA for all three groups. How would I go about doing this?

答:
Keeping it simple:

```<code>dat %>% group_by(v1) %>% summarize(foo = sum(dat$v2) - sum(v2))
</code>```

This is crass if you are in the middle of a long dplyr chain and have modified dat. (But then, why not relax and just store your data?)

Body:
Let's say I have the following data frame:

(dat  = data_frame(v1 = c(rep("a", 3), rep("b", 3), rep("c", 4)), v2 = 1:10))
# A tibble: 10 × 2
#       v1    v2
#    <chr> <int>
# 1      a     1
# 2      a     2
# 3      a     3
# 4      b     4
# 5      b     5
# 6      b     6
# 7      c     7
# 8      c     8
# 9      c     9
# 10     c    10

What I want to be able to do is compute a sum for each group (i.e. "a", "b", and "c") that is equal to the sum of v2 where v1 is not equal to the grouping value. So it should look like this:

# A tibble: 3 × 2
#      v1   sum
#   <chr> <int>
# 1     a    49
# 2     b    40
# 3     c    21

Based on what I've been seeing online, this looks like a job for do, but I can't wrap my head around how to achieve this. I thought it would look something like this:

x %>%
  group_by(v1) %>%
  do(data.frame(sum=sum(.$v2[x$v1 != unique(.$v1)])))

But this just gives me a dataframe with sum equal to NA for all three groups. How would I go about doing this?

Body:
Keeping it simple:

dat %>% group_by(v1) %>% summarize(foo = sum(dat$v2) - sum(v2))

This is crass if you are in the middle of a long dplyr chain and have modified dat. (But then, why not relax and just store your data?)


问:
WCF: How to create a method that will allow me to pass in and operate on an array of proxies with various types?
I was wondering if anyone can come up with a way that I can set the ClientCredentials of all my proxies using a single method call. For example, if I have:

```<code>public class ServiceOneClient : ClientBase<IServiceOne>, IServiceOne
...

public class ServiceTwoClient : ClientBase<IServiceTwo>, IServiceTwo
...
</code>```

how can I create a method that I can call like this?

```<code>SetProxyCredentials(serviceOneClient, serviceTwoClient);
</code>```

答:
not sure if its possible through an array since each proxy will have its own interface but maybe this would help :

```<code>public static void SetProxyCredential<T>(ClientBase<T> proxy) where T : class
{
  //set credential
}
</code>```

you could then call SetProxyCrendential<IMyInterface>(proxy);

Body:
I was wondering if anyone can come up with a way that I can set the ClientCredentials of all my proxies using a single method call. For example, if I have:

public class ServiceOneClient : ClientBase<IServiceOne>, IServiceOne
...

public class ServiceTwoClient : ClientBase<IServiceTwo>, IServiceTwo
...

how can I create a method that I can call like this?

SetProxyCredentials(serviceOneClient, serviceTwoClient);

Body:
not sure if its possible through an array since each proxy will have its own interface but maybe this would help :

public static void SetProxyCredential<T>(ClientBase<T> proxy) where T : class
{
  //set credential
}

you could then call SetProxyCrendential<IMyInterface>(proxy);


问:
How to send FB notification at specific time to different time zones using PHP SDK?
My website is relaying heavily on FB. There is only FB login and all comunication with members happens through facebook. Users are notified using FB api about activities in site that they would care about. Users can choose between three options:

Never notify

Notify once a day(for MVP version I am good with hardcoded time, lets say, 9 in moorning, but probably aiming for possability for user to choose when they want to be notified about everything that has happened in last 24h)

Notify on-the-go

First and third are easy, my concerns lies on second option. Basically its similar to newsletter. Here is my idea of this process so far:

When ever some action that is of concern for user happens, notification about that is saved in database

if user logs into site before scheduled time notification is marked as read

if user does not log into site before scheduled time unread notifications will be included in cron job

every hour cron job is run. It matches the users time zone with current time so that only only users that are awake will recive notification. Users will get basic "there are new things in site" notification.

Problem: From FB I can get only offset as integer, not actual timezone. I have spent some time on reading about timezone and different formats and it strikes me that FB call to get timezone results in offset.

Sending newletter(notification in my case) to different time zones is complex but there are a lot of good resource available. However it seems that best way to do that is save user time zone as TZ database format America/New_York. So my question is dual

Is it possible to somehow get user time zone in TZ from facebook?

If not, what would be my best actions? Whats important is that I dont care if user dont get notification at exact time. With that I mean that I dont care about summer time difference. it would be ok if user could chose between moorning, afternoon and evening(and if for example he chooses moorning, then he would get notification 9:00 +/- 1 hour). I am open to ideas, at given point my main consern is to get MVP running.

答:
```<code>$ch = curl_init("https://graph.facebook.com/v2.6/" . $user_id . "?fields=timezone&access_token=" . $fb_access_token);
curl_setopt_array($ch, array(
    CURLOPT_RETURNTRANSFER => 1
));

$result = curl_exec($ch);
</code>```

You can get the user timezone from the open graph api.

For converting the offset to an actual timezone see the answer here: Convert UTC offset to timezone or date

Body:
$ch = curl_init("https://graph.facebook.com/v2.6/" . $user_id . "?fields=timezone&access_token=" . $fb_access_token);
curl_setopt_array($ch, array(
    CURLOPT_RETURNTRANSFER => 1
));

$result = curl_exec($ch);

You can get the user timezone from the open graph api.

For converting the offset to an actual timezone see the answer here: Convert UTC offset to timezone or date