问:
In firebase, why don't transactions work in cloud functions like they do in the admin api?
I have existing admin api code that I've simplifile down to this for testing purposes (this works):

```<code>admin.database().ref('/dropbox').on('child_added', function (childSnap) {

  let item, itemRef = childSnap.ref;

  console.log(`Item: ${JSON.stringify(childSnap.val())} at ${childSnap.key}`);
  console.log(`Item ref: ${itemRef.toString()}`);

  itemRef.transaction(function (value) {
    console.log(`Value: ${JSON.stringify(value)}`);
    if (value) {
      item  = value;
      return null;
    }
  }).then(function (resolution) {
    console.log(`Txn resolution: ${resolution.committed ? 'committed' : 'NOT-COMMITTED'}`);
    if (resolution.committed) {
      // process item
      console.log(`Process: ${JSON.stringify(item)}`);
    } else {
      // assume that item must have been removed by someone else
    }
  }).catch(function (err) {
    console.log(`Txn error: ${JSON.stringify(err, null, 2)}`);
  });

});
</code>```

When I run:

firebase database:push /dropbox <<<'{"test":"abc123"}'

The console output is:

```<code>Item: {"test":"abc123"} at -KgTpp3FzgbLUrMNofNZ
Item ref: https://cloud-function-txn-test.firebaseio.com/dropbox/-KgTpp3FzgbLUrMNofNZ
Value: {"test":"abc123"}
Txn resolution: committed
Process: {"test":"abc123"}
</code>```

I've been trying to move my code and this example to a cloud function. I realize that .on('child_added', f) and .onWrite(f) treat existing data differently but I can't get the transaction code to work correctly. The parameter passed to my transaction function is always null.

As a cloud function (this does not work):

```<code>exports.receiveAndRemove = functions.database.ref('/dropbox/{entryId}').onWrite(function (event) {

  if (!event.data.exists()) {
    return;
  }

  let item, itemRef = event.data.adminRef;

  console.log(`Item: ${JSON.stringify(event.data.val())} at ${event.data.key}`);
  console.log(`Item ref: ${itemRef.toString()}`);

  itemRef.transaction(function (value) {
    console.log(`Value: ${JSON.stringify(value)}`);
    if (value) {
      item  = value;
      return null;
    }
  }).then(function (resolution) {
    console.log(`Txn resolution: ${resolution.committed ? 'committed' : 'NOT-COMMITTED'}`);
    if (resolution.committed) {
      // process item
      console.log(`Process: ${JSON.stringify(item)}`);
    } else {
      // bad to assume here that item must have been removed by someone else
    }
  }).catch(function (err) {
    console.log(`Txn error: ${JSON.stringify(err, null, 2)}`);
  });

});
</code>```

For some reason, the transaction never removes the item. Log output:

```<code>2017-03-30T10:51:19.387565284Z D receiveAndRemove: Function execution started
2017-03-30T10:51:19.395Z I receiveAndRemove: Item: {"test":"abc123"} at -KgTpp3FzgbLUrMNofNZ
2017-03-30T10:51:19.395Z I receiveAndRemove: Item ref: https://cloud-function-txn-test.firebaseio.com/dropbox/-KgTpp3FzgbLUrMNofNZ
2017-03-30T10:51:19.396Z I receiveAndRemove: Value: null
2017-03-30T10:51:19.396Z I receiveAndRemove: Txn resolution: NOT-COMMITTED
2017-03-30T10:51:19.418446269Z D receiveAndRemove: Function execution took 32 ms, finished with status: 'ok'
</code>```

Of course, the cloud function fails to remove the item and because the transaction didn't commit the remove, also doesn't process the item. I expect both to happen and I expect this code to work even when the node server version is running. The items should always be processed exactly once no matter how how many instances are running in the cloud and/or my server.

Is there some subtle difference in cloud functions I am missing? Is there something I'm doing with transactions incorrectly or that doesn't work with cloud functions?

Full source: https://github.com/mscalora/cloud-function-txn-test.git

答:
The problem here is that in the scenario when the transaction value is null, you return undefined, which cancels the transaction. You actually need to handle the case when the value is null since Firebase may pass that value. The reason for this dive a bit into how Firebase transactions work.

In the first example, you have a local listener on the node you are doing the transaction on. This means you have the exact value for that node stored in the local cache. In the second example, you have the value for the node, but there is no actual listener for that node locally. The value comes from Cloud Functions itself and is not stored locally. Thus, when you do the transaction, Firebase will try right away with a "guess" of the value, which is always null to start. The transaction will retry once it hears from the server that the value is not null, and the server will tell it what the new value is. Then, the transaction will retry. However, because you don't handle the null case and simply return undefined, the transaction is cancelled.

I don't think you really need a transaction for what you are trying to do though. You can get the value of item in both your code samples without doing a transaction. For example, here is how you can update your Cloud Functions example:

```<code>exports.receiveAndRemove = functions.database.ref('/dropbox/{entryId}').onWrite(function (event) {
  if (!event.data.exists()) {
    return;
  }

  let item = event.data.val();
  let itemRef = event.data.adminRef;

  console.log(`Item: ${JSON.stringify(item)} at ${event.data.key}`);
  console.log(`Item ref: ${itemRef.toString()}`);

  return itemRef.remove();
});
</code>```

Body:
I have existing admin api code that I've simplifile down to this for testing purposes (this works):

admin.database().ref('/dropbox').on('child_added', function (childSnap) {

  let item, itemRef = childSnap.ref;

  console.log(`Item: ${JSON.stringify(childSnap.val())} at ${childSnap.key}`);
  console.log(`Item ref: ${itemRef.toString()}`);

  itemRef.transaction(function (value) {
    console.log(`Value: ${JSON.stringify(value)}`);
    if (value) {
      item  = value;
      return null;
    }
  }).then(function (resolution) {
    console.log(`Txn resolution: ${resolution.committed ? 'committed' : 'NOT-COMMITTED'}`);
    if (resolution.committed) {
      // process item
      console.log(`Process: ${JSON.stringify(item)}`);
    } else {
      // assume that item must have been removed by someone else
    }
  }).catch(function (err) {
    console.log(`Txn error: ${JSON.stringify(err, null, 2)}`);
  });

});

When I run:

firebase database:push /dropbox <<<'{"test":"abc123"}'

The console output is:

Item: {"test":"abc123"} at -KgTpp3FzgbLUrMNofNZ
Item ref: https://cloud-function-txn-test.firebaseio.com/dropbox/-KgTpp3FzgbLUrMNofNZ
Value: {"test":"abc123"}
Txn resolution: committed
Process: {"test":"abc123"}

I've been trying to move my code and this example to a cloud function. I realize that .on('child_added', f) and .onWrite(f) treat existing data differently but I can't get the transaction code to work correctly. The parameter passed to my transaction function is always null.

As a cloud function (this does not work):

exports.receiveAndRemove = functions.database.ref('/dropbox/{entryId}').onWrite(function (event) {

  if (!event.data.exists()) {
    return;
  }

  let item, itemRef = event.data.adminRef;

  console.log(`Item: ${JSON.stringify(event.data.val())} at ${event.data.key}`);
  console.log(`Item ref: ${itemRef.toString()}`);

  itemRef.transaction(function (value) {
    console.log(`Value: ${JSON.stringify(value)}`);
    if (value) {
      item  = value;
      return null;
    }
  }).then(function (resolution) {
    console.log(`Txn resolution: ${resolution.committed ? 'committed' : 'NOT-COMMITTED'}`);
    if (resolution.committed) {
      // process item
      console.log(`Process: ${JSON.stringify(item)}`);
    } else {
      // bad to assume here that item must have been removed by someone else
    }
  }).catch(function (err) {
    console.log(`Txn error: ${JSON.stringify(err, null, 2)}`);
  });

});

For some reason, the transaction never removes the item. Log output:

2017-03-30T10:51:19.387565284Z D receiveAndRemove: Function execution started
2017-03-30T10:51:19.395Z I receiveAndRemove: Item: {"test":"abc123"} at -KgTpp3FzgbLUrMNofNZ
2017-03-30T10:51:19.395Z I receiveAndRemove: Item ref: https://cloud-function-txn-test.firebaseio.com/dropbox/-KgTpp3FzgbLUrMNofNZ
2017-03-30T10:51:19.396Z I receiveAndRemove: Value: null
2017-03-30T10:51:19.396Z I receiveAndRemove: Txn resolution: NOT-COMMITTED
2017-03-30T10:51:19.418446269Z D receiveAndRemove: Function execution took 32 ms, finished with status: 'ok'

Of course, the cloud function fails to remove the item and because the transaction didn't commit the remove, also doesn't process the item. I expect both to happen and I expect this code to work even when the node server version is running. The items should always be processed exactly once no matter how how many instances are running in the cloud and/or my server.

Is there some subtle difference in cloud functions I am missing? Is there something I'm doing with transactions incorrectly or that doesn't work with cloud functions?

Full source: https://github.com/mscalora/cloud-function-txn-test.git

Body:
The problem here is that in the scenario when the transaction value is null, you return undefined, which cancels the transaction. You actually need to handle the case when the value is null since Firebase may pass that value. The reason for this dive a bit into how Firebase transactions work.

In the first example, you have a local listener on the node you are doing the transaction on. This means you have the exact value for that node stored in the local cache. In the second example, you have the value for the node, but there is no actual listener for that node locally. The value comes from Cloud Functions itself and is not stored locally. Thus, when you do the transaction, Firebase will try right away with a "guess" of the value, which is always null to start. The transaction will retry once it hears from the server that the value is not null, and the server will tell it what the new value is. Then, the transaction will retry. However, because you don't handle the null case and simply return undefined, the transaction is cancelled.

I don't think you really need a transaction for what you are trying to do though. You can get the value of item in both your code samples without doing a transaction. For example, here is how you can update your Cloud Functions example:

exports.receiveAndRemove = functions.database.ref('/dropbox/{entryId}').onWrite(function (event) {
  if (!event.data.exists()) {
    return;
  }

  let item = event.data.val();
  let itemRef = event.data.adminRef;

  console.log(`Item: ${JSON.stringify(item)} at ${event.data.key}`);
  console.log(`Item ref: ${itemRef.toString()}`);

  return itemRef.remove();
});


来源: stackexchange

问:
How to redirect to another page in php using header after outputting message?
I was making an php file in which I have to add PHP Page redirection using header function after a certain condition is not true.

The problem is that before Redirection I have Outputted some message using echo because of this header function is not working and throwing warning:-

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs...\search.php:229) in C:\xampp\htdocs...\search.php on line 291

Please help me with this and if there any other alternative for this please tell except that

javscript method window.location=url;

答:
Sorry, in PHP there is none. You simply can not modify the headers after starting to send the response body.

There are 3 options

Use html meta refresh

As you mentioned use JavaScript

Move you code to a point where you are still able to manipulate the
response header

If you use modern frameworks you mostly don't have this issue. Frameworks like Symphony, Laravel, Slim and others are helping you to keep your business (controller) logic separated from your display (view) logic.

For starters I would recommend the Slim framework https://www.slimframework.com.
It's well documented and very lightweight.

ContentLicense: CC BY-SA 3.0


问:
MS Access 2010 Issue
Table1            feildes
Product{ID,Product,Quantity(in peices),Cost(per peice)}

table2

Customer{ID, Name, Type(local,sale's man)}

table 3

customer order{ID, date,customer*, product*,quntity,price}
here customer is coming from table 2 named as customer while product is coming from table1 named as products

i just want to show remaining items in order table. any can help me to make this happen?enter image description here

答:
You mean you want to know how much of each product remains after filling orders? This is calculating inventory balance - a common topic. You need a table that records receipt of product, which is apparently your Products table but I think would be better titled ProductReceived. Do an aggregate query on ProductReceived and an aggregate query on Orders then do another query that joins the two and subtracts the latter from the former. Customer table not needed for this. Products table would just be a lookup table for product info - no Quantity or Cost fields as these belong in ProductReceived. Products table should have the selling price you want to charge.

You have misspelled 'piece' in your field names.

Advise no spaces, punctuation, or special characters in field names (underscore is only exception). Better would be Qty_Pieces.

Title: MS Access 2010 Issue


问:
ruby - get command output, which is executing via ssh
I am new to ruby and I tried searching a lot but I cannot figure this out!

I need to execute this command:
I tried using Open3.popen, back-ticks but the output is not returned, it only returns for ssh command but I need the output of the hive query.

```<code>ssh -C -i key_rsa -l login_name server_name "/usr/bin/hive -i .hiverc -e \" some_query \"" > somefile.csv
</code>```

How can I get the output & errors if any for hive query and ssh both?

Thanks in advance, please let me know as early as possible

答:
Simplify by ensuring that your query outputs to STDOUT first by logging into your target server and manually running the query. Next use single quotes around the query that follows the ssh command. Finally, add the redirect when you are sure the individual pieces are working:</p>

```<code>    ssh -C -i key_rsa -l login_name server_name '/usr/bin/hive -i .hiverc -e " some_query "'
</code>```

Body:
I am new to ruby and I tried searching a lot but I cannot figure this out!

I need to execute this command:
I tried using Open3.popen, back-ticks but the output is not returned, it only returns for ssh command but I need the output of the hive query.

ssh -C -i key_rsa -l login_name server_name "/usr/bin/hive -i .hiverc -e \" some_query \"" > somefile.csv

How can I get the output & errors if any for hive query and ssh both?

Thanks in advance, please let me know as early as possible

Body:
Simplify by ensuring that your query outputs to STDOUT first by logging into your target server and manually running the query. Next use single quotes around the query that follows the ssh command. Finally, add the redirect when you are sure the individual pieces are working:

    ssh -C -i key_rsa -l login_name server_name '/usr/bin/hive -i .hiverc -e " some_query "'


问:
Grouping row by specified column from array
I have this array

```<code>   Array
(
    [0] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.4
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150400005
            [ItemName] => BIG BAG
            [OriginalPrice] => 289900.00
            [Price] => 289900.00
            [QtyBegining] => 0
            [QtyIn] => 4
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 4
            [QtyOpname] => 0
            [QtyAdjust] => -4
            [TotalAdjust] => -1159600.00
            [rak] =>
            [line] =>
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [1] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.5
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500063
            [ItemName] => BIG BAG
            [OriginalPrice] => 479900.00
            [Price] => 479900.00
            [QtyBegining] => 0
            [QtyIn] => 0
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 0
            [QtyOpname] => 1
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] => SS
            [line] => SS
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [2] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.5
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500063
            [ItemName] => BIG BAG
            [OriginalPrice] => 479900.00
            [Price] => 479900.00
            [QtyBegining] => 0
            [QtyIn] => 1
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 1
            [QtyOpname] => 0
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] =>
            [line] =>
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [3] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.6
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500081
            [ItemName] => BIG BAG
            [OriginalPrice] => 229900.00
            [Price] => 229900.00
            [QtyBegining] => 0
            [QtyIn] => 0
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 0
            [QtyOpname] => 1
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] => SS
            [line] => SS
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

)
</code>```

My array(s) comming from the query result . Then i'm trying to put it to HTML Table so i try this way.

```<code><table class="table ">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>ItemCode</th>
                            <th>ItemName</th>
                            <th>TransNo</th>
                            <th>Original Price</th>
                            <th>Price</th>
                             <th>QtyBeginning</th>
                            <th>QtyIn</th>
                            <th>QtySales</th>
                            <th>QtyMutasi</th>
                            <th>QtyStock</th>
                            <th>QtyOpname</th>
                            <th>QtyAdjust</th>
                            <th>TotalAdjust</th>
                            <th>Rak</th>
                            <th>Line</th>
                        </tr>
                    </thead>
                    <tbody> <?php $x=0; foreach ($datadetail as $data) { $x++;?>
                                 <tr>
                                    <td><?=$x;?></td>
                                    <td><?=$data->ItemCode;?></td>
                                    <td><?=$data->ItemName;?></td>
                                    <td><?=$data->StokOpnameTransNo;?></td>
                                    <td><?=$data->OriginalPrice;?></td>
                                    <td><?=$data->Price;?></td>
                                    <td><?=$data->QtyBegining;?></td>
                                    <td><?=$data->QtyIn;?></td>
                                    <td><?=$data->QtySales;?></td>
                                    <td><?=$data->QtyMutasi;?></td>
                                    <td><?=$data->QtyStock;?></td>
                                    <td><?=$data->QtyOpname;?></td>
                                    <td><?=$data->QtyAdjust;?></td>
                                    <td><?=currency($data->TotalAdjust);?></td>
                                    <td><?=$data->rak;?></td>
                                    <td><?=$data->line;?></td>
                                </tr>
                            <?php } ?>

                    </tbody>

            </table>
</code>```

the result is just a simple table like this. There is no problem when showing my table . But, I want to change the result(in HTML) to something like this

it just like grouping by ItemCode. SO after every itemcode I want to sum QtyBeginning,QtyIn,QtyOut etc.

答: recursive loop with key and values is the best way to print your array to your desired table format.</p>

Body:
I have this array

   Array
(
    [0] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.4
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150400005
            [ItemName] => BIG BAG
            [OriginalPrice] => 289900.00
            [Price] => 289900.00
            [QtyBegining] => 0
            [QtyIn] => 4
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 4
            [QtyOpname] => 0
            [QtyAdjust] => -4
            [TotalAdjust] => -1159600.00
            [rak] =>
            [line] =>
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [1] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.5
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500063
            [ItemName] => BIG BAG
            [OriginalPrice] => 479900.00
            [Price] => 479900.00
            [QtyBegining] => 0
            [QtyIn] => 0
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 0
            [QtyOpname] => 1
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] => SS
            [line] => SS
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [2] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.5
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500063
            [ItemName] => BIG BAG
            [OriginalPrice] => 479900.00
            [Price] => 479900.00
            [QtyBegining] => 0
            [QtyIn] => 1
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 1
            [QtyOpname] => 0
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] =>
            [line] =>
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

    [3] => stdClass Object
        (
            [TransactionNo] => OPM-EC-K-LFMCD2-21.6
            [StokOpnameTransNo] => OPM-EC-K-LFMCD2-21
            [ItemCode] => BBG150500081
            [ItemName] => BIG BAG
            [OriginalPrice] => 229900.00
            [Price] => 229900.00
            [QtyBegining] => 0
            [QtyIn] => 0
            [QtySales] => 0
            [QtyMutasi] => 0
            [QtyStock] => 0
            [QtyOpname] => 1
            [QtyAdjust] => 0
            [TotalAdjust] => .00
            [rak] => SS
            [line] => SS
            [TransDate] => 2017-03-31 10:46:00.000
            [CustomerCode] => K-LFMCD2
            [CreatedBy] => 1208496.
            [Remark] => re
            [Remark2] => re
            [SOTerakhir] =>
            [TglSoTerakhir] =>
        )

)

My array(s) comming from the query result . Then i'm trying to put it to HTML Table so i try this way.

                            No
                            ItemCode
                            ItemName
                            TransNo
                            Original Price
                            Price
                             QtyBeginning
                            QtyIn
                            QtySales
                            QtyMutasi
                            QtyStock
                            QtyOpname
                            QtyAdjust
                            TotalAdjust
                            Rak
                            Line

 <?php $x=0; foreach ($datadetail as $data) { $x++;?>

                                    <?=$x;?>
                                    <?=$data->ItemCode;?>
                                    <?=$data->ItemName;?>
                                    <?=$data->StokOpnameTransNo;?>
                                    <?=$data->OriginalPrice;?>
                                    <?=$data->Price;?>
                                    <?=$data->QtyBegining;?>
                                    <?=$data->QtyIn;?>
                                    <?=$data->QtySales;?>
                                    <?=$data->QtyMutasi;?>
                                    <?=$data->QtyStock;?>
                                    <?=$data->QtyOpname;?>
                                    <?=$data->QtyAdjust;?>
                                    <?=currency($data->TotalAdjust);?>
                                    <?=$data->rak;?>
                                    <?=$data->line;?>

                            <?php } ?>

the result is just a simple table like this. There is no problem when showing my table . But, I want to change the result(in HTML) to something like this

it just like grouping by ItemCode. SO after every itemcode I want to sum QtyBeginning,QtyIn,QtyOut etc.


问:
How to use Android R.java in other applications (web, for example)?
The Android Resource Management is very interesting to me. And I'm asking my self if there's a way to use it in other applications, like web, for example.

I want to do this because I find it very easy to manage and to use.

Is there a way to do that? To use an R.java Resources Management in other applications, not only in android?

答:
Since this is unanswered for too long, I'll compile the comments from @CommonsWare and @Rotwang.

My question is not very clear. Of course it's possible to use something close to Android Resource Management in other applications. But the concept is based in the language limitations too. For example, React and React native have a completely different way to manage resources because the language has its specific behavior.

Quoting @CommonsWare

Whether they are using some code-generation library to assist, I can't say, as I haven't gone looking for it. Since this code generation is performed by aapt (AFAIK), that code generation probably would be done in C/C++, as aapt is a platform-native binary. You might poke around the aapt source and see what you find.


问:
Changing child buttons with parent button
I'm trying to learn how to alter objects by referencing only the parent object. In this case I need three buttons; one that is the parent of the other two. When I click on the parent button, the text on both children should change. Trying this in jsFiddle, I have:

```<code><body>

<button class="parent" id="btn1">Parent button
  <button class="child" id="childbtn1">child 1</button>
  <button class="child" id="childbtn2">child 2</button>
</button>

</body>
</code>```

with the js:

```<code>document.getElementByClassName("parent").addEventListener('click',
function() {
    $("btn1.child").innerHTML="new text";
});
</code>```

I've looked at similar posts, but for me this requirement of having to use buttons that are related is throwing me off. If the button elements are set up correctly (which I don't know if they are), should I be getting elements by id or by class to change the children? Thanks.

答:
You can't put buttons inside of buttons.  If you open up inspect mode, you'll notice that children popped out of the parent button.  So if you were to change them to divs it would work fine.  Additionally, I converted your code to jQuery because you tagged the question as jQuery.

$(".parent").click(function () {
  $(this).find(".child").html("new text");
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
  padding:30px;
  cursor:pointer;
}</code>```

Parent button

child 1

child 2

```

Body:
I'm trying to learn how to alter objects by referencing only the parent object. In this case I need three buttons; one that is the parent of the other two. When I click on the parent button, the text on both children should change. Trying this in jsFiddle, I have:

<button class="parent" id="btn1">Parent button
  <button class="child" id="childbtn1">child 1</button>
  <button class="child" id="childbtn2">child 2</button>
</button>

with the js:

document.getElementByClassName("parent").addEventListener('click',
function() {
    $("btn1.child").innerHTML="new text";
});

I've looked at similar posts, but for me this requirement of having to use buttons that are related is throwing me off. If the button elements are set up correctly (which I don't know if they are), should I be getting elements by id or by class to change the children? Thanks.

Body:
You can't put buttons inside of buttons.  If you open up inspect mode, you'll notice that children popped out of the parent button.  So if you were to change them to divs it would work fine.  Additionally, I converted your code to jQuery because you tagged the question as jQuery.

$(".parent").click(function () {
  $(this).find(".child").html("new text");
});

div {
  padding:30px;
  cursor:pointer;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent" id="btn1">Parent button
  <div class="child" id="childbtn1">child 1</div>
  <div class="child" id="childbtn2">child 2</div>
</div>


问:
How to add column and row value from excel in list view with assets folder?
I want to retrieve one excel file data in list view with images from assets folder, is that possible ?   please help me how can i?</p>

答:
You have to consider using something called JExcelApi. I have no experience with it. The formal Java API for Microsoft Documents is Apache POI but as far as I know it was not compatible with Android and the Dalvik VM in the past. Actually JExcelApi is the proven method for reading, writing and even creating excel documents. Check out this article:

Using JExcelApi in an Android App

Here is the official API website with api documentation and simple examples for the usage:

Java Excel API - A Java API to read, write, and modify Excel spreadsheets

Good luck!


问:
asp.net webapi 2 attribute routing not working
I have visual studio 2012 installed with mvc4 using .net framework 4.5. Now I want to use webapi2 with attribute writing and i want my hlep page show all the endpoints properly.

In my solution i added a new mvc4 base emtpy project and using nuget i upgraded to mvc5 and then i have installed webapi2 packages. lastly i have installed help package for webapi2.

now when i use routeprefix I cant see any content on help page and when i try to access my webapi endpoint in browsers it throws following error.

http://expressiis.com/api/v1/

```<code>   <Error>
    <Message>
    No HTTP resource was found that matches the request URI 'http://expressiis.com/api/v1/'.
    </Message>
    <MessageDetail>
    No type was found that matches the controller named 'v1'.
    </MessageDetail>
    </Error>

namespace WebApi.Controllers
{
    [RoutePrefix("api/v1")]
    public class SubscribersController : ApiController
    {
        // GET api/<controller>
        [Route("")]
        [HttpGet]
        public IQueryable<string> Get()
        {
            return new string[] { "value1", "value2" }.AsQueryable();
        }

    }
}
</code>```

答:
In my case, VS create my controller with the name </p>

```<code>TestController1
</code>```

<p>I dont know why he put this number "one" in the end of name, but remove and will work. </p>

Body:
I have visual studio 2012 installed with mvc4 using .net framework 4.5. Now I want to use webapi2 with attribute writing and i want my hlep page show all the endpoints properly.

In my solution i added a new mvc4 base emtpy project and using nuget i upgraded to mvc5 and then i have installed webapi2 packages. lastly i have installed help package for webapi2.

now when i use routeprefix I cant see any content on help page and when i try to access my webapi endpoint in browsers it throws following error.

http://expressiis.com/api/v1/

   <Error>
    <Message>
    No HTTP resource was found that matches the request URI 'http://expressiis.com/api/v1/'.
    </Message>
    <MessageDetail>
    No type was found that matches the controller named 'v1'.
    </MessageDetail>
    </Error>

namespace WebApi.Controllers
{
    [RoutePrefix("api/v1")]
    public class SubscribersController : ApiController
    {
        // GET api/<controller>
        [Route("")]
        [HttpGet]
        public IQueryable<string> Get()
        {
            return new string[] { "value1", "value2" }.AsQueryable();
        }

    }
}

Body:
In my case, VS create my controller with the name

TestController1

I dont know why he put this number "one" in the end of name, but remove and will work.


问:
Obtain this exit status of a child process and from the parent process and print it in the parent.
and I was exploring the processes flow in c. I want to update the following program in a way that, the child terminates with an exit status (such as 10). Obtain this exit status from the parent process and print it in the parent. I have tried the following way, but the status am getting from the parent is wrong. Where i went wrong? Please help me on it guys. Thanks in advance. </p>

```<code>#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    int pid;
    int ppid;
    int status;
    pid=vfork();
    pid_t return_pid = waitpid(pid, &status, WNOHANG);
    //printf("%d\n", pid); --> value = 0

    if (pid < 0) {
        printf("\n Error ");
        exit(1);
    } else if (pid==0) {
        printf("\n Hello I am the child process\n");
        printf("\n My pid is:  %d\n", getpid());
        printf("\n My parent pid is:  %d\n", getppid());
        printf("\n My return_pid is:  %d\n", return_pid);
        printf("_______________________________________\n");
        int es = WEXITSTATUS(status);
        printf ("\n Child exit status:  %d\n", es);
        status = es;
        exit(0);
    } else {
        printf("The child has terminated!\n");
        printf("_______________________________________\n");
        printf("\n Hello I am the parent process\n");
        printf("\n My actual pid is %d\n" , getpid());
        printf("\n My parent pid is:  %d\n", getppid());
        printf("\n My return_pid is:  %d\n", return_pid);
        printf("_______________________________________\n");
        printf ("\n Child's Exit staus from parent:  %d\n", status);
        exit(1);
    }
}
</code>```

答:
This code, using fork() and not vfork(), does something close to what you're after.  You want to wait for the child to die — don't use the option that says "Don't wait for the child to die if it isn't already dead".  And it would be better to only wait in the parent.  This code also sometimes kills the child with an interrupt signal — mainly so you can see how exit statuses are coded.

```<code>#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    pid_t pid = fork();

    if (pid < 0)
    {
        perror("fork()");
        exit(1);
    }
    else if (pid == 0)
    {
        printf("Hello I am the child process\n");
        printf("My pid is:  %d\n", (int)getpid());
        printf("My parent pid is:  %d\n", (int)getppid());
        int status = getpid() % 256;
        printf("I am about to exit with status 0x%.2X (%d)\n", status, status);
        printf("_______________________________________\n");
        exit(status);
    }
    else
    {
        int status;
        if (pid % 10 == 0)
            kill(pid, SIGINT);
        pid_t return_pid = waitpid(pid, &status, 0);
        printf("The child has terminated!\n");
        printf("Hello I am the parent process\n");
        printf("My actual pid is %d\n", (int)getpid());
        printf("My parent pid is:  %d\n", (int)getppid());
        printf("My return_pid is:  %d\n", (int)return_pid);
        printf("Child's raw exit status:  0x%.4X (%d)\n", status, status);
        if (WIFEXITED(status))
            printf("Child's exit status: 0x%.2X (%d)\n",
                   WEXITSTATUS(status), WEXITSTATUS(status));
        if (WIFSIGNALED(status))
            printf("Child exited because of signal %d\n", WTERMSIG(status));
        printf("_______________________________________\n");
    }
    return 0;
}
</code>```

Sample outputs:

Normal run:

```<code>Hello I am the child process
My pid is:  40377
My parent pid is:  40376
I am about to exit with status 0xB9 (185)
_______________________________________
The child has terminated!
Hello I am the parent process
My actual pid is 40376
My parent pid is:  847
My return_pid is:  40377
Child's raw exit status:  0xB900 (47360)
Child's exit status: 0xB9 (185)
_______________________________________
</code>```

Signal run:

```<code>The child has terminated!
Hello I am the parent process
My actual pid is 40379
My parent pid is:  847
My return_pid is:  40380
Child's raw exit status:  0x0002 (2)
Child exited because of signal 2
_______________________________________
</code>```

Body:
and I was exploring the processes flow in c. I want to update the following program in a way that, the child terminates with an exit status (such as 10). Obtain this exit status from the parent process and print it in the parent. I have tried the following way, but the status am getting from the parent is wrong. Where i went wrong? Please help me on it guys. Thanks in advance.

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    int pid;
    int ppid;
    int status;
    pid=vfork();
    pid_t return_pid = waitpid(pid, &status, WNOHANG);
    //printf("%d\n", pid); --> value = 0

    if (pid < 0) {
        printf("\n Error ");
        exit(1);
    } else if (pid==0) {
        printf("\n Hello I am the child process\n");
        printf("\n My pid is:  %d\n", getpid());
        printf("\n My parent pid is:  %d\n", getppid());
        printf("\n My return_pid is:  %d\n", return_pid);
        printf("_______________________________________\n");
        int es = WEXITSTATUS(status);
        printf ("\n Child exit status:  %d\n", es);
        status = es;
        exit(0);
    } else {
        printf("The child has terminated!\n");
        printf("_______________________________________\n");
        printf("\n Hello I am the parent process\n");
        printf("\n My actual pid is %d\n" , getpid());
        printf("\n My parent pid is:  %d\n", getppid());
        printf("\n My return_pid is:  %d\n", return_pid);
        printf("_______________________________________\n");
        printf ("\n Child's Exit staus from parent:  %d\n", status);
        exit(1);
    }
}

Body:
This code, using fork() and not vfork(), does something close to what you're after.  You want to wait for the child to die — don't use the option that says "Don't wait for the child to die if it isn't already dead".  And it would be better to only wait in the parent.  This code also sometimes kills the child with an interrupt signal — mainly so you can see how exit statuses are coded.

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    pid_t pid = fork();

    if (pid < 0)
    {
        perror("fork()");
        exit(1);
    }
    else if (pid == 0)
    {
        printf("Hello I am the child process\n");
        printf("My pid is:  %d\n", (int)getpid());
        printf("My parent pid is:  %d\n", (int)getppid());
        int status = getpid() % 256;
        printf("I am about to exit with status 0x%.2X (%d)\n", status, status);
        printf("_______________________________________\n");
        exit(status);
    }
    else
    {
        int status;
        if (pid % 10 == 0)
            kill(pid, SIGINT);
        pid_t return_pid = waitpid(pid, &status, 0);
        printf("The child has terminated!\n");
        printf("Hello I am the parent process\n");
        printf("My actual pid is %d\n", (int)getpid());
        printf("My parent pid is:  %d\n", (int)getppid());
        printf("My return_pid is:  %d\n", (int)return_pid);
        printf("Child's raw exit status:  0x%.4X (%d)\n", status, status);
        if (WIFEXITED(status))
            printf("Child's exit status: 0x%.2X (%d)\n",
                   WEXITSTATUS(status), WEXITSTATUS(status));
        if (WIFSIGNALED(status))
            printf("Child exited because of signal %d\n", WTERMSIG(status));
        printf("_______________________________________\n");
    }
    return 0;
}

Sample outputs:

Normal run:

Hello I am the child process
My pid is:  40377
My parent pid is:  40376
I am about to exit with status 0xB9 (185)
_______________________________________
The child has terminated!
Hello I am the parent process
My actual pid is 40376
My parent pid is:  847
My return_pid is:  40377
Child's raw exit status:  0xB900 (47360)
Child's exit status: 0xB9 (185)
_______________________________________

Signal run:

The child has terminated!
Hello I am the parent process
My actual pid is 40379
My parent pid is:  847
My return_pid is:  40380
Child's raw exit status:  0x0002 (2)
Child exited because of signal 2
_______________________________________


问:
Y-axis starts from '32' in main window
First of all, here is first question of mine, it marked as duplicate(whereas it was not): https://stackoverflow.com/questions/43167650/setting-ovals-center-as-mouse-coordinates

I spent my last 9-10 hours to fix it.

I will not copy the whole question(I already shared link), but I will tell you more detail.

My window is 512x512.
When I click upper-left of window, x-axis was around 1-2, y-axis was around 30-35. So, checked low side of window, it was around 510 for y-axis, it's normal.

Here's what I've made:

```<code>public class Quadtree implements MouseListener{

    int x=256,y=256;
    JFrame frame=new JFrame();
    JPanel thePanel = new JPanel(){
        @Override
         protected void paintComponent(Graphics g)
           {
              super.paintComponent(g);
              drawCenteredCircle((Graphics2D) g,x,y,30);

    }

};

public void drawCenteredCircle(Graphics2D g, int x, int y, int r) {
      x = x-(r/2);
      y = y-(r/2);
      g.fillOval(x,y,r,r);
    }
public static void main(String[] args) {
    new Quadtree();
}
    public void mouseClicked(MouseEvent e) {
    //  Point p=e.getPoint();
        x=e.getX();
        System.out.println(x);
        y=e.getY();
        System.out.println(y);
        thePanel.repaint();
}
    public Quadtree(){

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(thePanel);
         frame.setLocationRelativeTo(null);
         frame.setSize(512,512);

        frame.addMouseListener(this);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setTitle("Quadtree");

    }
}
</code>```

But somehow, in this code which is below, I set oval's y-axis as 0, but it works fine.

```<code>public void drawCenteredCircle(Graphics2D g, int x, int y, int r) {
      x = x-(r/2);
      y = y-(r/2);
      g.fillOval(x,0,r,r);
    }
</code>```

Output is:

But when I make mouse click(explained in first sample), circle appears under the mouse.

Any idea to fix it?

答:
Y-axis starts from '32' in main window

```<code>frame.addMouseListener(this);
</code>```

The frame has a titlebar and border. Don't add the MouseListener to the frame.

Instead add the MouseListener to the panel. Then the mouse point will be relative to the panel, not the frame.

Title: Y-axis starts from '32' in main window

Body:
First of all, here is first question of mine, it marked as duplicate(whereas it was not): https://stackoverflow.com/questions/43167650/setting-ovals-center-as-mouse-coordinates

I spent my last 9-10 hours to fix it.

I will not copy the whole question(I already shared link), but I will tell you more detail.

My window is 512x512.
When I click upper-left of window, x-axis was around 1-2, y-axis was around 30-35. So, checked low side of window, it was around 510 for y-axis, it's normal.

Here's what I've made:

public class Quadtree implements MouseListener{

    int x=256,y=256;
    JFrame frame=new JFrame();
    JPanel thePanel = new JPanel(){
        @Override
         protected void paintComponent(Graphics g)
           {
              super.paintComponent(g);
              drawCenteredCircle((Graphics2D) g,x,y,30);

    }

};

public void drawCenteredCircle(Graphics2D g, int x, int y, int r) {
      x = x-(r/2);
      y = y-(r/2);
      g.fillOval(x,y,r,r);
    }
public static void main(String[] args) {
    new Quadtree();
}
    public void mouseClicked(MouseEvent e) {
    //  Point p=e.getPoint();
        x=e.getX();
        System.out.println(x);
        y=e.getY();
        System.out.println(y);
        thePanel.repaint();
}
    public Quadtree(){

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(thePanel);
         frame.setLocationRelativeTo(null);
         frame.setSize(512,512);

        frame.addMouseListener(this);
        frame.setVisible(true);
        frame.setResizable(false);
        frame.setTitle("Quadtree");

    }
}

But somehow, in this code which is below, I set oval's y-axis as 0, but it works fine.

public void drawCenteredCircle(Graphics2D g, int x, int y, int r) {
      x = x-(r/2);
      y = y-(r/2);
      g.fillOval(x,0,r,r);
    }

Output is:

But when I make mouse click(explained in first sample), circle appears under the mouse.

Any idea to fix it?

Body:
Y-axis starts from '32' in main window

frame.addMouseListener(this);

The frame has a titlebar and border. Don't add the MouseListener to the frame.

Instead add the MouseListener to the panel. Then the mouse point will be relative to the panel, not the frame.


问:
using spark with aws cluster
I setup a cluster successfully following the instruction here. Just wondering could I invoke Spark via the API with this type of cluster? Where can I find the Spark endpoint(s) detail(s) please? If the aforementioned tutorial is a dead-end, could anyone point me in the right direction please? </p>

<p>My ultimate POC aim is to add 2 columns in a flat file (e.g. csv) in some S3 bucket and compare the resulting values with a third column via spark (this is not a homework (-:) - ideally using Mobius as I am [former] .net dev).  </p>

答:
This reference should provide you the information you need. Here is a snippet:

"Go into the ec2 directory in the release of Apache Spark you downloaded.
Run ./spark-ec2 -k <keypair> -i <key-file> -s <num-slaves> launch <cluster-name>, where <keypair> is the name of your EC2 key pair (that you gave it when you created it), <key-file> is the private key file for your key pair, <num-slaves> is the number of slave nodes to launch (try 1 at first), and <cluster-name> is the name to give to your cluster.

For example:

```<code>export AWS_SECRET_ACCESS_KEY=AaBbCcDdEeFGgHhIiJjKkLlMmNnOoPpQqRrSsTtU
export AWS_ACCESS_KEY_ID=ABCDEFG1234567890123

./spark-ec2 --key-pair=awskey --identity-file=awskey.pem --region=us-west-1 --zone=us-west-1a launch my-spark-cluster
</code>```

After everything launches, check that the cluster scheduler is up and sees all the slaves by going to its web UI, which will be printed at the end of the script (typically http://master-hostname:8080)."

Title: using spark with aws cluster

Body:
I setup a cluster successfully following the instruction here. Just wondering could I invoke Spark via the API with this type of cluster? Where can I find the Spark endpoint(s) detail(s) please? If the aforementioned tutorial is a dead-end, could anyone point me in the right direction please?

My ultimate POC aim is to add 2 columns in a flat file (e.g. csv) in some S3 bucket and compare the resulting values with a third column via spark (this is not a homework (-:) - ideally using Mobius as I am [former] .net dev).

Body:
This reference should provide you the information you need. Here is a snippet:

"Go into the ec2 directory in the release of Apache Spark you downloaded.
Run ./spark-ec2 -k <keypair> -i <key-file> -s <num-slaves> launch <cluster-name>, where <keypair> is the name of your EC2 key pair (that you gave it when you created it), <key-file> is the private key file for your key pair, <num-slaves> is the number of slave nodes to launch (try 1 at first), and <cluster-name> is the name to give to your cluster.

For example:

export AWS_SECRET_ACCESS_KEY=AaBbCcDdEeFGgHhIiJjKkLlMmNnOoPpQqRrSsTtU
export AWS_ACCESS_KEY_ID=ABCDEFG1234567890123

./spark-ec2 --key-pair=awskey --identity-file=awskey.pem --region=us-west-1 --zone=us-west-1a launch my-spark-cluster

After everything launches, check that the cluster scheduler is up and sees all the slaves by going to its web UI, which will be printed at the end of the script (typically http://master-hostname:8080)."


问:
Using a POST request inside a GET request's call back (Closures)
I will demonstrate my problem with this simplified code:

```<code>app.get('/test', (req, res) => {
    let x = req.query.someVar;
    app.post('/test', (req, res) => {
        console.log(x);
    });
    res.send(`Hello ${req.query.someVar}`);
});
</code>```

The first time this code runs, the POST callback function saves a reference to x which is whatever I pass as query parameters. if I change the query parameters, send another GET request it will be updated in the server's response i.e.res.send(Hello ${req.query.someVar}); but a POST request will still log the original x value to the console.

Why is it behaving this way? I have tried many things like passing by objects and through other functions, etc..

I am familiar with how closures work, but obviously not entirely as this is most definitely a problem with the POST call back preserving the value of the query parameters and not updating them.

Thanks.

答:
I'm not sure what you are trying to do.  No one defines a POST inside of a GET, they do that at the root level, unless you want the GET request to change the behavior of your server.  app.post means 'add a new route to handle a POST'. Perhaps you wanted to actually send an HTTP request from the GET handler?

If you want the behavior to change maybe just handle the POST at the root level and set a global flag in the GET handler to indicate that POST should do something different with subsequent requests.

Body:
I will demonstrate my problem with this simplified code:

app.get('/test', (req, res) => {
    let x = req.query.someVar;
    app.post('/test', (req, res) => {
        console.log(x);
    });
    res.send(`Hello ${req.query.someVar}`);
});

The first time this code runs, the POST callback function saves a reference to x which is whatever I pass as query parameters. if I change the query parameters, send another GET request it will be updated in the server's response i.e.res.send(Hello ${req.query.someVar}); but a POST request will still log the original x value to the console.

Why is it behaving this way? I have tried many things like passing by objects and through other functions, etc..

I am familiar with how closures work, but obviously not entirely as this is most definitely a problem with the POST call back preserving the value of the query parameters and not updating them.

Thanks.


问:
How to pass a single variable from one PHP page to external Javascript function
I am very new to all this and have spent the last few hours looking at multiple sections of code on various pages.  I am trying to pass a single variable from a PHP page to a javascript function page.  The PHP variable will be filled from a database entry. On the javascript function page, I am going to use the variable in an if statement to decide what to do.
Below is the section of code I have in the PHP file.

```<code>if($UserName == $username && $UserPass == $password){
    $_SESSION['useris'] = $UserID;
    $_SESSION['access_level'] = $Authlevel;
    echo json_encode($Authlevel);
    header('Location:../HTML/AdminModal.html'); //removed for testing of the auth level
}
</code>```

I do not think that I have actually sent the data anywhere as yet.

Then in the javascript file, I am totally lost as to how to get the information I have passed.

I know there is a lot of big examples of various data being passed back and forth but I am struggling to understand or work out how to adapt to my needs.

Thanks

答:
Another option is to echo the variable directly into your Javascript function, this assumes the variable is available at the time.  Something like:</p>

```<code>function someFunction()
{
 if(<?php echo variableName;?> == value)
}
</code>```

Body:
I am very new to all this and have spent the last few hours looking at multiple sections of code on various pages.  I am trying to pass a single variable from a PHP page to a javascript function page.  The PHP variable will be filled from a database entry. On the javascript function page, I am going to use the variable in an if statement to decide what to do.
Below is the section of code I have in the PHP file.

if($UserName == $username && $UserPass == $password){
    $_SESSION['useris'] = $UserID;
    $_SESSION['access_level'] = $Authlevel;
    echo json_encode($Authlevel);
    header('Location:../HTML/AdminModal.html'); //removed for testing of the auth level
}

I do not think that I have actually sent the data anywhere as yet.

Then in the javascript file, I am totally lost as to how to get the information I have passed.

I know there is a lot of big examples of various data being passed back and forth but I am struggling to understand or work out how to adapt to my needs.

Thanks

Body:
Another option is to echo the variable directly into your Javascript function, this assumes the variable is available at the time.  Something like:

function someFunction()
{
 if(<?php echo variableName;?> == value)
}


问:
Connecting two server in socket
I am a newbie in socket programming but i have a trouble that i have two server started on my localhost on port 3500 and 5000.Now i want thatmy client fist connect to the port 3500 perform some operation and then disconnect from 3500 while server will be running only client wil disconnect from 3500 and the it will connect to port 5000 and agian perform some operations.

I am using the below code to do this but getting error:-

```<code>import socket

s=socket.socket()
s.connect(('127.0.0.1',3500))
print("connectd to 3500")
print("hello friends")
s.close()
print("disconnect from 3500")
s.connect(('127.0.0.1',5000))
print("connected to 5000")
s.close()
</code>```

But it is not able to connect to the second connection i.e port 5000.It gets connected to port 3500 successfully but while connecting to 5000 it throws an error.
Please any one to short out my mistake

Error:-

```<code>File "C:\Users\Lal rishav\Desktop\HubPort\test.py", line 9, in <module>
s.connect(('127.0.0.1',5000))
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
File "C:\Python27\lib\socket.py", line 174, in _dummy
raise error(EBADF, 'Bad file descriptor')
</code>```

答:
You cannot do any operations on a closed socket, create a new one instead.

```<code>s.close()
# the socket is closed, you can't use it anymore!

# get another one:
s2 = socket.socket()
s2.connect(('127.0.0.1',5000))
s2.close()
# now s2 is closed, you can't use it anymore!
</code>```

Title: Connecting two server in socket

Body:
I am a newbie in socket programming but i have a trouble that i have two server started on my localhost on port 3500 and 5000.Now i want thatmy client fist connect to the port 3500 perform some operation and then disconnect from 3500 while server will be running only client wil disconnect from 3500 and the it will connect to port 5000 and agian perform some operations.

I am using the below code to do this but getting error:-

import socket

s=socket.socket()
s.connect(('127.0.0.1',3500))
print("connectd to 3500")
print("hello friends")
s.close()
print("disconnect from 3500")
s.connect(('127.0.0.1',5000))
print("connected to 5000")
s.close()

But it is not able to connect to the second connection i.e port 5000.It gets connected to port 3500 successfully but while connecting to 5000 it throws an error.
Please any one to short out my mistake

Error:-

File "C:\Users\Lal rishav\Desktop\HubPort\test.py", line 9, in <module>
s.connect(('127.0.0.1',5000))
File "C:\Python27\lib\socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
File "C:\Python27\lib\socket.py", line 174, in _dummy
raise error(EBADF, 'Bad file descriptor')

Body:
You cannot do any operations on a closed socket, create a new one instead.

s.close()
# the socket is closed, you can't use it anymore!

# get another one:
s2 = socket.socket()
s2.connect(('127.0.0.1',5000))
s2.close()
# now s2 is closed, you can't use it anymore!


问:
If-statement with changing url
What is wrong with this function? The first if-statement does work. But the else-statement doesn't work.

```<code>function func() {
    if (document.getElementById("pic2").src = "pause.png") {
        document.getElementById("pic2").src = "play.png";
    } else {
        document.getElementById("pic2").src == "pause.png";
    }
}
</code>```

HTML:

```<code><div id="all" onclick="func()" onmouseover="func3()">
            <div id="background" onclick="func()" onmouseout="func2()"></div>
            <div id="pic">
                <img id="pic2" src="pause.png">
            </div>
            <video>
                <source src="test.mp4" type="video/mp4">
            </video>
        </div>
</code>```

答:
Try this one :

```<code>    function func() {

        var image = document.getElementById("pic2");// more efficient way

        if (image.src  == "pause.png") { // double equal sign here

            image.src = "play.png"; // equal sign here
        } else {
            image.src = "pause.png";// equal sign here
        }
    }
</code>```

Good Luck

Title: If-statement with changing url

Body:
What is wrong with this function? The first if-statement does work. But the else-statement doesn't work.

function func() {
    if (document.getElementById("pic2").src = "pause.png") {
        document.getElementById("pic2").src = "play.png";
    } else {
        document.getElementById("pic2").src == "pause.png";
    }
}

HTML:

            <video>
                <source src="test.mp4" type="video/mp4">
            </video>

Body:
Try this one :

    function func() {

        var image = document.getElementById("pic2");// more efficient way

        if (image.src  == "pause.png") { // double equal sign here

            image.src = "play.png"; // equal sign here
        } else {
            image.src = "pause.png";// equal sign here
        }
    }

Good Luck


问:
Execute a for loop in parallel instead of sequential order when underlying method returns void
I have a class in which my add method is being called by multiple threads to populate clientidToTimestampHolder LinkedBlockingQueue. And then in the same below class, I start a background thread which runs every 30 milliseconds and calls a processData() method which drains clientidToTimestampHolder to List of Map and then I iterate that List to send data to different service by calling appropriate method.

I can get same userid many times with different timestamp so that is why I am using LinkedBlockingQueue with map.

```<code>public class Handler {
  private final ScheduledExecutorService executorService = Executors
      .newSingleThreadScheduledExecutor();
  private final LinkedBlockingQueue<Map.Entry<String, Long>> clientidToTimestampHolder =
      new LinkedBlockingQueue<>();

  private static class Holder {
    private static final Handler INSTANCE = new Handler();
  }

  public static Handler getInstance() {
    return Holder.INSTANCE;
  }

  private Handler() {
    executorService.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        processData();
      }
    }, 0, 30, TimeUnit.MILLISECONDS);
  }

  // called by multiple threads to populate clientidToTimestampHolder map
  public void add(final String clientid, final Long timestamp) {
    clientidToTimestampHolder.offer(Maps.immutableEntry(clientid, timestamp));
  }

  // called by single background thread every 30 milliseconds
  public void processData() {
    final List<Map.Entry<String, Long>> entries = new ArrayList<>();
    clientidToTimestampHolder.drainTo(entries);
    for (Map.Entry<String, Long> entry : entries) {
      String clientid = entry.getKey();
      long timestamp = entry.getValue();
      boolean isUpdated = isUpdatedClient(clientid, timestamp);
      if (!isUpdated) {
        updateClient(String.valueOf(clientid));
      }
    }
  }
}
</code>```

Is my above code thread safe and there is no race condition? Since add method will be called from multiple threads and then I have a single background thread which runs every 30 milliseconds to calls processData() method which extracts data from clientidToTimestampHolder LinkedBlockingQueue.

Because right now it looks like under heavy load, my processData() method might be missing few entries which got added through add method. I added few logs in my add method which printed out the clientid but somehow that same clientid didn't got printed out in the logs I added in isUpdatedClient method so making it suspicious to me somehow.

I am working with Java 7.

答:
submit(Runnable) would work the same way as  submit(Callable) you use now.
There are also aspects which could kill all advantages of parallel execution.

First, you use newCachedThreadPool. This means, that when all pool threads are busy, a new pool thread is created. Thread creation is an expensive operation, and consumes a lot of memory. You should restrict the number of threads in the pool. If your tasks are purely computational, use number of available processors. If tasks access a database, use max number of simultaneous connections the database can handle.

Second, if your tasks (which include isUpdatedClient() and updateClient) are too small, then overhead of task creation and submission can be too high. In this case I'd create tasks which contain several entries, and process them in a loop.

Body:
I have a class in which my add method is being called by multiple threads to populate clientidToTimestampHolder LinkedBlockingQueue. And then in the same below class, I start a background thread which runs every 30 milliseconds and calls a processData() method which drains clientidToTimestampHolder to List of Map and then I iterate that List to send data to different service by calling appropriate method.

I can get same userid many times with different timestamp so that is why I am using LinkedBlockingQueue with map.

public class Handler {
  private final ScheduledExecutorService executorService = Executors
      .newSingleThreadScheduledExecutor();
  private final LinkedBlockingQueue<Map.Entry<String, Long>> clientidToTimestampHolder =
      new LinkedBlockingQueue<>();

  private static class Holder {
    private static final Handler INSTANCE = new Handler();
  }

  public static Handler getInstance() {
    return Holder.INSTANCE;
  }

  private Handler() {
    executorService.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        processData();
      }
    }, 0, 30, TimeUnit.MILLISECONDS);
  }

  // called by multiple threads to populate clientidToTimestampHolder map
  public void add(final String clientid, final Long timestamp) {
    clientidToTimestampHolder.offer(Maps.immutableEntry(clientid, timestamp));
  }

  // called by single background thread every 30 milliseconds
  public void processData() {
    final List<Map.Entry<String, Long>> entries = new ArrayList<>();
    clientidToTimestampHolder.drainTo(entries);
    for (Map.Entry<String, Long> entry : entries) {
      String clientid = entry.getKey();
      long timestamp = entry.getValue();
      boolean isUpdated = isUpdatedClient(clientid, timestamp);
      if (!isUpdated) {
        updateClient(String.valueOf(clientid));
      }
    }
  }
}

Is my above code thread safe and there is no race condition? Since add method will be called from multiple threads and then I have a single background thread which runs every 30 milliseconds to calls processData() method which extracts data from clientidToTimestampHolder LinkedBlockingQueue.

Because right now it looks like under heavy load, my processData() method might be missing few entries which got added through add method. I added few logs in my add method which printed out the clientid but somehow that same clientid didn't got printed out in the logs I added in isUpdatedClient method so making it suspicious to me somehow.

I am working with Java 7.


问:
Confusion about the text file encoding and how to transform between different encoding method?
I had a text file f.txt which encoded as UTF-8 as shown below:

```<code>chengs-MBP:test cheng$ cat f.txt
Wіnd
like
chengs-MBP:test cheng$ FILE -I f.txt
f.txt: text/plain; charset=utf-8
</code>```

However, this two words in this file Wind and like are diiferent, as the like can be find by grep command while Wind cannot, it confused me:

```<code>chengs-MBP:test cheng$ cat f.txt | grep like
like
chengs-MBP:test cheng$ cat f.txt | grep Wind
chengs-MBP:test cheng$
</code>```

And I want to transform this file to us-ascii by iconv command, but I failed:

```<code>chengs-MBP:test cheng$ iconv -f UTF-8 -t US-ASCII f.txt > new.txt
conv: f.txt:1:0: cannot convert
</code>```

My goal is to transform this file to a format which all of the words inside this file could be find by grep or sed... that's all.

答:
In my examples I will use 'i' in word 'Wind' is CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I in hex d196.

For finding out symbol hex representation you can use xxd or hexdump:

```<code>$ xxd -g 1 f.txt
00000000: 57 d1 96 6e 64 0a 6c 69 6b 65 0a                 W..nd.like.

$ hexdump -C f.txt
00000000  57 d1 96 6e 64 0a 6c 69  6b 65 0a                 |W..nd.like.|
</code>```

As you can see, on the right side, in ASCII section UTF symbols replaced with dots.

Also you can use Unicode Utitilies.

```<code>$ uniname f.txt
character  byte       UTF-32   encoded as     glyph   name
        0          0  000057   57             W      LATIN CAPITAL LETTER W
        1          1  000456   D1 96          і      CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I
        2          3  00006E   6E             n      LATIN SMALL LETTER N
        3          4  000064   64             d      LATIN SMALL LETTER D
        4          5  00000A   0A                     LINE FEED (LF)
        5          6  00006C   6C             l      LATIN SMALL LETTER L
        6          7  000069   69             i      LATIN SMALL LETTER I
        7          8  00006B   6B             k      LATIN SMALL LETTER K
        8          9  000065   65             e      LATIN SMALL LETTER E
        9         10  00000A   0A                     LINE FEED (LF)
</code>```

After you find out what symbols in your file are not ASCII, you can replace them in file to ASCII equivalent.

```<code>$ sed -i 's/\xd1\x96/i/g' f.txt
</code>```

Body:
I had a text file f.txt which encoded as UTF-8 as shown below:

chengs-MBP:test cheng$ cat f.txt
Wіnd
like
chengs-MBP:test cheng$ FILE -I f.txt
f.txt: text/plain; charset=utf-8

However, this two words in this file Wind and like are diiferent, as the like can be find by grep command while Wind cannot, it confused me:

chengs-MBP:test cheng$ cat f.txt | grep like
like
chengs-MBP:test cheng$ cat f.txt | grep Wind
chengs-MBP:test cheng$

And I want to transform this file to us-ascii by iconv command, but I failed:

chengs-MBP:test cheng$ iconv -f UTF-8 -t US-ASCII f.txt > new.txt
conv: f.txt:1:0: cannot convert

My goal is to transform this file to a format which all of the words inside this file could be find by grep or sed... that's all.

Body:
In my examples I will use 'i' in word 'Wind' is CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I in hex d196.

For finding out symbol hex representation you can use xxd or hexdump:

$ xxd -g 1 f.txt
00000000: 57 d1 96 6e 64 0a 6c 69 6b 65 0a                 W..nd.like.

$ hexdump -C f.txt
00000000  57 d1 96 6e 64 0a 6c 69  6b 65 0a                 |W..nd.like.|

As you can see, on the right side, in ASCII section UTF symbols replaced with dots.

Also you can use Unicode Utitilies.

$ uniname f.txt
character  byte       UTF-32   encoded as     glyph   name
        0          0  000057   57             W      LATIN CAPITAL LETTER W
        1          1  000456   D1 96          і      CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I
        2          3  00006E   6E             n      LATIN SMALL LETTER N
        3          4  000064   64             d      LATIN SMALL LETTER D
        4          5  00000A   0A                     LINE FEED (LF)
        5          6  00006C   6C             l      LATIN SMALL LETTER L
        6          7  000069   69             i      LATIN SMALL LETTER I
        7          8  00006B   6B             k      LATIN SMALL LETTER K
        8          9  000065   65             e      LATIN SMALL LETTER E
        9         10  00000A   0A                     LINE FEED (LF)

After you find out what symbols in your file are not ASCII, you can replace them in file to ASCII equivalent.

$ sed -i 's/\xd1\x96/i/g' f.txt


问:
selecting unique row from a table- ORACLE
I have a table employee that has employee’s benefit data.
I have a field in the table called isenrolled if field is 1 that means employee has enrolled for benefit and if field is 0 that means not enrolled.
My problem is i have multiple recs of a employee, that means Scott has two entries with isenrolled =1 and isenrolled =0.
I want to select only one rec of SCOTT where his isenrolled =1 and reject the one where isenrolled =0, that way i will get only unique recs for employees who has enrolled and who has not enrolled. How do i select those employees? I tried the qry below and it doesn't work</p>

```<code>select * FROM  employee e
WHERE e.empid not IN( SELECT empid FROM employee  e2
WHERE e2.isenrolled =1)
</code>```

答:
select unique(e.empid) from employee e where e2.isenrolled =1

this will give you unique list of employees who are enrolled. Is that what you want to get?

ContentLicense: CC BY-SA 2.5

Body:
I have a table employee that has employee’s benefit data.
I have a field in the table called isenrolled if field is 1 that means employee has enrolled for benefit and if field is 0 that means not enrolled.
My problem is i have multiple recs of a employee, that means Scott has two entries with isenrolled =1 and isenrolled =0.
I want to select only one rec of SCOTT where his isenrolled =1 and reject the one where isenrolled =0, that way i will get only unique recs for employees who has enrolled and who has not enrolled. How do i select those employees? I tried the qry below and it doesn't work

select * FROM  employee e
WHERE e.empid not IN( SELECT empid FROM employee  e2
WHERE e2.isenrolled =1)


问:
Rails error on starting new server: invalid timezone
I have a new install of Ruby 2.4.1 and Rails 5.0.2 on Linux. After creating a new Rails project, I get the following errors after running "rails server":

```<code>/home/___/.rvm/gems/ruby-2.4.1/gems/activesupport-5.0.2/lib/active_support/core_ext/time/zones.rb:98:in `rescue in find_zone!': Invalid Timezone: UTC (ArgumentError)
        from /home/___/.rvm/gems/ruby-2.4.1/gems/activesupport-5.0.2/lib/active_support/core_ext/time/zones.rb:81:in `find_zone!'
        from /home/___/.rvm/gems/ruby-2.4.1/gems/activesupport-5.0.2/lib/active_support/railtie.rb:25:in `block in <class:Railtie>'
        from /home/___/.rvm/gems/ruby-2.4.1/gems/railties-5.0.2/lib/rails/initializable.rb:30:in `instance_exec'
        from /home/___/.rvm/gems/ruby-2.4.1/gems/railties-5.0.2/lib/rails/initializable.rb:30:in `run'
        from /home/___/.rvm/gems/ruby-2.4.1/gems/railties-5.0.2/lib/rails/initializable.rb:55:in `block in run_initializers'
        from /home/___/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:228:in `block in tsort_each'
...
</code>```

This looks similar to a problem that some Windows users had a while back, but I tried the fix suggested (adding "require 'tzinfo'" to environment.rb), and still have the same problem.

答:
Check in application.rb that the command: config.time_zone is being run. If it is not, try adding the following line:

config.time_zone = "Eastern Time (US & Canada)" (in application.rb'.)

Let me know if that solves it!

Body:
I have a new install of Ruby 2.4.1 and Rails 5.0.2 on Linux. After creating a new Rails project, I get the following errors after running "rails server":

/home/___/.rvm/gems/ruby-2.4.1/gems/activesupport-5.0.2/lib/active_support/core_ext/time/zones.rb:98:in `rescue in find_zone!': Invalid Timezone: UTC (ArgumentError)
        from /home/___/.rvm/gems/ruby-2.4.1/gems/activesupport-5.0.2/lib/active_support/core_ext/time/zones.rb:81:in `find_zone!'
        from /home/___/.rvm/gems/ruby-2.4.1/gems/activesupport-5.0.2/lib/active_support/railtie.rb:25:in `block in <class:Railtie>'
        from /home/___/.rvm/gems/ruby-2.4.1/gems/railties-5.0.2/lib/rails/initializable.rb:30:in `instance_exec'
        from /home/___/.rvm/gems/ruby-2.4.1/gems/railties-5.0.2/lib/rails/initializable.rb:30:in `run'
        from /home/___/.rvm/gems/ruby-2.4.1/gems/railties-5.0.2/lib/rails/initializable.rb:55:in `block in run_initializers'
        from /home/___/.rvm/rubies/ruby-2.4.1/lib/ruby/2.4.0/tsort.rb:228:in `block in tsort_each'
...

This looks similar to a problem that some Windows users had a while back, but I tried the fix suggested (adding "require 'tzinfo'" to environment.rb), and still have the same problem.


问:
This is the error Android studio is showing me when i am pressing the button
Logcat Output:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String firebase.firebasepractice.User.getUsername()' on a null object reference. ...

User:

MainActivity:

```<code>public class MainActivity extends AppCompatActivity {

  private EditText name,password;
  Button btn;
  TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    name = (EditText) findViewById(R.id.userName);
    password= (EditText) findViewById(R.id.password);
    btn= (Button) findViewById(R.id.submit);
    tv= (TextView) findViewById(R.id.tv);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DatabaseReference myRef=FirebaseDatabase.getInstance().getReference("Users");

                String userId=myRef.push().getKey();

            myRef.child(userId).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    User user=dataSnapshot.getValue(User.class);
                    tv.setText("Name is "+user.getUsername()+"    Email is "+user.getEmail());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    });
}
}
</code>```

答:
Because mapping between datasnapshot and User model is failed.</p>

```<code>User user=dataSnapshot.getValue(User.class);
// check it null there
if(user != null) {
 tv.setText("Name is "+user.getUsername()+"    Email is "+user.getEmail());
}
</code>```

Body:
Logcat Output:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String firebase.firebasepractice.User.getUsername()' on a null object reference. ...

User:

MainActivity:

public class MainActivity extends AppCompatActivity {

  private EditText name,password;
  Button btn;
  TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    name = (EditText) findViewById(R.id.userName);
    password= (EditText) findViewById(R.id.password);
    btn= (Button) findViewById(R.id.submit);
    tv= (TextView) findViewById(R.id.tv);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DatabaseReference myRef=FirebaseDatabase.getInstance().getReference("Users");

                String userId=myRef.push().getKey();

            myRef.child(userId).addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    User user=dataSnapshot.getValue(User.class);
                    tv.setText("Name is "+user.getUsername()+"    Email is "+user.getEmail());
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    });
}
}

Body:
Because mapping between datasnapshot and User model is failed.

User user=dataSnapshot.getValue(User.class);
// check it null there
if(user != null) {
 tv.setText("Name is "+user.getUsername()+"    Email is "+user.getEmail());
}


问:
Replace nth occurrence of substring in string
I want to replace the n'th occurrence of a substring in a string.

There's got to be something equivalent to what I WANT to do which is

mystring.replace("substring", 2nd)

What is the simplest and most Pythonic way to achieve this?

Why not duplicate: I don't want to use regex for this approach and most of answers to similar questions I found are just regex stripping or really complex function. I really want as simple as possible and not regex solution.

答:
I have come up with the below, which considers also options to replace all 'old' string occurrences to the left or to the right. Naturally, there is no option to replace all occurrences, as standard str.replace works perfect.</p>

```<code>def nth_replace(string, old, new, n=1, option='only nth'):
    """
    This function replaces occurrences of string 'old' with string 'new'.
    There are three types of replacement of string 'old':
    1) 'only nth' replaces only nth occurrence (default).
    2) 'all left' replaces nth occurrence and all occurrences to the left.
    3) 'all right' replaces nth occurrence and all occurrences to the right.
    """
    if option == 'only nth':
        left_join = old
        right_join = old
    elif option == 'all left':
        left_join = new
        right_join = old
    elif option == 'all right':
        left_join = old
        right_join = new
    else:
        print("Invalid option. Please choose from: 'only nth' (default), 'all left' or 'all right'")
        return None
    groups = string.split(old)
    nth_split = [left_join.join(groups[:n]), right_join.join(groups[n:])]
    return new.join(nth_split)
</code>```

Body:
I have come up with the below, which considers also options to replace all 'old' string occurrences to the left or to the right. Naturally, there is no option to replace all occurrences, as standard str.replace works perfect.

def nth_replace(string, old, new, n=1, option='only nth'):
    """
    This function replaces occurrences of string 'old' with string 'new'.
    There are three types of replacement of string 'old':
    1) 'only nth' replaces only nth occurrence (default).
    2) 'all left' replaces nth occurrence and all occurrences to the left.
    3) 'all right' replaces nth occurrence and all occurrences to the right.
    """
    if option == 'only nth':
        left_join = old
        right_join = old
    elif option == 'all left':
        left_join = new
        right_join = old
    elif option == 'all right':
        left_join = old
        right_join = new
    else:
        print("Invalid option. Please choose from: 'only nth' (default), 'all left' or 'all right'")
        return None
    groups = string.split(old)
    nth_split = [left_join.join(groups[:n]), right_join.join(groups[n:])]
    return new.join(nth_split)


问:
Timer only works in debug mode
I have a Console Application with the following main program:

```<code>    static void Main(string[] args)
    {
        var timer = new System.Threading.Timer(
         e =>
            {
            //some code here
        },
        null,
        TimeSpan.Zero,
        TimeSpan.FromMinutes(1));

        var backupTimer = new System.Threading.Timer(
         e =>
         {
             //some code here

         },
        null,
        TimeSpan.Zero,
        TimeSpan.FromHours(24));

        Console.ReadLine();

    }
</code>```

The problem is that in debug mode it works fine and call methods in both timers in right period and if enter something in console the program ends working (Console.ReadLine() is for that) , but when i'm running program in Release mode both timers called only once (the first time) and then program just waiting until i enter something.

How to fix the problem , so i can compile a standalone program working properly?

答:
Hope the following solution helps!

Problem:

The following code always works as expected by showing the current clock time.

```<code> class Program
 {
        static void TimerProcedure(object param)
        {
            Console.Clear();
            Console.WriteLine(DateTime.Now.TimeOfDay);

            GC.Collect();

        }

        static void Main(string[] args)
        {
            Console.Title = "Desktop Clock";
            Console.SetWindowSize(20, 2);
            Timer timer = new Timer(TimerProcedure, null,
                TimeSpan.Zero, TimeSpan.FromSeconds(1));
            Console.ReadLine();
        }
    }
</code>```

However, if you run the same code in release mode, it shows current time only for the first time but it never updates after that.

Solution

A simple tweak by adding GC.KeepAlive(object) will make it work in Release mode also as expected. Refer to code below.

```<code>class Program
    {
        static void TimerProcedure(object param)
        {
            Console.Clear();
            Console.WriteLine(DateTime.Now.TimeOfDay);
            #region Hidden
            GC.Collect();
            #endregion
        }

        static void Main(string[] args)
        {
            Console.Title = "Desktop Clock";
            Console.SetWindowSize(20, 2);
            Timer timer = new Timer(TimerProcedure, null,
                TimeSpan.Zero, TimeSpan.FromSeconds(1));
            Console.ReadLine();
            GC.KeepAlive(timer);
        }
    }
</code>```

Alternate solution: is making timer a class level static variable

Title: Timer only works in debug mode

Body:
I have a Console Application with the following main program:

    static void Main(string[] args)
    {
        var timer = new System.Threading.Timer(
         e =>
            {
            //some code here
        },
        null,
        TimeSpan.Zero,
        TimeSpan.FromMinutes(1));

        var backupTimer = new System.Threading.Timer(
         e =>
         {
             //some code here

         },
        null,
        TimeSpan.Zero,
        TimeSpan.FromHours(24));

        Console.ReadLine();

    }

The problem is that in debug mode it works fine and call methods in both timers in right period and if enter something in console the program ends working (Console.ReadLine() is for that) , but when i'm running program in Release mode both timers called only once (the first time) and then program just waiting until i enter something.

How to fix the problem , so i can compile a standalone program working properly?

Body:
Hope the following solution helps!

Problem:

The following code always works as expected by showing the current clock time.

 class Program
 {
        static void TimerProcedure(object param)
        {
            Console.Clear();
            Console.WriteLine(DateTime.Now.TimeOfDay);

            GC.Collect();

        }

        static void Main(string[] args)
        {
            Console.Title = "Desktop Clock";
            Console.SetWindowSize(20, 2);
            Timer timer = new Timer(TimerProcedure, null,
                TimeSpan.Zero, TimeSpan.FromSeconds(1));
            Console.ReadLine();
        }
    }

However, if you run the same code in release mode, it shows current time only for the first time but it never updates after that.

Solution

A simple tweak by adding GC.KeepAlive(object) will make it work in Release mode also as expected. Refer to code below.

class Program
    {
        static void TimerProcedure(object param)
        {
            Console.Clear();
            Console.WriteLine(DateTime.Now.TimeOfDay);
            #region Hidden
            GC.Collect();
            #endregion
        }

        static void Main(string[] args)
        {
            Console.Title = "Desktop Clock";
            Console.SetWindowSize(20, 2);
            Timer timer = new Timer(TimerProcedure, null,
                TimeSpan.Zero, TimeSpan.FromSeconds(1));
            Console.ReadLine();
            GC.KeepAlive(timer);
        }
    }

Alternate solution: is making timer a class level static variable


问:
How not to calculate a value twice in select?
psql (9.6.1, server 9.5.5)

employees

```<code>     Column     |            Type             |                            Modifiers                            | Storage  | Stats target | Description
----------------+-----------------------------+-----------------------------------------------------------------+----------+--------------+----    ---------
 employee_id    | integer                     | not null default nextval('employees_employee_id_seq'::regclass) | plain    |              |
 first_name     | character varying(20)       |                                                                 | extended |              |
 last_name      | character varying(25)       | not null                                                        | extended |              |
 email          | character varying(25)       | not null                                                        | extended |              |
 phone_number   | character varying(20)       |                                                                 | extended |              |
 hire_date      | timestamp without time zone | not null                                                        | plain    |              |
 job_id         | character varying(10)       | not null                                                        | extended |              |
 salary         | numeric(8,2)                |                                                                 | main     |              |
 commission_pct | numeric(2,2)                |                                                                 | main     |              |
 manager_id     | integer                     |                                                                 | plain    |              |
 department_id  | integer
</code>```

I need to extract employee number, last name, salary, salary increased by 15.5 % (expressed as a whole number), and the difference between the new and old salary.

I have done like this:

```<code>select employee_id,
    last_name,
    salary,
    round(salary * 1.155, 0) as "New Salary",
    round(salary * 1.155, 0) - salary as "Increase"
from employees;
</code>```

What troubles me is that I have calculated the new salary twice.

I tried to use alias in the same select. Experimented like this:

```<code>select 2 as val_a, val_a - 4; --not working
</code>```

Well, my solution outputs acceptable result. But isn't there a better solution?

答:
You can write it with a subquery, if you are "picky" about not computing twice the same values:

```<code>SELECT
     *, "New Salary" - salary as "Increase"
FROM
(
    SELECT
        employee_id,
        last_name,
        salary,
        round(salary * 1.155, 0) as "New Salary"
    FROM
        employees
) AS s0 ;
</code>```

In practice, the difference when you run it a few times is neglectable:

dbfiddle here

Body:
psql (9.6.1, server 9.5.5)

employees

     Column     |            Type             |                            Modifiers                            | Storage  | Stats target | Description
----------------+-----------------------------+-----------------------------------------------------------------+----------+--------------+----    ---------
 employee_id    | integer                     | not null default nextval('employees_employee_id_seq'::regclass) | plain    |              |
 first_name     | character varying(20)       |                                                                 | extended |              |
 last_name      | character varying(25)       | not null                                                        | extended |              |
 email          | character varying(25)       | not null                                                        | extended |              |
 phone_number   | character varying(20)       |                                                                 | extended |              |
 hire_date      | timestamp without time zone | not null                                                        | plain    |              |
 job_id         | character varying(10)       | not null                                                        | extended |              |
 salary         | numeric(8,2)                |                                                                 | main     |              |
 commission_pct | numeric(2,2)                |                                                                 | main     |              |
 manager_id     | integer                     |                                                                 | plain    |              |
 department_id  | integer

I need to extract employee number, last name, salary, salary increased by 15.5 % (expressed as a whole number), and the difference between the new and old salary.

I have done like this:

select employee_id,
    last_name,
    salary,
    round(salary * 1.155, 0) as "New Salary",
    round(salary * 1.155, 0) - salary as "Increase"
from employees;

What troubles me is that I have calculated the new salary twice.

I tried to use alias in the same select. Experimented like this:

select 2 as val_a, val_a - 4; --not working

Well, my solution outputs acceptable result. But isn't there a better solution?

Body:
You can write it with a subquery, if you are "picky" about not computing twice the same values:

SELECT
     *, "New Salary" - salary as "Increase"
FROM
(
    SELECT
        employee_id,
        last_name,
        salary,
        round(salary * 1.155, 0) as "New Salary"
    FROM
        employees
) AS s0 ;

In practice, the difference when you run it a few times is neglectable:

dbfiddle here


问:
Two table merge in single table
I have two tables in my database #1 is payment records and #2 is sales records of one customer now I want to show two tables' values in one single table that shows sales details and payment details at once like the 3rd image

So how should I write query that brings result set what I want.

I am creating this view in php, mysql and html

#1 is payment records

#2 is sales records

desired output

sales table

Payments table

答:
Any of valid inner join form should work:</p>

```<code>select *
from payment, sale
where payment.customer_id = sale.customer_id

select *
from payment inner join sale using (customer_id)

select *
from payment inner join sale on payment.customer_id = sale.customer_id
</code>```

Title: Two table merge in single table

Body:
Any of valid inner join form should work:

select *
from payment, sale
where payment.customer_id = sale.customer_id

select *
from payment inner join sale using (customer_id)

select *
from payment inner join sale on payment.customer_id = sale.customer_id


问:
Customizing tables in Stata
Using Stata14 on windows, I am wondering how to build customized tables from several regression results. Here is an example. We have

```<code>reg y, x1
predict resid1, residuals
summarize resid1
</code>```

Which gives:

```<code>    Variable |        Obs        Mean    Std. Dev.       Min        Max
-------------+---------------------------------------------------------
      resid1 |  5,708,529    4.83e-11    .7039736  -3.057633   3.256382
</code>```

And run another regrerssion and similarly obtain the residuals:

```<code>reg y, x2
predict resid2, residuals
</code>```

I would like to create a table which has the two standard deviations of the two residuals, and optimally output it to latex. I am familiar with the esttab and estout commands for outputting regression results to latex, but these do not work for customized tables as in the above example.

答:
You need to use estpost. This should get you started.

```<code>sysuse auto, clear
regress price weight
predict error1, residuals
regress price trunk
predict error2, residuals

eststo clear
estpost summarize error1 error2
eststo
esttab, cells("count mean sd min max") noobs nonum
esttab using so.tex, cells("count mean sd min max") noobs nonum replace
</code>```

More here.

Title: Customizing tables in Stata

Body:
Using Stata14 on windows, I am wondering how to build customized tables from several regression results. Here is an example. We have

reg y, x1
predict resid1, residuals
summarize resid1

Which gives:

    Variable |        Obs        Mean    Std. Dev.       Min        Max
-------------+---------------------------------------------------------
      resid1 |  5,708,529    4.83e-11    .7039736  -3.057633   3.256382

And run another regrerssion and similarly obtain the residuals:

reg y, x2
predict resid2, residuals

I would like to create a table which has the two standard deviations of the two residuals, and optimally output it to latex. I am familiar with the esttab and estout commands for outputting regression results to latex, but these do not work for customized tables as in the above example.

Body:
You need to use estpost. This should get you started.

sysuse auto, clear
regress price weight
predict error1, residuals
regress price trunk
predict error2, residuals

eststo clear
estpost summarize error1 error2
eststo
esttab, cells("count mean sd min max") noobs nonum
esttab using so.tex, cells("count mean sd min max") noobs nonum replace

More here.


问:
How can I get a commit message from a bzr post-commit hook?
I'm trying to write a bzr post-commit hook for my private bugtracker, but I'm stuck at the function signature of

```<code>post_commit(local, master, old_revno, old_revid, new_revno, mew_revid)
</code>```

How can I extract the commit message for the branch from this with bzrlib in Python?

答:
And the answer is like so:

```<code>def check_commit_msg(local, master, old_revno, old_revid, new_revno, new_revid):
    branch = local or master
    revision = branch.repository.get_revision(new_revid)
    print revision.message
</code>```

local and master are Branch objects, so once you have a revision, it's easy to extract the message.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a bzr post-commit hook for my private bugtracker, but I'm stuck at the function signature of

post_commit(local, master, old_revno, old_revid, new_revno, mew_revid)

How can I extract the commit message for the branch from this with bzrlib in Python?

Body:
And the answer is like so:

def check_commit_msg(local, master, old_revno, old_revid, new_revno, new_revid):
    branch = local or master
    revision = branch.repository.get_revision(new_revid)
    print revision.message

local and master are Branch objects, so once you have a revision, it's easy to extract the message.

OwnerDisplayName: Josh Matthews


问:
Equivalent of shell 'cd' command to change the working directory?
cd is the shell command to change the working directory.

How do I change the current working directory in Python?

答:
I would use os.chdir like this:

```<code>os.chdir("/path/to/change/to")
</code>```

By the way, if you need to figure out your current path, use os.getcwd().

More here

OwnerDisplayName: Peter

Body:
I would use os.chdir like this:

os.chdir("/path/to/change/to")

By the way, if you need to figure out your current path, use os.getcwd().

More here

OwnerDisplayName: Evan Fosmark