问:
PHP/SQL problem: Data from sql wont display
I have this problem on my payroll processing system.
Below the area where the data are added is a table where the data added into the pay table are shown (except for the empID since the payroll details shown on the table must be from those that are associated to the employee that was selected.)

Payroll System image

Please refer to the link above to see image to further understand what's written below.

*[A]*is where the user selects which employee's payroll details be updated. After selecting the radio button and clicking the "Update Payroll Details" button, the user shall be brought to the Update Payroll Details page which is B.

*[B]*The upper part is where the user enters all the payroll details associated to the employee selected. Once the user clicks save the data shall be added to the database (pay table) and these details shall be shown on the table located below the input area.

However, although I have data in my pay table it wouldn't seem to display on the table below that's why the message shows "No Records Found". Here is my code for the entire Update Payroll Data page:

```<code>elseif ($_GET["k"]==41)
{
    session_start();
    if (isset($_SESSION["uname"]))
    {
            $empID=$_POST["empID"];
            $aBulan=0; $aPetsa=0; $aTuig=0; $tuigYana=date("Y"); $tuigHadto=$tuigYana-5;

            $anoBulan=array("January","February","March","April","May","June","July","August","September","October","November","December");

            if ($_POST["sButton"]=="Update Payroll Details")
            {
                    $anoSulod ="Payroll Details<hr>";
                    $anoSulod.="<form method='post' action='logged.php?k=42'>";
                    $anoSulod.="<input type='hidden' name='empID' value='".$empID."'>";
                    $anoSulod.="<table>";
                    $anoSulod.="    <tr><td>Name of employee : </td><td>".accessDatabase::hinoEmployee($empID)."</td></tr>";
                    $anoSulod.="    <tr>";
                    $anoSulod.="            <td>For the month ending : </td>";
                    $anoSulod.="            <td>";

// Kanan month ini dinhi
                    $anoSulod.="                    <select name='bBulan'>";
                    for ($bulan=1; $bulan<=12; $bulan++)
                    {
                        if ($bulan==$aBulan) $anoSulod.="       <option value='".$bulan."' selected>".$anoBulan[$bulan-1];
                        else $anoSulod.="       <option value='".$bulan."'>".$anoBulan[$bulan-1];
                    }
                    $anoSulod.="                    </select> ";

// Kanan year ini dinhi
                    $anoSulod.="                    <select name='bTuig'>";
                    for ($tuig=$tuigYana; $tuig>=$tuigHadto; $tuig--)
                    {
                        if ($tuig==$aTuig) $anoSulod.=" <option value='".$tuig."' selected>".$tuig;
                        else $anoSulod.="       <option value='".$tuig."'>".$tuig;
                    }
                    $anoSulod.="                    </select>";
                    $anoSulod.="            </td>";
                    $anoSulod.="    <tr>";
                    $anoSulod.="    <tr><td>Basic Salary : PhP</td><td><input type='text' name='bs'></td></tr>";
                    $anoSulod.="    <tr><td>PERA/ACA : PhP</td><td><input type='text' name='pa'></td></tr>";
                    $anoSulod.="    <tr><td>PAIC : PhP</td><td><input type='text' name='pc'></td></tr>";
                    $anoSulod.="    <tr><td>REL : PhP</td><td><input type='text' name='rl'></td></tr>";
                    $anoSulod.="    <tr><td>GSIS Premium/Loans : PhP</td><td><input type='text' name='gs'></td></tr>";
                    $anoSulod.="    <tr><td>HDMF Premium/Loans : PhP</td><td><input type='text' name='hd'></td></tr>";
                    $anoSulod.="    <tr><td>Coop Loans : PhP</td><td><input type='text' name='cl'></td></tr>";
                    $anoSulod.="    <tr><td>Union Dues : PhP</td><td><input type='text' name='ud'></td></tr>";
                    $anoSulod.="    <tr><td>Withholding Tax : PhP</td><td><input type='text' name='tx'></td></tr>";
                    $anoSulod.="    <tr><td colspan='2'><hr></tr>";
                    $anoSulod.="    <tr><td colspan='2'><input type='submit' value='Save'></tr>";
                    $anoSulod.="    <tr><td colspan='2'><hr></tr>";
                    $anoSulod.="    <tr>";
                    $anoSulod.="     <td colspan='2'>";
                    $anoSulod.="     <table border='1'>";

                    $anoSulod.="     <caption>Payroll Details</caption>";
                    $anoSulod.="     <tr>";
                    $anoSulod.="     <td> </td>";
                    $anoSulod.="     <td>Pay period</td>";
                    $anoSulod.="     <td>Basic Salary</td>";
                    $anoSulod.="     <td>PERA/ACA</td>";
                    $anoSulod.="     <td>PAIC</td>";
                    $anoSulod.="     <td>REL</td>";
                    $anoSulod.="     <td>GSIS Premium/Loans</td>";
                    $anoSulod.="     <td>HDMF Premium/Loans</td>";
                    $anoSulod.="     <td>Coop Loans</td>";
                    $anoSulod.="     <td>Union Dues</td>";
                    $anoSulod.="     <td>Withholding Tax</td>";
                    $anoSulod.="     </tr>";

                    $k="select b.payID, a.empname, date_format(b.date,'%M %Y') as date, b.bs, b.pa, b.pc, b.rl, b.gs, b.hd, b.cl, b.ud, b.tx, from emp a, pay b where a.empID=b.empID and a.empID=".$empID;
                    $q=mysql_query($k);
                    if (mysql_num_rows($q)>0)
                    {
                        while ($akonRows=mysql_fetch_array($q))
                        {
                            $anoSulod.="    <tr>";
                            $anoSulod.="     <td><input type='radio' name='payID' value='".$akonRows["payID"]."'></td>";
                            $anoSulod.="     <td>".$akonRows["date"]."</td>";
                            $anoSulod.="     <td>".$akonRows["bs"]."</td>";
                            $anoSulod.="     <td>".$akonRows["pa"]."</td>";
                            $anoSulod.="     <td>".$akonRows["pc"]."</td>";
                            $anoSulod.="     <td>".$akonRows["rl"]."</td>";
                            $anoSulod.="     <td>".$akonRows["gs"]."</td>";
                            $anoSulod.="     <td>".$akonRows["hd"]."</td>";
                            $anoSulod.="     <td>".$akonRows["cl"]."</td>";
                            $anoSulod.="     <td>".$akonRows["ud"]."</td>";
                            $anoSulod.="     <td>".$akonRows["tx"]."</td>";
                            $anoSulod.="    </tr>";
                        }
                    }
                    else
                    {
                        $anoSulod.="    <tr>";
                        $anoSulod.="     <td colspan='11' align='center'>No records found</td>";
                        $anoSulod.="    </tr>";
                    }

                    $anoSulod.="     </table>";

                    $anoSulod.="     </td>";
                    $anoSulod.="    </tr>";
                    $anoSulod.="</table>";
                    $anoSulod.="</form>";
                    $kadamoTD=2;
           }

      }
}
</code>```

Please help. I really can't figure out what went wrong. Please do... Thanks so much!

答:
Add the error checking for every mysql_query. At least make a call like:

mysql_query($k) or die(mysql_error());

Was: Don't expect that PHP functions (e.g. date_format) will work inside the SQL query. (Comments say date_format is a MySQL function too)

Body:
I have this problem on my payroll processing system.
Below the area where the data are added is a table where the data added into the pay table are shown (except for the empID since the payroll details shown on the table must be from those that are associated to the employee that was selected.)

Payroll System image

Please refer to the link above to see image to further understand what's written below.

*[A]*is where the user selects which employee's payroll details be updated. After selecting the radio button and clicking the "Update Payroll Details" button, the user shall be brought to the Update Payroll Details page which is B.

*[B]*The upper part is where the user enters all the payroll details associated to the employee selected. Once the user clicks save the data shall be added to the database (pay table) and these details shall be shown on the table located below the input area.

However, although I have data in my pay table it wouldn't seem to display on the table below that's why the message shows "No Records Found". Here is my code for the entire Update Payroll Data page:

elseif ($_GET["k"]==41)
{
    session_start();
    if (isset($_SESSION["uname"]))
    {
            $empID=$_POST["empID"];
            $aBulan=0; $aPetsa=0; $aTuig=0; $tuigYana=date("Y"); $tuigHadto=$tuigYana-5;

            $anoBulan=array("January","February","March","April","May","June","July","August","September","October","November","December");

            if ($_POST["sButton"]=="Update Payroll Details")
            {
                    $anoSulod ="Payroll Details
";
                    $anoSulod.="<form method='post' action='logged.php?k=42'>";
                    $anoSulod.="<input type='hidden' name='empID' value='".$empID."'>";
                    $anoSulod.="
";
                    $anoSulod.="
Name of employee : 	".accessDatabase::hinoEmployee($empID)."
";
                    $anoSulod.="
";
                    $anoSulod.="            For the month ending : 	";
                    $anoSulod.="            ";

// Kanan month ini dinhi
                    $anoSulod.="                    <select name='bBulan'>";
                    for ($bulan=1; $bulan<=12; $bulan++)
                    {
                        if ($bulan==$aBulan) $anoSulod.="       <option value='".$bulan."' selected>".$anoBulan[$bulan-1];
                        else $anoSulod.="       <option value='".$bulan."'>".$anoBulan[$bulan-1];
                    }
                    $anoSulod.="                    </select> ";

// Kanan year ini dinhi
                    $anoSulod.="                    <select name='bTuig'>";
                    for ($tuig=$tuigYana; $tuig>=$tuigHadto; $tuig--)
                    {
                        if ($tuig==$aTuig) $anoSulod.=" <option value='".$tuig."' selected>".$tuig;
                        else $anoSulod.="       <option value='".$tuig."'>".$tuig;
                    }
                    $anoSulod.="                    </select>";
                    $anoSulod.="            	";
                    $anoSulod.="
";
                    $anoSulod.="
Basic Salary : PhP	<input type='text' name='bs'>
";
                    $anoSulod.="
PERA/ACA : PhP	<input type='text' name='pa'>
";
                    $anoSulod.="
PAIC : PhP	<input type='text' name='pc'>
";
                    $anoSulod.="
REL : PhP	<input type='text' name='rl'>
";
                    $anoSulod.="
GSIS Premium/Loans : PhP	<input type='text' name='gs'>
";
                    $anoSulod.="
HDMF Premium/Loans : PhP	<input type='text' name='hd'>
";
                    $anoSulod.="
Coop Loans : PhP	<input type='text' name='cl'>
";
                    $anoSulod.="
Union Dues : PhP	<input type='text' name='ud'>
";
                    $anoSulod.="
Withholding Tax : PhP	<input type='text' name='tx'>
";
                    $anoSulod.="

";
                    $anoSulod.="
<input type='submit' value='Save'>
";
                    $anoSulod.="

";
                    $anoSulod.="
";
                    $anoSulod.="     ";
                    $anoSulod.="
";

                    $anoSulod.="
Payroll Details
";
                    $anoSulod.="
";
                    $anoSulod.="      	";
                    $anoSulod.="     Pay period	";
                    $anoSulod.="     Basic Salary	";
                    $anoSulod.="     PERA/ACA	";
                    $anoSulod.="     PAIC	";
                    $anoSulod.="     REL	";
                    $anoSulod.="     GSIS Premium/Loans	";
                    $anoSulod.="     HDMF Premium/Loans	";
                    $anoSulod.="     Coop Loans	";
                    $anoSulod.="     Union Dues	";
                    $anoSulod.="     Withholding Tax	";
                    $anoSulod.="
";

                    $k="select b.payID, a.empname, date_format(b.date,'%M %Y') as date, b.bs, b.pa, b.pc, b.rl, b.gs, b.hd, b.cl, b.ud, b.tx, from emp a, pay b where a.empID=b.empID and a.empID=".$empID;
                    $q=mysql_query($k);
                    if (mysql_num_rows($q)>0)
                    {
                        while ($akonRows=mysql_fetch_array($q))
                        {
                            $anoSulod.="
";
                            $anoSulod.="     <input type='radio' name='payID' value='".$akonRows["payID"]."'>	";
                            $anoSulod.="     ".$akonRows["date"]."	";
                            $anoSulod.="     ".$akonRows["bs"]."	";
                            $anoSulod.="     ".$akonRows["pa"]."	";
                            $anoSulod.="     ".$akonRows["pc"]."	";
                            $anoSulod.="     ".$akonRows["rl"]."	";
                            $anoSulod.="     ".$akonRows["gs"]."	";
                            $anoSulod.="     ".$akonRows["hd"]."	";
                            $anoSulod.="     ".$akonRows["cl"]."	";
                            $anoSulod.="     ".$akonRows["ud"]."	";
                            $anoSulod.="     ".$akonRows["tx"]."	";
                            $anoSulod.="
";
                        }
                    }
                    else
                    {
                        $anoSulod.="
";
                        $anoSulod.="     No records found	";
                        $anoSulod.="
";
                    }

                    $anoSulod.="
";

                    $anoSulod.="     	";
                    $anoSulod.="
";
                    $anoSulod.="
";
                    $anoSulod.="</form>";
                    $kadamoTD=2;
           }

      }
}

Please help. I really can't figure out what went wrong. Please do... Thanks so much!


来源: stackexchange

问:
Why class instance itself has no public constructor?
While reading Reflection API i got this "Every Java Type has a class Instance And the class instance itself has no public Constructor" .

Now this is really confusing for me. Because what i have read till now says . All classes have constructor even when we don't specify any, we get constructor by default (even if the class is static) once we create its instance. Can someone explain me this in simple word

(to show even static class has constructor)

```<code>public class Reader1 {
    private int pageNumber;

    private class ReaderName1{
    public int getPage(){
        return pageNumber;
    }
    }
    static class ReaderFound{

    }
}
</code>```

using javap

```<code>class Reader1$ReaderFound {
          Reader1$ReaderFound();
        }
</code>```

答:
Directly cited from the official website. I hope it can help you.

The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.
  Class has no public constructor. Instead a Class object is constructed automatically by the Java Virtual Machine when a class loader invokes one of the defineClass methods and passes the bytes of a class file.

https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html

ContentLicense: CC BY-SA 3.0

Body:
While reading Reflection API i got this "Every Java Type has a class Instance And the class instance itself has no public Constructor" .

Now this is really confusing for me. Because what i have read till now says . All classes have constructor even when we don't specify any, we get constructor by default (even if the class is static) once we create its instance. Can someone explain me this in simple word

(to show even static class has constructor)

public class Reader1 {
    private int pageNumber;

    private class ReaderName1{
    public int getPage(){
        return pageNumber;
    }
    }
    static class ReaderFound{

    }
}

using javap

class Reader1$ReaderFound {
          Reader1$ReaderFound();
        }

ContentLicense: CC BY-SA 4.0


问:
Remove empty field from selection list
Excuse me but I'm quite a novice and I'm trying to remove that empty space from my list.
This is the code I am trying to modify from a wordpress template.
The categories are loaded in the Wordpress administrator and a parent category can be assigned.

```<code><select id="wyz-cat-filter" name="<?php echo $this->name;?>" class="form-control" data-size="5">
    <option value="">
<?php
    echo apply_filters( 'wyz_categories_filter_placeholder', esc_html__( 'Categories...', 'wyzi-business-finder' ) );
?></option>
<?php
for ( $i = 0; $i < $len; $i++ ) {
    echo '<optgroup label="'.$taxonomies[$i]['name'].'">
          <option value="'.$taxonomies[ $i ]['id'].'"></option>
          </optgroup>';
    if ( isset( $taxonomies[ $i ]['children'] ) && ! empty( $taxonomies[ $i ]['children'] ) ) {
        foreach ( $taxonomies[ $i ]['children'] as $chld ) {
            echo '<option ' . ( $category == $chld['id'] ? 'selected ' : '' ) . 'value="' . $chld['id'] . '">' . $chld['name'] . '</option>';
        }
    }
}
?>
</select>
</code>```

See image 1

See image 2

答:
Try replacing with the following code:

```<code><select id="wyz-cat-filter" name="<?php echo $this->name;?>" class="form-control" data-size="5">
<option value=""><?php
echo apply_filters( 'wyz_categories_filter_placeholder', esc_html__( 'Categories...', 'wyzi-business-finder' ) );?></option>
<?php for ( $i = 0; $i < $len; $i++ ) {
    echo '<optgroup label="'.$taxonomies[$i]['name'].'"><option value="'.$taxonomies[ $i ]['id'].'"></option></optgroup>';
    if ( isset( $taxonomies[ $i ]['children'] ) && ! empty( $taxonomies[ $i ]['children'] ) ) {
        foreach ( $taxonomies[ $i ]['children'] as $chld ) {
            if ( ! empty( trim( $chld['name'] ) ) ) {
                echo '<option ' . ( $category == $chld['id'] ? 'selected ' : '' ) . 'value="' . $chld['id'] . '">' . $chld['name'] . '</option>';
            }
        }
    }
}?>
</code>```

Title: Remove empty field from selection list

Body:
Excuse me but I'm quite a novice and I'm trying to remove that empty space from my list.
This is the code I am trying to modify from a wordpress template.
The categories are loaded in the Wordpress administrator and a parent category can be assigned.

<select id="wyz-cat-filter" name="<?php echo $this->name;?>" class="form-control" data-size="5">
    <option value="">
<?php
    echo apply_filters( 'wyz_categories_filter_placeholder', esc_html__( 'Categories...', 'wyzi-business-finder' ) );
?></option>
<?php
for ( $i = 0; $i < $len; $i++ ) {
    echo '<optgroup label="'.$taxonomies[$i]['name'].'">
          <option value="'.$taxonomies[ $i ]['id'].'"></option>
          </optgroup>';
    if ( isset( $taxonomies[ $i ]['children'] ) && ! empty( $taxonomies[ $i ]['children'] ) ) {
        foreach ( $taxonomies[ $i ]['children'] as $chld ) {
            echo '<option ' . ( $category == $chld['id'] ? 'selected ' : '' ) . 'value="' . $chld['id'] . '">' . $chld['name'] . '</option>';
        }
    }
}
?>
</select>

See image 1

See image 2

Body:
Try replacing with the following code:

<select id="wyz-cat-filter" name="<?php echo $this->name;?>" class="form-control" data-size="5">
<option value=""><?php
echo apply_filters( 'wyz_categories_filter_placeholder', esc_html__( 'Categories...', 'wyzi-business-finder' ) );?></option>
<?php for ( $i = 0; $i < $len; $i++ ) {
    echo '<optgroup label="'.$taxonomies[$i]['name'].'"><option value="'.$taxonomies[ $i ]['id'].'"></option></optgroup>';
    if ( isset( $taxonomies[ $i ]['children'] ) && ! empty( $taxonomies[ $i ]['children'] ) ) {
        foreach ( $taxonomies[ $i ]['children'] as $chld ) {
            if ( ! empty( trim( $chld['name'] ) ) ) {
                echo '<option ' . ( $category == $chld['id'] ? 'selected ' : '' ) . 'value="' . $chld['id'] . '">' . $chld['name'] . '</option>';
            }
        }
    }
}?>


问:
python - is there a way to use list comprehension to create a list based on the extracted common indexes of sublists?
I am trying to figure out a clean way to get the elements at the same index of each sublist and create a new list based on those extracted elements, so first I would like a sublist containing element 0 of each earlier sublist, then same the same for element 1, 2 etc. At the moment I am using the following code to get the results I want:

```<code>lst = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [True, True, False, True], [14.5, 15.6, 12.5, 12.3]]
approach_1 = []

for i, item in enumerate(lst[0]):
    approach_1.append([item, lst[1][i], lst[2][i], lst[3][i]])
</code>```

which gives me

```<code>approach_1 = [[1, 'a', True, 14.5], [2, 'b', True, 15.6], [3, 'c', False, 12.5], [4, 'd', True, 12.3]]
</code>```

The results are what I am looking for but is there a way for me to achieve this in one line? I am able to use the following for one element:

```<code>approach_2 = [x[0] for x in lst]
</code>```

Is there anything similar to this that would return the same results as approach_1?

答:
You can write two for loops in one line!</p>

```<code>new_list = [[j[i] for j in lst] for i in range(0, len(lst[0]))]
</code>```

Body:
I am trying to figure out a clean way to get the elements at the same index of each sublist and create a new list based on those extracted elements, so first I would like a sublist containing element 0 of each earlier sublist, then same the same for element 1, 2 etc. At the moment I am using the following code to get the results I want:

lst = [[1, 2, 3, 4], ['a', 'b', 'c', 'd'], [True, True, False, True], [14.5, 15.6, 12.5, 12.3]]
approach_1 = []

for i, item in enumerate(lst[0]):
    approach_1.append([item, lst[1][i], lst[2][i], lst[3][i]])

which gives me

approach_1 = [[1, 'a', True, 14.5], [2, 'b', True, 15.6], [3, 'c', False, 12.5], [4, 'd', True, 12.3]]

The results are what I am looking for but is there a way for me to achieve this in one line? I am able to use the following for one element:

approach_2 = [x[0] for x in lst]

Is there anything similar to this that would return the same results as approach_1?

Body:
You can write two for loops in one line!

new_list = [[j[i] for j in lst] for i in range(0, len(lst[0]))]


问:
question about information_schema.TABLES result
1.we use this sql check big object info of mysql,

```<code>SELECT TABLE_SCHEMA,
       TABLE_NAME,
       CONCAT(ROUND(DATA_LENGTH/1024/1024),'MB') AS DATA_LENGTH,
       CONCAT(ROUND(INDEX_LENGTH/1024/1024),'MB') AS INDEX_LENGTH,
       CONCAT(ROUND(SUM(DATA_LENGTH+INDEX_LENGTH)/1024/1024),'MB') AS TOTDB_SIZE,
       TABLE_ROWS
FROM information_schema.TABLES
where TABLE_SCHEMA not in ('information_schema','performance_schema','sys')
GROUP BY TABLE_NAME
order by 6 desc limit 50
</code>```

the sql result is:

```<code>TABLE_SCHEMA TABLE_NAME      DATA_LENGTH  INDEX_LENGTH TOTDB_SIZE    TABLE_ROWS
report       report_opr_detl 1078MB         0MB             1078MB      1778206
</code>```

it report table report_opr_detl size is 1078MB .the number rows is 1778206 ,

2.but when we check the table size in os filesystem.

it report the size is 1.5G. it is diffrent wih step 1 result (1078MB)

```<code>[root@pommodb02 report]# du -sh report_opr_detl*

46K     report_opr_detl.frm
1.5G    report_opr_detl.ibd
</code>```

it report the count(*) of the table is 2162772 rows. it is diffrent wih step 1 result (1778206 rows)

```<code> mysql> select count(*) from report.report_opr_detl;
+----------+
| count(*) |
+----------+
|  2162772 |
+----------+
1 row in set (0.65 sec)
</code>```

3.so my question is why step 1 and step 2 is different ,

答:
The SUM did not include Data_free.

TABLE_ROWS is an approximation for InnoDB; the COUNT(*) is exact.

Another way to get similar info is SHOW TABLE STATUS.

Body:
1.we use this sql check big object info of mysql,

SELECT TABLE_SCHEMA,
       TABLE_NAME,
       CONCAT(ROUND(DATA_LENGTH/1024/1024),'MB') AS DATA_LENGTH,
       CONCAT(ROUND(INDEX_LENGTH/1024/1024),'MB') AS INDEX_LENGTH,
       CONCAT(ROUND(SUM(DATA_LENGTH+INDEX_LENGTH)/1024/1024),'MB') AS TOTDB_SIZE,
       TABLE_ROWS
FROM information_schema.TABLES
where TABLE_SCHEMA not in ('information_schema','performance_schema','sys')
GROUP BY TABLE_NAME
order by 6 desc limit 50

the sql result is:

TABLE_SCHEMA TABLE_NAME      DATA_LENGTH  INDEX_LENGTH TOTDB_SIZE    TABLE_ROWS
report       report_opr_detl 1078MB         0MB             1078MB      1778206

it report table report_opr_detl size is 1078MB .the number rows is 1778206 ,

2.but when we check the table size in os filesystem.

it report the size is 1.5G. it is diffrent wih step 1 result (1078MB)

[root@pommodb02 report]# du -sh report_opr_detl*

46K     report_opr_detl.frm
1.5G    report_opr_detl.ibd

it report the count(*) of the table is 2162772 rows. it is diffrent wih step 1 result (1778206 rows)

 mysql> select count(*) from report.report_opr_detl;
+----------+
| count(*) |
+----------+
|  2162772 |
+----------+
1 row in set (0.65 sec)

3.so my question is why step 1 and step 2 is different ,


问:
How to find all stored procedures that delete rows from a particular table
If there's a way of doing this without regular expressions, that's great. If there isn't, here's what I've got so far:

I've written a simple CLR user-defined function (which as you can see I've called CLR_RegExMatch) that performs regex matches on a supplied string. I use it to search for patterns inside stored procedures, triggers, functions etc.

Here's an example of its use - searching for inserts into a table called ExampleTable:

```<code>SELECT O.name, O.type_desc
FROM
    SYS.OBJECTS O
    INNER JOIN SYS.SQL_MODULES M ON
        M.object_id = O.object_id
        AND dbo.CLR_RegExMatch('INSERT\s+(INTO\s+)?ExampleTable\b', M.definition) = 1
</code>```

The issue I've got is that I can't come up with a regex pattern to find all routines that delete rows from a given table. Obviously I could substitute the following for the last line in the previous example:

```<code>        AND dbo.CLR_RegExMatch('DELETE\s+(FROM\s+)?ExampleTable\b', M.definition) = 1
</code>```

and that gets me part of the way there. However it wouldn't pick up the following:

```<code>DELETE T1
FROM
    ExampleTable T1
    INNER JOIN AnotherTable T2 ON T2.ParentId = T1.Id
</code>```

So what I'm looking for is either a regex pattern that will match deletes as above, or alternatively a different way of going about this.

N.B. The reason that I'm querying the definition column of SYS.SQL_MODULES instead of the ROUTINE_DEFINITION column of INFORMATION_SCHEMA.ROUTINES is that the latter only contains the first 4000 characters a routine definition, whereas the former contains the full text.

答:
Have a look at the FREE Red-Gate tool called SQL Search which does this - it searches your entire database for any kind of string(s).

It's a great must-have tool for any DBA or database developer - did I already mention it's absolutely FREE to use for any kind of use??

It will not tell you which procedures actually delete something from a table - but it will very easily and nicely find all procedures which reference that table in any way. Look at those and find those you need!

Body:
If there's a way of doing this without regular expressions, that's great. If there isn't, here's what I've got so far:

I've written a simple CLR user-defined function (which as you can see I've called CLR_RegExMatch) that performs regex matches on a supplied string. I use it to search for patterns inside stored procedures, triggers, functions etc.

Here's an example of its use - searching for inserts into a table called ExampleTable:

SELECT O.name, O.type_desc
FROM
    SYS.OBJECTS O
    INNER JOIN SYS.SQL_MODULES M ON
        M.object_id = O.object_id
        AND dbo.CLR_RegExMatch('INSERT\s+(INTO\s+)?ExampleTable\b', M.definition) = 1

The issue I've got is that I can't come up with a regex pattern to find all routines that delete rows from a given table. Obviously I could substitute the following for the last line in the previous example:

        AND dbo.CLR_RegExMatch('DELETE\s+(FROM\s+)?ExampleTable\b', M.definition) = 1

and that gets me part of the way there. However it wouldn't pick up the following:

DELETE T1
FROM
    ExampleTable T1
    INNER JOIN AnotherTable T2 ON T2.ParentId = T1.Id

So what I'm looking for is either a regex pattern that will match deletes as above, or alternatively a different way of going about this.

N.B. The reason that I'm querying the definition column of SYS.SQL_MODULES instead of the ROUTINE_DEFINITION column of INFORMATION_SCHEMA.ROUTINES is that the latter only contains the first 4000 characters a routine definition, whereas the former contains the full text.


问:
Remove delay from php's error_log file
I can't find an answer to this anywhere, so I'm asking here.

I'm just wondering if there's a way where I can see an error instantly printed into the php's error_log file when the error happens. Right now, my server is a standard setup running with cpanel/whm and the CPU usage and memory usage are always at normal levels.

The crazy thing is when errors happen, it seems I have to wait five minutes or more to see the entry in the php error_log file. If I check the log file right after I generate the error, then it doesn't get printed.

What can I do to minimize the waiting time for new errors to appear in the php's error_log file from the time the errors happen?

答:
It is a workaround not solution for the delay isssue. You can add this line at the end  of your function</p>

```<code>error_log(PHP_EOL, 3, $file);
</code>```

Title: Remove delay from php's error_log file

Body:
It is a workaround not solution for the delay isssue. You can add this line at the end  of your function

error_log(PHP_EOL, 3, $file);


答:
A solution with list comprehension:

```<code>[list(i) for i in zip(*lst)]

# [[1, 'a', True, 14.5], [2, 'b', True, 15.6], [3, 'c', False, 12.5], [4, 'd', True, 12.3]]
</code>```

Or, using map

```<code>list(map(list, zip(*lst)))
</code>```

will give you same result

Title: python - is there a way to use list comprehension to create a list based on the extracted common indexes of sublists?

Body:
A solution with list comprehension:

[list(i) for i in zip(*lst)]

# [[1, 'a', True, 14.5], [2, 'b', True, 15.6], [3, 'c', False, 12.5], [4, 'd', True, 12.3]]

Or, using map

list(map(list, zip(*lst)))

will give you same result


问:
Adding an outside int into an action listener
I have to do a very small project for school: making a game of tic tac toe in Java using JButtons and I have a short question.

Here's the code:

```<code>public void FensterAufbauen() {
    int i = 0;
    myPanel.setLayout(null);
    myButton.setText("");
    myButton.setBounds(40,70,80,80);
    myButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent arg0) {
            if (i % 2 == 0){
            myButton.setText("X");
            }
            else {
            myButton.setText("O");
            }
            i++;
        }
    });
}
</code>```

Now how would I add the int i into the action listener
(I have this for all 9 buttons so I can't just define i inside the listener)?
I am sorry in advance if anything here seems sloppy - I'm pretty new to Java

答:
i has to be final if you want to access it from within an anonymous inline class:

```<code>final int i = 0;
</code>```

That, of course, will mean you can no longer change it. Thus, instead, declare i as a non-final, private variable in the surrounding class, rather than a local variable. Or you could also declare i as a private variable inside your ActionListener, just above the actionPerformed() function.

Body:
I have to do a very small project for school: making a game of tic tac toe in Java using JButtons and I have a short question.

Here's the code:

public void FensterAufbauen() {
    int i = 0;
    myPanel.setLayout(null);
    myButton.setText("");
    myButton.setBounds(40,70,80,80);
    myButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent arg0) {
            if (i % 2 == 0){
            myButton.setText("X");
            }
            else {
            myButton.setText("O");
            }
            i++;
        }
    });
}

Now how would I add the int i into the action listener
(I have this for all 9 buttons so I can't just define i inside the listener)?
I am sorry in advance if anything here seems sloppy - I'm pretty new to Java

Body:
i has to be final if you want to access it from within an anonymous inline class:

final int i = 0;

That, of course, will mean you can no longer change it. Thus, instead, declare i as a non-final, private variable in the surrounding class, rather than a local variable. Or you could also declare i as a private variable inside your ActionListener, just above the actionPerformed() function.


问:
"Use of unresolved identifier" Can't for the life of me figure out what's going on. (Xcode, Swift)
Okay, so I'm playing around with the nfc capabilities on xcode, and potentially writing them. but as I try to move forward, I find that I'm unable to because my "documentTypes." I have made sure that it is set to target the ios platform, I just don't know what to do now.

答:
I can not see any declaration of documentTypes in the code screenshot.

You have to pass an array of documentTypes. You can use the line below.

```<code>var docPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.text"], inMode: UIDocumentPickerMode.Import)
</code>```

Body:
I can not see any declaration of documentTypes in the code screenshot.

You have to pass an array of documentTypes. You can use the line below.

var docPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.text"], inMode: UIDocumentPickerMode.Import)


问:
Flutter replace "," with "."
I have a TextField where I allow numbers like 1,4. I am trying ti replace the , to a . so the number will be 1.4.

I am trying this

```<code>double alphareceipe = double.parse(_alphareceipe.text);
    alphareceipe = alphareceipe.replace("," ".");

</code>```

But get this error:

error: The method 'replace' isn't defined for the class 'double'. (undefined_method at [brewingapp] lib/screens/calculator/alphaacid.dart:227).

The total code looks like this:

```<code>import 'package:flutter/material.dart';

import 'package:firebase_admob/firebase_admob.dart';
import 'package:brewingapp/app_localizations.dart';
import 'package:flutter/services.dart';
import 'package:devicelocale/devicelocale.dart';

const String testDevice = "Mobile_id";

class AlphaAcid extends StatefulWidget {
  @override
  _AlphaAcidState createState() => _AlphaAcidState();
}

class _AlphaAcidState extends State<AlphaAcid> {

  }

  String _emiResult = "";

  final TextEditingController _weight = TextEditingController();
  final TextEditingController _alphareceipe = TextEditingController();
  final TextEditingController _alphanew = TextEditingController();

  @override
  void initState() {

    initPlatformState();

    super.initState();
  }

  @override

  String _locale;

  Future<void> initPlatformState() async {

    String currentLocale;

    // Platform messages may fail, so we use a try/catch PlatformException.

    try {
      currentLocale = await Devicelocale.currentLocale;
      print(currentLocale);
    } on PlatformException {
      print("Error obtaining current locale");
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {

      _locale = currentLocale;
    });
  }

  @override

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(AppLocalizations.of(context).translate('Hopsalpha'),),
          backgroundColor: Colors.green[800],

          //elevation: 0.0,
        ),
        body: Center(
          child: Container(

            child: Column(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.all(20.0),
                  child: TextField(
                    cursorColor: Colors.green[800],
                    controller: _alphareceipe,
                    decoration: InputDecoration(
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
                        ),

                        filled: true,
                        fillColor: Colors.green[10],
                        labelText: _locale != 'da-DK'
                            ? "Alpha acid receipe"
                            : "Alpha syre opskrift",

                        labelStyle: TextStyle(color: Colors.green[800])
                    ),
                    keyboardType: TextInputType.numberWithOptions(decimal: true),

                    inputFormatters: <TextInputFormatter>[
//                      WhitelistingTextInputFormatter.digitsOnly
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(20.0),
                  child: TextField(
                    cursorColor: Colors.green[800],
                    controller: _alphanew,
                    decoration: InputDecoration(
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
                      ),
                      filled: true,
                      fillColor: Colors.green[10],
                      //labelText: "Final Gravity (1018)",
                      labelText: _locale != 'da-DK'
                          ? "Your alpha acid"
                          : "Din alpha syre",
                      labelStyle: TextStyle(color: Colors.green[800]),

                    ),
                    keyboardType: TextInputType.numberWithOptions(decimal: true),
                    inputFormatters: <TextInputFormatter>[
                      //WhitelistingTextInputFormatter.digitsOnly
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(20.0),
                  child: TextField(
                    cursorColor: Colors.green[800],
                    controller: _weight,
                    decoration: InputDecoration(
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
                      ),
                      filled: true,
                      fillColor: Colors.green[10],
                      //labelText: "Final Gravity (1018)",
                      labelText: _locale != 'da-DK'
                          ? "Weight receipe"
                          : "Vægt i opskrift",
                      labelStyle: TextStyle(color: Colors.green[800]),

                    ),
                    keyboardType: TextInputType.number,
                    inputFormatters: <TextInputFormatter>[
                      WhitelistingTextInputFormatter.digitsOnly
                    ],
                  ),
                ),
                Flexible(
                  fit: FlexFit.loose,
                  child: FlatButton(
                    onPressed: _handleCalculation,
                    //child: Text("Calculate"),
                    child: Text(AppLocalizations.of(context).translate('calculate'),),
                    color: Colors.green[600],
                    textColor: Colors.white,
                    padding: EdgeInsets.only(top: 10.0, bottom: 10.0, left: 24.0, right: 24.0),

                  ),

                ),

                emiResultsWidget(_emiResult)
              ],

            ),
          ),
        ));
  }

  void _handleCalculation() {

    double newWeight = 0.0;
//
//
//
//
//
    double alphareceipe = double.parse(_alphareceipe.text);
    alphareceipe = alphareceipe.replace("," ".");

    int alphanew =int.parse(_alphanew.text);
    int weightreceipe = int.parse(_weight.text);
//
    try {
      newWeight = (weightreceipe * alphareceipe) / alphanew;
      _emiResult =  newWeight.toStringAsFixed(0);

      setState(() {

      });

    } //catch(e) {
    on Exception catch(e){
      print(e);
      setState(() {

      });

    }

    //_emiResult =  A.toStringAsFixed(1);
    //setState(() {

    //});
  }

  Widget emiResultsWidget(emiResult) {

    bool canShow = false;
    String _emiResult = emiResult;

    if(_emiResult.length > 0) {
      canShow = true;
    }

    return

      Container(
        margin: EdgeInsets.only(top: 30.0, left: 20.0, right: 20.0),
        alignment: FractionalOffset.center,
        color: Colors.green[50],

        child: canShow ? Column(

            mainAxisAlignment: MainAxisAlignment.center,

            children: <Widget>[

              Row(
                //crossAxisAlignment: CrossAxisAlignment.start,
                //mainAxisAlignment: MainAxisAlignment.spaceEvenly,

                  children: <Widget> [
                    Padding(
                        padding: EdgeInsets.all(10.0),
                        child:

                        Text(AppLocalizations.of(context).translate('newweight'),
                          style: TextStyle(
                            fontSize: 20.0,
                            fontWeight: FontWeight.bold,
                            color: Colors.green[800],
                          ),

                        )
                    ),
                    SizedBox(width: 20.0,),

                    Text(_emiResult,
                        style: TextStyle(
                          fontSize: 20.0,
                          fontWeight: FontWeight.bold,
                          color: Colors.green[800],

                        )
                    ),
                    SizedBox(width: 10.0,),

                  ]),

            ]

        ) : Container(),
      );

  }

}
</code>```

答:
You are trying to replace the characters after the text has already been converted to a double. Try this instead:

```<code>double alphareceipe = double.parse(_alphareceipe.text.replaceAll(",", "."));
</code>```

Title: Flutter replace "," with "."

Body:
I have a TextField where I allow numbers like 1,4. I am trying ti replace the , to a . so the number will be 1.4.

I am trying this

double alphareceipe = double.parse(_alphareceipe.text);
    alphareceipe = alphareceipe.replace("," ".");

But get this error:

error: The method 'replace' isn't defined for the class 'double'. (undefined_method at [brewingapp] lib/screens/calculator/alphaacid.dart:227).

The total code looks like this:

import 'package:flutter/material.dart';

import 'package:firebase_admob/firebase_admob.dart';
import 'package:brewingapp/app_localizations.dart';
import 'package:flutter/services.dart';
import 'package:devicelocale/devicelocale.dart';

const String testDevice = "Mobile_id";

class AlphaAcid extends StatefulWidget {
  @override
  _AlphaAcidState createState() => _AlphaAcidState();
}

class _AlphaAcidState extends State<AlphaAcid> {

  }

  String _emiResult = "";

  final TextEditingController _weight = TextEditingController();
  final TextEditingController _alphareceipe = TextEditingController();
  final TextEditingController _alphanew = TextEditingController();

  @override
  void initState() {

    initPlatformState();

    super.initState();
  }

  @override

  String _locale;

  Future<void> initPlatformState() async {

    String currentLocale;

    // Platform messages may fail, so we use a try/catch PlatformException.

    try {
      currentLocale = await Devicelocale.currentLocale;
      print(currentLocale);
    } on PlatformException {
      print("Error obtaining current locale");
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {

      _locale = currentLocale;
    });
  }

  @override

  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(AppLocalizations.of(context).translate('Hopsalpha'),),
          backgroundColor: Colors.green[800],

          //elevation: 0.0,
        ),
        body: Center(
          child: Container(

            child: Column(
              children: <Widget>[
                Container(
                  padding: EdgeInsets.all(20.0),
                  child: TextField(
                    cursorColor: Colors.green[800],
                    controller: _alphareceipe,
                    decoration: InputDecoration(
                        focusedBorder: UnderlineInputBorder(
                          borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
                        ),

                        filled: true,
                        fillColor: Colors.green[10],
                        labelText: _locale != 'da-DK'
                            ? "Alpha acid receipe"
                            : "Alpha syre opskrift",

                        labelStyle: TextStyle(color: Colors.green[800])
                    ),
                    keyboardType: TextInputType.numberWithOptions(decimal: true),

                    inputFormatters: <TextInputFormatter>[
//                      WhitelistingTextInputFormatter.digitsOnly
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(20.0),
                  child: TextField(
                    cursorColor: Colors.green[800],
                    controller: _alphanew,
                    decoration: InputDecoration(
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
                      ),
                      filled: true,
                      fillColor: Colors.green[10],
                      //labelText: "Final Gravity (1018)",
                      labelText: _locale != 'da-DK'
                          ? "Your alpha acid"
                          : "Din alpha syre",
                      labelStyle: TextStyle(color: Colors.green[800]),

                    ),
                    keyboardType: TextInputType.numberWithOptions(decimal: true),
                    inputFormatters: <TextInputFormatter>[
                      //WhitelistingTextInputFormatter.digitsOnly
                    ],
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(20.0),
                  child: TextField(
                    cursorColor: Colors.green[800],
                    controller: _weight,
                    decoration: InputDecoration(
                      focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Colors.green[800], width: 2.0,),
                      ),
                      filled: true,
                      fillColor: Colors.green[10],
                      //labelText: "Final Gravity (1018)",
                      labelText: _locale != 'da-DK'
                          ? "Weight receipe"
                          : "Vægt i opskrift",
                      labelStyle: TextStyle(color: Colors.green[800]),

                    ),
                    keyboardType: TextInputType.number,
                    inputFormatters: <TextInputFormatter>[
                      WhitelistingTextInputFormatter.digitsOnly
                    ],
                  ),
                ),
                Flexible(
                  fit: FlexFit.loose,
                  child: FlatButton(
                    onPressed: _handleCalculation,
                    //child: Text("Calculate"),
                    child: Text(AppLocalizations.of(context).translate('calculate'),),
                    color: Colors.green[600],
                    textColor: Colors.white,
                    padding: EdgeInsets.only(top: 10.0, bottom: 10.0, left: 24.0, right: 24.0),

                  ),

                ),

                emiResultsWidget(_emiResult)
              ],

            ),
          ),
        ));
  }

  void _handleCalculation() {

    double newWeight = 0.0;
//
//
//
//
//
    double alphareceipe = double.parse(_alphareceipe.text);
    alphareceipe = alphareceipe.replace("," ".");

    int alphanew =int.parse(_alphanew.text);
    int weightreceipe = int.parse(_weight.text);
//
    try {
      newWeight = (weightreceipe * alphareceipe) / alphanew;
      _emiResult =  newWeight.toStringAsFixed(0);

      setState(() {

      });

    } //catch(e) {
    on Exception catch(e){
      print(e);
      setState(() {

      });

    }

    //_emiResult =  A.toStringAsFixed(1);
    //setState(() {

    //});
  }

  Widget emiResultsWidget(emiResult) {

    bool canShow = false;
    String _emiResult = emiResult;

    if(_emiResult.length > 0) {
      canShow = true;
    }

    return

      Container(
        margin: EdgeInsets.only(top: 30.0, left: 20.0, right: 20.0),
        alignment: FractionalOffset.center,
        color: Colors.green[50],

        child: canShow ? Column(

            mainAxisAlignment: MainAxisAlignment.center,

            children: <Widget>[

              Row(
                //crossAxisAlignment: CrossAxisAlignment.start,
                //mainAxisAlignment: MainAxisAlignment.spaceEvenly,

                  children: <Widget> [
                    Padding(
                        padding: EdgeInsets.all(10.0),
                        child:

                        Text(AppLocalizations.of(context).translate('newweight'),
                          style: TextStyle(
                            fontSize: 20.0,
                            fontWeight: FontWeight.bold,
                            color: Colors.green[800],
                          ),

                        )
                    ),
                    SizedBox(width: 20.0,),

                    Text(_emiResult,
                        style: TextStyle(
                          fontSize: 20.0,
                          fontWeight: FontWeight.bold,
                          color: Colors.green[800],

                        )
                    ),
                    SizedBox(width: 10.0,),

                  ]),

            ]

        ) : Container(),
      );

  }

}

Body:
You are trying to replace the characters after the text has already been converted to a double. Try this instead:

double alphareceipe = double.parse(_alphareceipe.text.replaceAll(",", "."));


问:
Why -1 * 0 = -0 in JavaScript?
As reported in the title:

Why in Javascript -1 * 0 = -0 ?

How I can prevent it?

I would have expected to have 0 as result.

答:
Do you have a specific reason for wanting to prevent that?

If your concern is related to the fact that you want to get 0 instead of -0 you don't need to worry about that since  -0 === 0 return true

console.log(-1 * 0)
console.log(-1 * 0 === 0)

const turnItToNegative = n => -1 * n

const myNumber = turnItToNegative(0)

if (myNumber === 0) {
  console.log('This is still zero, don\'t worry')
}```

Title: Why -1 * 0 = -0 in JavaScript?


问:
How to dynamically load a C# dll from a C++ DLL
I have a C++ application.  This supports users' C++ plugin DLL's, it will dynamically load these DLL's and then be able to create and use the user's types dynamically. These user types derive from base types and interfaces defined in the main application's core library, so I hold user's objects as pointers to the base class and call the user's virtual functions to make their magic happen.

Now I want to extend the plugin DLL's to allow managed DLL's (I care about C# mostly). I want all of the same magic to happen in C# plugin DLL's.

How can I dynamically load these dll's, some how I think win32's LoadLibrary which I am currently using is going to be happy with a managed DLL.  I will not have access to these libraries at compile/link time, they come from the user.

After I get the library loaded, unfortunately I suspect COM in my future as the way to call the derived functions.  Possibly I could use the CLI/C++ wrapper I have been reading about but I am very inexperienced here and would appreciate any advice or links to appropriate articles.

答:
What you'd do is basically start up an instance of the CLR in your process.
Have a look at this article on CLR hosting</p>


问:
*args and **kwargs Python
I'm working on an exercise, I tried to solve it, but no result, I had to look at the solution, in order to have an idea and repeat it, the problem, I am stuck, a little lost.

```<code># Create an @authenticated decorator that only allows the function to run is user1 has 'valid' set to True:

 user1 = { 'name': 'Sorna',
           'valid': True }         #changing this will either run or not run the message_friends function.
</code>```

Solution :

```<code>def authenticated(fn):
  def wrapper(*args, **kwargs):
    if args[0]['valid']:
      return fn(*args, **kwargs)
  return wrapper

@authenticated
def message_friends(user):
    print('message has been sent')

message_friends(user1)
</code>```

I really don't get this part :

```<code>if args[0]['valid']:
</code>```

My question is if user1 = dict, why can't i just use **kwards so i can just check if the value is True by calling only [valid]:
where it comes from the args[0]?

Help, i'm really stuck with this..

答:
You can use kwargs if you pass in user1 as a keyword-argument. For example, message_friends(user_argument=user1) would then have args == [] and kwargs == {'user_argument': user1}

Further illustration of this point

```<code>def my_func(*args, **kwargs):
   print(f"Args: {args}")
   print(f"Kwargs: {kwargs}")

>> my_func(1, 2, 3, 4)
Args: [1, 2, 3, 4]
Kwargs: {}

>> my_func(1, 2, three=3, four=4)
Args: [1, 2]
Kwargs: {"three": 3, "four": 4}
</code>```

Title: *args and **kwargs Python

Body:
I'm working on an exercise, I tried to solve it, but no result, I had to look at the solution, in order to have an idea and repeat it, the problem, I am stuck, a little lost.

# Create an @authenticated decorator that only allows the function to run is user1 has 'valid' set to True:

 user1 = { 'name': 'Sorna',
           'valid': True }         #changing this will either run or not run the message_friends function.

Solution :

def authenticated(fn):
  def wrapper(*args, **kwargs):
    if args[0]['valid']:
      return fn(*args, **kwargs)
  return wrapper

@authenticated
def message_friends(user):
    print('message has been sent')

message_friends(user1)

I really don't get this part :

if args[0]['valid']:

My question is if user1 = dict, why can't i just use **kwards so i can just check if the value is True by calling only [valid]:
where it comes from the args[0]?

Help, i'm really stuck with this..

Body:
You can use kwargs if you pass in user1 as a keyword-argument. For example, message_friends(user_argument=user1) would then have args == [] and kwargs == {'user_argument': user1}

Further illustration of this point

def my_func(*args, **kwargs):
   print(f"Args: {args}")
   print(f"Kwargs: {kwargs}")

>> my_func(1, 2, 3, 4)
Args: [1, 2, 3, 4]
Kwargs: {}

>> my_func(1, 2, three=3, four=4)
Args: [1, 2]
Kwargs: {"three": 3, "four": 4}


问:
How to concat to last item in array state?
say I have an array like this: ['uk', 'germany', 'spain']

and then I want to concat onto the end of it but for every keystroke how would I do that?

so it could resemble the following:

['uk', 'germany', 'spain', 'f']

['uk', 'germany', 'spain', 'fr']

['uk', 'germany', 'spain', 'fra']

['uk', 'germany', 'spain', 'fran']

etc

I was going to just get the value and then remove the last value in the array and append the new one so like

['uk', 'germany', 'spain', 'fr'] // I would remove fr then add the next val, fra e.g.

problem is the first time it happens

['uk', 'germany', 'spain'] if I did that here I would end up removing Spain

before you ask why am I doing it like this. I'm getting users to add random things they want to a list but they could feasibly save at any point so ['uk', 'germany', 'spain', 'fr'] would be perfectly valid in my use case

any ideas how I can achieve this?

答:
Here is a demonstration of the requirement using useState hook on an input; that is written immutable-friendly manner; that 3 number is hard-coded but can be dynamic as well.

ReactDOM.render(<App/>, root);

function App(){
  const [countries, setCountries] = React.useState(['uk', 'germany', 'spain']);

  function changeHandler(e){
    if(countries[3]){
      let countriesCopy = countries.slice(0);
      countriesCopy[3] = e.target.value;
      setCountries(countriesCopy)
    }else{
      setCountries(countries.concat(e.target.value))
    }
  }

  return(
    <input onChange={changeHandler} value={countries[3]} />
  )
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div></code>```

Body:
Here is a demonstration of the requirement using useState hook on an input; that is written immutable-friendly manner; that 3 number is hard-coded but can be dynamic as well.

ReactDOM.render(<App/>, root);

function App(){
  const [countries, setCountries] = React.useState(['uk', 'germany', 'spain']);

  function changeHandler(e){
    if(countries[3]){
      let countriesCopy = countries.slice(0);
      countriesCopy[3] = e.target.value;
      setCountries(countriesCopy)
    }else{
      setCountries(countries.concat(e.target.value))
    }
  }

  return(
    <input onChange={changeHandler} value={countries[3]} />
  )
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>


问:
Why docker build is so slow
My docker is very slow when I'm trying to build images on my laptop.
I tried to build same image at my ubuntu inside virtual machine with same docker version and it builds it in 5 seconds, but on my laptop it evaluates every statement like 30 times slower.
Even ENV command!

Laptop uses OpenSUSE 42.2 Leap with Btrfs as root file system, HDD with 5400 rpm and also it's encrypted.
I know all these factors but are they so significant that my build takes 15mins instead of 5sec?

Docker 1.13.1.

Thanks.

UPD.

not sure if it helps or not, but when I run docker build -t test . on my virtual machine, it uses 10% of my 4-core CPU for 5 secs and heavilly uses HDD.

however on laptop it uses one core of my 4-core CPU for 100% all the time and HDD remains idle almost all the time.

here is nmon statistics:

答:
Not sure if this was the same problem but just made my build go from 5 minutes to 5 seconds, by adding the following .dockerignore file to the same directory as my docker-compose.yml file.

```<code>**/bin
**/obj
**/node_modules
.git
</code>```

Title: Why docker build is so slow

Body:
Not sure if this was the same problem but just made my build go from 5 minutes to 5 seconds, by adding the following .dockerignore file to the same directory as my docker-compose.yml file.

**/bin
**/obj
**/node_modules
.git


问:
Flask app config.py vs dotenv to access environment variables
Hi I am relatively new to programming and building my first flask project and I haven't been able to figure out if I should prefer accessing environment variables by using dotenv / load_dotenv or using them from a config.py file.

I understand the config route is more flexible but my question is specifically to do with environment variables.

Is there a best practice here? [I am building a simple app that will be hosted externally]

答:
Best practices dictate that any value which is secret should not be hard-coded into any files which persist with the project or are checked into source control. Your config file is very likely to be saved in source control, so it should not store secrets, but instead load them from the environment variables set at execution time of the app. For example, let's say you are configuring an SMTP relay:

MAIL_PORT is a value that is not secret and not likely to change so it is a good candidate to be set in your config file.

MAIL_PASSWORD is a secret value that you do not want saved in your project's repository, so it should be loaded from the host's environment variables.

In this example, your config file might contain entries that look something like this:

```<code>MAIL_PORT = 465
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
</code>```

Beyond evaluating whether or not a config value is a secret, also consider how often the value will change and how hard it would be to make that change. Anything hard-coded into your config file will require changing the file and adding a new commit to your source control, possibly even triggering a full CI/CD pipeline process. If the value were instead loaded from environment variables then this value could be changed by simply stopping the application, exporting the new value as an environment variable, and restarting the application.

Dotenv files are simply a convenience for grouping a number of variables together and auto-loading them to be read by your configuration. A .env file is not always used as these values can be manually exported when the app is invoked or handled by another system responsible for starting or scaling your application. Do not check .env or .flaskenv files into your source control.

Body:
Best practices dictate that any value which is secret should not be hard-coded into any files which persist with the project or are checked into source control. Your config file is very likely to be saved in source control, so it should not store secrets, but instead load them from the environment variables set at execution time of the app. For example, let's say you are configuring an SMTP relay:

MAIL_PORT is a value that is not secret and not likely to change so it is a good candidate to be set in your config file.

MAIL_PASSWORD is a secret value that you do not want saved in your project's repository, so it should be loaded from the host's environment variables.

In this example, your config file might contain entries that look something like this:

MAIL_PORT = 465
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')

Beyond evaluating whether or not a config value is a secret, also consider how often the value will change and how hard it would be to make that change. Anything hard-coded into your config file will require changing the file and adding a new commit to your source control, possibly even triggering a full CI/CD pipeline process. If the value were instead loaded from environment variables then this value could be changed by simply stopping the application, exporting the new value as an environment variable, and restarting the application.

Dotenv files are simply a convenience for grouping a number of variables together and auto-loading them to be read by your configuration. A .env file is not always used as these values can be manually exported when the app is invoked or handled by another system responsible for starting or scaling your application. Do not check .env or .flaskenv files into your source control.


问:
Creating a widget
Hi i want to create a widget which can be embedded on other websites similar to the twitter profile widget, an example is here;

http://twitter.com/about/resources/widgets/widget_profile

The way i would approach this is to return the data in json format via my wcf, the problem is looking at the twitter example there seems to be some javascript and i am not to clued up on the purpose. My question to the more experienced devlopers is am i on the right track and what else will i need to do. Thanks alot

答: The purpose of the javascript would be to actually call your wcf service to retrieve data and write the html results to the screen. In the twitter example, many options are set inside a javascript object that is used to manage the configuration (background color, username, etc). You can return json, and then take the values from json and plug them into an html template on the client side. If you want this to be used on other sites however, I would probably avoid the use of jquery as you can't be sure the user has included it, and so you would need to include it. And then you have versioning issues if you use an older version, and the website your widget is on wants to use a newer version.</p>

Title: Creating a widget


答:
The decorator can be written a bit more clearly to not use args[0], does this help you understand?

```<code>def authenticated(fn):
    def wrapper(user, *args, **kwargs):
        if user['valid']:
            return fn(user, *args, **kwargs)

    return wrapper

@authenticated
def message_friends(user):
    print('message has been sent to', user['name'])

message_friends({'name': 'Sorna', 'valid': True})
message_friends({'name': 'Bob', 'valid': False})
</code>```

Now *args, **kwargs is only there to pass along any other arguments the decorated function might have.

This is also more robust because it works whether user is passed positionally or as a keyword argument.

Title: *args and **kwargs Python

Body:
The decorator can be written a bit more clearly to not use args[0], does this help you understand?

def authenticated(fn):
    def wrapper(user, *args, **kwargs):
        if user['valid']:
            return fn(user, *args, **kwargs)

    return wrapper

@authenticated
def message_friends(user):
    print('message has been sent to', user['name'])

message_friends({'name': 'Sorna', 'valid': True})
message_friends({'name': 'Bob', 'valid': False})

Now *args, **kwargs is only there to pass along any other arguments the decorated function might have.

This is also more robust because it works whether user is passed positionally or as a keyword argument.


问:
How to turn a list of lists of 2 into a single list of 2?
So I have a list of curves, each curve is represented with a list of x and y coordinates. I want to essentially make a single long curve by combining the x coordinates of all the curves and the y coordinates of all the curves into a single list of x and y coordinates.

Here is an example, suppose I have

```<code>toy <- list(list(c(1,2,3), c(4,5,6)), list(c(0,0), c(1,1)), list(c(1,2), c(1,2)))
toy
</code>```

```<code>[[1]]
[[1]][[1]]
[1] 1 2 3

[[1]][[2]]
[1] 4 5 6

[[2]]
[[2]][[1]]
[1] 0 0

[[2]][[2]]
[1] 1 1

[[3]]
[[3]][[1]]
[1] 1 2

[[3]][[2]]
[1] 1 2
</code>```

How do I get toy to look like

```<code>[[1]]
[[1]][[1]]
[1] 1 2 3 0 0 1 2

[[1]][[2]]
[1] 4 5 6 1 1 1 2
</code>```

?

答:
Here is one option with transpose

```<code>library(dplyr)
library(purrr)
transpose(toy)  %>%
       map(flatten_dbl) %>%
       list
#[[1]]
#[[1]][[1]]
#[1] 1 2 3 0 0 1 2

#[[1]][[2]]
#[1] 4 5 6 1 1 1 2
</code>```

Or using base R

```<code>list(lapply(asplit(t(simplify2array(toy)), 2), unlist))
</code>```

Body:
So I have a list of curves, each curve is represented with a list of x and y coordinates. I want to essentially make a single long curve by combining the x coordinates of all the curves and the y coordinates of all the curves into a single list of x and y coordinates.

Here is an example, suppose I have

toy <- list(list(c(1,2,3), c(4,5,6)), list(c(0,0), c(1,1)), list(c(1,2), c(1,2)))
toy

[[1]]
[[1]][[1]]
[1] 1 2 3

[[1]][[2]]
[1] 4 5 6

[[2]]
[[2]][[1]]
[1] 0 0

[[2]][[2]]
[1] 1 1

[[3]]
[[3]][[1]]
[1] 1 2

[[3]][[2]]
[1] 1 2

How do I get toy to look like

[[1]]
[[1]][[1]]
[1] 1 2 3 0 0 1 2

[[1]][[2]]
[1] 4 5 6 1 1 1 2

?

Body:
Here is one option with transpose

library(dplyr)
library(purrr)
transpose(toy)  %>%
       map(flatten_dbl) %>%
       list
#[[1]]
#[[1]][[1]]
#[1] 1 2 3 0 0 1 2

#[[1]][[2]]
#[1] 4 5 6 1 1 1 2

Or using base R

list(lapply(asplit(t(simplify2array(toy)), 2), unlist))


问:
Property 'controls' does not exist on type 'AbstractControl' - angular8
In Component I Have

```<code>  @Input() CaseFormIn: FormGroup;
get f() { return this.CaseFormIn.controls; }
</code>```

In Template

```<code> <div class="error-message" *ngIf="this.f.generalInfoFormGroup.controls.primaryStore.touched&&this.f.generalInfoFormGroup.controls.primaryStore.errors">
           Primary Store is a Required Field.
        </div>
</code>```

in development code is working fine but getting below error in prod mode
 Property 'controls' does not exist on type 'AbstractControl'.

答:
Angular show this kind of problem when u have mistake in code.
Sometimes there is no info...
Also good practice is doing multiple getters for controls.</p>

Body:
In Component I Have

  @Input() CaseFormIn: FormGroup;
get f() { return this.CaseFormIn.controls; }

In Template

           Primary Store is a Required Field.

in development code is working fine but getting below error in prod mode
 Property 'controls' does not exist on type 'AbstractControl'.


问:
Laravel dynamic config variable get
This is my config/filesystems.php file.

```<code>'default' => env('FILESYSTEM_DRIVER', 's3'),

'disks' => [
       's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
        ],
       'b2' => [
            'driver' => 's3',
            'key' => env('B2_KEY_ID'),
            'secret' => env('B2_APP_KEY'),
        ],
]
</code>```

How can I get default filesystem's key value?
I think this is possible.

config("filesystems.disks." . config("filesystems.default") . ".key");

I believe there is any better way.
Can anyone help me?

答: If you want to change config value you should call config helper function and pass the value you want to set as the second argument. You can check it in Laravel documentation

Title: Laravel dynamic config variable get

Body:
This is my config/filesystems.php file.

'default' => env('FILESYSTEM_DRIVER', 's3'),

'disks' => [
       's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
        ],
       'b2' => [
            'driver' => 's3',
            'key' => env('B2_KEY_ID'),
            'secret' => env('B2_APP_KEY'),
        ],
]

How can I get default filesystem's key value?
I think this is possible.

config("filesystems.disks." . config("filesystems.default") . ".key");

I believe there is any better way.
Can anyone help me?


问:
How to Convert Special Chars to Standard Chars?
I'm looking for way to convert chars like āžšķūņrūķīš to azskunrukis. In other words, to replace ā with a, ž with z and so. Is there anything built-in, or I should create my own "library" of from-to symbols?

答: As an alternative to iconv, you could check out the Normalize functions of the intl extension (if available).


问:
Highcharts: send chart object as Javascript variable?
I want a Javascript function that will build different Highcharts when I send the charts as a variable. This is because my users can draw and redraw charts with triggers. My question is similar to this one except I want to pass all the chart parameters to the function and I want to call the function onload and when certain buttons are clicked.
How to create highcharts dynamically on click buttons</p>

答:
After doing more reading, I think this will work:

```<code><script>
var options = {
    chart: {
        renderTo: 'container',
        type: 'bar'
    },
    series: [{
        name: 'Jane',
        data: [1, 0, 4]
    }]
};

function draw() {
    new Highcharts.Chart(options);
}

jQuery( document ).ready(function() {
    draw();
});
</code>```

Body:
After doing more reading, I think this will work:

<script>
var options = {
    chart: {
        renderTo: 'container',
        type: 'bar'
    },
    series: [{
        name: 'Jane',
        data: [1, 0, 4]
    }]
};

function draw() {
    new Highcharts.Chart(options);
}

jQuery( document ).ready(function() {
    draw();
});


问:
Rails 5 I18n default_locale and fallback locale
How do I set a fallback locale in Rails 5.2?

Right now it prints ''(blank) for attribute names if not found in locale. I would like it to fallback to :en when that happens.

Rails 5 specific?

```<code># config/application.rb
config.load_defaults 5.0
config.i18n.default_locale = :nb
</code>```

run specs and get:

```<code>#<ActiveRecord::RecordInvalid: Det oppstod en feil: er allerede i bruk>
see the missing part here:
#<ActiveRecord::RecordInvalid: Det oppstod en feil: [MISSING RECORD NAME] er allerede i bruk>

# switch to
# config.i18n.default_locale = :en
#<ActiveRecord::RecordInvalid: Validation failed: Report date has already been taken>
</code>```

UPDATE:

@Nate got the fallback config correct in his answer below (https://stackoverflow.com/a/53453211/252799)

That wasn't the issue though. The problem, I learned, was in my nb.yml.

Experiment 1.
Deleting the entire content of nb.yml, leaving just hello world. Works: It prints the attribute (associated record) name.

Experiment 2.
Replacing our nb.yml with the official Rails nb.yml: https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/nb.yml :  Works. I get the helpful norwegian-english message Det oppstod feil: Company må eksistere. Not pretty, but helpful and what I wanted!

Experiment 3. Proof. The nb.yml reproduces the problem.

Two approaches

```<code># A: SHOW attribute name
nb:
  errors:
    format: "%{attribute} %{message}"

# B: HIDE attribute name
nb:
  errors:
    format: "%{message}"
</code>```

Which leads to another problem.

Approach B: HIDE makes you blind serverside. the specs, logs and console will show Validation Failed: can't be blank but it looks good in UI.

I posted another Q: Simpleform errors without attribute name, but using attribute name in logs, console, specs

答:
Spree (4.1.5) + spree_i18n (3.3.2) on Rails (6.0.3.1), I wanted the site in Spanish and to fall back to English for missing translations. This is what worked for me:

```<code># config/application.rb

config.after_initialize do
    config.i18n.default_locale = :es
    config.i18n.locale = :en
end
config.i18n.fallbacks = true
</code>```

The config.after_initialize block is necessary, otherwise it wouldn't work (spree_i18n would mess the locales on initialization). That last config.i18n.fallbacks line is actually not needed since spree_i18n sets it to true on initialization. But I leave it there anyway so I know what is going on (furthermore, spree might stop overriding this in future versions since in development it might be useful not to use fallbacks thus making missing translations more visible).

Body:
How do I set a fallback locale in Rails 5.2?

Right now it prints ''(blank) for attribute names if not found in locale. I would like it to fallback to :en when that happens.

Rails 5 specific?

# config/application.rb
config.load_defaults 5.0
config.i18n.default_locale = :nb

run specs and get:

#<ActiveRecord::RecordInvalid: Det oppstod en feil: er allerede i bruk>
see the missing part here:
#<ActiveRecord::RecordInvalid: Det oppstod en feil: [MISSING RECORD NAME] er allerede i bruk>

# switch to
# config.i18n.default_locale = :en
#<ActiveRecord::RecordInvalid: Validation failed: Report date has already been taken>

UPDATE:

@Nate got the fallback config correct in his answer below (https://stackoverflow.com/a/53453211/252799)

That wasn't the issue though. The problem, I learned, was in my nb.yml.

Experiment 1.
Deleting the entire content of nb.yml, leaving just hello world. Works: It prints the attribute (associated record) name.

Experiment 2.
Replacing our nb.yml with the official Rails nb.yml: https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/nb.yml :  Works. I get the helpful norwegian-english message Det oppstod feil: Company må eksistere. Not pretty, but helpful and what I wanted!

Experiment 3. Proof. The nb.yml reproduces the problem.

Two approaches

# A: SHOW attribute name
nb:
  errors:
    format: "%{attribute} %{message}"

# B: HIDE attribute name
nb:
  errors:
    format: "%{message}"

Which leads to another problem.

Approach B: HIDE makes you blind serverside. the specs, logs and console will show Validation Failed: can't be blank but it looks good in UI.

I posted another Q: Simpleform errors without attribute name, but using attribute name in logs, console, specs

Body:
Spree (4.1.5) + spree_i18n (3.3.2) on Rails (6.0.3.1), I wanted the site in Spanish and to fall back to English for missing translations. This is what worked for me:

# config/application.rb

config.after_initialize do
    config.i18n.default_locale = :es
    config.i18n.locale = :en
end
config.i18n.fallbacks = true

The config.after_initialize block is necessary, otherwise it wouldn't work (spree_i18n would mess the locales on initialization). That last config.i18n.fallbacks line is actually not needed since spree_i18n sets it to true on initialization. But I leave it there anyway so I know what is going on (furthermore, spree might stop overriding this in future versions since in development it might be useful not to use fallbacks thus making missing translations more visible).


问:
Converting a string date to useful date
I'm pretty new to programming and I'm working with a database that has a date field. All the data in the field are saved as strings on the yyyymmdd format. I want to convert those to something friendlier to display to the user. I created the following struct and function to do it. It works, but I was wondering if there are any simpler ideas.

```<code>struct MyDate {
   var day: String
   var month: String
   var year: String
}

func ConvertToUsefullDate (_ date: String) -> MyDate {
    var myDate: MyDate = .init(day: "", month: "", year: "")

    myDate.year =
    String(date[date.index(date.startIndex, offsetBy: 0)]) +
    String(date[date.index(date.startIndex, offsetBy: 1)]) +
    String(date[date.index(date.startIndex, offsetBy: 2)]) +
    String(date[date.index(date.startIndex, offsetBy: 3)])

myDate.month =
    String(date[date.index(date.startIndex, offsetBy: 4)]) +
    String(date[date.index(date.startIndex, offsetBy: 5)])

myDate.day =
    String(date[date.index(date.startIndex, offsetBy: 6)]) +
    String(date[date.index(date.startIndex, offsetBy: 7)])

switch myDate.month {
    case "01": myDate.month = "Jan"
    case "02": myDate.month = "Feb"
    case "03": myDate.month = "Mar"
    case "04": myDate.month = "Apr"
    case "05": myDate.month = "May"
    case "06": myDate.month = "Jun"
    case "07": myDate.month = "Jul"
    case "08": myDate.month = "Aug"
    case "09": myDate.month = "Sep"
    case "10": myDate.month = "Oct"
    case "11": myDate.month = "Nov"
    case "12": myDate.month = "Dec"
    default: myDate.month = "Invalid"
}

return myDate
</code>```

}

Thank you  --  all feedback is welcome.

Daniel

答:
try this:

```<code>let unformattedDate = your unformatted date

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd" (or whatever your current format is)
let newDate : NSDate = dateFormatter.date(from: unformattedDate!)! as NSDate
</code>```

//new date format, change to the format you like (I like MM/dd/yyyy)

```<code>dateFormatter.dateFormat = "MM/dd/yyyy"
let formattedDate = dateFormatter.string(from: dateFromStringstartDate as Date)
</code>```

then you can use formattedDate as you'd like

use MMMM to represent month

use dddd to represent day of week

use dd to represent day

use yyyy to represent year

and use HH:mm:ss to represent time

for more formats check out the image below!
image of all formats

Title: Converting a string date to useful date

Body:
I'm pretty new to programming and I'm working with a database that has a date field. All the data in the field are saved as strings on the yyyymmdd format. I want to convert those to something friendlier to display to the user. I created the following struct and function to do it. It works, but I was wondering if there are any simpler ideas.

struct MyDate {
   var day: String
   var month: String
   var year: String
}

func ConvertToUsefullDate (_ date: String) -> MyDate {
    var myDate: MyDate = .init(day: "", month: "", year: "")

    myDate.year =
    String(date[date.index(date.startIndex, offsetBy: 0)]) +
    String(date[date.index(date.startIndex, offsetBy: 1)]) +
    String(date[date.index(date.startIndex, offsetBy: 2)]) +
    String(date[date.index(date.startIndex, offsetBy: 3)])

myDate.month =
    String(date[date.index(date.startIndex, offsetBy: 4)]) +
    String(date[date.index(date.startIndex, offsetBy: 5)])

myDate.day =
    String(date[date.index(date.startIndex, offsetBy: 6)]) +
    String(date[date.index(date.startIndex, offsetBy: 7)])

switch myDate.month {
    case "01": myDate.month = "Jan"
    case "02": myDate.month = "Feb"
    case "03": myDate.month = "Mar"
    case "04": myDate.month = "Apr"
    case "05": myDate.month = "May"
    case "06": myDate.month = "Jun"
    case "07": myDate.month = "Jul"
    case "08": myDate.month = "Aug"
    case "09": myDate.month = "Sep"
    case "10": myDate.month = "Oct"
    case "11": myDate.month = "Nov"
    case "12": myDate.month = "Dec"
    default: myDate.month = "Invalid"
}

return myDate

}

Thank you  --  all feedback is welcome.

Daniel

Body:
try this:

let unformattedDate = your unformatted date

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd" (or whatever your current format is)
let newDate : NSDate = dateFormatter.date(from: unformattedDate!)! as NSDate

//new date format, change to the format you like (I like MM/dd/yyyy)

dateFormatter.dateFormat = "MM/dd/yyyy"
let formattedDate = dateFormatter.string(from: dateFromStringstartDate as Date)

then you can use formattedDate as you'd like

use MMMM to represent month

use dddd to represent day of week

use dd to represent day

use yyyy to represent year

and use HH:mm:ss to represent time

for more formats check out the image below!
image of all formats


问:
Unable to Connect to Excel via SSIS
Excel file is not being recognized by SSIS.

Error :

Could not retrieve table information from connection manager "Excel Connection Manager

  Failed to connect to the source using the connection manager 'Excel Connection Manager'

I have tried installing 32-bit of redistributable which resolved this error but when I run this outside using SQL stored procedure it is failing, which is in turn resolved if i install 64 of redistributable but this is failing in SSIS,

Hence, I need 32-bit to run in SP, and 64-bit to run in SSIS but I cannot install both at the same time. Is there any solution to this issue.

答:
Since I came across this problem with the same error code-- </p>

<p>You could also have the wrong of version of excel selected when you create the Connection Manager, i.e Excel 2007-2010 vs Excel 2016, etc </p>

Title: Unable to Connect to Excel via SSIS

Body:
Since I came across this problem with the same error code--

You could also have the wrong of version of excel selected when you create the Connection Manager, i.e Excel 2007-2010 vs Excel 2016, etc


问:
Missed scanf and function goes on without it. If I add a space still doesn't work
```<code>#include <stdio.h>

struct mychar {
    char value;
    struct mychar *nextPtr;
};

typedef struct mychar Mychar;

void instructions();
void append(Mychar **, char );
void printlist(Mychar *);

int main(){
    instructions();

    Mychar *startPtr = NULL;

    unsigned int choice;
    char newchar;
    do {
        scanf("%d",&choice);
        switch (choice) {
            case 1:
                printf("\nWrite the character you want to add.");
                printf("\n> ");
                scanf(" %c", &newchar);
                append(&startPtr, newchar);
                printlist(startPtr);
                break;
            case 2:
                break;
            default:
                printf("\nError, try again.\n");
                //main();
                instructions();
                break;
        }
    } while (choice!=3);
    printf("\n\nEnd of run.\n");
}

void instructions(){
    printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
    printf("\n> ");
}

void append(Mychar **sPtr, char newvalue){
    Mychar *newlinkPtr = calloc (1, sizeof(Mychar));
    newlinkPtr->value = newvalue;
    newlinkPtr->nextPtr = NULL;

    Mychar *previousPtr = NULL;
    Mychar *currentPtr = *sPtr;

    while(currentPtr!=NULL && newvalue > currentPtr->value){
        previousPtr = currentPtr;
        currentPtr = currentPtr->nextPtr;
    }

    if (previousPtr){
        previousPtr->nextPtr = newlinkPtr;
        newlinkPtr->nextPtr = currentPtr;
    } else {
        *sPtr = newlinkPtr;
    }

}

void printlist(Mychar *currentPtr){
    printf("\n\nCurrent list:\n");
    while (currentPtr!=NULL){
        printf("%c", currentPtr->value);
        currentPtr = currentPtr->nextPtr;
    }
}
</code>```

Why do I have this behaviour? If I run the program, after I enter 1, it  prints the "current list" and leave the scanf input opened, so I can enter the value only after "current list" printed. Also, "current list" should be called only after I enter the character with scanf, since the function printlist is AFTER the scanf... but actually this is what happens:

```<code>Select operation. 1 to add, 2 to remove, 3 to exit.
> 1

Write the character you want to add.
> a

Current list:
ab

Write the character you want to add.
>

Current list:
abc

Write the character you want to add.
>

Current list:
abcd

Write the character you want to add.
>

Current list:
abcd
</code>```

答:
The lesson to take form this is to always check scanf for 0 return, at the very least, EOF check is also advised, and act accordingly, as for the order of events of your code, it's not quite there, with some tweaks you can have a nice, bad input proof, I/O sequence:

```<code>void clear_stdin() { //stdin buffer clearing function
    int c;
    while ((c = getchar()) != '\n' && c != EOF){}
}
</code>```

```<code>do {
    instructions(); //move inside the loop, user will be prompted in each cycle
    while (scanf("%d", &choice) == 0) {
        printf("\nError, try again.\n");
        instructions();
        clear_stdin(); // if input fails clear the buffer
    }
    clear_stdin(); // clear the buffer for 1hjh type input
    switch (choice) {
    case 1:

        printf("\nWrite the character you want to add.");
        printf("\n> ");
        while (scanf(" %c", &newchar) == 0) { //this can be a pattern
            clear_stdin();                    //see @ismick comment
        }                                     //
        clear_stdin();                        //
        append(&startPtr, newchar);
        printlist(startPtr);
        break;
    case 2:
        break;
    case 3:
        printf("\n\nEnd of run.\n"); //if you dont have a case default will catch 3
        break;
    default:
        printf("\nError, try again.\n");
        break;
    }
} while (choice != 3);
</code>```

Body:
#include <stdio.h>

struct mychar {
    char value;
    struct mychar *nextPtr;
};

typedef struct mychar Mychar;

void instructions();
void append(Mychar **, char );
void printlist(Mychar *);

int main(){
    instructions();

    Mychar *startPtr = NULL;

    unsigned int choice;
    char newchar;
    do {
        scanf("%d",&choice);
        switch (choice) {
            case 1:
                printf("\nWrite the character you want to add.");
                printf("\n> ");
                scanf(" %c", &newchar);
                append(&startPtr, newchar);
                printlist(startPtr);
                break;
            case 2:
                break;
            default:
                printf("\nError, try again.\n");
                //main();
                instructions();
                break;
        }
    } while (choice!=3);
    printf("\n\nEnd of run.\n");
}

void instructions(){
    printf("\nSelect operation. 1 to add, 2 to remove, 3 to exit.");
    printf("\n> ");
}

void append(Mychar **sPtr, char newvalue){
    Mychar *newlinkPtr = calloc (1, sizeof(Mychar));
    newlinkPtr->value = newvalue;
    newlinkPtr->nextPtr = NULL;

    Mychar *previousPtr = NULL;
    Mychar *currentPtr = *sPtr;

    while(currentPtr!=NULL && newvalue > currentPtr->value){
        previousPtr = currentPtr;
        currentPtr = currentPtr->nextPtr;
    }

    if (previousPtr){
        previousPtr->nextPtr = newlinkPtr;
        newlinkPtr->nextPtr = currentPtr;
    } else {
        *sPtr = newlinkPtr;
    }

}

void printlist(Mychar *currentPtr){
    printf("\n\nCurrent list:\n");
    while (currentPtr!=NULL){
        printf("%c", currentPtr->value);
        currentPtr = currentPtr->nextPtr;
    }
}

Why do I have this behaviour? If I run the program, after I enter 1, it  prints the "current list" and leave the scanf input opened, so I can enter the value only after "current list" printed. Also, "current list" should be called only after I enter the character with scanf, since the function printlist is AFTER the scanf... but actually this is what happens:

Select operation. 1 to add, 2 to remove, 3 to exit.
> 1

Write the character you want to add.
> a

Current list:
ab

Write the character you want to add.
>

Current list:
abc

Write the character you want to add.
>

Current list:
abcd

Write the character you want to add.
>

Current list:
abcd

Body:
The lesson to take form this is to always check scanf for 0 return, at the very least, EOF check is also advised, and act accordingly, as for the order of events of your code, it's not quite there, with some tweaks you can have a nice, bad input proof, I/O sequence:

void clear_stdin() { //stdin buffer clearing function
    int c;
    while ((c = getchar()) != '\n' && c != EOF){}
}

do {
    instructions(); //move inside the loop, user will be prompted in each cycle
    while (scanf("%d", &choice) == 0) {
        printf("\nError, try again.\n");
        instructions();
        clear_stdin(); // if input fails clear the buffer
    }
    clear_stdin(); // clear the buffer for 1hjh type input
    switch (choice) {
    case 1:

        printf("\nWrite the character you want to add.");
        printf("\n> ");
        while (scanf(" %c", &newchar) == 0) { //this can be a pattern
            clear_stdin();                    //see @ismick comment
        }                                     //
        clear_stdin();                        //
        append(&startPtr, newchar);
        printlist(startPtr);
        break;
    case 2:
        break;
    case 3:
        printf("\n\nEnd of run.\n"); //if you dont have a case default will catch 3
        break;
    default:
        printf("\nError, try again.\n");
        break;
    }
} while (choice != 3);


问:
JSON how find another value at the same index from a value in Javascript Object
A simple question I'm sure, but I can't figure it out.

I have some JSON returned from the server

```<code>    while ($Row = mysql_fetch_array($params))
    {
        $jsondata[]= array('adc'=>$Row["adc"],
                           'adSNU'=>$Row["adSNU"],
                           'adname'=>$Row["adname"],
                           'adcl'=>$Row["adcl"],
                           'adt'=>$Row["adt"]);
    };

echo json_encode(array("Ships" => $jsondata));
</code>```

...which I use on the client side in an ajax call. It should be noted that the JSON is parsed into a globally declared object so to be available later, and that I've assumed that you know that I formated the ajax call properly...

```<code>if (ajaxRequest.readyState==4 && ajaxRequest.status==200 || ajaxRequest.status==0)
        {
            WShipsObject = JSON.parse(ajaxRequest.responseText);

            var eeWShips = document.getElementById("eeWShipsContainer");

                for (i=0;i<WShipsObject.Ships.length;i++)
                {
                    newElement = WShipsObject.Ships;
                    newWShip = document.createElement("div");

                    newWShip.id = newElement[i].adSNU;
                    newWShip.class = newElement[i].adc;

                    eeWShips.appendChild(newWShip);

                } // end for

        }// If
</code>```

You can see for example here that I've created HTML DIV elements inside a parent div with each new div having an id and a class. You will note also that I haven't used all the data returned in the object...

I use JQuery to handle the click on the object, and here is my problem, what I want to use is the id from the element to return another value, say for example adt value from the JSON at the same index. The trouble is that at the click event I no longer know the index because it is way after the element was created. ie I'm no longer in the forloop.

So how do I do this?

Here's what I tried, but I think I'm up the wrong tree... the .inArray() returns minus 1 in both test cases. Remember the object is globally available...

```<code>$(".wShip").click(function(){

    var test1 = $.inArray(this.id, newElement.test);
    var test2 = $.inArray(this.id, WShipsObject);

    //alert(test1+"\n"+test2+"\n"+this.id);

});
</code>```

答:
I could not find a way of finding the index as asked, but I created a variation on the answer by Devraj.

In the solution I created a custom attribute called key into which I stored the index.

```<code>newWShip.key = i;
</code>```

Later when I need the index back again I can use this.key inside the JQuery .click()method:

```<code>var key = this.key;
var adt = WShipsObject.Ships[key].adt;
</code>```

You could argue that in fact I could store all the data into custom attributes, but I would argue that that would be unnecessary duplication of memory.

Body:
A simple question I'm sure, but I can't figure it out.

I have some JSON returned from the server

    while ($Row = mysql_fetch_array($params))
    {
        $jsondata[]= array('adc'=>$Row["adc"],
                           'adSNU'=>$Row["adSNU"],
                           'adname'=>$Row["adname"],
                           'adcl'=>$Row["adcl"],
                           'adt'=>$Row["adt"]);
    };

echo json_encode(array("Ships" => $jsondata));

...which I use on the client side in an ajax call. It should be noted that the JSON is parsed into a globally declared object so to be available later, and that I've assumed that you know that I formated the ajax call properly...

if (ajaxRequest.readyState==4 && ajaxRequest.status==200 || ajaxRequest.status==0)
        {
            WShipsObject = JSON.parse(ajaxRequest.responseText);

            var eeWShips = document.getElementById("eeWShipsContainer");

                for (i=0;i<WShipsObject.Ships.length;i++)
                {
                    newElement = WShipsObject.Ships;
                    newWShip = document.createElement("div");

                    newWShip.id = newElement[i].adSNU;
                    newWShip.class = newElement[i].adc;

                    eeWShips.appendChild(newWShip);

                } // end for

        }// If

You can see for example here that I've created HTML DIV elements inside a parent div with each new div having an id and a class. You will note also that I haven't used all the data returned in the object...

I use JQuery to handle the click on the object, and here is my problem, what I want to use is the id from the element to return another value, say for example adt value from the JSON at the same index. The trouble is that at the click event I no longer know the index because it is way after the element was created. ie I'm no longer in the forloop.

So how do I do this?

Here's what I tried, but I think I'm up the wrong tree... the .inArray() returns minus 1 in both test cases. Remember the object is globally available...

$(".wShip").click(function(){

    var test1 = $.inArray(this.id, newElement.test);
    var test2 = $.inArray(this.id, WShipsObject);

    //alert(test1+"\n"+test2+"\n"+this.id);

});

Body:
I could not find a way of finding the index as asked, but I created a variation on the answer by Devraj.

In the solution I created a custom attribute called key into which I stored the index.

newWShip.key = i;

Later when I need the index back again I can use this.key inside the JQuery .click()method:

var key = this.key;
var adt = WShipsObject.Ships[key].adt;

You could argue that in fact I could store all the data into custom attributes, but I would argue that that would be unnecessary duplication of memory.


问:
CSS - Show both linear and radial backgrounds together
I want a background that has both linear and radial gradients. The linear should display a blue->white gradient and the radial should display a polka dot pattern on top of it. I followed the guide on W3Schools but I cant get them both to display at the same time. I have attached a codesandbox for this problem. Can anyone please help me out and tell me what I am missing here?

I want something like this

But instead of stars it should show circles and they need to cover the whole page.

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>

        I want to display both the linear and radial backgrounds here. Linear
        will show the blue->white gradiant and radial will show the black polka
        dots.

```

答:
You need to correct you gradient like below:

.container {
  height: 100vh;
  background-image:
    /* the radial on the top and a transparent color at the end */
    radial-gradient(black 20%, transparent 21%),
    linear-gradient(#ffffff 44%, #01a2ce 100%);
  background-size: 50px 50px, auto; /* no comma between 50px and 50px*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">

</div></code>```

Body:
You need to correct you gradient like below:

.container {
  height: 100vh;
  background-image:
    /* the radial on the top and a transparent color at the end */
    radial-gradient(black 20%, transparent 21%),
    linear-gradient(#ffffff 44%, #01a2ce 100%);
  background-size: 50px 50px, auto; /* no comma between 50px and 50px*/
}

<div class="container">

</div>