问:
Optional parameters in cursor where clause
I have the following sample query which takes values from procedure parameters. The parameter can be either passed or default to null.

```<code>SELECT * FROM table
              WHERE( table_term_code = '201931'
              OR (table_term_code = '201931' and table_DETL_CODE ='CA02')
              OR ( table_term_code = '201931' and table_ACTIVITY_DATE = sysdate)
              OR ( table_term_code = '201931' and table_SEQNO = NULL));
</code>```

i.e the user can input term code and not input any other parameter, or can input term code and  table_DETL_CODE and not any other input parameter.

Same goes for the other 2 or conditions.

If a term code is passed and table_DETL_CODE is null, the query should return all the values for that term_code, whereas this query returns null.

Is there a way to achieve this without case or if conditions in PL/SQL?

答:
If I understood you correctly, this might be what you're looking for:</p>

```<code>select *
from your_table
where (table_term_code     = :par_term_code     or :par_term_code     is null)
  and (table_detl_code     = :par_detl_code     or :par_detl_code     is null)
  and (table_activity_date = :par_activity_date or :par_activity_date is null)
  and (table_seqno         = :par_seqno         or :par_seqno         is null)
</code>```

Body:
I have the following sample query which takes values from procedure parameters. The parameter can be either passed or default to null.

SELECT * FROM table
              WHERE( table_term_code = '201931'
              OR (table_term_code = '201931' and table_DETL_CODE ='CA02')
              OR ( table_term_code = '201931' and table_ACTIVITY_DATE = sysdate)
              OR ( table_term_code = '201931' and table_SEQNO = NULL));

i.e the user can input term code and not input any other parameter, or can input term code and  table_DETL_CODE and not any other input parameter.

Same goes for the other 2 or conditions.

If a term code is passed and table_DETL_CODE is null, the query should return all the values for that term_code, whereas this query returns null.

Is there a way to achieve this without case or if conditions in PL/SQL?

Body:
If I understood you correctly, this might be what you're looking for:

select *
from your_table
where (table_term_code     = :par_term_code     or :par_term_code     is null)
  and (table_detl_code     = :par_detl_code     or :par_detl_code     is null)
  and (table_activity_date = :par_activity_date or :par_activity_date is null)
  and (table_seqno         = :par_seqno         or :par_seqno         is null)


来源: stackexchange

问:
Re-run the same macro until last row of data
I'm a beginner. Just learning by Googleing, but cannot find a solution for this. Please help.

I want to run the below macro.
I have multiple cells named "CV_=CVCAL" in the same column.
What I want is for the macro to find the first cell with the value "CV_=CVCAL" and offset to the adjacent cell. If the adjacent cell has a particular value, if the value is below lets say "1.5" i want to fill it will a cell style 'bad'.

I want the macro to go through all the cells that have the name CV_=CVCAL and do the same thing until there is no more cells named CV_=CVCAL.

```<code>Sub If_CV()

Range("A1").Select

    Set FoundItem = Range("C1:C1000").Find("CV_=CVCAL")
    FoundItem.Offset(columnOffset:=1).Select

    If ActiveCell.Value >= 1.5 Then
    ActiveCell.Style = "Bad"

    End If

End Sub
</code>```

答:
Sounds like you want to loop through your values.

Determine the end of your range

Loop through your range and check your criteria

```<code>Sub If_CV()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim lr As Long, i As Long

lr = ws.Range("C" & ws.Rows.Count).End(xlUp).Row

For i = 2 To lr
    If ws.Range("C" & i) = "CV_=CVCAL" Then
        If ws.Range("D" & i) >= 1.5 Then
            ws.Range("D" & i) = "Bad"
        End If
    End If
Next i

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm a beginner. Just learning by Googleing, but cannot find a solution for this. Please help.

I want to run the below macro.
I have multiple cells named "CV_=CVCAL" in the same column.
What I want is for the macro to find the first cell with the value "CV_=CVCAL" and offset to the adjacent cell. If the adjacent cell has a particular value, if the value is below lets say "1.5" i want to fill it will a cell style 'bad'.

I want the macro to go through all the cells that have the name CV_=CVCAL and do the same thing until there is no more cells named CV_=CVCAL.

Sub If_CV()

Range("A1").Select

    Set FoundItem = Range("C1:C1000").Find("CV_=CVCAL")
    FoundItem.Offset(columnOffset:=1).Select

    If ActiveCell.Value >= 1.5 Then
    ActiveCell.Style = "Bad"

    End If

End Sub

Body:
Sounds like you want to loop through your values.

Determine the end of your range

Loop through your range and check your criteria

Sub If_CV()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim lr As Long, i As Long

lr = ws.Range("C" & ws.Rows.Count).End(xlUp).Row

For i = 2 To lr
    If ws.Range("C" & i) = "CV_=CVCAL" Then
        If ws.Range("D" & i) >= 1.5 Then
            ws.Range("D" & i) = "Bad"
        End If
    End If
Next i

End Sub


问:
Select statement in custom SQL Tableau based on another custom SQL
I am creating lots of new data sources using custom SQL option in Tableau.
I want to create another new data source that will contain Select statement referring to another custom SQL. Example :

Tables provided in database :

school, fields including : area, area_code, school_id, school_name

student, fields including: school_id, student_id, student_name

mark, fields inclusing: school_id, student_id, mark_value

custom SQL #1, named testresult :

```<code>SELECT student.student_name, mark.mark_value,
CASE WHEN mark.mark_value > 70 THEN 'passed'
WHEN mark.mark_value BETWEEN 50 AND 60 THEN 'retake'
ELSE 'failed'
END AS student_result
FROM student
LEFT JOIN mark ON student.student_id = mark.student_id
</code>```

custom SQL #2, named arearesult :

```<code>SELECT school.area, school.area_code, student.student_name, testresult.student_result
FROM school
LEFT JOIN student ON school.school_id = student.school_id
INNER JOIN testresult ON school.student_name = testresult.student_name
</code>```

It all works well until I try to create custom SQL #2 arearesult. It seems Tableau does not recognize custom SQL as a table. Is there anyway I can do this?

Please note that because of the condition of my real data, it is only possible to do it by joining the 3 tables as I explained above, instead of using 1 SQL script. I know based on the data I provided in my example, it is possible and much easier to use 1 SQL script. But in reality I just can not do that.

答:
I think you can do all of this using a subquery instead of CTE.</p>

```<code>SELECT school.area,
   school.area_code,
   student.student_name,
   testresult.student_result

FROM school
LEFT JOIN student ON school.school_id = student.school_id
INNER JOIN (SELECT student.student_name, mark.mark_value,
              CASE WHEN mark.mark_value > 70 THEN 'passed'
                   WHEN mark.mark_value BETWEEN 50 AND 60 THEN 'retake'
                   ELSE 'failed'
                   END AS student_result
            FROM student
            LEFT JOIN mark ON student.student_id = mark.student_id) testresult ON school.student_name = testresult.student_name
</code>```

Body:
I am creating lots of new data sources using custom SQL option in Tableau.
I want to create another new data source that will contain Select statement referring to another custom SQL. Example :

Tables provided in database :

school, fields including : area, area_code, school_id, school_name

student, fields including: school_id, student_id, student_name

mark, fields inclusing: school_id, student_id, mark_value

custom SQL #1, named testresult :

SELECT student.student_name, mark.mark_value,
CASE WHEN mark.mark_value > 70 THEN 'passed'
WHEN mark.mark_value BETWEEN 50 AND 60 THEN 'retake'
ELSE 'failed'
END AS student_result
FROM student
LEFT JOIN mark ON student.student_id = mark.student_id

custom SQL #2, named arearesult :

SELECT school.area, school.area_code, student.student_name, testresult.student_result
FROM school
LEFT JOIN student ON school.school_id = student.school_id
INNER JOIN testresult ON school.student_name = testresult.student_name

It all works well until I try to create custom SQL #2 arearesult. It seems Tableau does not recognize custom SQL as a table. Is there anyway I can do this?

Please note that because of the condition of my real data, it is only possible to do it by joining the 3 tables as I explained above, instead of using 1 SQL script. I know based on the data I provided in my example, it is possible and much easier to use 1 SQL script. But in reality I just can not do that.

Body:
I think you can do all of this using a subquery instead of CTE.

SELECT school.area,
   school.area_code,
   student.student_name,
   testresult.student_result

FROM school
LEFT JOIN student ON school.school_id = student.school_id
INNER JOIN (SELECT student.student_name, mark.mark_value,
              CASE WHEN mark.mark_value > 70 THEN 'passed'
                   WHEN mark.mark_value BETWEEN 50 AND 60 THEN 'retake'
                   ELSE 'failed'
                   END AS student_result
            FROM student
            LEFT JOIN mark ON student.student_id = mark.student_id) testresult ON school.student_name = testresult.student_name


问:
Problem with #ifndef and #pragma once
I want write the program with next struct

stdafx.h - contains some #define defenitions of program constants and #include of headers wich uses in all project.

frmMain.h - contatins code of Form1 also can Show form2 and uses some code from BckHeadr.h and some functions call that headers included in stdafx.h.

frmIniPrgs.h - contatins code of Form2 and uses some code from BckHeadr.h and some functions call that headers included in stdafx.h.

BckHeadr.h - contatins some definitions of functions and some functions call that headers included in stdafx.h.

I know what i must use #ifndef or #pragma once directives. But i can not decided this problem. I included in stdafx.h: frmIniPrgs.H, BckHeadr.h, frmMain.h. And use #ifndef in all modules. I uset it like this:

```<code>#ifndef MYMODULE_H
#define MYMODULE_H
//module code
#endif
</code>```

There is next errors in my project (i have russian visual studio and text of errors is translate by google translate and may contain the errors, ScnIniPackages is my function in BckHeadr.h ):

```<code>BckHeadr.h (96): error C3861: PtrToStringChars: identifier not found
BckHeadr.h (141): error C2065: vector: undeclared identifier
BckHeadr.h (141): error C2062: type "int" is not required
BckHeadr.h (141): error C2143: syntax error: no ";" before "("
BckHeadr.h (141): error C2447: (: missing function header (possibly using a formal list of old type)
BckHeadr.h (169): error C2065: vector: undeclared identifier
frmIniPrgs.h (119): error C2065: vector: undeclared identifier
frmIniPrgs.h (122): error C3861: ScnIniPackages: identifier not found
frmIniPrgs.h (121): error C2065: vector: undeclared identifier
C: \ Program Files \ Microsoft SDKs \ Windows \ v6.0A \ include \ Wininet.h (381): error C2872: FILETIME: ambiguous symbol
    be 'C: \ Program Files \ Microsoft SDKs \ Windows \ v6.0A \ include \ windef.h (377): _FILETIME FILETIME'
    or 'c: \ windows \ microsoft.net \ framework \ v2.0.50727 \ mscorlib.dll: System:: Runtime:: InteropServices:: FILETIME'
</code>```

答:
You have to include proper STL headers.

```<code>#include <vector>
</code>```

Also you can add namespace as

```<code>using namespace std;
</code>```

Or use STL classes as

```<code>std::vector<>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Problem with #ifndef and #pragma once

Body:
I want write the program with next struct

stdafx.h - contains some #define defenitions of program constants and #include of headers wich uses in all project.

frmMain.h - contatins code of Form1 also can Show form2 and uses some code from BckHeadr.h and some functions call that headers included in stdafx.h.

frmIniPrgs.h - contatins code of Form2 and uses some code from BckHeadr.h and some functions call that headers included in stdafx.h.

BckHeadr.h - contatins some definitions of functions and some functions call that headers included in stdafx.h.

I know what i must use #ifndef or #pragma once directives. But i can not decided this problem. I included in stdafx.h: frmIniPrgs.H, BckHeadr.h, frmMain.h. And use #ifndef in all modules. I uset it like this:

#ifndef MYMODULE_H
#define MYMODULE_H
//module code
#endif

There is next errors in my project (i have russian visual studio and text of errors is translate by google translate and may contain the errors, ScnIniPackages is my function in BckHeadr.h ):

BckHeadr.h (96): error C3861: PtrToStringChars: identifier not found
BckHeadr.h (141): error C2065: vector: undeclared identifier
BckHeadr.h (141): error C2062: type "int" is not required
BckHeadr.h (141): error C2143: syntax error: no ";" before "("
BckHeadr.h (141): error C2447: (: missing function header (possibly using a formal list of old type)
BckHeadr.h (169): error C2065: vector: undeclared identifier
frmIniPrgs.h (119): error C2065: vector: undeclared identifier
frmIniPrgs.h (122): error C3861: ScnIniPackages: identifier not found
frmIniPrgs.h (121): error C2065: vector: undeclared identifier
C: \ Program Files \ Microsoft SDKs \ Windows \ v6.0A \ include \ Wininet.h (381): error C2872: FILETIME: ambiguous symbol
    be 'C: \ Program Files \ Microsoft SDKs \ Windows \ v6.0A \ include \ windef.h (377): _FILETIME FILETIME'
    or 'c: \ windows \ microsoft.net \ framework \ v2.0.50727 \ mscorlib.dll: System:: Runtime:: InteropServices:: FILETIME'

Body:
You have to include proper STL headers.

#include <vector>

Also you can add namespace as

using namespace std;

Or use STL classes as

std::vector<>

ContentLicense: CC BY-SA 3.0


问:
How to display button opposite of level in React?
How to display button opposite of its status. Suppose its showing open then the button should appear Withdraw and if the status is appearing Withdraw button should appear Open in Reactjs.

I have a Json object which carries the necessary information.

Here is code is what I have had tried..

```<code>const initial = {
  description: [
    {
      name: 'Alex',
      level: 'open',
    },
    {
      name: 'Sycus',
      level: 'open',
    },
    {
      name: 'Rasku',
      level: 'Withdraw',
    }
  ]
}

export default function App() {

  const [state, setState] = React.useState(initial)
  const [show , setshow] = React.useState(true)

  const handleClick = () => {
    return
  }

  const butFunction = () => {
      return state.description.map(sub => {
          const { level } = sub
          return (
            if(level === 'open'){
              <button>Withdraw</button>
            }
            else{
              <button>Open</buton>
            }
          )
      })
  }

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div>
        <table>
          <tbody>
            {
              state.description.map(desc => (
                <tr>
                  <td>
                  {desc.name}
                  </td>
                  <td>
                  {desc.level}
                  </td>
                <td>

                { show && butFunction()}
                </td>
                </tr>
              ))
              }
          </tbody>
        </table>
      </div>
    </div>
  );
}
</code>```

答:
Instead of rendering two different buttons for two conditions you can use ternary operator to conditionally change the text of single button like this:</p>

```<code>return(
    <button>{level===‘open’?’withdraw’:’open’}</button>
)
</code>```

Body:
How to display button opposite of its status. Suppose its showing open then the button should appear Withdraw and if the status is appearing Withdraw button should appear Open in Reactjs.

I have a Json object which carries the necessary information.

Here is code is what I have had tried..

const initial = {
  description: [
    {
      name: 'Alex',
      level: 'open',
    },
    {
      name: 'Sycus',
      level: 'open',
    },
    {
      name: 'Rasku',
      level: 'Withdraw',
    }
  ]
}

export default function App() {

  const [state, setState] = React.useState(initial)
  const [show , setshow] = React.useState(true)

  const handleClick = () => {
    return
  }

  const butFunction = () => {
      return state.description.map(sub => {
          const { level } = sub
          return (
            if(level === 'open'){
              <button>Withdraw</button>
            }
            else{
              <button>Open</buton>
            }
          )
      })
  }

  return (

Hello CodeSandbox

            {
              state.description.map(desc => (

                  {desc.name}

                  {desc.level}

                { show && butFunction()}

              ))
              }

  );
}

Body:
Instead of rendering two different buttons for two conditions you can use ternary operator to conditionally change the text of single button like this:

return(
    <button>{level===‘open’?’withdraw’:’open’}</button>
)


问:
Issue with grep merged with IF under linux
Hi I  am trying to use grep with if and if the value is found under the directory it should update the file name with "_1" else copy to other directory  </p>

```<code>cd /home/inbound/ftp
f3=822220222 #ordernumber which change every time for this instance we use this

   if [ grep -lq $f3 ]; then
   f4=`find . -name *$f3*` #trying to get the existing file name if available
   mv "$f4" "$f4_1"        #updating existing file with "_1"
else
   cp $file /home/outbound/ftp
</code>```

答:
grep command can be used to search a pattern in a file or an output. it can be connected to ls with a pipe to check this. However for your scenario the below would be an better alternative to find if the file is present

```<code>cd /home/inbound/ftp
f3=822220222 #ordernumber which change every time for this instance we use this

   if [ -f "*$f3*" ]; then
   f4=`find . -name *$f3*` #trying to get the existing file name if available
   mv "$f4" "$f4_1"        #updating existing file with "_1"
else
   cp $file /home/outbound/ftp

</code>```

However this checks for your order number in the variable f3. However you already know the filename that you are going to copy. so you can use that instead of f3.

```<code>cd /home/inbound/ftp
filename=`basename $file` #file name of the File being FTPed

   if [ -f $filename ]; then
   mv "$filename" "$filename_1"        #updating existing file with "_1"
   fi   # closing this here will make sure the file gets copied all the time
   cp $file /home/outbound/ftp
</code>```

Body:
Hi I  am trying to use grep with if and if the value is found under the directory it should update the file name with "_1" else copy to other directory

cd /home/inbound/ftp
f3=822220222 #ordernumber which change every time for this instance we use this

   if [ grep -lq $f3 ]; then
   f4=`find . -name *$f3*` #trying to get the existing file name if available
   mv "$f4" "$f4_1"        #updating existing file with "_1"
else
   cp $file /home/outbound/ftp

Body:
grep command can be used to search a pattern in a file or an output. it can be connected to ls with a pipe to check this. However for your scenario the below would be an better alternative to find if the file is present

cd /home/inbound/ftp
f3=822220222 #ordernumber which change every time for this instance we use this

   if [ -f "*$f3*" ]; then
   f4=`find . -name *$f3*` #trying to get the existing file name if available
   mv "$f4" "$f4_1"        #updating existing file with "_1"
else
   cp $file /home/outbound/ftp

However this checks for your order number in the variable f3. However you already know the filename that you are going to copy. so you can use that instead of f3.

cd /home/inbound/ftp
filename=`basename $file` #file name of the File being FTPed

   if [ -f $filename ]; then
   mv "$filename" "$filename_1"        #updating existing file with "_1"
   fi   # closing this here will make sure the file gets copied all the time
   cp $file /home/outbound/ftp


问:
iOS push notification sound doesn't cancel on open
I am creating an application that uses Apple Push Notifications with custom sound (about 15 sec length). If I open notification when phone is in use, sound terminates, but if I open notification when it wakes up phone from sleep mode, sound continues to play until the end. How can I avoid unnecessary push sound playing?</p>

答:
As of iOS 10, you can remove all notifications from Notification Center by calling

```<code>UNUserNotificationCenter.current().removeAllDeliveredNotifications()
</code>```

The audio stops playing, but all the notifications are removed from Notification Center.

Alternatively, to stop the sound for only a specific notification, you can use:

```<code>UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [String])
</code>```

This stops the audio for only the given notifications, and removes them from Notification Center.

To get the ids for all the delivered notifications, use

```<code>UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
  let ids = notifications.map { $0.request.identifier }
}
</code>```

Of course, the downside is that the notifications are removed from the user's Notification Center.

Body:
As of iOS 10, you can remove all notifications from Notification Center by calling

UNUserNotificationCenter.current().removeAllDeliveredNotifications()

The audio stops playing, but all the notifications are removed from Notification Center.

Alternatively, to stop the sound for only a specific notification, you can use:

UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [String])

This stops the audio for only the given notifications, and removes them from Notification Center.

To get the ids for all the delivered notifications, use

UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
  let ids = notifications.map { $0.request.identifier }
}

Of course, the downside is that the notifications are removed from the user's Notification Center.


问:
Searching byte encoded integers, is it faster to convert to int or match the bytes?
I have a binary file containing integers at known positions. I want to seek a specific integer, or byte sequence. I got the idea converting to integer would be more efficient given the byte version's resemblance to a string.

Should I convert each byte sequence to an integer for comparisons or use bytes?

How does the size of the byte sequence comprising each int effect this, eg would using 3 bytes incur an overhead of masking off the odd byte?

答:
To answer I devised a small script. The slowest part is generating the randoms.

```<code>import random
import time

endianness = "big"
bytes_given_to_int = 3

def some_nums(top_end: int):
    return [x + random.randint(0, 42) for x in range(top_end)]

top_end = 9_999_999

bs = [x.to_bytes(bytes_given_to_int, endianness) for x in some_nums(top_end)]
bs2 = [x.to_bytes(bytes_given_to_int, endianness) for x in some_nums(top_end)]
cs = some_nums(top_end)
cs2 = some_nums(top_end)

iicmps=[]
bbcmps=[]
bicmps=[]
ibcmps=[]

for i in range(10):
    t0 = time.time()
    rs1 = [1 for i in range(top_end) if bs[i] == bs2[i]]
    # Each sum should be roughly equal. Using it here helps instruct the interpreter/compiler
    # not to optimise away the arbitrary task we give it.
    print(sum(rs1))
    bbcmps.append((time.time() - t0))
    t0 = time.time()
    rs2 = [1 for i in range(top_end) if cs[i] == cs2[i]]
    print(sum(rs2))
    iicmps.append((time.time() - t0))
    t0 = time.time()
    rs3 = [1 for i in range(top_end) if int.from_bytes(bs[i], endianness) == cs[i]]
    print(sum(rs3))
    bicmps.append((time.time() - t0))
    t0 = time.time()
    rs4 = [1 for i in range(top_end) if cs[i].to_bytes(bytes_given_to_int, endianness) == bs[i]]
    print(sum(rs4))
    ibcmps.append((time.time() - t0))

print("Comparing byte sequences took {:.2f}s".format(sum(bbcmps) / len(bbcmps)))
print("Comparing ints took {:.2f}s".format(sum(iicmps) / len(iicmps)))
print("Comparing byte sequences (converted to ints) to ints took {:.2f}s".format(sum(bicmps) / len(bicmps)))
print("Comparing ints (converted to byte sequences) to byte sequences took {:.2f}s".format(sum(ibcmps) / len(ibcmps)))
</code>```

Comparing byte sequences took 1.54s

Comparing ints took 1.50s

Comparing byte sequences (converted to ints) to ints took 3.53s

Comparing ints (converted to byte sequences) to byte sequences took 3.52s

Ok, this shows byte sequences to be first class objects, as we might deduce from even strings being a thin veneer on lists.

What happens with other word lengths? Let's try 4.

Comparing byte sequences took 1.31s

Comparing ints took 5.89s

Comparing byte sequences (converted to ints) to ints took 3.29s

Comparing ints (converted to byte sequences) to byte sequences took 3.20s

I guess the variables in this script are useful! byte sequences FTW!

Body:
To answer I devised a small script. The slowest part is generating the randoms.

import random
import time

endianness = "big"
bytes_given_to_int = 3

def some_nums(top_end: int):
    return [x + random.randint(0, 42) for x in range(top_end)]

top_end = 9_999_999

bs = [x.to_bytes(bytes_given_to_int, endianness) for x in some_nums(top_end)]
bs2 = [x.to_bytes(bytes_given_to_int, endianness) for x in some_nums(top_end)]
cs = some_nums(top_end)
cs2 = some_nums(top_end)

iicmps=[]
bbcmps=[]
bicmps=[]
ibcmps=[]

for i in range(10):
    t0 = time.time()
    rs1 = [1 for i in range(top_end) if bs[i] == bs2[i]]
    # Each sum should be roughly equal. Using it here helps instruct the interpreter/compiler
    # not to optimise away the arbitrary task we give it.
    print(sum(rs1))
    bbcmps.append((time.time() - t0))
    t0 = time.time()
    rs2 = [1 for i in range(top_end) if cs[i] == cs2[i]]
    print(sum(rs2))
    iicmps.append((time.time() - t0))
    t0 = time.time()
    rs3 = [1 for i in range(top_end) if int.from_bytes(bs[i], endianness) == cs[i]]
    print(sum(rs3))
    bicmps.append((time.time() - t0))
    t0 = time.time()
    rs4 = [1 for i in range(top_end) if cs[i].to_bytes(bytes_given_to_int, endianness) == bs[i]]
    print(sum(rs4))
    ibcmps.append((time.time() - t0))

print("Comparing byte sequences took {:.2f}s".format(sum(bbcmps) / len(bbcmps)))
print("Comparing ints took {:.2f}s".format(sum(iicmps) / len(iicmps)))
print("Comparing byte sequences (converted to ints) to ints took {:.2f}s".format(sum(bicmps) / len(bicmps)))
print("Comparing ints (converted to byte sequences) to byte sequences took {:.2f}s".format(sum(ibcmps) / len(ibcmps)))

Comparing byte sequences took 1.54s

Comparing ints took 1.50s

Comparing byte sequences (converted to ints) to ints took 3.53s

Comparing ints (converted to byte sequences) to byte sequences took 3.52s

Ok, this shows byte sequences to be first class objects, as we might deduce from even strings being a thin veneer on lists.

What happens with other word lengths? Let's try 4.

Comparing byte sequences took 1.31s

Comparing ints took 5.89s

Comparing byte sequences (converted to ints) to ints took 3.29s

Comparing ints (converted to byte sequences) to byte sequences took 3.20s

I guess the variables in this script are useful! byte sequences FTW!


问:
Problem with saving values from function in C++
Im bad with pointers and references so i have a question why in function hoffman the values are good and fine but when im trying see them out of function hoffman in main() i cant see almost none of this values.
This is my code:

```<code>#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

struct element {
char letter;
int number;
string code;
element *left;
element *right;
};

bool my_cmp(const element& a, const element& b)
{
  return a.number<b.number;
}

void hoffman(element &tab)
{
   if(tab.left!=NULL)
   {
    tab.left->code=tab.code;
    tab.left->code.push_back('0');
    if(tab.left->letter!=' ')
    {
        cout<<tab.left->letter<<" "<<tab.left->code<<endl;
    }
    hoffman(*tab.left);
}
if(tab.right!=NULL)
{
    tab.right->code=tab.code;
    tab.right->code.push_back('1');
    if(tab.right->letter!=' ')
    {
        cout<<tab.right->letter<<" "<<tab.right->code<<endl;
    }
    hoffman(*tab.right);
     }
    }

 int main()
 {
string C="abcdefghijklmnopqestuvwxyz",text;
int T[26]={0};
vector<element> tab;
cin>>text;
int rozmiar=text.length();
int rozm=0;
for(int i=0;i<rozmiar;i++)
{
    for(int j=0;j<26;j++)
    {
        if(text[i]==C[j])
        {
            T[j]++;
            break;
        }
    }
}
for(int j=0;j<26;j++)
{
    if(T[j]!=0)
    {
        tab.push_back({C[j],T[j],"",NULL,NULL});
    }
}

sort(tab.begin(),tab.end(),my_cmp);

while((rozm+1)!=tab.size())
{
    tab.push_back({' ',tab[rozm].number+tab[rozm+1].number,"",&tab[rozm],&tab[rozm+1]});
    rozm+=2;
    sort(tab.begin()+rozm,tab.end(),my_cmp);
}

hoffman(tab[tab.size()-1]);
cout<<endl;

for(int i=0;i<tab.size();i++)
{
    if(tab[i].letter!=' ') cout<<tab[i].letter<<" = "<<tab[i].code<<endl;
}

return 0;
</code>```

}

In function hoffman im assigning string code to every element of struct but i cant see it out of function using the last loop, any ideas?

答:
The problem is you have undefined behaviour in your code (aka UB). When following loop is executed first time:

```<code>while ((rozm + 1) != tab.size()) {
    tab.push_back({' ', tab[rozm].number + tab[rozm + 1].number, "", &tab[rozm], &tab[rozm + 1]});
</code>```

tab is empty, but you dereference its element with tab[rozm] which causes undefined behaviour. Everything after this place is an unknown land.

You can quickly find any such UBs in your code using sanitization, ie. with clang use parameter -fsanitize=undefined. Example:

https://coliru.stacked-crooked.com/a/037fb17598ea2050

output gives you exact place of error:

```<code>clang++ -fsanitize=undefined -std=c++17 -O0 -g -Wall -pedantic -pthread main.cpp && ./a.out
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.5.0/../../../../include/c++/5.5.0/bits/stl_vector.h:780:16: runtime error: reference binding to null pointer of type 'element'
main.cpp:80:24: runtime error: member access within null pointer of type '__gnu_cxx::__alloc_traits<std::allocator<element> >::value_type' (aka 'element')
bash: line 7: 24391 Segmentation fault      (core dumped) ./a.out
</code>```

but its better to execute it in debugger to see full callstack, with variables lookup etc.

Body:
Im bad with pointers and references so i have a question why in function hoffman the values are good and fine but when im trying see them out of function hoffman in main() i cant see almost none of this values.
This is my code:

#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

struct element {
char letter;
int number;
string code;
element *left;
element *right;
};

bool my_cmp(const element& a, const element& b)
{
  return a.numbercode=tab.code;
    tab.left->code.push_back('0');
    if(tab.left->letter!=' ')
    {
        cout<<tab.left->letter<<" "<<tab.left->code<<endl;
    }
    hoffman(*tab.left);
}
if(tab.right!=NULL)
{
    tab.right->code=tab.code;
    tab.right->code.push_back('1');
    if(tab.right->letter!=' ')
    {
        cout<<tab.right->letter<<" "<<tab.right->code<<endl;
    }
    hoffman(*tab.right);
     }
    }

 int main()
 {
string C="abcdefghijklmnopqestuvwxyz",text;
int T[26]={0};
vector<element> tab;
cin>>text;
int rozmiar=text.length();
int rozm=0;
for(int i=0;i<rozmiar;i++)
{
    for(int j=0;j<26;j++)
    {
        if(text[i]==C[j])
        {
            T[j]++;
            break;
        }
    }
}
for(int j=0;j<26;j++)
{
    if(T[j]!=0)
    {
        tab.push_back({C[j],T[j],"",NULL,NULL});
    }
}

sort(tab.begin(),tab.end(),my_cmp);

while((rozm+1)!=tab.size())
{
    tab.push_back({' ',tab[rozm].number+tab[rozm+1].number,"",&tab[rozm],&tab[rozm+1]});
    rozm+=2;
    sort(tab.begin()+rozm,tab.end(),my_cmp);
}

hoffman(tab[tab.size()-1]);
cout<<endl;

for(int i=0;i<tab.size();i++)
{
    if(tab[i].letter!=' ') cout<<tab[i].letter<<" = "<<tab[i].code<<endl;
}

return 0;

}

In function hoffman im assigning string code to every element of struct but i cant see it out of function using the last loop, any ideas?

Body:
The problem is you have undefined behaviour in your code (aka UB). When following loop is executed first time:

while ((rozm + 1) != tab.size()) {
    tab.push_back({' ', tab[rozm].number + tab[rozm + 1].number, "", &tab[rozm], &tab[rozm + 1]});

tab is empty, but you dereference its element with tab[rozm] which causes undefined behaviour. Everything after this place is an unknown land.

You can quickly find any such UBs in your code using sanitization, ie. with clang use parameter -fsanitize=undefined. Example:

https://coliru.stacked-crooked.com/a/037fb17598ea2050

output gives you exact place of error:

clang++ -fsanitize=undefined -std=c++17 -O0 -g -Wall -pedantic -pthread main.cpp && ./a.out
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.5.0/../../../../include/c++/5.5.0/bits/stl_vector.h:780:16: runtime error: reference binding to null pointer of type 'element'
main.cpp:80:24: runtime error: member access within null pointer of type '__gnu_cxx::__alloc_traits<std::allocator<element> >::value_type' (aka 'element')
bash: line 7: 24391 Segmentation fault      (core dumped) ./a.out

but its better to execute it in debugger to see full callstack, with variables lookup etc.


问:
Update charts in chartjs and angular
I have the problem with update chart js in angular. I am using for it ngrx store.

In selector subscriber (run in ngOnInit) I tried update the chart data:

```<code>this.yrSubscription = this.userDataStore.pipe(select(selectYrReport))
  .subscribe(el => {
    el.sessions.forEach(item => {
      this.datasetsSessions[0].data.push(+item);
    });
  });
</code>```

And my chart data:

```<code>datasetsSessions: ChartDataSets[] = [{
  label: 'Sessions',
  data: [],
  fill: false
}];
</code>```

Register charts:

```<code>private _registerCustomChartJSPlugin(): void {
  (window as any).Chart.plugins.register({
    afterDatasetsDraw: (chart, easing): any => {
      if (!chart.options.plugins.xLabelsOnTop
        || (chart.options.plugins.xLabelsOnTop && chart.options.plugins.xLabelsOnTop.active === false)) {
        return;
      }

      const ctx = chart.ctx;

      chart.data.datasets.forEach((dataset, i): any => {
        const meta = chart.getDatasetMeta(i);
        if (!meta.hidden) {
          meta.data.forEach((element, index): any => {
            // Draw the text in black, with the specified font
            ctx.fillStyle = 'rgba(255, 255, 255, 0.7)';
            const fontSize = 13;
            const fontStyle = 'normal';
            const fontFamily = 'Roboto, Helvetica Neue, Arial';
            ctx.font = (window as any).Chart.helpers.fontString(fontSize, fontStyle, fontFamily);

            const dataString = dataset.data[index].toString() + 'k';

            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            const padding = 15;
            const startY = 24;
            const position = element.tooltipPosition();
            ctx.fillText(dataString, position.x, startY);

            ctx.save();

            ctx.beginPath();
            ctx.setLineDash([5, 3]);
            ctx.moveTo(position.x, startY + padding);
            ctx.lineTo(position.x, position.y - padding);
            ctx.strokeStyle = 'rgba(255,255,255,0.12)';
            ctx.stroke();

            ctx.restore();
          });
        }
      });
    }
  });
}
</code>```

And I call it in constructor.

I know, that I need run chart.update(). But still I have got an error about chart is undefined etc.

答:
Above Component Decorator have this :-

```<code>var require: any;
var Chart = require('chart.js');
</code>```

In component have a property for keeping instance of chart

```<code>public chart: Chart;
</code>```

First you need to understand is that Chart.plugins.register will only register a plugin globally for all charts.
https://www.chartjs.org/docs/latest/developers/plugins.html#global-plugins

You need a chart for this plugin to apply

Lets Say you have a Canvas in your HTML like :-

```<code><div>
  <canvas id="canvas">{{ chart }}</canvas>
</div>
</code>```

You need to update your inside ngoninit to ngrx Subscription To create a new chart if its not available.

```<code>ngOnInit() {
this._registerCustomChartJSPlugin();
this.yrSubscription = this.userDataStore.pipe(select(selectYrReport))
  .subscribe(el => {
      if(!this.chart) {
        this.createChart();
      }
    el.sessions.forEach(item => {
      this.datasetsSessions[0].data.push(+item);
    });
    this.chart.update();
  });
}
public createChart() {
   this.chart = new Chart('canvas'); //Include if any object required as second Parameter
}
</code>```

Title: Update charts in chartjs and angular

Body:
I have the problem with update chart js in angular. I am using for it ngrx store.

In selector subscriber (run in ngOnInit) I tried update the chart data:

this.yrSubscription = this.userDataStore.pipe(select(selectYrReport))
  .subscribe(el => {
    el.sessions.forEach(item => {
      this.datasetsSessions[0].data.push(+item);
    });
  });

And my chart data:

datasetsSessions: ChartDataSets[] = [{
  label: 'Sessions',
  data: [],
  fill: false
}];

Register charts:

private _registerCustomChartJSPlugin(): void {
  (window as any).Chart.plugins.register({
    afterDatasetsDraw: (chart, easing): any => {
      if (!chart.options.plugins.xLabelsOnTop
        || (chart.options.plugins.xLabelsOnTop && chart.options.plugins.xLabelsOnTop.active === false)) {
        return;
      }

      const ctx = chart.ctx;

      chart.data.datasets.forEach((dataset, i): any => {
        const meta = chart.getDatasetMeta(i);
        if (!meta.hidden) {
          meta.data.forEach((element, index): any => {
            // Draw the text in black, with the specified font
            ctx.fillStyle = 'rgba(255, 255, 255, 0.7)';
            const fontSize = 13;
            const fontStyle = 'normal';
            const fontFamily = 'Roboto, Helvetica Neue, Arial';
            ctx.font = (window as any).Chart.helpers.fontString(fontSize, fontStyle, fontFamily);

            const dataString = dataset.data[index].toString() + 'k';

            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            const padding = 15;
            const startY = 24;
            const position = element.tooltipPosition();
            ctx.fillText(dataString, position.x, startY);

            ctx.save();

            ctx.beginPath();
            ctx.setLineDash([5, 3]);
            ctx.moveTo(position.x, startY + padding);
            ctx.lineTo(position.x, position.y - padding);
            ctx.strokeStyle = 'rgba(255,255,255,0.12)';
            ctx.stroke();

            ctx.restore();
          });
        }
      });
    }
  });
}

And I call it in constructor.

I know, that I need run chart.update(). But still I have got an error about chart is undefined etc.

Body:
Above Component Decorator have this :-

var require: any;
var Chart = require('chart.js');

In component have a property for keeping instance of chart

public chart: Chart;

First you need to understand is that Chart.plugins.register will only register a plugin globally for all charts.
https://www.chartjs.org/docs/latest/developers/plugins.html#global-plugins

You need a chart for this plugin to apply

Lets Say you have a Canvas in your HTML like :-

<div>
  <canvas id="canvas">{{ chart }}</canvas>
</div>

You need to update your inside ngoninit to ngrx Subscription To create a new chart if its not available.

ngOnInit() {
this._registerCustomChartJSPlugin();
this.yrSubscription = this.userDataStore.pipe(select(selectYrReport))
  .subscribe(el => {
      if(!this.chart) {
        this.createChart();
      }
    el.sessions.forEach(item => {
      this.datasetsSessions[0].data.push(+item);
    });
    this.chart.update();
  });
}
public createChart() {
   this.chart = new Chart('canvas'); //Include if any object required as second Parameter
}


问:
dyld: Library not loaded: @rpath/libswiftCore.dylib
I am trying to run a Swift app on my iPhone 4s. It works fine on the simulator, and my friend can successfully run it on his iPhone 4s. I have iOS 8 and the official release of Xcode 6.

I have tried

Restarting Xcode, iPhone, computer

Cleaning & rebuilding

Revoking and creating new certificate/provision profile

Runpath Search Paths is $(inherited) @executable_path/Frameworks

Embedded Content Contains Swift Code is 'Yes'

Code Signing Identity is developer

Below is the error in entirety

```<code>dyld: Library not loaded: @rpath/libswiftCore.dylib
  Referenced from: /private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/AppName.app/AppName
  Reason: no suitable image found.  Did find:
    /private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/AppName.app/Frameworks/libswiftCore.dylib: mmap() error 1 at
address=0x008A1000, size=0x001A4000 segment=__TEXT in Segment::map() mapping
/private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/APPLICATION_NAME/Frameworks/libswiftCore.dylib
</code>```

答: What worked for me in Xcode 11 was going to General -> Frameworks, Libraries, and Embedded Content and changing the "Embed" option for the framework in question to "Embed & Sign"

Body:
I am trying to run a Swift app on my iPhone 4s. It works fine on the simulator, and my friend can successfully run it on his iPhone 4s. I have iOS 8 and the official release of Xcode 6.

I have tried

Restarting Xcode, iPhone, computer

Cleaning & rebuilding

Revoking and creating new certificate/provision profile

Runpath Search Paths is $(inherited) @executable_path/Frameworks

Embedded Content Contains Swift Code is 'Yes'

Code Signing Identity is developer

Below is the error in entirety

dyld: Library not loaded: @rpath/libswiftCore.dylib
  Referenced from: /private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/AppName.app/AppName
  Reason: no suitable image found.  Did find:
    /private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/AppName.app/Frameworks/libswiftCore.dylib: mmap() error 1 at
address=0x008A1000, size=0x001A4000 segment=__TEXT in Segment::map() mapping
/private/var/mobile/Containers/Bundle/Application/LONGSERIALNUMBER/APPLICATION_NAME/Frameworks/libswiftCore.dylib


问:
How can I divide a table into pages without using Bootstrap?
I have a table with about 14000 rows and I want to split the table into 1400 pages(10 rows each) and on changing the page I wanna read some data with AJAX... How is it possible? I don't want to use Bootstrap table datatype or anything...

Any solution?
Thanks in advance. :)

Here is my table :

```<code><?php
    echo '<table id="table" class="table">
        <thead>
            <th>username</th>
            <th>service</th>
            <th>Date_created</th>
            <th></th>
        </thead>';

        foreach($$list as &$res){
            $username = $res['username'];
            $group = $res['service'];
            $cr = $res['creation'];

            echo "
            <tbody>
                <td>$username</td>
                <td>$group</td>
                <td>$cr</td>
                <td><button type='button' rel='tooltip' title='More info' class='btn btn-primary btn-link btn-  sm' onclick='userDetailsModal(`$username`)'><i class='material-icons'>edit</i></button></td>
            </tbody>
            ";
        }

        echo '</table>
    </div>';
?>
</code>```

答:
Use this library build in php

https://phppot.com/php/ajax-pagination-with-php/

or you can use https://datatables.net/ plugin along with ajax in php.

Body:
I have a table with about 14000 rows and I want to split the table into 1400 pages(10 rows each) and on changing the page I wanna read some data with AJAX... How is it possible? I don't want to use Bootstrap table datatype or anything...

Any solution?
Thanks in advance. :)

Here is my table :

<?php
    echo '

            username
            service
            Date_created

';

        foreach($$list as &$res){
            $username = $res['username'];
            $group = $res['service'];
            $cr = $res['creation'];

            echo "

                $username
                $group
                $cr
                <button type='button' rel='tooltip' title='More info' class='btn btn-primary btn-link btn-  sm' onclick='userDetailsModal(`$username`)'>edit</button>

            ";
        }

        echo '

';
?>


问:
IDisposable - automated check for using construct
Does anybody know of a way to automatically find any variable, where the type implements IDisposable but the using construct is not used?

ie. a way to check for potentially unreleased unmanaged resources?

Also, is it possible to see the number and types of resource held by a running application?

答:
There's a code analysis rule for this:

http://msdn.microsoft.com/en-us/library/ms182289%28VS.100%29.aspx

This can be run from VS 2010 Premium or Ultimate or separately with FxCop:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=917023f6-d5b7-41bb-bbc0-411a7d66cf3c

Another thing I've seen done is to capture a stack trace when an IDisposable object is constructed and then if the finalize is hit (meaning Dispose() was not called) log an error with the constructed stack trace.  This is expensive so you may only want to do it in development, or only start collecting stack traces the second time your app runs into this problem (if you run into it once, you're most likely going to run into it many times within a single app execution).  This method works for IDisposable instances that are longer lived (not just local variables).  Of course it also only works for custom IDisposable objects since it requires custom code in the constructor/dispose/finalizer.


问:
How to make a dot product in a vector of matrices in numpy?
I have

```<code>a = np.ones((10, 4, 3))
b = np.ones((10, 3, 5))
</code>```

and I want

```<code>c = np.dot(a, b, axis=0)
assert c.shape == (10, 4, 5)
</code>```

How do I do this?

答:
c = np.matmul(a, b) is probably what you are looking for. It produces the shape you need.

But this does not mean it is the kind of calculation you want to be executed. I would look into the documentation in order to be sure.

Body:
I have

a = np.ones((10, 4, 3))
b = np.ones((10, 3, 5))

and I want

c = np.dot(a, b, axis=0)
assert c.shape == (10, 4, 5)

How do I do this?


问:
How to copy files from AWS EFS To AWS S3?
I want to migrate data from AWS EFS to S3?

The total number files required from migrations are huge and will lead to data in TB

What is the best approach to copy files from EFS to S3?

答:
1) Please check the below link. use DataSync to transfer data.

2) Other approach can be

```<code>aws s3 sync /sourcepath/ s3://dest
</code>```

3) AWS data Pipeline

Body:
1) Please check the below link. use DataSync to transfer data.

2) Other approach can be

aws s3 sync /sourcepath/ s3://dest

3) AWS data Pipeline


问:
Someone can explain to me the design of a Convolutional NN with tensorflow (hand written digits)? (input img : 28 x 28 | output : 10 (n_classes))
I'm trying to get started with CNN designs, i found this piece of code that I try to infer the design from (f.maps size, strides ....).

What I've understoud is that we have :
input --> Conv5-32 --> maxpool --> Conv5-5 --> maxpool --> fc1 --> outputs.

what I'm not getting right is the input of the fc1, why it's a 7 by 7 ?

Could someone please help me ? (I'm a beginner)

```<code>import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('/tmp/data/', one_hot=True)

#Parameters
learning_rate = 0.001
training_iters = 200000
batch_size = 28
display_step = 10

#Network Parameters

n_input = 784
n_output = 10
dropout  = 0.75

#tf grath input
x = tf.placeholder(tf.float32, [None,n_input])
y = tf.placeholder(tf.float32, [None, n_output])
keep_prob = tf.placeholder(tf.float32)

# Create some wrappers for simplicity
def conv2d(x, W, b, strides=1):
    # Conv2D wrapper, with bias and relu activation
    x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
    x = tf.nn.bias_add(x, b)
    return tf.nn.relu(x)

def maxpool2d(x, k=2):
    # MaxPool2D wrapper
    return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],
                          padding='SAME')

# Create model
def conv_net(x, weights, biases, dropout):
    # Reshape input picture
    x = tf.reshape(x, shape=[-1, 28, 28, 1])

    # Convolution Layer
    conv1 = conv2d(x, weights['wc1'], biases['bc1'])
    # Max Pooling (down-sampling)
    conv1 = maxpool2d(conv1, k=2)

    # Convolution Layer
    conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
    # Max Pooling (down-sampling)
    conv2 = maxpool2d(conv2, k=2)

    # Fully connected layer
    # Reshape conv2 output to fit fully connected layer input
    fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
    fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
    fc1 = tf.nn.relu(fc1)
    # Apply Dropout
    fc1 = tf.nn.dropout(fc1, dropout)

    # Output, class prediction
    out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
    return out

# Store layers weight & bias
weights = {
    # 5x5 conv, 1 input, 32 outputs
    'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),
    # 5x5 conv, 32 inputs, 64 outputs
    'wc2': tf.Variable(tf.random_normal([5, 5, 32, 5])),
    # fully connected, 7*7*64 inputs, 1024 outputs
    'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),
    # 1024 inputs, 10 outputs (class prediction)
    'out': tf.Variable(tf.random_normal([1024, n_classes]))
}

biases = {
    'bc1': tf.Variable(tf.random_normal([32])),
    'bc2': tf.Variable(tf.random_normal([64])),
    'bd1': tf.Variable(tf.random_normal([1024])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}
</code>```

答: I hope my following image would clarify your doubt

Body:
I'm trying to get started with CNN designs, i found this piece of code that I try to infer the design from (f.maps size, strides ....).

What I've understoud is that we have :
input --> Conv5-32 --> maxpool --> Conv5-5 --> maxpool --> fc1 --> outputs.

what I'm not getting right is the input of the fc1, why it's a 7 by 7 ?

Could someone please help me ? (I'm a beginner)

import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('/tmp/data/', one_hot=True)

#Parameters
learning_rate = 0.001
training_iters = 200000
batch_size = 28
display_step = 10

#Network Parameters

n_input = 784
n_output = 10
dropout  = 0.75

#tf grath input
x = tf.placeholder(tf.float32, [None,n_input])
y = tf.placeholder(tf.float32, [None, n_output])
keep_prob = tf.placeholder(tf.float32)

# Create some wrappers for simplicity
def conv2d(x, W, b, strides=1):
    # Conv2D wrapper, with bias and relu activation
    x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
    x = tf.nn.bias_add(x, b)
    return tf.nn.relu(x)

def maxpool2d(x, k=2):
    # MaxPool2D wrapper
    return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],
                          padding='SAME')

# Create model
def conv_net(x, weights, biases, dropout):
    # Reshape input picture
    x = tf.reshape(x, shape=[-1, 28, 28, 1])

    # Convolution Layer
    conv1 = conv2d(x, weights['wc1'], biases['bc1'])
    # Max Pooling (down-sampling)
    conv1 = maxpool2d(conv1, k=2)

    # Convolution Layer
    conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
    # Max Pooling (down-sampling)
    conv2 = maxpool2d(conv2, k=2)

    # Fully connected layer
    # Reshape conv2 output to fit fully connected layer input
    fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
    fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
    fc1 = tf.nn.relu(fc1)
    # Apply Dropout
    fc1 = tf.nn.dropout(fc1, dropout)

    # Output, class prediction
    out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
    return out

# Store layers weight & bias
weights = {
    # 5x5 conv, 1 input, 32 outputs
    'wc1': tf.Variable(tf.random_normal([5, 5, 1, 32])),
    # 5x5 conv, 32 inputs, 64 outputs
    'wc2': tf.Variable(tf.random_normal([5, 5, 32, 5])),
    # fully connected, 7*7*64 inputs, 1024 outputs
    'wd1': tf.Variable(tf.random_normal([7*7*64, 1024])),
    # 1024 inputs, 10 outputs (class prediction)
    'out': tf.Variable(tf.random_normal([1024, n_classes]))
}

biases = {
    'bc1': tf.Variable(tf.random_normal([32])),
    'bc2': tf.Variable(tf.random_normal([64])),
    'bd1': tf.Variable(tf.random_normal([1024])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}


问:
Angular SSR double loading on client
I have an angular 7.2.16 application and due to SEO reason I installed angular SSR as described in https://angular.io/guide/universal. When I load the application I noticed that it's loaded twice, i.e. on the client I have an html version at the beginning and when the javascript is executed on the client then it shows a loader re-brings everything.

I checked link, I installed and I still have the same issue. The way I have implemented it doesn't make sense that this solution is going to work. For instance:

```<code>  ngOnInit()  {

    this.myItems = []
    this.spinner.show();
    this.httpClient.post(myurl).subscribe((val) => {
        this.myItems = val; // it has images that are shown on html through ngFor

        // add some og: metadata

        this.spinner.hide();
      }, (err) => {

         this.spinner.hide();
    });
  }
</code>```

On the client I get the full html version at the beginning...Due to TransferHttpCacheModule  the httpClient is intercepted so it will not call it again. Since I don't have any condition that I'm on the client or server side it seems that it's going to be executed twice, which what it happens.

What I have to solve are:
1. On the server having proper og meta tags
2. On the client do not show something that has already been loaded on the server, or do not show any content when I'm on client.

Any ideas would be helpful.

答:
After some searching and with the help of @David this was the solution:</p>

```<code>import {Inject, Injectable, PLATFORM_ID} from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

...

constructor(@Inject(PLATFORM_ID) private _platformId: Object){}

  ngOnInit()  {

    this.myItems = []
    this.spinner.show();
    this.httpClient.post(myurl).subscribe((val) => {

        if (isPlatformBrowser(this._platformId)) {
            this.myItems = val; // it has images that are shown on html through ngFor
        }
        // add some og: metadata

        this.spinner.hide();
      }, (err) => {

         this.spinner.hide();
    });
  }
</code>```

Title: Angular SSR double loading on client

Body:
I have an angular 7.2.16 application and due to SEO reason I installed angular SSR as described in https://angular.io/guide/universal. When I load the application I noticed that it's loaded twice, i.e. on the client I have an html version at the beginning and when the javascript is executed on the client then it shows a loader re-brings everything.

I checked link, I installed and I still have the same issue. The way I have implemented it doesn't make sense that this solution is going to work. For instance:

  ngOnInit()  {

    this.myItems = []
    this.spinner.show();
    this.httpClient.post(myurl).subscribe((val) => {
        this.myItems = val; // it has images that are shown on html through ngFor

        // add some og: metadata

        this.spinner.hide();
      }, (err) => {

         this.spinner.hide();
    });
  }

On the client I get the full html version at the beginning...Due to TransferHttpCacheModule  the httpClient is intercepted so it will not call it again. Since I don't have any condition that I'm on the client or server side it seems that it's going to be executed twice, which what it happens.

What I have to solve are:
1. On the server having proper og meta tags
2. On the client do not show something that has already been loaded on the server, or do not show any content when I'm on client.

Any ideas would be helpful.

Body:
After some searching and with the help of @David this was the solution:

import {Inject, Injectable, PLATFORM_ID} from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

...

constructor(@Inject(PLATFORM_ID) private _platformId: Object){}

  ngOnInit()  {

    this.myItems = []
    this.spinner.show();
    this.httpClient.post(myurl).subscribe((val) => {

        if (isPlatformBrowser(this._platformId)) {
            this.myItems = val; // it has images that are shown on html through ngFor
        }
        // add some og: metadata

        this.spinner.hide();
      }, (err) => {

         this.spinner.hide();
    });
  }


问:
How to import an existing data factory ARM template?
I went to an existing data factory, and chose to export template:

I then manually created a new data factory, and now I am trying to import the existing data factory to this new one, by going to the new one, and selecting import template:

However, this leads us to a generic page:

How do we publish or import a data factory using the same templates as were generated when we exported the data factory?

答:
Unzip the file you got when you hit "Export ARM Template" in ADF.

If you hit "Build your own template in the editor" you can then click "Load file" to upload the file named "arm_template.json" from the zip, then hit "Save" at the bottom.

Then click the "Edit Parameters" button and upload the "arm_template_parameters.json" file the same way as above, change the "factoryName" field' value to the desired factory and hit "Save" again.

Note: If you have any passwords or other hidden credentials you will have to re-enter them.

You should be all set to hit purchase and you will be able to create your ADF Factory from the ARM templates.


问:
LeetCode Dynamic Programming Robber Question Mistake
I am currently doing LeetCode's Robber Question. I passed 68/69 test cases, and the only one I failed is the following: an array full or zeros like this [0, 0, 0, 0, 0.....]. Can you please explain to me how to fix my code to fix this error? Also, if you have any suggestions about optimization, please let me know! My code:</p>

```<code>class Solution {
public int rob(int[] nums) {

    if (nums.length == 0 ) {
        return 0;
    }

    if (nums.length == 1) {
        return nums[0];
    }

    int[] memo = new int[nums.length];

    return Math.max(dp(0, nums, memo), dp(1, nums, memo));

}

public int dp(int index, int[] nums, int[] memo)  {

    int max;

    if (memo[index] != 0) {
        return memo[index];
    }

    if (index == nums.length - 1 || index == nums.length - 2) {
        max = nums[index];
    } else if (index == nums.length - 3) {
        max = nums[index] + nums[nums.length - 1];
    }
        else {
        max = Math.max(nums[index] + dp(index + 2, nums, memo), nums[index] + dp(index + 3, nums, memo));
    }

    memo[index] = max;
    return max;

}
}
</code>```

答:
This is how I have solved the same problem using bottom up DP which handles every test cases.

```<code>class Solution {
    public int rob(int[] nums) {
     int n=nums.length;
     if(n==0)
         return 0;
     if(n==1)
          return nums[0];

     int[] dp= new int[n];
     dp[0]=nums[0];
     dp[1]=Math.max(nums[0],nums[1]);
     for(int i=2;i<n;i++)
      dp[i]=Math.max(dp[i-1],dp[i-2]+nums[i]);
      return dp[n-1];
    }
</code>```

The reason your code is failing for [0,0,0,0....] is because the answer is zero and your recursion base case if(memo[index] != 0) is never getting satisfied and resulting in StackOverflow . Below is the correct version of your code

```<code> class Solution {
    public int rob(int[] nums) {

        if (nums.length == 0 ) {
            return 0;
        }

        if (nums.length == 1) {
            return nums[0];
        }

        int[] memo = new int[nums.length];
        Arrays.fill(memo,Integer.MAX_VALUE); // add this to check if memo is not updated
        return Math.max(dp(0, nums, memo), dp(1, nums, memo));

    }

    public int dp(int index, int[] nums, int[] memo)  {

        int max;

        if (memo[index] != Integer.MAX_VALUE) { // check for this condition
            return memo[index];
        }

        if (index == nums.length - 1 || index == nums.length - 2) {
            max = nums[index];
        } else if (index == nums.length - 3) {
            max = nums[index] + nums[nums.length - 1];
        }
            else {
            max = Math.max(nums[index] + dp(index + 2, nums, memo), nums[index] + dp(index + 3, nums, memo));
        }

        memo[index] = max;
        return max;
    }
    }
</code>```

Body:
I am currently doing LeetCode's Robber Question. I passed 68/69 test cases, and the only one I failed is the following: an array full or zeros like this [0, 0, 0, 0, 0.....]. Can you please explain to me how to fix my code to fix this error? Also, if you have any suggestions about optimization, please let me know! My code:

class Solution {
public int rob(int[] nums) {

    if (nums.length == 0 ) {
        return 0;
    }

    if (nums.length == 1) {
        return nums[0];
    }

    int[] memo = new int[nums.length];

    return Math.max(dp(0, nums, memo), dp(1, nums, memo));

}

public int dp(int index, int[] nums, int[] memo)  {

    int max;

    if (memo[index] != 0) {
        return memo[index];
    }

    if (index == nums.length - 1 || index == nums.length - 2) {
        max = nums[index];
    } else if (index == nums.length - 3) {
        max = nums[index] + nums[nums.length - 1];
    }
        else {
        max = Math.max(nums[index] + dp(index + 2, nums, memo), nums[index] + dp(index + 3, nums, memo));
    }

    memo[index] = max;
    return max;

}
}

Body:
This is how I have solved the same problem using bottom up DP which handles every test cases.

class Solution {
    public int rob(int[] nums) {
     int n=nums.length;
     if(n==0)
         return 0;
     if(n==1)
          return nums[0];

     int[] dp= new int[n];
     dp[0]=nums[0];
     dp[1]=Math.max(nums[0],nums[1]);
     for(int i=2;i<n;i++)
      dp[i]=Math.max(dp[i-1],dp[i-2]+nums[i]);
      return dp[n-1];
    }

The reason your code is failing for [0,0,0,0....] is because the answer is zero and your recursion base case if(memo[index] != 0) is never getting satisfied and resulting in StackOverflow . Below is the correct version of your code

 class Solution {
    public int rob(int[] nums) {

        if (nums.length == 0 ) {
            return 0;
        }

        if (nums.length == 1) {
            return nums[0];
        }

        int[] memo = new int[nums.length];
        Arrays.fill(memo,Integer.MAX_VALUE); // add this to check if memo is not updated
        return Math.max(dp(0, nums, memo), dp(1, nums, memo));

    }

    public int dp(int index, int[] nums, int[] memo)  {

        int max;

        if (memo[index] != Integer.MAX_VALUE) { // check for this condition
            return memo[index];
        }

        if (index == nums.length - 1 || index == nums.length - 2) {
            max = nums[index];
        } else if (index == nums.length - 3) {
            max = nums[index] + nums[nums.length - 1];
        }
            else {
            max = Math.max(nums[index] + dp(index + 2, nums, memo), nums[index] + dp(index + 3, nums, memo));
        }

        memo[index] = max;
        return max;
    }
    }


问:
Dynamically calling JS files to load in classic asp application - what was our developer trying to achieve?
I've recently taken over development of a classic ASP application after the sole developer on the project left. There is the following bit of code which for the life of me I can't work out the benefit of, maybe some of you more experienced guys and gals could shed some light on the logic?

In the head section of our default.asp page, the code calls an another asp page with a parameter in order to load/include some files. This asp page reads the parameter and then selects an array of files. It then loops through this array, and for each object in the array, it performs the following function:

```<code>Sub SendFile(ByRef sFilename)
    If Len(sFilename) = 0 Then
        Exit Sub
    End If

    If IsEmpty([__SendFile_sSuffixCompressed]) Then
        [__SendFile_sSuffixCompressed] = ".js"
    End If

    If IsEmpty([__SendFile_fso]) Then
        Set [__SendFile_fso] = Server.CreateObject("Scripting.FileSystemObject")
    End If

    Dim sPath
    sPath = Server.MapPath(sFilename)
    Dim stream
    Dim sData
    Set stream = Server.CreateObject("ADODB.Stream")
    Response.Write sPath
    With stream
        .Charset = "utf-8"
        .Type = 2
        .Open
        .LoadFromFile sPath
        sData = .ReadText
        .Close
    End With

    OurResponse.Write sData
End Sub
</code>```

I would have thought this would be a way of dynamically loading those files, but wouldn't it be much easier just to have a conditional IF block around a normal

答: A

Body:
I've recently taken over development of a classic ASP application after the sole developer on the project left. There is the following bit of code which for the life of me I can't work out the benefit of, maybe some of you more experienced guys and gals could shed some light on the logic?

In the head section of our default.asp page, the code calls an another asp page with a parameter in order to load/include some files. This asp page reads the parameter and then selects an array of files. It then loops through this array, and for each object in the array, it performs the following function:

Sub SendFile(ByRef sFilename)
    If Len(sFilename) = 0 Then
        Exit Sub
    End If

    If IsEmpty([__SendFile_sSuffixCompressed]) Then
        [__SendFile_sSuffixCompressed] = ".js"
    End If

    If IsEmpty([__SendFile_fso]) Then
        Set [__SendFile_fso] = Server.CreateObject("Scripting.FileSystemObject")
    End If

    Dim sPath
    sPath = Server.MapPath(sFilename)
    Dim stream
    Dim sData
    Set stream = Server.CreateObject("ADODB.Stream")
    Response.Write sPath
    With stream
        .Charset = "utf-8"
        .Type = 2
        .Open
        .LoadFromFile sPath
        sData = .ReadText
        .Close
    End With

    OurResponse.Write sData
End Sub

I would have thought this would be a way of dynamically loading those files, but wouldn't it be much easier just to have a conditional IF block around a normal

Body:
A <script src"...> line will load a script from a valid URL, but perhaps this is a way for the web application to include script files on the server that are elsewhere on the filesystem not directly accessible by public URL?

I am not sure why you would want to do this because one could still call this ASP page from a public URL to get the scripts however so it really wouldn't buy you security, just obfuscation.

I am personally a huge fan of deleting code whenever possible.  Try replacing this functionality with a conditional script tag like you mentioned on a development environment and test for changes.  If their is any hidden reasons for this nonsense then you should be able to find them.


问:
How to squash commits which have merge-commit in between?
I am working on a feature branch.

Made several commits. Squashed commits.

Pushed changes to remote branch. Got conflicts.

Merged changes from master, resolved conflicts on feature branch.

git fetch origin master

git merge FETCH_HEAD

Resolved conflicts manually.

git commit

git push

I made one more commit.

So, current commit history looks like this.
From current to old:

commit 3

commit M yyy (Merged)

commit 2

How do I squash above 3 commits into 1 before I merge my feature branch to master?

答:
You can use the tool I've created specifically for this task:

https://github.com/sheerun/git-squash

It's only necessary to merge master branch, and then run squashing command:

```<code>git merge master
git squash master
</code>```

Body:
You can use the tool I've created specifically for this task:

https://github.com/sheerun/git-squash

It's only necessary to merge master branch, and then run squashing command:

git merge master
git squash master


问:
find_all() method from BeautifulSoup returns empty list
I am new to programming and also new to pyhon.

My intension is to built an ebay webscraper.

I am trying to extract an list of links with the bs4 find_all() method, but no matter what I try, it returns always an empty list.

```<code>def get_index_data(soup):

    try:
        links = soup.find_all('a', {'class': 's-item__link'})
        print(links)
    except:
        links = []
        print(links)
</code>```

I wrote it also that way.

```<code>links = soup.find_all('a', class_= 's-item__link')
</code>```

It also returns an empty list. I absolutely don´t know what is wrong

Edit:

```<code>    import requests
from bs4 import BeautifulSoup

def get_page(url):

    response = requests.get(url)

    if not response.ok:
        print('server responded: ', response.status_code)
    else:
        soup = BeautifulSoup(response.text, 'lxml')
    return soup

def get_index_data(soup):
    links = soup.find_all('a')

    print(links)

def main():

    url = 'https://www.ebay.de/sch/i.html?_nkw=armbanduhr&_pgn=1 '
    get_index_data(get_page(url))

if __name__ == '__main__':
    main()
</code>```

Edit2

Error after I run the code with only .find_all('a')

```<code>Traceback (most recent call last):
  File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 29, in <module>
    main()
  File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 25, in main
    get_index_data(get_page(url))
  File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 19, in get_index_data
    print(links)
  File "C:\Users\Aleksandar\AppData\Local\Programs\Python\Python38\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2705' in position 28776: character maps to <undefined>
</code>```

答:
Your code do not show us the url that you are trying to parse.

Please... Try to undestand the Concepts parsing one simple page...

Ebay uses JavaScript and it is a little bit harder to scrape...

I will write down a simple one...

Hope that help you to understand some concepts...

```<code>from bs4 import BeautifulSoup
import requests

page = "https://en.wikipedia.org/wiki/Main_Page"

page_text = requests.get(page).text

soup = BeautifulSoup(page_text, 'lxml')

# print(soup)
links = []
links = soup.find_all("a")

for link in links:
    print(link)
</code>```

Body:
I am new to programming and also new to pyhon.

My intension is to built an ebay webscraper.

I am trying to extract an list of links with the bs4 find_all() method, but no matter what I try, it returns always an empty list.

def get_index_data(soup):

    try:
        links = soup.find_all('a', {'class': 's-item__link'})
        print(links)
    except:
        links = []
        print(links)

I wrote it also that way.

links = soup.find_all('a', class_= 's-item__link')

It also returns an empty list. I absolutely don´t know what is wrong

Edit:

    import requests
from bs4 import BeautifulSoup

def get_page(url):

    response = requests.get(url)

    if not response.ok:
        print('server responded: ', response.status_code)
    else:
        soup = BeautifulSoup(response.text, 'lxml')
    return soup

def get_index_data(soup):
    links = soup.find_all('a')

    print(links)

def main():

    url = 'https://www.ebay.de/sch/i.html?_nkw=armbanduhr&_pgn=1 '
    get_index_data(get_page(url))

if __name__ == '__main__':
    main()

Edit2

Error after I run the code with only .find_all('a')

Traceback (most recent call last):
  File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 29, in <module>
    main()
  File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 25, in main
    get_index_data(get_page(url))
  File "C:\Users\Aleksandar\Desktop\My ebay scraper\test", line 19, in get_index_data
    print(links)
  File "C:\Users\Aleksandar\AppData\Local\Programs\Python\Python38\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2705' in position 28776: character maps to <undefined>

Body:
Your code do not show us the url that you are trying to parse.

Please... Try to undestand the Concepts parsing one simple page...

Ebay uses JavaScript and it is a little bit harder to scrape...

I will write down a simple one...

Hope that help you to understand some concepts...

from bs4 import BeautifulSoup
import requests

page = "https://en.wikipedia.org/wiki/Main_Page"

page_text = requests.get(page).text

soup = BeautifulSoup(page_text, 'lxml')

# print(soup)
links = []
links = soup.find_all("a")

for link in links:
    print(link)


问:
Place point over boxplot using plotlyjs and vue
I'm trying to place point over boxplot, however my attempt results in the point placed next to the boxplot:

```<code> data: [
        {
          x: [1, 2, 3, 4, 4, 4, 8, 9, 10],
          type: "box",
          name: "Set 1"
        },
        {
          x: [5],
          name: 'My special marker',
          text: 'Some really interesting hover info',
          marker: {
            size: 5
          }
        },
      ],
      layout: {
        title: 'Revenues',
        font:{
        size:10
        },
        margin: {
          l: 0,
          r: 0,
          b: 15,
          t: 25,
          pad: 0
        },
        height: 90,
        dragmode: "pan"
      },
</code>```

Is it possible to place that point over boxplot using vue-plotly library?

Here I recreted the issue:
https://codesandbox.io/s/vue-plotly-delsw?file=/src/App.vue

EDIT:
For the desired result I need that addiotional point to be on top of the chart like this:

答:
One solution is to set the size of the point's marker and the width of the bar such that they overlap each other.  For example:

      data: [
        {
          x: [1, 2, 3, 4, 4, 4, 8, 9, 10],
          type: "box",
          name: "Set 1",
          width: 30,
        },
        {
          x: [5],
          name: "My special marker",
          text: "Some really interesting hover info",
          marker: {
            size: 30
          }
        }
      ],
```

Body:
I'm trying to place point over boxplot, however my attempt results in the point placed next to the boxplot:

 data: [
        {
          x: [1, 2, 3, 4, 4, 4, 8, 9, 10],
          type: "box",
          name: "Set 1"
        },
        {
          x: [5],
          name: 'My special marker',
          text: 'Some really interesting hover info',
          marker: {
            size: 5
          }
        },
      ],
      layout: {
        title: 'Revenues',
        font:{
        size:10
        },
        margin: {
          l: 0,
          r: 0,
          b: 15,
          t: 25,
          pad: 0
        },
        height: 90,
        dragmode: "pan"
      },

Is it possible to place that point over boxplot using vue-plotly library?

Here I recreted the issue:
https://codesandbox.io/s/vue-plotly-delsw?file=/src/App.vue

EDIT:
For the desired result I need that addiotional point to be on top of the chart like this:


问:
How to display user json data base on href id?
Ihave Json data stored in my main local folder and I want to display user data into another page "view.php" if i-click View User Data href="view.php?id=1" automatically user id=1 is displayed in view.php file.

data.json

```<code>{
    "UserData": [

    {
        "id": "1",
        "fname": "Joey",
        "lname": "Tulang",
        "age": "29",
        "gender": "Male"
    },
    {
        "id": "2",
        "fname": "Angelica",
        "lname": "Bacle",
        "age": "20",
        "gender": "Female"
    },
    {
        "id": "3",
        "fname": "Mj",
        "lname": "King",
        "age": "21",
        "gender": "male"
    }

    ]
}
</code>```

index.php

```<code>$jsondata = file_get_contents("data.json");
$json = json_decode($jsondata, true);
$output = "<ul>";

  foreach ( $json['UserData'] as $display ) {

    $output .="<li>" .$display['fname']. " <a href='view.php?".$display['id']."'>View User Data</a></li> </br>";

  }

  $output .= "</ul>";

  echo $output;
</code>```

Output:

https://ibb.co/MCfgWVZ

view.php

```<code><!DOCTYPE html>
<html>
<head>
    <title>View User Data</title>
</head>
<body>

    <!-- Display User Data Here -->

    <p>First Name: </p>
    <p>Last Name: </p>
    <p>Age: </p>
    <p>Gender: </p>

</body>
</html>
</code>```

答:
index.php

Your forgetting the id param and just setting the number.

```<code>$jsondata = file_get_contents("data.json");
$json = json_decode($jsondata, true);
$output = "<ul>";

foreach ( $json['UserData'] as $display ) {
  $output .="<li>" .$display['fname']. " <a href='view.php?id=".$display['id']."'>View User Data</a></li> </br>";
}

$output .= "</ul>";

echo $output;
</code>```

view.php

Use $_GET['id'] to query your json:

```<code><?php
$jsondata = file_get_contents("data.json");
$json = json_decode($jsondata, true);

$key = array_search((int) $_GET['id'], array_column($json['UserData'], 'id'));

// if $key false, was not found, presume it was...

$user = $json['UserData'][$key];
?>
<!DOCTYPE html>
<html>
<head>
    <title>View User Data</title>
</head>
<body>

    <!-- Display User Data Here -->

    <p>First Name: <?= $user['fname'] ?></p>
    <p>Last Name: <?= $user['lname'] ?></p>
    <p>Age: <?= $user['age'] ?></p>
    <p>Gender: <?= $user['gender'] ?></p>

</body>
</html>
</code>```

Body:
Ihave Json data stored in my main local folder and I want to display user data into another page "view.php" if i-click View User Data href="view.php?id=1" automatically user id=1 is displayed in view.php file.

data.json

{
    "UserData": [

    {
        "id": "1",
        "fname": "Joey",
        "lname": "Tulang",
        "age": "29",
        "gender": "Male"
    },
    {
        "id": "2",
        "fname": "Angelica",
        "lname": "Bacle",
        "age": "20",
        "gender": "Female"
    },
    {
        "id": "3",
        "fname": "Mj",
        "lname": "King",
        "age": "21",
        "gender": "male"
    }

    ]
}

index.php

$jsondata = file_get_contents("data.json");
$json = json_decode($jsondata, true);
$output = "
";

  foreach ( $json['UserData'] as $display ) {

    $output .="
" .$display['fname']. " View User Data

";

  }

  $output .= "
";

  echo $output;

Output:

https://ibb.co/MCfgWVZ

view.php

<!DOCTYPE html>

    <title>View User Data</title>

First Name:

Last Name:

Age:

Gender:

Body:
index.php

Your forgetting the id param and just setting the number.

$jsondata = file_get_contents("data.json");
$json = json_decode($jsondata, true);
$output = "<ul>";

foreach ( $json['UserData'] as $display ) {
  $output .="<li>" .$display['fname']. " <a href='view.php?id=".$display['id']."'>View User Data</a></li> </br>";
}

$output .= "</ul>";

echo $output;

view.php

Use $_GET['id'] to query your json:

<?php
$jsondata = file_get_contents("data.json");
$json = json_decode($jsondata, true);

$key = array_search((int) $_GET['id'], array_column($json['UserData'], 'id'));

// if $key false, was not found, presume it was...

$user = $json['UserData'][$key];
?>
<!DOCTYPE html>
<html>
<head>
    <title>View User Data</title>
</head>
<body>

    <!-- Display User Data Here -->

    <p>First Name: <?= $user['fname'] ?></p>
    <p>Last Name: <?= $user['lname'] ?></p>
    <p>Age: <?= $user['age'] ?></p>
    <p>Gender: <?= $user['gender'] ?></p>

</body>
</html>


问:
Kafka AMQ Stream - Topics command
I've never used AMQ Streams (Kafka). How can I connect to topics through the route (read/create/delete)? With Kafka, for example from my local machine, I used the CLI with the basic command. But with AMQ Streams I have only the route. It is a HTTPS URL.</p>

答:
I am guessing you are using the AMQ Streams Operator to run your Pods. There is a good explanation in the following blog post on how to use OpenShift Routes to connect to Kafka.

The Route can be exposed by defining it in the Kafka object like so:

```<code>apiVersion: kafka.strimzi.io/v1beta1
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
    listeners:
      # ...
      external:
        type: route
    # ...
</code>```

Title: Kafka AMQ Stream - Topics command

Body:
I am guessing you are using the AMQ Streams Operator to run your Pods. There is a good explanation in the following blog post on how to use OpenShift Routes to connect to Kafka.

The Route can be exposed by defining it in the Kafka object like so:

apiVersion: kafka.strimzi.io/v1beta1
kind: Kafka
metadata:
  name: my-cluster
spec:
  kafka:
    # ...
    listeners:
      # ...
      external:
        type: route
    # ...


问:
Understanding nested Monad constraints
Say I have the following type:

```<code>data Row = Row
  {
    id                          :: !AddressID
  }
</code>```

with the following internal transformation function:

```<code>makeAddress :: MonadIO m => MonadError Error m => Connection -> Row -> m Address
makeAddress _ Row{..} = return $ Address "Potato"
</code>```

I then have the following function to read from a database using Postgres.Simple:

```<code>findMany
  :: MonadIO m
  => MonadReader Context m
  => MonadError Error m
  => [AddressID]
  -> m [Address]

findMany ids = do
  db <- view Context.db
  xs <- liftIO $ PG.query db sql_query_addr $ PG.Only (PG.In (map unAddressId ids))
  if (length xs) == (length ids)
    then do
      let addresses = concat (map (makeAddress db) xs)
      return addresses
    else
      throwError $ AddressNotFound Nothing

-----------------------------------------------------------------------------------------------------------------------

sql_query_addr :: PG.Query
sql_query_addr = [qms|
  SELECT *
  FROM addresses a
  WHERE a.id in ?
|]
</code>```

This fails to compile with:

```<code>    • Could not deduce (MonadIO [])
        arising from a use of ‘makeAddress’
      from the context: (MonadIO m, MonadReader Context m,
                         MonadError Error m)
        bound by the type signature for:
                   findMany :: forall (m :: * -> *).
                               (MonadIO m, MonadReader Context m, MonadError Error m) =>
                               [AddressID] -> m [Address]
        at app/Impl/ReadModelApi/FindMany.hs:(22,1)-(27,18)
    • In the first argument of ‘map’, namely ‘(makeAddress db)’
      In the first argument of ‘concat’, namely
        ‘(map (makeAddress db) xs)’
      In the expression: concat (map (makeAddress db) xs)
   |
34 |       let quotations = concat (map (makeAddress db) xs)
   |                                     ^^^^^^^^^^^^^^^^^
</code>```

I realize that my makeAddress function is needlessly complex, this is a minimal case, boiled down from a much larger, more sideffecty transformation function.

But I don't understand why this fails to compile, I would have thought that:

Given this type: makeAddress :: MonadIO m => MonadError Error m => Connection -> Row -> m Address, the type of makeAddress db is MonadIO m => MonadError Error m -> Row -> m Address. Given xs has type [Row], map (makeAddress db) xs should give [Addresses].

And given that both the inner and outer m (in makeAddress and in findMany) is an instance of the MonadIO typeclass, these should be compatible monads?

Clearly this is incorrect, but I have no idea where my reasoning breaks down, or how to therefore fix my implementation.

答:
You say:

```<code>makeAddress :: MonadIO m => MonadError Error m => Connection -> Row -> m Address
</code>```

Sure. And:

```<code>makeAddress db :: MonadIO m => MonadError Error m -> Row -> m
</code>```

Close enough. It's actually m Address at the end, but I assume this was just a typo. And:

```<code>map (makeAddress db) xs :: [Address]
</code>```

This is your first mistake. You have lost the m! It is actually:

```<code>map (makeAddress db) xs :: MonadIO m => MonadError Error m => [m Address]
</code>```

The explanation for the error is that we have

```<code>concat :: [[a]] -> [a]
</code>```

and so, for [m Address] to be equal to [[a]], we must choose m ~ [] and a ~ Address¹; but then [] is not a monad that can do IO, so the MonadIO m constraint isn't satisfied. Whoops!

Instead of concat, you can use sequenceA:

```<code>sequenceA :: Applicative m => [m a] -> m [a]
-- OR, specializing,
sequenceA :: MonadIO m => MonadError m => [m Address] -> m [Address]
</code>```

This map-sequenceA combo is so common, it has its own name:

```<code>traverse :: Applicative m => (a -> m b) -> [a] -> m [b]
</code>```

¹ If you haven't seen ~ before, you may replace it with = everywhere in this answer and nothing of importance will be lost.

Title: Understanding nested Monad constraints

Body:
Say I have the following type:

data Row = Row
  {
    id                          :: !AddressID
  }

with the following internal transformation function:

makeAddress :: MonadIO m => MonadError Error m => Connection -> Row -> m Address
makeAddress _ Row{..} = return $ Address "Potato"

I then have the following function to read from a database using Postgres.Simple:

findMany
  :: MonadIO m
  => MonadReader Context m
  => MonadError Error m
  => [AddressID]
  -> m [Address]

findMany ids = do
  db <- view Context.db
  xs <- liftIO $ PG.query db sql_query_addr $ PG.Only (PG.In (map unAddressId ids))
  if (length xs) == (length ids)
    then do
      let addresses = concat (map (makeAddress db) xs)
      return addresses
    else
      throwError $ AddressNotFound Nothing

-----------------------------------------------------------------------------------------------------------------------

sql_query_addr :: PG.Query
sql_query_addr = [qms|
  SELECT *
  FROM addresses a
  WHERE a.id in ?
|]

This fails to compile with:

    • Could not deduce (MonadIO [])
        arising from a use of ‘makeAddress’
      from the context: (MonadIO m, MonadReader Context m,
                         MonadError Error m)
        bound by the type signature for:
                   findMany :: forall (m :: * -> *).
                               (MonadIO m, MonadReader Context m, MonadError Error m) =>
                               [AddressID] -> m [Address]
        at app/Impl/ReadModelApi/FindMany.hs:(22,1)-(27,18)
    • In the first argument of ‘map’, namely ‘(makeAddress db)’
      In the first argument of ‘concat’, namely
        ‘(map (makeAddress db) xs)’
      In the expression: concat (map (makeAddress db) xs)
   |
34 |       let quotations = concat (map (makeAddress db) xs)
   |                                     ^^^^^^^^^^^^^^^^^

I realize that my makeAddress function is needlessly complex, this is a minimal case, boiled down from a much larger, more sideffecty transformation function.

But I don't understand why this fails to compile, I would have thought that:

Given this type: makeAddress :: MonadIO m => MonadError Error m => Connection -> Row -> m Address, the type of makeAddress db is MonadIO m => MonadError Error m -> Row -> m Address. Given xs has type [Row], map (makeAddress db) xs should give [Addresses].

And given that both the inner and outer m (in makeAddress and in findMany) is an instance of the MonadIO typeclass, these should be compatible monads?

Clearly this is incorrect, but I have no idea where my reasoning breaks down, or how to therefore fix my implementation.

Body:
You say:

makeAddress :: MonadIO m => MonadError Error m => Connection -> Row -> m Address

Sure. And:

makeAddress db :: MonadIO m => MonadError Error m -> Row -> m

Close enough. It's actually m Address at the end, but I assume this was just a typo. And:

map (makeAddress db) xs :: [Address]

This is your first mistake. You have lost the m! It is actually:

map (makeAddress db) xs :: MonadIO m => MonadError Error m => [m Address]

The explanation for the error is that we have

concat :: [[a]] -> [a]

and so, for [m Address] to be equal to [[a]], we must choose m ~ [] and a ~ Address¹; but then [] is not a monad that can do IO, so the MonadIO m constraint isn't satisfied. Whoops!

Instead of concat, you can use sequenceA:

sequenceA :: Applicative m => [m a] -> m [a]
-- OR, specializing,
sequenceA :: MonadIO m => MonadError m => [m Address] -> m [Address]

This map-sequenceA combo is so common, it has its own name:

traverse :: Applicative m => (a -> m b) -> [a] -> m [b]

¹ If you haven't seen ~ before, you may replace it with = everywhere in this answer and nothing of importance will be lost.


问:
Why aren't I getting any definitions when I type "get-command -type cmdlet"?
This is my first day learning powershell so forgive me if this is a silly question...

But the instruction video I am watching shows the teacher typing in  "get-command -type cmdlet" to demonstrate how to get a list of all available cmdlets and their definitions. I'm getting the cmdlets, but my powershell is not listing the definitions. I'm attaching screenshots to show you the what he has and what I have. what changes do I have to make to get this fixed?

答:
The command get-command -type cmdlet does not show definitions. Perhaps you want to see the definition of get-command? :)

To see definitions, you can use one of two things, if the command supports it, you can simply add a -? after the command to get help. Example:

```<code>get-command -?
</code>```

-? is equivalent to --h or --help in bash. Some commands don't support taht since that would be an argument in the command like in if commands. For these types of commands, you can use:

```<code>get-help if
</code>```

And it will either show you help for if or show you things that have similar names that you can get help about. An example of this would be the break command. break does not support the -? method so you would have to use get-help break but it will not appear there either. Instead you get the output of:

```<code>Name                              Category  Module                    Synopsis
----                              --------  ------                    --------
Disable-PSBreakpoint              Cmdlet    Microsoft.PowerShell.U... Disables the breakpoints in the current console.
Enable-PSBreakpoint               Cmdlet    Microsoft.PowerShell.U... Enables the breakpoints in the current console.
Get-PSBreakpoint                  Cmdlet    Microsoft.PowerShell.U... Gets the breakpoints that are set in the curre...
Remove-PSBreakpoint               Cmdlet    Microsoft.PowerShell.U... Deletes breakpoints from the current console.
Set-PSBreakpoint                  Cmdlet    Microsoft.PowerShell.U... Sets a breakpoint on a line, command, or varia...
about_Break                       HelpFile                            Describes a statement you can use to immediate...

</code>```

Which you can see has the break help-file under the alias about_Break. So if I type get-help about_Break it will show me help.

You can also use get-help to find all cmdlets like with get-command with get-help -type cmdlet but if you want to check that out I suggest you look at help for get-help :).

MORE INFO (Literally): You can find more info about certain cmdlets if it is available using one of the four commands below:

```<code>To see the examples, type: "get-help <command name> -examples".
For more information, type: "get-help <command name> -detailed".
For technical information, type: "get-help <command name> -full".
For online help, type: "get-help <command name> -online"
</code>```

For example (no pun intended), you can find help on get-help using:

```<code>get-help Get-Help -examples
get-help Get-Help -detailed
get-help Get-Help -full
get-help Get-Help -online
</code>```

and the switches will have the criteria above (examples, extra information, technical information, and online help since there is more documentation for things online)

Body:
The command get-command -type cmdlet does not show definitions. Perhaps you want to see the definition of get-command? :)

To see definitions, you can use one of two things, if the command supports it, you can simply add a -? after the command to get help. Example:

get-command -?

-? is equivalent to --h or --help in bash. Some commands don't support taht since that would be an argument in the command like in if commands. For these types of commands, you can use:

get-help if

And it will either show you help for if or show you things that have similar names that you can get help about. An example of this would be the break command. break does not support the -? method so you would have to use get-help break but it will not appear there either. Instead you get the output of:

Name                              Category  Module                    Synopsis
----                              --------  ------                    --------
Disable-PSBreakpoint              Cmdlet    Microsoft.PowerShell.U... Disables the breakpoints in the current console.
Enable-PSBreakpoint               Cmdlet    Microsoft.PowerShell.U... Enables the breakpoints in the current console.
Get-PSBreakpoint                  Cmdlet    Microsoft.PowerShell.U... Gets the breakpoints that are set in the curre...
Remove-PSBreakpoint               Cmdlet    Microsoft.PowerShell.U... Deletes breakpoints from the current console.
Set-PSBreakpoint                  Cmdlet    Microsoft.PowerShell.U... Sets a breakpoint on a line, command, or varia...
about_Break                       HelpFile                            Describes a statement you can use to immediate...

Which you can see has the break help-file under the alias about_Break. So if I type get-help about_Break it will show me help.

You can also use get-help to find all cmdlets like with get-command with get-help -type cmdlet but if you want to check that out I suggest you look at help for get-help :).

MORE INFO (Literally): You can find more info about certain cmdlets if it is available using one of the four commands below:

To see the examples, type: "get-help <command name> -examples".
For more information, type: "get-help <command name> -detailed".
For technical information, type: "get-help <command name> -full".
For online help, type: "get-help <command name> -online"

For example (no pun intended), you can find help on get-help using:

get-help Get-Help -examples
get-help Get-Help -detailed
get-help Get-Help -full
get-help Get-Help -online

and the switches will have the criteria above (examples, extra information, technical information, and online help since there is more documentation for things online)


问:
Arabic encoding in Java Studio Creator
I'm using Java Studio Creator with a MySQL dataBase to build my new small system..

When I pass Arabic characters from the browser to the MySQL database, they appear as question marks, ???, in MySQL database.

I check the encoding in the JSP code, it looks like the following.

```<code><?xml version="1.0" encoding="UTF-8"?>
<jsp:root version="1.2" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:ui="http://www.sun.com/web/ui">
<jsp:directive.page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"/>
</code>```

That means it's UTF-8.

I tried encoding like Windows-1256 (code page used to write Arabic), but it gave me strange symbols, not question marks.

Someone here, called "Rashad", suggested to use something called Servletrequest, but I don't know where to put it. And what does Got, Post mean to solve this problem?

答:
For MySQL you need to specify the encoding in the JDBC URL.

So, you should not use this JDBC URL syntax:

```jdbc:mysql://localhost:3306/db_name```

But you should use this JDBC URL syntax:

```jdbc:mysql://localhost:3306/db_name?useUnicode=yes&characterEncoding=UTF-8```

Title: Arabic encoding in Java Studio Creator

Body:
I'm using Java Studio Creator with a MySQL dataBase to build my new small system..

When I pass Arabic characters from the browser to the MySQL database, they appear as question marks, ???, in MySQL database.

I check the encoding in the JSP code, it looks like the following.

<?xml version="1.0" encoding="UTF-8"?>
<jsp:root version="1.2" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:ui="http://www.sun.com/web/ui">
<jsp:directive.page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"/>

That means it's UTF-8.

I tried encoding like Windows-1256 (code page used to write Arabic), but it gave me strange symbols, not question marks.

Someone here, called "Rashad", suggested to use something called Servletrequest, but I don't know where to put it. And what does Got, Post mean to solve this problem?

Body:
For MySQL you need to specify the encoding in the JDBC URL.

So, you should not use this JDBC URL syntax:

jdbc:mysql://localhost:3306/db_name

But you should use this JDBC URL syntax:

jdbc:mysql://localhost:3306/db_name?useUnicode=yes&characterEncoding=UTF-8