问:
errno 1048, 'Column 'username' cannot be null'
Can you tell me why my code isn't working ? In my username table I have two columns, user_id and username. user_id is auto increment so I don't have that in my Sql statement, which I believe is the correct thing to do.

```<code><?php
require('dbConnect.php');
$Number = $_POST['phonenumber'];

// The ? below are parameter markers used for variable binding
// auto increment does not need prepared statements
$query = "INSERT INTO user (username) VALUES (?)";

$stmt = mysqli_prepare($con,$query) or die(mysqli_error($con));
//bind variables

mysqli_stmt_bind_param($stmt,"s",$u);
//$stmt->bind_param("s",$u);

mysqli_stmt_execute($stmt);

if(mysqli_query($con,$query))
{
echo 'Inserted correctly';
}

else

    {
  echo 'Error';
   echo var_dump($stmt);
    }

mysqli_stmt_close($stmt);
mysqli_close($con);

?>
</code>```

I keep getting 'Error', and in my var_dump I get :

```<code>C:\wamp64\www\phpproject\php-project\insert.php:28:
object(mysqli_stmt)[2]
  public 'affected_rows' => int -1
  public 'insert_id' => int 0
  public 'num_rows' => int 0
  public 'param_count' => int 1
  public 'field_count' => int 0
  public 'errno' => int 1048
  public 'error' => string 'Column 'username' cannot be null' (length=32)
  public 'error_list' =>
    array (size=1)
      0 =>
        array (size=3)
          'errno' => int 1048
          'sqlstate' => string '23000' (length=5)
          'error' => string 'Column 'username' cannot be null' (length=32)
  public 'sqlstate' => string '23000' (length=5)
  public 'id' => int 1
</code>```

答:
use null for autoincrement like this  </p>

```<code>$query = "INSERT INTO user (user_id,username) VALUES (null,$username)";
</code>```

Body:
Can you tell me why my code isn't working ? In my username table I have two columns, user_id and username. user_id is auto increment so I don't have that in my Sql statement, which I believe is the correct thing to do.

<?php
require('dbConnect.php');
$Number = $_POST['phonenumber'];

// The ? below are parameter markers used for variable binding
// auto increment does not need prepared statements
$query = "INSERT INTO user (username) VALUES (?)";

$stmt = mysqli_prepare($con,$query) or die(mysqli_error($con));
//bind variables

mysqli_stmt_bind_param($stmt,"s",$u);
//$stmt->bind_param("s",$u);

mysqli_stmt_execute($stmt);

if(mysqli_query($con,$query))
{
echo 'Inserted correctly';
}

else

    {
  echo 'Error';
   echo var_dump($stmt);
    }

mysqli_stmt_close($stmt);
mysqli_close($con);

?>

I keep getting 'Error', and in my var_dump I get :

C:\wamp64\www\phpproject\php-project\insert.php:28:
object(mysqli_stmt)[2]
  public 'affected_rows' => int -1
  public 'insert_id' => int 0
  public 'num_rows' => int 0
  public 'param_count' => int 1
  public 'field_count' => int 0
  public 'errno' => int 1048
  public 'error' => string 'Column 'username' cannot be null' (length=32)
  public 'error_list' =>
    array (size=1)
      0 =>
        array (size=3)
          'errno' => int 1048
          'sqlstate' => string '23000' (length=5)
          'error' => string 'Column 'username' cannot be null' (length=32)
  public 'sqlstate' => string '23000' (length=5)
  public 'id' => int 1

Body:
use null for autoincrement like this

$query = "INSERT INTO user (user_id,username) VALUES (null,$username)";


来源: stackexchange

问:
Removing text from NSString between "@" and ":" while keeping the text after it
So I'm reading the most recent tweet from a twitter bot and assigning it to a string, but sometimes it tweets directly to users. Here's an example of what that might look like.

```<code>NSString tweet = @("@user hey heres my message: BLah blah with symbols!");
//part I want to keep is: " BLah blah with symbols!"
//or it could end up being

NSString tweet = @("@otheruser my msg is: Wow heres some more blah: and a second colon");
//part I want to keep is: " Wow heres some more blah: and a second colon"
</code>```

I want to always remove the first part that talks to the user, while keeping the message on the end. There are too many different messages to use "stringByReplacingOccurrencesOfString"

I don't want to use "exlude-replies" from the twitter API because this bot is very popular and that would require fetching up to 100 since "count" applies before

any idea how I could do this? I think it has something to do with regular expressions, but I haven't ever used them before or been able to get one working how I want. I would really appreciate the help from anyone whos comfortable with regex

edit: also if a regex won't work for this case, id accept an explanation of the limitation preventing that :)

答:
The easiest solution that I can think of is to create an NSMutable array, by using the NSString function componentsSeparatedBy:@":", and simply remove the first element.

```<code>NSMutableArray *tweetArray = [[NSMutableArray alloc] initWithArray: [tweet componentsSeparatedByString:@":"]];
[tweetArray removeObjectAtIndex:0];
</code>```

Your issue with a colon appearing at random afterwards can be fixed by joining the pieces back together again.

```<code>tweet = [tweetArray componentsJoinedByString:@":"];
</code>```

Edit: Fix an error pointed out by user 'maddy'

You'll have to stick this code in an if statement so that it does not execute in tweets that have a colon normally. You can use the fact that it always begins with @user however.

```<code>if ([tweet characterAtIndex:0] == '@' && [tweet characterAtIndex:1] != ' '){
    NSMutableArray *tweetArray = [[NSMutableArray alloc] initWithArray: [tweet componentsSeparatedByString:@":"]];
    [tweetArray removeObjectAtIndex:0];

    tweet = [tweetArray componentsJoinedByString:@":"];
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I'm reading the most recent tweet from a twitter bot and assigning it to a string, but sometimes it tweets directly to users. Here's an example of what that might look like.

NSString tweet = @("@user hey heres my message: BLah blah with symbols!");
//part I want to keep is: " BLah blah with symbols!"
//or it could end up being

NSString tweet = @("@otheruser my msg is: Wow heres some more blah: and a second colon");
//part I want to keep is: " Wow heres some more blah: and a second colon"

I want to always remove the first part that talks to the user, while keeping the message on the end. There are too many different messages to use "stringByReplacingOccurrencesOfString"

I don't want to use "exlude-replies" from the twitter API because this bot is very popular and that would require fetching up to 100 since "count" applies before

any idea how I could do this? I think it has something to do with regular expressions, but I haven't ever used them before or been able to get one working how I want. I would really appreciate the help from anyone whos comfortable with regex

edit: also if a regex won't work for this case, id accept an explanation of the limitation preventing that :)

Body:
The easiest solution that I can think of is to create an NSMutable array, by using the NSString function componentsSeparatedBy:@":", and simply remove the first element.

NSMutableArray *tweetArray = [[NSMutableArray alloc] initWithArray: [tweet componentsSeparatedByString:@":"]];
[tweetArray removeObjectAtIndex:0];

Your issue with a colon appearing at random afterwards can be fixed by joining the pieces back together again.

tweet = [tweetArray componentsJoinedByString:@":"];

Edit: Fix an error pointed out by user 'maddy'

You'll have to stick this code in an if statement so that it does not execute in tweets that have a colon normally. You can use the fact that it always begins with @user however.

if ([tweet characterAtIndex:0] == '@' && [tweet characterAtIndex:1] != ' '){
    NSMutableArray *tweetArray = [[NSMutableArray alloc] initWithArray: [tweet componentsSeparatedByString:@":"]];
    [tweetArray removeObjectAtIndex:0];

    tweet = [tweetArray componentsJoinedByString:@":"];
}


问:
Display thumbnail of category in category.tpl module in opencart?
I need to display thumbnail images of category in category.tpl module in opencart?

I want display thumbnail of category in extension/module/category.tpl not product/product.tpl

how i can do this?

opencart 2.3.0.2

答:
Show images for the sub-categories in the opencart version 2.3

Find following code at catalog\controller\product\category.php

```<code>$data['categories'][] = array(
    'name' => $result['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
    'href' => $this->url->link('product/category', 'path=' . $this->request->get['path'] . '_' . $result['category_id'] . $url)
);
</code>```

Replace the code with below code:

```<code>$data['categories'][] = array(
    'name' => $result['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
    'image' => $this->model_tool_image->resize($result['image'], 100,100),
    'href' => $this->url->link('product/category', 'path=' . $this->request->get['path'] . '_' . $result['category_id'] . $url)
);
</code>```

Changed is 'image' => $this->model_tool_image->resize($result['image'], 100,100), if you have to increase the size then change 100 to other values.

Find following code at catalog\view\theme\default\template\product\category.tpl

```<code><?php if ($categories) { ?>
<h3><?php echo $text_refine; ?></h3>
<?php if (count($categories) <= 5) { ?>
<div class="row">
  <div class="col-sm-3">
    <ul>
      <?php foreach ($categories as $category) { ?>
      <li><a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?></a></li>
      <?php } ?>
    </ul>
  </div>
</div>
<?php } else { ?>
<div class="row">
  <?php foreach (array_chunk($categories, ceil(count($categories) / 4)) as $categories) { ?>
  <div class="col-sm-3">
    <ul>
      <?php foreach ($categories as $category) { ?>
      <li><a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?></a></li>
      <?php } ?>
    </ul>
  </div>
  <?php } ?>
</div>
<?php } ?>
<?php } ?>
</code>```

Replace with the below code

```<code><?php if ($categories) { ?>
      <h3><?php echo $text_refine; ?></h3>
      <?php if (count($categories) <= 5) { ?>
      <div class="row">
        <div class="col-sm-3">
          <ul>
            <?php foreach ($categories as $category) { ?>
            <li> <a href="<?php echo $category['href']; ?>">
                <?php if($category['image']){ ?>
                <img src="<?php echo $category['image']; ?>" ><br>
                <?php } ?>
                <?php echo $category['name']; ?></a></li>
            <?php } ?>
          </ul>
        </div>
      </div>
      <?php } else { ?>
      <div class="row">
        <?php  foreach (array_chunk($categories, ceil(count($categories) / 4)) as $categories) { ?>
        <div class="col-sm-3">
          <ul>
            <?php  foreach ($categories as $category) { ?>
            <li><a href="<?php echo $category['href']; ?>">
                <?php if($category['image']){ ?>
                <img src="<?php echo $category['image']; ?>" ><br>
                <?php } ?>
                <?php echo $category['name']; ?></a></li>
            <?php } ?>
          </ul>
        </div>
        <?php } ?>
      </div>
      <?php } ?>
<?php } ?>
</code>```

Extra code added is below and there are two places to add the code:

```<code><?php if($category['image']){ ?>
      <img src="<?php echo $category['image']; ?>" ><br>
<?php } ?>
</code>```

You are set for the default theme, but if you are using custom theme then you have to manage as per your theme.

https://webocreation.com/blog/show-images-sub-categories-opencart-version-2-3

Body:
Show images for the sub-categories in the opencart version 2.3

Find following code at catalog\controller\product\category.php

$data['categories'][] = array(
    'name' => $result['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
    'href' => $this->url->link('product/category', 'path=' . $this->request->get['path'] . '_' . $result['category_id'] . $url)
);

Replace the code with below code:

$data['categories'][] = array(
    'name' => $result['name'] . ($this->config->get('config_product_count') ? ' (' . $this->model_catalog_product->getTotalProducts($filter_data) . ')' : ''),
    'image' => $this->model_tool_image->resize($result['image'], 100,100),
    'href' => $this->url->link('product/category', 'path=' . $this->request->get['path'] . '_' . $result['category_id'] . $url)
);

Changed is 'image' => $this->model_tool_image->resize($result['image'], 100,100), if you have to increase the size then change 100 to other values.

Find following code at catalog\view\theme\default\template\product\category.tpl

<?php if ($categories) { ?>
<h3><?php echo $text_refine; ?></h3>
<?php if (count($categories) <= 5) { ?>
<div class="row">
  <div class="col-sm-3">
    <ul>
      <?php foreach ($categories as $category) { ?>
      <li><a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?></a></li>
      <?php } ?>
    </ul>
  </div>
</div>
<?php } else { ?>
<div class="row">
  <?php foreach (array_chunk($categories, ceil(count($categories) / 4)) as $categories) { ?>
  <div class="col-sm-3">
    <ul>
      <?php foreach ($categories as $category) { ?>
      <li><a href="<?php echo $category['href']; ?>"><?php echo $category['name']; ?></a></li>
      <?php } ?>
    </ul>
  </div>
  <?php } ?>
</div>
<?php } ?>
<?php } ?>

Replace with the below code

<?php if ($categories) { ?>
      <h3><?php echo $text_refine; ?></h3>
      <?php if (count($categories) <= 5) { ?>
      <div class="row">
        <div class="col-sm-3">
          <ul>
            <?php foreach ($categories as $category) { ?>
            <li> <a href="<?php echo $category['href']; ?>">
                <?php if($category['image']){ ?>
                <img src="<?php echo $category['image']; ?>" ><br>
                <?php } ?>
                <?php echo $category['name']; ?></a></li>
            <?php } ?>
          </ul>
        </div>
      </div>
      <?php } else { ?>
      <div class="row">
        <?php  foreach (array_chunk($categories, ceil(count($categories) / 4)) as $categories) { ?>
        <div class="col-sm-3">
          <ul>
            <?php  foreach ($categories as $category) { ?>
            <li><a href="<?php echo $category['href']; ?>">
                <?php if($category['image']){ ?>
                <img src="<?php echo $category['image']; ?>" ><br>
                <?php } ?>
                <?php echo $category['name']; ?></a></li>
            <?php } ?>
          </ul>
        </div>
        <?php } ?>
      </div>
      <?php } ?>
<?php } ?>

Extra code added is below and there are two places to add the code:

<?php if($category['image']){ ?>
      <img src="<?php echo $category['image']; ?>" ><br>
<?php } ?>

You are set for the default theme, but if you are using custom theme then you have to manage as per your theme.

https://webocreation.com/blog/show-images-sub-categories-opencart-version-2-3


问:
How to get the student id where student got grade A but not C
table
.......

```<code>student_id   Grade
1              A
1              B
1              D
2              B
2              C
2              A
</code>```

Desired Output
.............

```<code>student_id
1
</code>```

i have tried
............

```<code>select student_id from student where grade='A' and not grade='c';
</code>```

but i am getting wrong output

答:
One simple method is aggregation and a having clause:

```<code>select student_id
from student
group by student_id
having sum(case when grade = 'A' then 1 else 0 end) > 0 and
       sum(case when grade = 'C' then 1 else 0 end) = 0;
</code>```

Body:
table
.......

student_id   Grade
1              A
1              B
1              D
2              B
2              C
2              A

Desired Output
.............

student_id
1

i have tried
............

select student_id from student where grade='A' and not grade='c';

but i am getting wrong output

Body:
One simple method is aggregation and a having clause:

select student_id
from student
group by student_id
having sum(case when grade = 'A' then 1 else 0 end) > 0 and
       sum(case when grade = 'C' then 1 else 0 end) = 0;


问:
Using openlayer3 in typescript/angular2
I have a Javascript code which use openLayer3. I need to implement this code in a angular2 project, in Typescript.

Someone knows how use openlayer with angular2 / Typescript please ?

Thanks a lot,

John

答: You could use angular2-openlayers, available as a npm package or here : https://github.com/quentin-ol/angular2-openlayers</p>

Title: Using openlayer3 in typescript/angular2


问:
Create table with different PHP variables including if statement
I have multiple quires retrieving data from mysql database (multiple tables)

```<code>SELECT description FROM table1 As descr WHERE type='MYTYPE'; //this shows description of each product type
SELECT count(id) FROM table2 As tp1 WHERE ACTIVE='Y' AND type=1"); //this is to count records that has this product type =1
SELECT count(id) FROM table2 As tp2 WHERE ACTIVE='Y' AND type=2");
SELECT count(id) FROM table2 As tp3 WHERE ACTIVE='Y' AND type=3");
SELECT count(id) FROM table2 As tp4 WHERE ACTIVE='Y' AND type=4");
</code>```

What I'm trying to have is a table of each type description, along with count of active products has this type: ignoring the count if the count is 0

Here is modest try, I know it isn't perfect, therefore seeking help here, perhaps different approach will be also helpful, but this doesn't work as it have defining variable which has if statement and also logic is not correct?

```<code>$tbl_header = '<tr>
<th width=220px align=left>Type description</th>
<th width=10px align=left>Active products of this type</th>
</tr>';

$tbl_data =

if (tp1>0) {
'<tr>
<td width=220px align=left><font color=#000000>'. {descr[0][0]}.'</td></font>
<td width=10px align=left><font color=#FF0000>.'$tp1.'</td></font>
</tr>';}

if (tp2>0) {
'<tr>
<td width=220px align=left><font color=#000000>'. {descr[1][0]}.'</td></font>
<td width=10px align=left><font color=#FF0000>.'$tp2.'</td></font>
</tr>';}

;

echo "<table> $tbl_header $tbl_data </table>";
</code>```

答:
Try this method. It should work and you don't have to worry about if statements being in the middle of variable

    Type description
    Active products of this type

  <?php
    if ($tp1 > 0) {
  ?>

          <?php echo descr[0][0]; ?>

          <?php echo $tp1; ?>

    <?php
      }
    ?>

      <?php
        if ($tp2 > 0) {
      ?>

              <?php echo descr[1][0]; ?>

              <?php echo $tp2; ?>

       <?php
        }
       ?>

```
</div>
</div>
</p>

<p>How about this?</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
  $table_head = "<tr>
    <th width=220px align=left>Type description</th>
    <th width=10px align=left>Active products of this type</th>
  </tr>";
        if ($tp1 > 0) {
        $table_data_1 = "<tr>
          <td width=2 20 px align=l eft>
            < font color=# 000000>". descr[0][0] . "</font>
          </td>
          <td width=10px align=left>
            <font color=#FF0000>". $tp1. "</font>
          </td>
        </tr>";
       }

       if ($tp2 > 0) {
        $table_data_2 = "<tr>
          <td width=2 20 px align=l eft>
            < font color=# 000000>". descr[1][0] . "</font>
          </td>
          <td width=10px align=left>
            <font color=#FF0000>". $tp2. "</font>
          </td>
        </tr>";
       }

   echo "<table> $table_ head $table_data_1 $table_data_2 </table>";
   ?></code>```

<?php
$table_data = "";
      $table_head = "

        Type description
        Active products of this type

";
            if ($tp1 > 0) {
            $table_data = "

                ". descr[0][0] . "

                ". $tp1. "

";
           }

           if ($tp2 > 0) {
            $table_data .= "

                ". descr[1][0] . "

                ". $tp2. "

";
           }

       echo "
 $table_ head $table_data
";
       ?>```

Body:
I have multiple quires retrieving data from mysql database (multiple tables)

SELECT description FROM table1 As descr WHERE type='MYTYPE'; //this shows description of each product type
SELECT count(id) FROM table2 As tp1 WHERE ACTIVE='Y' AND type=1"); //this is to count records that has this product type =1
SELECT count(id) FROM table2 As tp2 WHERE ACTIVE='Y' AND type=2");
SELECT count(id) FROM table2 As tp3 WHERE ACTIVE='Y' AND type=3");
SELECT count(id) FROM table2 As tp4 WHERE ACTIVE='Y' AND type=4");

What I'm trying to have is a table of each type description, along with count of active products has this type: ignoring the count if the count is 0

Here is modest try, I know it isn't perfect, therefore seeking help here, perhaps different approach will be also helpful, but this doesn't work as it have defining variable which has if statement and also logic is not correct?

$tbl_header = '

Type description
Active products of this type

';

$tbl_data =

if (tp1>0) {
'

'. {descr[0][0]}.'
.'$tp1.'

';}

if (tp2>0) {
'

'. {descr[1][0]}.'
.'$tp2.'

';}

;

echo "
 $tbl_header $tbl_data
";

Body:
Try this method. It should work and you don't have to worry about if statements being in the middle of variable

<table>
  <tr>
    <th width=220px align=left>Type description</th>
    <th width=10px align=left>Active products of this type</th>
  </tr>

  <?php
    if ($tp1 > 0) {
  ?>
    <tr>
      <td width=2 20 px align=l eft>
        < font color=# 000000>
          <?php echo descr[0][0]; ?>
          </font>
      </td>
      <td width=10px align=left>
        <font color=#FF0000>
          <?php echo $tp1; ?>
        </font>
      </td>
    </tr>
    <?php
      }
    ?>

      <?php
        if ($tp2 > 0) {
      ?>
        <tr>
          <td width=2 20 px align=l eft>
            < font color=# 000000>
              <?php echo descr[1][0]; ?>
              </font>
          </td>
          <td width=10px align=left>
            <font color=#FF0000>
              <?php echo $tp2; ?>
            </font>
          </td>
        </tr>
       <?php
        }
       ?>
</table>

How about this?

<?php
  $table_head = "<tr>
    <th width=220px align=left>Type description</th>
    <th width=10px align=left>Active products of this type</th>
  </tr>";
        if ($tp1 > 0) {
        $table_data_1 = "<tr>
          <td width=2 20 px align=l eft>
            < font color=# 000000>". descr[0][0] . "</font>
          </td>
          <td width=10px align=left>
            <font color=#FF0000>". $tp1. "</font>
          </td>
        </tr>";
       }

       if ($tp2 > 0) {
        $table_data_2 = "<tr>
          <td width=2 20 px align=l eft>
            < font color=# 000000>". descr[1][0] . "</font>
          </td>
          <td width=10px align=left>
            <font color=#FF0000>". $tp2. "</font>
          </td>
        </tr>";
       }

   echo "<table> $table_ head $table_data_1 $table_data_2 </table>";
   ?>

<?php
$table_data = "";
      $table_head = "<tr>
        <th width=220px align=left>Type description</th>
        <th width=10px align=left>Active products of this type</th>
      </tr>";
            if ($tp1 > 0) {
            $table_data = "<tr>
              <td width=2 20 px align=l eft>
                < font color=# 000000>". descr[0][0] . "</font>
              </td>
              <td width=10px align=left>
                <font color=#FF0000>". $tp1. "</font>
              </td>
            </tr>";
           }

           if ($tp2 > 0) {
            $table_data .= "<tr>
              <td width=2 20 px align=l eft>
                < font color=# 000000>". descr[1][0] . "</font>
              </td>
              <td width=10px align=left>
                <font color=#FF0000>". $tp2. "</font>
              </td>
            </tr>";
           }

       echo "<table> $table_ head $table_data </table>";
       ?>


问:
How to export an Excel sheet range to a picture, from within R
We are trying to automate the creation of some picture files within an R Script.

We have the Excel files looking the way that we want them to, but now need to make a JPG or PNG picture-copy of those excel tables for easier web posting.

We've been using the library(xlsx) package for most of our interactions between R and Excel, and it looks like we should be able to send specific java commands through something like ?.jmethods but it's unclear how we would pass as many lines as we need to.

In an R session, here's a minimal reproducible example...

Here's an example Excel file with a range to print

```<code>library(xlsx)
file <- system.file("tests", "test_import.xlsx", package = "xlsx")
file
</code>```

And here's the Excel macro that exports the Excel range to a picture file

```<code>Sub Tester()

    Worksheets("deletedFields").Range("A8:J36").CopyPicture xlScreen, xlBitmap

    Application.DisplayAlerts = False
    Set oCht = Charts.Add
    With oCht
        .Paste
        .Export Filename:="C:\temp\SavedRange.jpg", Filtername:="JPG"
        .Delete
    End With

End Sub
</code>```

Any help automating this would be much appreciated!

答:
You can do this with vbs.  Most vbs is identical to vba so you can write out your dynamic vbs script which includes your macro as text and then call it with shell.

Here is a working example:

```<code>fileConn<-file("c:/rworking/test/test.vbs")
writeLines(c("Dim xlApp, xlBook, xlSht",
    "Dim filename",
    "filename = \"c:\\Rworking\\test\\test_import.xlsx\"",
    "Set xlApp = CreateObject(\"Excel.Application\")",
    "xlApp.Visible = True",
    "set xlBook = xlApp.WorkBooks.Open(filename)",
    "set xlSht = xlApp.Worksheets(1)",
    "set rng = xlSht.Range(\"A8:J36\")",
    "rng.CopyPicture",
    "Set oCht = xlApp.Charts",
    "oCht.Add() ",
    "Set oCht = oCht(1)",
    "oCht.paste",
    "oCht.Export \"C:\\rworking\\test\\Test.jpg\", \"JPG\""),
    fileConn)

close(fileConn)

shell.exec("c:/rworking/test/test.vbs")
</code>```

Body:
We are trying to automate the creation of some picture files within an R Script.

We have the Excel files looking the way that we want them to, but now need to make a JPG or PNG picture-copy of those excel tables for easier web posting.

We've been using the library(xlsx) package for most of our interactions between R and Excel, and it looks like we should be able to send specific java commands through something like ?.jmethods but it's unclear how we would pass as many lines as we need to.

In an R session, here's a minimal reproducible example...

Here's an example Excel file with a range to print

library(xlsx)
file <- system.file("tests", "test_import.xlsx", package = "xlsx")
file

And here's the Excel macro that exports the Excel range to a picture file

Sub Tester()

    Worksheets("deletedFields").Range("A8:J36").CopyPicture xlScreen, xlBitmap

    Application.DisplayAlerts = False
    Set oCht = Charts.Add
    With oCht
        .Paste
        .Export Filename:="C:\temp\SavedRange.jpg", Filtername:="JPG"
        .Delete
    End With

End Sub

Any help automating this would be much appreciated!

Body:
You can do this with vbs.  Most vbs is identical to vba so you can write out your dynamic vbs script which includes your macro as text and then call it with shell.

Here is a working example:

fileConn<-file("c:/rworking/test/test.vbs")
writeLines(c("Dim xlApp, xlBook, xlSht",
    "Dim filename",
    "filename = \"c:\\Rworking\\test\\test_import.xlsx\"",
    "Set xlApp = CreateObject(\"Excel.Application\")",
    "xlApp.Visible = True",
    "set xlBook = xlApp.WorkBooks.Open(filename)",
    "set xlSht = xlApp.Worksheets(1)",
    "set rng = xlSht.Range(\"A8:J36\")",
    "rng.CopyPicture",
    "Set oCht = xlApp.Charts",
    "oCht.Add() ",
    "Set oCht = oCht(1)",
    "oCht.paste",
    "oCht.Export \"C:\\rworking\\test\\Test.jpg\", \"JPG\""),
    fileConn)

close(fileConn)

shell.exec("c:/rworking/test/test.vbs")


问:
Python: Find URLs and add querystring pair
I'm trying to affilliateize some legacy text in a Django webapp. It's a pretty simple scope. The text has some amazon URLs in and I want to munge my ?tag=xxx identifier onto the end of them.

I've written a template filter that I can quickly pass my text through but I'm slightly stuck on writing the regex logic.

```<code>t = text_from_template_engine
return re.sub(r'(https?://(?:www\.)?amazon\.co\.uk[\S]+)', r'\\\1?tag=xxx', t)
</code>```

This seems to work on a very basic level but if the URL already has a querystring (as lots of organic Amazon URLs do by default), I would need an ampersand instead of a question mark.

There might be a quick way to detect two question marks and replace the second. I'm open to that suggestion.

What I'm really looking for is a regex-replace where I can pass the found string off to another method (in which I can detect existing question marks) that is expected to return the replacement string. Something like PHP's preg_replace_callback (et al). Does that exist?

答:
There might be a quick way to detect two question marks and replace the second. I'm open to that suggestion.

this will get the 2 question marks.

```<code>(\?|(\?\?))
</code>```

I believe the non-passive group number for the double question mark will  be $4 but you'll need to double check that and you can add back the single question mark in your replace.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to affilliateize some legacy text in a Django webapp. It's a pretty simple scope. The text has some amazon URLs in and I want to munge my ?tag=xxx identifier onto the end of them.

I've written a template filter that I can quickly pass my text through but I'm slightly stuck on writing the regex logic.

t = text_from_template_engine
return re.sub(r'(https?://(?:www\.)?amazon\.co\.uk[\S]+)', r'\\\1?tag=xxx', t)

This seems to work on a very basic level but if the URL already has a querystring (as lots of organic Amazon URLs do by default), I would need an ampersand instead of a question mark.

There might be a quick way to detect two question marks and replace the second. I'm open to that suggestion.

What I'm really looking for is a regex-replace where I can pass the found string off to another method (in which I can detect existing question marks) that is expected to return the replacement string. Something like PHP's preg_replace_callback (et al). Does that exist?

Body:
There might be a quick way to detect two question marks and replace the second. I'm open to that suggestion.

this will get the 2 question marks.

(\?|(\?\?))

I believe the non-passive group number for the double question mark will  be $4 but you'll need to double check that and you can add back the single question mark in your replace.


问:
facebook page plugin not working properly
I need a embedded facebook page plugin.
But the code generator of facebook doesn't work. When i give the url of the facebook page, the generator doens't give the code for this page.

Also doesn't appear the page in the preview modus.

The facebook page is: https://www.facebook.com/Tapas.Enschede/

The code generator is on this page.
https://developers.facebook.com/docs/plugins/page-plugin/

For other facebookpages the code generator works perfect. I have no idea what the problem is.

I really appreciate any help.

答:
I had the same issue today.

Check to see if:

Your page is unpublished.

You have Age Restriction (which was my issue) activated. Any age restriction above 13+ will cause the page plugin to not work.

You have Country Restrictions activated.

Any of the above will cause the page plugin not to display.

You can find these settings in the General tab in your page settings.


问:
rename a log file in python using a logging module
I need to rename a logging file but continue logging to it afterwards. I'm running Python 3.x and using a logging module to create logs.

```<code>logger = logging.getLogger(r'mylogger')
handler = logging.FileHandler(r'mylog.txt', mode = r'w')
logger.addHandler(handler)
logger.info(r'msg 1')
logger.info(r'msg 2')

handler.renameFile(r'my_newlog.txt')  # <--- Is something like this possible?

logger.info(r'msg 3')
</code>```

Does anyone know if something like this is possible? If no, how would I go about doing it? One idea that I had was to close the file (handler.close()), remove the handler from the logger, rename the old file, create a new handler with the new file name and add it to the logger. The issue however is that I would need to create a completely identical handler, i.e it would need to have the same attributes as the old one (with exception of the file name of course). Is there a simple way to store old attributes and then use them to set the attributes of the new handler?

Any help is appreciated.

答:
Late the party, but I ran into this problem as well and here's how I've (tentatively) solved it.  Needs more testing though.

Note in my case, I do have access to the previous handler, so I just wound up using the same handler configuration I used earlier.  I agree a FileHandler.'rename_file()' method would be great.  One could likely be cooked up by sub-classing FileHandler(), but that's an exercise for another day.

```<code>#!/usr/bin/env python3

import os
import logging

logger_name1 = 'my_log.txt'
logger_name2 = 'my_new_log.txt'

logger = logging.getLogger('mylogger')
logger.level = logging.INFO
handler = logging.FileHandler(logger_name1, mode='w')
logger.addHandler(handler)
logger.info('msg 1')
logger.info('msg 2')

# handler.renameFile('my_newlog.txt')  # <--- Is something like this possible?

logger.removeHandler(handler)

# Rename the logfile on disk
os.rename(logger_name1, logger_name2)

# New handler using new filename.  Note the 'append' flag
new_handler = logging.FileHandler(logger_name2, mode='a')
logger.addHandler(new_handler)

# Try out the new logfile
logger.info('msg 3')
</code>```

Body:
I need to rename a logging file but continue logging to it afterwards. I'm running Python 3.x and using a logging module to create logs.

logger = logging.getLogger(r'mylogger')
handler = logging.FileHandler(r'mylog.txt', mode = r'w')
logger.addHandler(handler)
logger.info(r'msg 1')
logger.info(r'msg 2')

handler.renameFile(r'my_newlog.txt')  # <--- Is something like this possible?

logger.info(r'msg 3')

Does anyone know if something like this is possible? If no, how would I go about doing it? One idea that I had was to close the file (handler.close()), remove the handler from the logger, rename the old file, create a new handler with the new file name and add it to the logger. The issue however is that I would need to create a completely identical handler, i.e it would need to have the same attributes as the old one (with exception of the file name of course). Is there a simple way to store old attributes and then use them to set the attributes of the new handler?

Any help is appreciated.

Body:
Late the party, but I ran into this problem as well and here's how I've (tentatively) solved it.  Needs more testing though.

Note in my case, I do have access to the previous handler, so I just wound up using the same handler configuration I used earlier.  I agree a FileHandler.'rename_file()' method would be great.  One could likely be cooked up by sub-classing FileHandler(), but that's an exercise for another day.

#!/usr/bin/env python3

import os
import logging

logger_name1 = 'my_log.txt'
logger_name2 = 'my_new_log.txt'

logger = logging.getLogger('mylogger')
logger.level = logging.INFO
handler = logging.FileHandler(logger_name1, mode='w')
logger.addHandler(handler)
logger.info('msg 1')
logger.info('msg 2')

# handler.renameFile('my_newlog.txt')  # <--- Is something like this possible?

logger.removeHandler(handler)

# Rename the logfile on disk
os.rename(logger_name1, logger_name2)

# New handler using new filename.  Note the 'append' flag
new_handler = logging.FileHandler(logger_name2, mode='a')
logger.addHandler(new_handler)

# Try out the new logfile
logger.info('msg 3')


问:
User Agent Stylesheet - css property for strong is disabled?

In my codepen I placed  tags within a paragraph, but I noticed no emphasis being displayed.  Chrome developer tools shows the user agent stylesheet for strong has a line through it.  What could possibly be disabling this setting as I do not override strong myself or change any font-weight within my code?

I am using chrome version 56.

```<code><p id="p10">offset() - Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document. <strong>[returns: object]</strong>
</p>
</code>```

答:
Is it possible that you are setting the font-weight or calling font: inherit on the
 tag or possibly from the id? I think that might be overwriting the  tag. You could redeclare it as follows:

strong { font-weight: bold; }

If the above solution does not work, try using it with !important, like this:

strong { font-weight: bold !important; }

Body:
In my codepen I placed  tags within a paragraph, but I noticed no emphasis being displayed.  Chrome developer tools shows the user agent stylesheet for strong has a line through it.  What could possibly be disabling this setting as I do not override strong myself or change any font-weight within my code?

I am using chrome version 56.

offset() - Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document. [returns: object]


问:
How to generate type checking in JavaScript at run time?
With TypeScript or Facebook's Flow(type) I can statically type variables like

```<code>function add (x: integer, y: integer) { ... }
</code>```

Both TypeScript and Flow catch any illegal invocation such as add('1',0) at compile time.

However, when the library is compiled and exported, the types are gone. That means, the library consumer using that function gets no errors, that may potentially lead to hard-to-debug problems.

Is there any way to auto-generate additional code that would throw exactly the same errors at run time?

I can surely manually place guards every time a typecheck is expected but that feels boring and repetitive.

答:
You can also try babel-plugin-runtyper that performs type checking in runtime and does not require manual annotations.

For your example, if function looks like:

```<code>function add(x, y) {
   return x + y;
}
</code>```

And you call it as

```<code>add('1', 0);
</code>```

you will get warning in console:

Plus operation with different types: "1" (string) + 0 (number)

Body:
With TypeScript or Facebook's Flow(type) I can statically type variables like

function add (x: integer, y: integer) { ... }

Both TypeScript and Flow catch any illegal invocation such as add('1',0) at compile time.

However, when the library is compiled and exported, the types are gone. That means, the library consumer using that function gets no errors, that may potentially lead to hard-to-debug problems.

Is there any way to auto-generate additional code that would throw exactly the same errors at run time?

I can surely manually place guards every time a typecheck is expected but that feels boring and repetitive.

Body:
You can also try babel-plugin-runtyper that performs type checking in runtime and does not require manual annotations.

For your example, if function looks like:

function add(x, y) {
   return x + y;
}

And you call it as

add('1', 0);

you will get warning in console:

Plus operation with different types: "1" (string) + 0 (number)


问:
How to assign values from array to buttons in Swift
Hi I'm a beginner in Swift and I would like to know how I can make string values, stored in an array, the title of buttons.

Specific to my case: I have 24 buttons in my storyboard, all put into one action in the controller view. In my model I have an array with 24 emoji's and I would like to know how I can (randomly) assign these emoji's to my buttons.

```<code>var emoji : [String] = ["","", "","", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "","", "", "", "", ""]
</code>```

Thank you in advance.

答:
When connecting the buttons to the code, connect them as an Outlet Connection. Then you will have an array of buttons. To set the button text accordingly:

```<code>for button in buttons {
    button.setTitle(emoji[buttons.index(of: button)!], for: [])
}
</code>```

This will loop through all the buttons and set their title to the corresponding emojis. You can look at how to shuffle an array to randomize the emoji: How do I shuffle an array in Swift?

Body:
Hi I'm a beginner in Swift and I would like to know how I can make string values, stored in an array, the title of buttons.

Specific to my case: I have 24 buttons in my storyboard, all put into one action in the controller view. In my model I have an array with 24 emoji's and I would like to know how I can (randomly) assign these emoji's to my buttons.

var emoji : [String] = ["","", "","", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "","", "", "", "", ""]

Thank you in advance.

Body:
When connecting the buttons to the code, connect them as an Outlet Connection. Then you will have an array of buttons. To set the button text accordingly:

for button in buttons {
    button.setTitle(emoji[buttons.index(of: button)!], for: [])
}

This will loop through all the buttons and set their title to the corresponding emojis. You can look at how to shuffle an array to randomize the emoji: How do I shuffle an array in Swift?


问:
iOS 10.3 beta 3 doesn't persist data of KeychainItem
I have observed behavior of app in iOS 10.2.1 device and iOS 10.3 beta 3 device for https://developer.apple.com/library/content/samplecode/GenericKeychain/Introduction/Intro.html

Keychain data is being deleted in iOS 10.3 beta 3.
That was still found in earlier versions.

Do we have any alternative to do this?

答:
Originally (Since iOS 10.3 beta 1 to 5?) the keychain WAS NOT persisted.

Apple staff:

This is an intentional change in iOS 10.3 to protect user privacy. Information that can identify a user should not be left on the device after the app that created it has been removed.

But since iOS 10.3 beta 6, the keychain IS persisted again.

Nobody gives you any reassurances it will work that way in the future.

While it is fine to use it the way we do, I strongly encourage you to write your app so that it acts reasonably if this behaviour change.


答: Once you find the URL, you're better off parsing it properly rather than hacking it into a regex.</p>

Title: Python: Find URLs and add querystring pair


问:
Two objects having same hashcode means they are referring to same object ..right?
Being new to Scala, I have created an Object (singleton). and assinged two different variables to that object as shown below. Both of them show me the same hashcode. Because "School" is a singleton. Is that right?</p>

```<code> object Main extends  App{

 //we can import within the method as well .
 import Scala_DemoSingletonPackage._

  //See both the objeccts have same hashcode.
  println("The hasshcode for first object is " + aSchool.hashCode())
  println("The Hashcode from second object is " + bSchool.hashCode())

}

object School {

  def Printwhateveryouwant(input:String) {
     println(s"This is a singleton object  $input")

 }
</code>```

答:
There are two misconceptions in your statement:

You assume that an equal hashCode implies object equality. That is not true. In fact, it cannot possibly be true because there are only finitely many hashes but infinitely many objects, so there must be an infinite number of objects with the same hashCode. An unequal hashCode means that the objects are unequal, but an equal hashCode tells you precisely nothing at all. However, the "other direction" is true: if two objects are equal, then they have the same hashCode.

You assume that equality implies identity. That is also not true. The fact that two objects are equal does not mean that they are also identical. Again, the "other direction" is (trivially) true: an object is equal to itself.

Note: all of these actually depend on properly implemented methods, of course. It is perfectly possible to write an equality method that violates reflexivity, for example. It's just that when you do something like that, you lose the guarantees Scala gives you.

So, you cannot conclude from the fact the two hashCodes are equal that the two objects are equal. And even if you could conclude that, you still cannot conclude from the fact the two objects are equal that they are actually one and the same object.

Nonetheless, that is true: there exists only one instance of a singleton object, that's why it is called a singleton object. So, your two references must refer to the same object, for the simple reason that there is only one object to begin with. However, the test you used to arrive at that conclusion is wrong.

Body:
Being new to Scala, I have created an Object (singleton). and assinged two different variables to that object as shown below. Both of them show me the same hashcode. Because "School" is a singleton. Is that right?

 object Main extends  App{

 //we can import within the method as well .
 import Scala_DemoSingletonPackage._

  //See both the objeccts have same hashcode.
  println("The hasshcode for first object is " + aSchool.hashCode())
  println("The Hashcode from second object is " + bSchool.hashCode())

}

object School {

  def Printwhateveryouwant(input:String) {
     println(s"This is a singleton object  $input")

 }


问:
JavaScript password and page variation
I am using this code for easy password protection of web pages but I want to edit the code so I can have two different passwords opening two different web pages. So when I enter "Password No.1" it will open "Page No.1" but if I type "Password No.2" it will open "Page No.2".</p>
```<code><script>

function TheLogin() {

var password = 'password1';

if (this.document.login.pass.value == password) {
  top.location.href="pageno1.php";
}
else {
  window.alert("Incorrect password, please try again.");
  }
}

</script>
</code>```

答:
```<code><script>

function TheLogin() {

if (this.document.login.pass.value == 'password1') {
  top.location.href="pageno1.php";
}
else if (this.document.login.pass.value == 'password2') {
  top.location.href="pageno2.php";
}
else {
  window.alert("Incorrect password, please try again.");
  }
}

</script>
</code>```

ContentLicense: CC BY-SA 4.0

Title: JavaScript password and page variation


问:
Select only certain columns in related model when eager loading
I have two related models:

```<code>class Attribute extends Eloquent
{
    public function categories()
    {
        return $this->hasMany('Category');
    }
}

class Category extends Eloquent
{
    public function attributes()
    {
        return $this->belongsTo('Attribute');
    }
}
</code>```

I want to return all attributes and their categories as a JSON object, but I only want to select certain fields in both models (i.e. not return fields like 'created_at' in the JSON).

I've tried this:

```<code>$attributes = Attribute::select('id', 'name')
 ->with(['categories' => function ($query) {
   $query->select('categories.id', 'categories.name', 'categories.attribute_id');
 }]);

Response::JSON($attributes->get());
</code>```

but despite the select query for the related model, unrequested fields are returned:

```<code>attributes: [{
 id: 3,
 name: "Organisation",
 categories: [{
  id: 3,
  name: "Asia HQ",
  attribute_id: 3,
  created_at: "2013-11-30 00:00:00",
  updated_at: "2013-11-30 00:00:00"
 }]
}]
</code>```

How do I select only certain columns in related model when eager loading?

答:
Make use of select() laravel method:

```<code>$attributes = Attribute::select('id', 'name')->with(['categories' =>function($query){
        $query->select(['categories.id', 'categories.name','categories.attribute_id'])->get();
}]);

Response::JSON($attributes->get());
</code>```

To make select method work in eager loading you need to include foreign_key in
selected column list.

Reference : http://laravel-tricks.com/tricks/column-selection-in-eager-loading

Body:
I have two related models:

class Attribute extends Eloquent
{
    public function categories()
    {
        return $this->hasMany('Category');
    }
}

class Category extends Eloquent
{
    public function attributes()
    {
        return $this->belongsTo('Attribute');
    }
}

I want to return all attributes and their categories as a JSON object, but I only want to select certain fields in both models (i.e. not return fields like 'created_at' in the JSON).

I've tried this:

$attributes = Attribute::select('id', 'name')
 ->with(['categories' => function ($query) {
   $query->select('categories.id', 'categories.name', 'categories.attribute_id');
 }]);

Response::JSON($attributes->get());

but despite the select query for the related model, unrequested fields are returned:

attributes: [{
 id: 3,
 name: "Organisation",
 categories: [{
  id: 3,
  name: "Asia HQ",
  attribute_id: 3,
  created_at: "2013-11-30 00:00:00",
  updated_at: "2013-11-30 00:00:00"
 }]
}]

How do I select only certain columns in related model when eager loading?

Body:
Make use of select() laravel method:

$attributes = Attribute::select('id', 'name')->with(['categories' =>function($query){
        $query->select(['categories.id', 'categories.name','categories.attribute_id'])->get();
}]);

Response::JSON($attributes->get());

To make select method work in eager loading you need to include foreign_key in
selected column list.

Reference : http://laravel-tricks.com/tricks/column-selection-in-eager-loading


问:
Prevent user from typing certain characters into a text input field
I'm not sure what this is called. It's really simple. I tried using a pipe, but I got an error. I'm looking for something as simple as:

```<code><input [(ngModel)]="order.name | lettersOnlyPipe"/>
</code>```

That doesn't work. What can I do that would accomplish this?

答:
Your best bet for this is your own directive.

Some simple ideas to get you going:

your directive monitors the input event on its host element

on every input event, you check whether the input value is valid, if not, you set your input back to its old value

or alternatively,
* monitor the keydown event and on each keydown, check if the key is a valid key - if not, set your input back to its old value

That's the basic approach. You can look at the highlight directive example in the angular docs as a guide to get going.

Body:
I'm not sure what this is called. It's really simple. I tried using a pipe, but I got an error. I'm looking for something as simple as:

<input [(ngModel)]="order.name | lettersOnlyPipe"/>

That doesn't work. What can I do that would accomplish this?


答:
With the recent Angular 4 release, you can use the pattern attribute to restrict characters as mentioned in this feature

```<code><input [(ngModel)]="order.name" pattern="" />
</code>```

In other case, you should handle it using custom directive. Refer to this answer for a sample.

Title: Prevent user from typing certain characters into a text input field

Body:
With the recent Angular 4 release, you can use the pattern attribute to restrict characters as mentioned in this feature

<input [(ngModel)]="order.name" pattern="" />

In other case, you should handle it using custom directive. Refer to this answer for a sample.


问:
Anything wrong with this design to initialize the array in the DLL?
Lets assume we've got a DLL and there should be an array stored globally in it that's going to be exported, the thing is we want to initialize it by reading some content from a file, so personally I find myself no other way than putting it in a struct to be able to initialize using constructor:

```<code>struct Construction{
 public:
  Construction(){
   //do the initialization thing and read the needed data from the file
  }
  SomeType sTArray[100];
};

__declspec(dllexport) Construction obj();
</code>```

Now where it's going to be used, the programmer can initialize a reference to it and then use the reference like below:

```<code>SomeType (&arrayRef)[100]=obj.sTArray;
</code>```

Now would you think I'm wrong in any context?

答:
Since CRT in the DLL and in the executable could be different you should supply Construction with a release method that will delete allocated object. In this way you will guarantee that the deallocation function will be called from the appropriate CRT. Also you need to return Construction by pointer to exclude copying operations. The following code illustrates the method how it could be implemented:

```<code>// DLL export header
struct IConstruction {
protected:
  virtual ~IConstruction() {}
public:
  virtual void release() =0;
  virtual SomeType& get_array() =0;
};

__declspec(dllexport) IConstruction* obj();
</code>```

-

```<code>// DLL implementation
struct Construction : public IConstruction {
  SomeType sTArray[100];

  Construction() { /* do initialization */ }
  virtual void release() { delete this; }
  virtual SomeType& get_array() { return sTArray; }
  virtual ~Construction() { /* do clean up */ }
};

IConstruction* obj() { return new Construction; }
</code>```

Body:
Lets assume we've got a DLL and there should be an array stored globally in it that's going to be exported, the thing is we want to initialize it by reading some content from a file, so personally I find myself no other way than putting it in a struct to be able to initialize using constructor:

struct Construction{
 public:
  Construction(){
   //do the initialization thing and read the needed data from the file
  }
  SomeType sTArray[100];
};

__declspec(dllexport) Construction obj();

Now where it's going to be used, the programmer can initialize a reference to it and then use the reference like below:

SomeType (&arrayRef)[100]=obj.sTArray;

Now would you think I'm wrong in any context?

Body:
Since CRT in the DLL and in the executable could be different you should supply Construction with a release method that will delete allocated object. In this way you will guarantee that the deallocation function will be called from the appropriate CRT. Also you need to return Construction by pointer to exclude copying operations. The following code illustrates the method how it could be implemented:

// DLL export header
struct IConstruction {
protected:
  virtual ~IConstruction() {}
public:
  virtual void release() =0;
  virtual SomeType& get_array() =0;
};

__declspec(dllexport) IConstruction* obj();

-

// DLL implementation
struct Construction : public IConstruction {
  SomeType sTArray[100];

  Construction() { /* do initialization */ }
  virtual void release() { delete this; }
  virtual SomeType& get_array() { return sTArray; }
  virtual ~Construction() { /* do clean up */ }
};

IConstruction* obj() { return new Construction; }


问:
Is it possible to make a real function type in C++ which is callable with itself?
I am trying to write recursion without referencing the function name in C++ by means of Y-combinator. However, I can't figure out the type of the Function in the following attempt:

```<code>#include <iostream>

using std::cin;
using std::cout;

template<class Function> unsigned long factorial1(Function self, unsigned long n) {
    return n ? n * self(self, n - 1) : 1;
}

unsigned long factorial(unsigned long n) {
    return factorial1(factorial1, n);
}

int main() {
    unsigned long n;
    cin >> n;
    cout << factorial(n) << '\n';
    return 0;
}
</code>```

The compiler cannot deduce what is Function, neither can me. Then I tried the following:

```<code>#include <iostream>

using std::cin;
using std::cout;

struct Factorial {
    template<class Function> unsigned long operator()(Function self, unsigned long n) const {
        return n ? n * self(self, n - 1) : 1;
    }
};

unsigned long factorial(unsigned long n) {
    return Factorial()(Factorial(), n);
}

int main() {
    unsigned long n;
    cin >> n;
    cout << factorial(n) << '\n';
    return 0;
}
</code>```

This, when compared to the above example, the difference is I changed the work function to a callable object, which Function is deduced easily as Factorial, leading to the following complete implementation of the combinator:

```<code>#include <iostream>

using std::cin;
using std::cout;

struct Factorial {
    template<class Function> unsigned long operator()(Function self, unsigned long n) const {
        return n ? n * self(self, n - 1) : 1;
    }
};

template<class Function> auto y(Function f) {
    return [f](auto n) {
        return f(f, n);
    };
}

int main() {
    unsigned long n;
    cin >> n;
    cout << y(Factorial())(n) << '\n';
    return 0;
}
</code>```

The question is that, is it possible to rewrite the struct Factorial to a plain function?

答:
You are doing it slightly wrong: first argument to factorial1 should be already fixed point of the factorial1 with  the type unsigned long(*)(unsigned long), not the factorial1 itself, so no need to provide self to it as an argument:

```<code>unsigned long factorial1(unsigned long(*self)(unsigned long), unsigned long n) {
    return n ? n * self(n - 1) : 1;
}
</code>```

C++ doesn't allow to pass a closure as a function pointer, so we must either:

Pass std::function or some other wrapper as self. Not interesting IMO.

Use template magic to generate fixed point function at compile time.

Second option can be done easily:

```<code>template<class X, X(*Fn)(X(*)(X), X)>
struct Fix {
    static X Function(X x) {
        return Fn(Fix<X, Fn>::Function, x);
    }
};
</code>```

Now, Fix<unsigned long, factorial1>::Function is a fixed point of factorial1:

```<code>unsigned long factorial(unsigned long n) {
    return Fix<unsigned long, factorial1>::Function(n);
};
</code>```

Note that this Fix implementation still refers to itself by name, so will any implementation of fixed point combinator without type system hacks.

Body:
I am trying to write recursion without referencing the function name in C++ by means of Y-combinator. However, I can't figure out the type of the Function in the following attempt:

#include <iostream>

using std::cin;
using std::cout;

template<class Function> unsigned long factorial1(Function self, unsigned long n) {
    return n ? n * self(self, n - 1) : 1;
}

unsigned long factorial(unsigned long n) {
    return factorial1(factorial1, n);
}

int main() {
    unsigned long n;
    cin >> n;
    cout << factorial(n) << '\n';
    return 0;
}

The compiler cannot deduce what is Function, neither can me. Then I tried the following:

#include <iostream>

using std::cin;
using std::cout;

struct Factorial {
    template<class Function> unsigned long operator()(Function self, unsigned long n) const {
        return n ? n * self(self, n - 1) : 1;
    }
};

unsigned long factorial(unsigned long n) {
    return Factorial()(Factorial(), n);
}

int main() {
    unsigned long n;
    cin >> n;
    cout << factorial(n) << '\n';
    return 0;
}

This, when compared to the above example, the difference is I changed the work function to a callable object, which Function is deduced easily as Factorial, leading to the following complete implementation of the combinator:

#include <iostream>

using std::cin;
using std::cout;

struct Factorial {
    template<class Function> unsigned long operator()(Function self, unsigned long n) const {
        return n ? n * self(self, n - 1) : 1;
    }
};

template<class Function> auto y(Function f) {
    return [f](auto n) {
        return f(f, n);
    };
}

int main() {
    unsigned long n;
    cin >> n;
    cout << y(Factorial())(n) << '\n';
    return 0;
}

The question is that, is it possible to rewrite the struct Factorial to a plain function?

Body:
You are doing it slightly wrong: first argument to factorial1 should be already fixed point of the factorial1 with  the type unsigned long(*)(unsigned long), not the factorial1 itself, so no need to provide self to it as an argument:

unsigned long factorial1(unsigned long(*self)(unsigned long), unsigned long n) {
    return n ? n * self(n - 1) : 1;
}

C++ doesn't allow to pass a closure as a function pointer, so we must either:

Pass std::function or some other wrapper as self. Not interesting IMO.

Use template magic to generate fixed point function at compile time.

Second option can be done easily:

template<class X, X(*Fn)(X(*)(X), X)>
struct Fix {
    static X Function(X x) {
        return Fn(Fix<X, Fn>::Function, x);
    }
};

Now, Fix<unsigned long, factorial1>::Function is a fixed point of factorial1:

unsigned long factorial(unsigned long n) {
    return Fix<unsigned long, factorial1>::Function(n);
};

Note that this Fix implementation still refers to itself by name, so will any implementation of fixed point combinator without type system hacks.


问:
Extract word before all matching character in bash
How to extract all the string before :, I could get only the first as below

```<code>$ echo "cc_dd:qqq www;aa_bb:ll fi;ee_ff:bb dd ee" | sed 's/:.*//g'
$ cc_dd
# want to print cc_dd aa_bb and ee_ff
</code>```

答:
```<code>awk -F'[;:]' '{print $1,$3,$5}' OFS='\n' file

cc_dd
aa_bb
ee_ff
</code>```

Body:
How to extract all the string before :, I could get only the first as below

$ echo "cc_dd:qqq www;aa_bb:ll fi;ee_ff:bb dd ee" | sed 's/:.*//g'
$ cc_dd
# want to print cc_dd aa_bb and ee_ff


问:
DateTime.ParseExact is not doing what i want it to do
When use the .ParseExact() method for the DateTime, i always get the same output as the string i put in. Here is my code:

```<code>    [Authorize(Roles = "Backoffice, Manager")]
    [HttpPost]
    public ActionResult FilmShowCreate(FilmShowViewModel newFilmShow)
    {
        if (ModelState.IsValidField("FilmId") && ModelState.IsValidField("Time"))
        {
            DateTime unformattedDateTime = newFilmShow.Date.Date + newFilmShow.Time.TimeOfDay;
            string dateString = unformattedDateTime.ToString("yyyy-MM-dd HH:mm:ss");
            DateTime dbDate = DateTime.ParseExact(dateString, "yyyy-MM-dd HH:mm:ss",
                CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.AdjustToUniversal);

            FilmShow filmShow = new FilmShow
            {
                  Film = filmRepository.GetFilm(newFilmShow.FilmId),
                  Cinema = cinemaRepository.GetCinema(newFilmShow.CinemaId),
                  ThreeDimensional = newFilmShow.ThreeDimensional,
                  Date = dbDate,
                  SpecialEvent = newFilmShow.SpecialEvent
            };

            filmShowsRepository.AddShow(filmShow);

            return View("SuccesfullFilmShowCreate");
</code>```

The string dateString is formatted good, but it is a string and I need to store it in the database as a format DateTime like this "year-month-day hours:minutes:seconds". But for whatever reason the ParseExact doesn't seem to work in my case. The DateTime format i get is "dd-MM-yyyy HH:mm".

答:
It doesn't do what you want because, well, that function isn't supposed to do what you are describing.

ParseExact simply indicates that the input must match the given format in order to be used (and not throw an exception). It is a counterpart to Parse which will accept any valid Date/Time format. It has absolutely no bearing on the future format of any string representation of the DateTime object it creates.

If you want to output it in a given format, pass your format string into ToString before sending that string to the database. Of course, if you are using something like EF, the conversion is done for you and it shouldn't matter.

Example:

```<code>string myFormattedDateTime = dbDate.ToString("yyyy-MM-dd HH:mm:ss");
</code>```

Reading your question more closely, I realize that you seem to think that DateTime has some "stored" format. It does not. DateTime is just a collection of numbers that hold the information required to represent a date and time. The format you are describing only exists in string representations.

Body:
When use the .ParseExact() method for the DateTime, i always get the same output as the string i put in. Here is my code:

    [Authorize(Roles = "Backoffice, Manager")]
    [HttpPost]
    public ActionResult FilmShowCreate(FilmShowViewModel newFilmShow)
    {
        if (ModelState.IsValidField("FilmId") && ModelState.IsValidField("Time"))
        {
            DateTime unformattedDateTime = newFilmShow.Date.Date + newFilmShow.Time.TimeOfDay;
            string dateString = unformattedDateTime.ToString("yyyy-MM-dd HH:mm:ss");
            DateTime dbDate = DateTime.ParseExact(dateString, "yyyy-MM-dd HH:mm:ss",
                CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.AdjustToUniversal);

            FilmShow filmShow = new FilmShow
            {
                  Film = filmRepository.GetFilm(newFilmShow.FilmId),
                  Cinema = cinemaRepository.GetCinema(newFilmShow.CinemaId),
                  ThreeDimensional = newFilmShow.ThreeDimensional,
                  Date = dbDate,
                  SpecialEvent = newFilmShow.SpecialEvent
            };

            filmShowsRepository.AddShow(filmShow);

            return View("SuccesfullFilmShowCreate");

The string dateString is formatted good, but it is a string and I need to store it in the database as a format DateTime like this "year-month-day hours:minutes:seconds". But for whatever reason the ParseExact doesn't seem to work in my case. The DateTime format i get is "dd-MM-yyyy HH:mm".

Body:
It doesn't do what you want because, well, that function isn't supposed to do what you are describing.

ParseExact simply indicates that the input must match the given format in order to be used (and not throw an exception). It is a counterpart to Parse which will accept any valid Date/Time format. It has absolutely no bearing on the future format of any string representation of the DateTime object it creates.

If you want to output it in a given format, pass your format string into ToString before sending that string to the database. Of course, if you are using something like EF, the conversion is done for you and it shouldn't matter.

Example:

string myFormattedDateTime = dbDate.ToString("yyyy-MM-dd HH:mm:ss");

Reading your question more closely, I realize that you seem to think that DateTime has some "stored" format. It does not. DateTime is just a collection of numbers that hold the information required to represent a date and time. The format you are describing only exists in string representations.


问:
Why is an additional backslash '\' being added to substring in list when re.split is used?
So I'm trying to solve an issue in my code where an additional backslash is added to a substring(s) in my split list once re.split(regex_pattern, str) is used.  The problem goes something like this:

```<code>In [63]: str = r'/dir/hello\/hell/dir2/hello\end'

In [64]: regex_pattern = '(hello)'

In [65]: a = re.split(regex_pattern, str)

In [66]: a
Out[66]: ['/dir/', 'hello', '\\/hell/dir2/', 'hello', '\\end']
</code>```

As you can see, Out[66] shows the list as having two substrings with '\\' instead of two with '\'.  I know this problem has something to do with how the compiler interprets backslashes, but ultimately cannot figure out why specifically this is happening.

I've also tried making my str variable a raw string, and adding additional '\' to my str variable (up to four '\\\\') where one exists, i.e.

```<code>In [63]: str = r'/dir/hello\\/hell/dir2/hello\\end'
</code>```

This still gives the same output.

I am using Python 2.7 on Ubuntu.  Sorry if this is a duplicate, but I couldn't find a question whose answer applies to mine.

答:
This has nothing to with re.split. \ usually defines an escape sequence. To use a literal \ you'll need to double it:

Consider your original string:

```<code>In [15]: s = r'/dir/hello\/hell/dir2/hello\end'

In [16]: s
Out[16]: '/dir/hello\\/hell/dir2/hello\\end'

In [17]: len(s)
Out[17]: 31
</code>```

The extra \ are not counted with len. They only help to specify that the \ does not define any other escape sequence; asides \\ which is also an escape sequence.

Body:
So I'm trying to solve an issue in my code where an additional backslash is added to a substring(s) in my split list once re.split(regex_pattern, str) is used.  The problem goes something like this:

In [63]: str = r'/dir/hello\/hell/dir2/hello\end'

In [64]: regex_pattern = '(hello)'

In [65]: a = re.split(regex_pattern, str)

In [66]: a
Out[66]: ['/dir/', 'hello', '\\/hell/dir2/', 'hello', '\\end']

As you can see, Out[66] shows the list as having two substrings with '\\' instead of two with '\'.  I know this problem has something to do with how the compiler interprets backslashes, but ultimately cannot figure out why specifically this is happening.

I've also tried making my str variable a raw string, and adding additional '\' to my str variable (up to four '\\\\') where one exists, i.e.

In [63]: str = r'/dir/hello\\/hell/dir2/hello\\end'

This still gives the same output.

I am using Python 2.7 on Ubuntu.  Sorry if this is a duplicate, but I couldn't find a question whose answer applies to mine.

Body:
This has nothing to with re.split. \ usually defines an escape sequence. To use a literal \ you'll need to double it:

Consider your original string:

In [15]: s = r'/dir/hello\/hell/dir2/hello\end'

In [16]: s
Out[16]: '/dir/hello\\/hell/dir2/hello\\end'

In [17]: len(s)
Out[17]: 31

The extra \ are not counted with len. They only help to specify that the \ does not define any other escape sequence; asides \\ which is also an escape sequence.


问:
How do I get the corresponding column value for MAX function?
I have the following query which gives the latest date_announced for MAX(date_announced) but doesnt give the corresponding value for software_product_build?
how do I get it the corresponding software_product_build value for MAX(date_announced)?

```<code>   select
   software_product_build,
   MAX(date_announced) as date_announced
    from software_product_builds
   group by software_product_id
</code>```

One case:-

```<code>   select software_product_build,
   MAX(date_announced) as date_announced
    from software_product_builds
    where software_product_build LIKE '%QCA6290.LA.0.1%' group by software_product_id;

OUTPUT:-
|------software_product_build------|-------date_announced------|
--QCA6290.LA.0.1-00001-STD.INT-6---|------2017-03-13 21:13:32---

select software_product_build from software_product_builds where date_announced='2017-03-13 21:13:32';

OUTPUT:-
CI_QCA6290.LA.0.1-03091-STD.INT-61
</code>```

答:
First you need to get max date for every softwared prduct id then you can find software product build for that max date.

Select spb.software_product_build,
   Tmp.date_announced
    from software_product_builds spb join
(Select software_product_id,
   MAX(date_announced) as date_announced
    from software_product_builds
   group by software_product_id) as tmp on (tmp.software_product_id=spb.software_product_id and tmp.date_announced=spb.date_announced)

Body:
I have the following query which gives the latest date_announced for MAX(date_announced) but doesnt give the corresponding value for software_product_build?
how do I get it the corresponding software_product_build value for MAX(date_announced)?

   select
   software_product_build,
   MAX(date_announced) as date_announced
    from software_product_builds
   group by software_product_id

One case:-

   select software_product_build,
   MAX(date_announced) as date_announced
    from software_product_builds
    where software_product_build LIKE '%QCA6290.LA.0.1%' group by software_product_id;

OUTPUT:-
|------software_product_build------|-------date_announced------|
--QCA6290.LA.0.1-00001-STD.INT-6---|------2017-03-13 21:13:32---

select software_product_build from software_product_builds where date_announced='2017-03-13 21:13:32';

OUTPUT:-
CI_QCA6290.LA.0.1-03091-STD.INT-61


问:
Rx.NET TakeUntil example
The following example

```<code>var subject = new Subject<int>();
var otherSubject = new Subject<Unit>();
subject
.SkipUntil(otherSubject)
.Subscribe(Console.WriteLine, () => Console.WriteLine("Completed"));
subject.OnNext(1);
subject.OnNext(2);
subject.OnNext(3);
otherSubject.OnNext(Unit.Default);
subject.OnNext(4);
subject.OnNext(5);
subject.OnNext(6);
subject.OnNext(7);
subject.OnNext(8);
subject.OnCompleted();
</code>```

produces the output

```<code>4
5
6
7
completed
</code>```

Shouldn't it emit the value 8 also? Why is it not emitting the value 8?

答: ...brought to you by the works on my machine certification program

Title: Rx.NET TakeUntil example

Body:
The following example

var subject = new Subject<int>();
var otherSubject = new Subject<Unit>();
subject
.SkipUntil(otherSubject)
.Subscribe(Console.WriteLine, () => Console.WriteLine("Completed"));
subject.OnNext(1);
subject.OnNext(2);
subject.OnNext(3);
otherSubject.OnNext(Unit.Default);
subject.OnNext(4);
subject.OnNext(5);
subject.OnNext(6);
subject.OnNext(7);
subject.OnNext(8);
subject.OnCompleted();

produces the output

4
5
6
7
completed

Shouldn't it emit the value 8 also? Why is it not emitting the value 8?


问:
Turn off animation at runtime in angular
I understand I can use BrowserAnimationModule and NoopAnimationsModule when I bootstrap the application. What is the recommended way to turn off animation at run-time, if the user requests it for ADA and other reasons?</p>

答:
There may be an elegant solution but this works as of angular 4.0.0:
(Disclaimer I found the basis for this code for 2.0)

In your app.module add these imports:

```<code>import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AnimationDriver, ɵWebAnimationsDriver } from '@angular/animations/browser';
</code>```

Add this function:

```<code>export function animationFactory(): any {
  const noop = AnimationDriver.NOOP;
  const driver = new ɵWebAnimationsDriver();
  return {
    animate: (element: any, keyframes: {
        [key: string]: string | number;
    }[], duration: number, delay: number, easing: string, previousPlayers?: any[]) => {
      if (!wantToAnimate) {
        return noop.animate(element, keyframes, duration, delay, easing, previousPlayers);
      } else {
        return driver.animate(element, keyframes, duration, delay, easing, previousPlayers);
      }
    }
  };
};
</code>```

import BrowserAnimationModule

```<code>imports: [
  ...,
  BrowserAnimationsModule,
]
</code>```

provide AnimationDriver, using the factory function above

```<code>providers: [
  ...,
  { provide: AnimationDriver, useFactory: animationFactory },
]
</code>```

Body:
There may be an elegant solution but this works as of angular 4.0.0:
(Disclaimer I found the basis for this code for 2.0)

In your app.module add these imports:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AnimationDriver, ɵWebAnimationsDriver } from '@angular/animations/browser';

Add this function:

export function animationFactory(): any {
  const noop = AnimationDriver.NOOP;
  const driver = new ɵWebAnimationsDriver();
  return {
    animate: (element: any, keyframes: {
        [key: string]: string | number;
    }[], duration: number, delay: number, easing: string, previousPlayers?: any[]) => {
      if (!wantToAnimate) {
        return noop.animate(element, keyframes, duration, delay, easing, previousPlayers);
      } else {
        return driver.animate(element, keyframes, duration, delay, easing, previousPlayers);
      }
    }
  };
};

import BrowserAnimationModule

imports: [
  ...,
  BrowserAnimationsModule,
]

provide AnimationDriver, using the factory function above

providers: [
  ...,
  { provide: AnimationDriver, useFactory: animationFactory },
]


问:
Why does Spark SQL turn nullable on for string column even when all values specified?
So for something like this:

```<code>case class RandomClass(stringOne: String, stringTwo: String, numericOne: Int)
val ds = Seq(
  RandomClass("a", null, 1),
  RandomClass("a", "x", 3),
  RandomClass("a", "y", 4),
  RandomClass("a", null, 5)
).toDS()

ds.printSchema()
</code>```

results in

```<code>root
 |-- stringOne: string (nullable = true)
 |-- stringTwo: string (nullable = true)
 |-- numericOne: integer (nullable = false)
</code>```

why would stringOne be nullable? Strangely, numericOne is inferred correctly. I assume I am just missing something about the relationship between Dataset and DataFrame API?

答:
It is true that Spark makes a best guess on nullability depending on whether the inferred type lies on the AnyRef or AnyVal side of the Scala object hierarchy, but note also that it can be more complicated than that. For example, when working with Parquet files, everything is inferred to be nullable for compatibility purposes.

Meanwhile, when you create a schema, you can simply set nullable = true everywhere if you like:

```<code>StructField(fieldName, LongType, nullable = true)

// or using a "DSL"
$"fieldName".long.copy(nullable = false)
</code>```

Body:
So for something like this:

case class RandomClass(stringOne: String, stringTwo: String, numericOne: Int)
val ds = Seq(
  RandomClass("a", null, 1),
  RandomClass("a", "x", 3),
  RandomClass("a", "y", 4),
  RandomClass("a", null, 5)
).toDS()

ds.printSchema()

results in

root
 |-- stringOne: string (nullable = true)
 |-- stringTwo: string (nullable = true)
 |-- numericOne: integer (nullable = false)

why would stringOne be nullable? Strangely, numericOne is inferred correctly. I assume I am just missing something about the relationship between Dataset and DataFrame API?

Body:
It is true that Spark makes a best guess on nullability depending on whether the inferred type lies on the AnyRef or AnyVal side of the Scala object hierarchy, but note also that it can be more complicated than that. For example, when working with Parquet files, everything is inferred to be nullable for compatibility purposes.

Meanwhile, when you create a schema, you can simply set nullable = true everywhere if you like:

StructField(fieldName, LongType, nullable = true)

// or using a "DSL"
$"fieldName".long.copy(nullable = false)


问:
Child process sends a number through a pipe, then waits
I'm trying to spawn two child processes connected with a pipe.
Child 1 is supposed to send a number through a pipe to child 2 and child 2 should print it. I managed to do that, but when I try to do this in a loop, with child 1 waiting 1 second each time before sending another number, it doesn't send anything.

What am I doing wrong?

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <windows.h>

int main(int argc, char *argv[]) {
    int fd[2];
    pipe(fd);
    pid_t pid1 = fork();
    if (pid1) {
        pid_t pid2 = fork();
        if (pid2) { //parent
            // do stuff as parent
        } else { //child 2
            close(fd[1]);
            char stringNumberReceived[10];
            while (1) {
                read(fd[0], stringNumberReceived, sizeof (stringNumberReceived));
                printf("number received: %s\n", stringNumberReceived);
            }
        }
    } else {//child 1
        close(fd[0]);
        int num;
        char stringnumber [10];
        while (1) {
            num = rand();
            snprintf(stringnumber, 10, "%d", num);
            printf("attempting to sent: %s\n", stringnumber);
            write(fd[1], stringnumber, strlen(stringnumber) + 1);
            Sleep(1000);
        }
    }
}
</code>```

答:
Here's a mildly modified version of your code:

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

enum { MAX_COUNT = 20 };

int main(void)
{
    int fd[2];
    pipe(fd);
    pid_t pid1 = fork();
    if (pid1)
    {
        pid_t pid2 = fork();
        if (pid2)   // parent
        {
            printf("Child 1: %d; child 2: %d\n", (int)pid1, (int)pid2);
            close(fd[0]);   // Let the child detect EOF!
            close(fd[1]);   // Let the child detect EOF!
            int corpse;
            int status;
            while ((corpse = wait(&status)) > 0)
                printf("PID %d exited with status 0x%.4X\n", corpse, status);
        }
        else     // child 2
        {
            close(fd[1]);
            char stringNumberReceived[10];
            int nbytes;
            while ((nbytes = read(fd[0], stringNumberReceived, sizeof(stringNumberReceived))) > 0)
                printf("number received: %.*s\n", nbytes, stringNumberReceived);
            printf("Child 2: EOF or ERR\n");
        }
    }
    else    // child 1
    {
        close(fd[0]);
        int num;
        char stringnumber[10];
        for (int counter = 0; counter < MAX_COUNT; counter++)
        {
            num = rand();
            snprintf(stringnumber, sizeof(stringnumber), "%d", num);
            printf("attempting to send: [%s] (len %zu)\n", stringnumber, strlen(stringnumber));
            write(fd[1], stringnumber, strlen(stringnumber) + 1);
            sleep(1);
        }
    }
    return 0;
}
</code>```

What changed?  Various things.  You can ignore the changes in placement of braces; that's purely cosmetic.

Parent code is implemented.

Parent reports child process IDs.

Parent closes the pipe — it is neither reading nor writing.

Parent waits for children to die, reporting statuses as they do.

Child records how many bytes it read, and ensures it prints no more than that.

It terminates the loop and reports before exiting when it gets an error or EOF (0 bytes read) on the pipe.

Other child does a fixed number of cycles (20 as shown) before exiting.

If the random number generator ever generates a 10+ digit number, you could have array bounds problems.  The maximum length I got was 9, which is just safe.

Generating child could/should report when it is done.

Of the changes, I suspect that close the pipe in the parent may be the key one.

Sample output (on a Unix machine):

```<code>$ pp43
attempting to send: [16807] (len 5)
Child 1: 69198; child 2: 69199
number received: 16807
attempting to send: [282475249] (len 9)
number received: 282475249
attempting to send: [162265007] (len 9)
number received: 162265007
attempting to send: [984943658] (len 9)
number received: 984943658
attempting to send: [114410893] (len 9)
number received: 114410893
attempting to send: [470211272] (len 9)
number received: 470211272
attempting to send: [101027544] (len 9)
number received: 101027544
attempting to send: [145785087] (len 9)
number received: 145785087
attempting to send: [145877792] (len 9)
number received: 145877792
attempting to send: [200723770] (len 9)
number received: 200723770
attempting to send: [823564440] (len 9)
number received: 823564440
attempting to send: [111543816] (len 9)
number received: 111543816
attempting to send: [178448449] (len 9)
number received: 178448449
attempting to send: [74243042] (len 8)
number received: 74243042
attempting to send: [114807987] (len 9)
number received: 114807987
attempting to send: [113752250] (len 9)
number received: 113752250
attempting to send: [144128232] (len 9)
number received: 144128232
attempting to send: [16531729] (len 8)
number received: 16531729
attempting to send: [823378840] (len 9)
number received: 823378840
attempting to send: [143542612] (len 9)
number received: 143542612
Child 2: EOF or ERR
PID 69198 exited with status 0x0000
PID 69199 exited with status 0x0000
$
</code>```

Body:
I'm trying to spawn two child processes connected with a pipe.
Child 1 is supposed to send a number through a pipe to child 2 and child 2 should print it. I managed to do that, but when I try to do this in a loop, with child 1 waiting 1 second each time before sending another number, it doesn't send anything.

What am I doing wrong?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <windows.h>

int main(int argc, char *argv[]) {
    int fd[2];
    pipe(fd);
    pid_t pid1 = fork();
    if (pid1) {
        pid_t pid2 = fork();
        if (pid2) { //parent
            // do stuff as parent
        } else { //child 2
            close(fd[1]);
            char stringNumberReceived[10];
            while (1) {
                read(fd[0], stringNumberReceived, sizeof (stringNumberReceived));
                printf("number received: %s\n", stringNumberReceived);
            }
        }
    } else {//child 1
        close(fd[0]);
        int num;
        char stringnumber [10];
        while (1) {
            num = rand();
            snprintf(stringnumber, 10, "%d", num);
            printf("attempting to sent: %s\n", stringnumber);
            write(fd[1], stringnumber, strlen(stringnumber) + 1);
            Sleep(1000);
        }
    }
}

Body:
Here's a mildly modified version of your code:

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

enum { MAX_COUNT = 20 };

int main(void)
{
    int fd[2];
    pipe(fd);
    pid_t pid1 = fork();
    if (pid1)
    {
        pid_t pid2 = fork();
        if (pid2)   // parent
        {
            printf("Child 1: %d; child 2: %d\n", (int)pid1, (int)pid2);
            close(fd[0]);   // Let the child detect EOF!
            close(fd[1]);   // Let the child detect EOF!
            int corpse;
            int status;
            while ((corpse = wait(&status)) > 0)
                printf("PID %d exited with status 0x%.4X\n", corpse, status);
        }
        else     // child 2
        {
            close(fd[1]);
            char stringNumberReceived[10];
            int nbytes;
            while ((nbytes = read(fd[0], stringNumberReceived, sizeof(stringNumberReceived))) > 0)
                printf("number received: %.*s\n", nbytes, stringNumberReceived);
            printf("Child 2: EOF or ERR\n");
        }
    }
    else    // child 1
    {
        close(fd[0]);
        int num;
        char stringnumber[10];
        for (int counter = 0; counter < MAX_COUNT; counter++)
        {
            num = rand();
            snprintf(stringnumber, sizeof(stringnumber), "%d", num);
            printf("attempting to send: [%s] (len %zu)\n", stringnumber, strlen(stringnumber));
            write(fd[1], stringnumber, strlen(stringnumber) + 1);
            sleep(1);
        }
    }
    return 0;
}

What changed?  Various things.  You can ignore the changes in placement of braces; that's purely cosmetic.

Parent code is implemented.

Parent reports child process IDs.

Parent closes the pipe — it is neither reading nor writing.

Parent waits for children to die, reporting statuses as they do.

Child records how many bytes it read, and ensures it prints no more than that.

It terminates the loop and reports before exiting when it gets an error or EOF (0 bytes read) on the pipe.

Other child does a fixed number of cycles (20 as shown) before exiting.

If the random number generator ever generates a 10+ digit number, you could have array bounds problems.  The maximum length I got was 9, which is just safe.

Generating child could/should report when it is done.

Of the changes, I suspect that close the pipe in the parent may be the key one.

Sample output (on a Unix machine):

$ pp43
attempting to send: [16807] (len 5)
Child 1: 69198; child 2: 69199
number received: 16807
attempting to send: [282475249] (len 9)
number received: 282475249
attempting to send: [162265007] (len 9)
number received: 162265007
attempting to send: [984943658] (len 9)
number received: 984943658
attempting to send: [114410893] (len 9)
number received: 114410893
attempting to send: [470211272] (len 9)
number received: 470211272
attempting to send: [101027544] (len 9)
number received: 101027544
attempting to send: [145785087] (len 9)
number received: 145785087
attempting to send: [145877792] (len 9)
number received: 145877792
attempting to send: [200723770] (len 9)
number received: 200723770
attempting to send: [823564440] (len 9)
number received: 823564440
attempting to send: [111543816] (len 9)
number received: 111543816
attempting to send: [178448449] (len 9)
number received: 178448449
attempting to send: [74243042] (len 8)
number received: 74243042
attempting to send: [114807987] (len 9)
number received: 114807987
attempting to send: [113752250] (len 9)
number received: 113752250
attempting to send: [144128232] (len 9)
number received: 144128232
attempting to send: [16531729] (len 8)
number received: 16531729
attempting to send: [823378840] (len 9)
number received: 823378840
attempting to send: [143542612] (len 9)
number received: 143542612
Child 2: EOF or ERR
PID 69198 exited with status 0x0000
PID 69199 exited with status 0x0000
$


问:
Android Firebase Analytics not working correcty
I want to track which button is clicked using Google Firebase Analytics.

Code I tried:

```<code>public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
  }

  public void onClick(View view) {
    int btn_id = view.getId();
    if (view.getId() == R.id.Btn1) {
        //Some content
    } else if (view.getId() == R.id.Btn2 {
        //Some content
    } else if (view.getId() == R.id.Btn3) {
        //Some content
    }
        Bundle params = new Bundle();
        params.putString(FirebaseAnalytics.Param.ITEM_ID, String.valueOf(btn_id));
        mFirebaseAnalytics.logEvent("homebtn_event", params);
  }
}
</code>```

The above code tracks clicks on buttons but does not returns btn_id or which button is clicked in Firebase Analytics data

答:
Unfortunately Firebase Analytics doesn't automatically provide parameter reporting for custom events/parameters. You have two options to understand how your button is clicked:

You can link the account to BigQuery and select the "homebtn_event" event with "homebtn_event" parameters of given value. BigQuery has free tier that should allow you to do this for free (assuming your app is not one of the major apps). This will give you a lot of flexibility to query the data.

You can use one of the predefined events + predefined parameter that has reporting in Firebase Analytics. You can use SELECT_CONTENT(ITEM_ID) for example:

Bundle bundle = new Bundle();
bundle.putString(Param.ITEM_ID, String.valueOf(btn_id));
bundle.putString(Param.CONTENT_TYPE, "button");
mFirebaseAnalytics.logEvent(Event.SELECT_CONTENT, bundle);

Body:
I want to track which button is clicked using Google Firebase Analytics.

Code I tried:

public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
  }

  public void onClick(View view) {
    int btn_id = view.getId();
    if (view.getId() == R.id.Btn1) {
        //Some content
    } else if (view.getId() == R.id.Btn2 {
        //Some content
    } else if (view.getId() == R.id.Btn3) {
        //Some content
    }
        Bundle params = new Bundle();
        params.putString(FirebaseAnalytics.Param.ITEM_ID, String.valueOf(btn_id));
        mFirebaseAnalytics.logEvent("homebtn_event", params);
  }
}

The above code tracks clicks on buttons but does not returns btn_id or which button is clicked in Firebase Analytics data


问:
Check if user input matches any of several words in a variable, and if there is a match, show image
PRESENT: WHAT WORKS
I have a search page in an application that has a predominantly voice interface and also has a text input search option (to search for images). I first worked out the voice commands and have all the images and that works fine, and now I am adding text configurations. Below is the example of what works now, I tested it using only one word as the variable:

HTML

```<code><div id="searchBoxPage"class="videoContainer">
  <form>
    <input type="text" name="search" placeholder="Search">
  </form>
  <img id="button1960s_002" class="hiddenElement" src="animsAll/Anims_002_Button_1960s.gif">

  <video    autoplay loop muted>
<source src="videos/music_saint_etienne_only_love_cropped_370x660.mp4" type="video/mp4">
Your browser does not support the video tag.
</video></div>
</code>```

JQUERY

```<code>$( "input" )
      .keyup(function() {
        var value = $( this ).val();
        var sixties = "sixties";
      if (value === sixties) {
        $("#button1960s_002").show().delay(10000).fadeOut();
      }
      })
</code>```

THE ISSUE: ADDING SEVERAL VARIATIONS OF ONE WORD AND CHECKING IF USER INPUT MATCHES ANY OF THEM Now I am working with the text  part and just realized that unlike voice, where it has to match the ONE string or string combination (as per API specs), text can have several options for one word as people sometimes misspell words.
I used the code above which worked perfectly to show me that one particular image, but now I want to add several options for the same word, as well as a possible combination of words.

in this case the word is "sixties".
and I created the single variable of

```<code>var sixties = "sixties";
</code>```

which worked. But now I want to add these two additional options below:

```<code>var sixties =["sixty", "sixtys", "sixties"];
</code>```

and that did not work with the other code I had. What is the best way to also add these words into an array (?) and if there is a match, among any of them, show the image? I know I am missing the "check if there is a match among these words" option but I can't figure out how to change what I already have.

答:
Since you're using jQuery you can use $.inArray to check
http://api.jquery.com/jQuery.inArray/</p>

```<code>var sixties =["sixty", "sixtys", "sixties"];
if($.inArray(value, sixties) !== false) {
    $("#button1960s_002").show().delay(10000).fadeOut();
}
</code>```

Body:
PRESENT: WHAT WORKS
I have a search page in an application that has a predominantly voice interface and also has a text input search option (to search for images). I first worked out the voice commands and have all the images and that works fine, and now I am adding text configurations. Below is the example of what works now, I tested it using only one word as the variable:

HTML

  <form>
    <input type="text" name="search" placeholder="Search">
  </form>

  <video    autoplay loop muted>
<source src="videos/music_saint_etienne_only_love_cropped_370x660.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>

JQUERY

$( "input" )
      .keyup(function() {
        var value = $( this ).val();
        var sixties = "sixties";
      if (value === sixties) {
        $("#button1960s_002").show().delay(10000).fadeOut();
      }
      })

THE ISSUE: ADDING SEVERAL VARIATIONS OF ONE WORD AND CHECKING IF USER INPUT MATCHES ANY OF THEM Now I am working with the text  part and just realized that unlike voice, where it has to match the ONE string or string combination (as per API specs), text can have several options for one word as people sometimes misspell words.
I used the code above which worked perfectly to show me that one particular image, but now I want to add several options for the same word, as well as a possible combination of words.

in this case the word is "sixties".
and I created the single variable of

var sixties = "sixties";

which worked. But now I want to add these two additional options below:

var sixties =["sixty", "sixtys", "sixties"];

and that did not work with the other code I had. What is the best way to also add these words into an array (?) and if there is a match, among any of them, show the image? I know I am missing the "check if there is a match among these words" option but I can't figure out how to change what I already have.

Body:
Since you're using jQuery you can use $.inArray to check
http://api.jquery.com/jQuery.inArray/

var sixties =["sixty", "sixtys", "sixties"];
if($.inArray(value, sixties) !== false) {
    $("#button1960s_002").show().delay(10000).fadeOut();
}


答:
This will return true if value is in sixties array: </p>

```<code>if (value.indexOf(sixties) > -1)) {
    $("#button1960s_002").show().delay(10000).fadeOut();
}
</code>```

Title: Check if user input matches any of several words in a variable, and if there is a match, show image

Body:
This will return true if value is in sixties array:

if (value.indexOf(sixties) > -1)) {
    $("#button1960s_002").show().delay(10000).fadeOut();
}


答: While the question has already been answered to give you an example of how to accomplish this, its important to note that password protection using javascript is very insecure. The passwords are published plain text in your source and are downloaded onto every user's computer. For any real world protection, this is not acceptable, but perhaps this is ok in your particular use case. Either way, you should at least be aware of it.</p>

Title: JavaScript password and page variation

Body: I am using this code for easy password protection of web pages but I want to edit the code so I can have two different passwords opening two different web pages. So when I enter "Password No.1" it will open "Page No.1" but if I type "Password No.2" it will open "Page No.2".


问:
UITapGestureRecogniser add target not working
i have a objc function:

```<code>@objc private func segmentedControlViewTapped(gestureRecognizer: UITapGestureRecognizer)
</code>```

I am trying to add this as a target for a gestureRecognizer but the code keeps crashing when i tap the segment control.

```<code>let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SegmentedControl.segmentedControlViewTapped(gestureRecognizer:)))
</code>```

crashes due to: unrecognized selector sent

答:
The action needs to point to a function in the target you specified.

Assuming the segmentedControlViewTapped is in your view or controller, change your code like this:

```<code>let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(segmentedControlViewTapped(gestureRecognizer:)))
</code>```

Body:
i have a objc function:

@objc private func segmentedControlViewTapped(gestureRecognizer: UITapGestureRecognizer)

I am trying to add this as a target for a gestureRecognizer but the code keeps crashing when i tap the segment control.

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SegmentedControl.segmentedControlViewTapped(gestureRecognizer:)))

crashes due to: unrecognized selector sent

Body:
The action needs to point to a function in the target you specified.

Assuming the segmentedControlViewTapped is in your view or controller, change your code like this:

let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(segmentedControlViewTapped(gestureRecognizer:)))