问:
What is the best way to download a big file in NodeJS?
The below server code is working fine for 5GB file using
 wget http://localhost:11146/base/bigFile.zip but not using client side code.

Server side code.

```<code>var http = require("http");
var fs = require("fs");
var filename = "base/bigFile.zip";

var serv = http.createServer(function (req, res) {
    var stat = fs.statSync(filename);
    res.writeHeader(200, {"Content-Length": stat.size});
    var fReadStream = fs.createReadStream(filename);
    fReadStream.on('data', function (chunk) {
       if(!res.write(chunk)){
           fReadStream.pause();
       }
   });
   fReadStream.on('end', function () {
      res.end();
   });
   res.on("drain", function () {
      fReadStream.resume();
   });
});

serv.listen(1114);
</code>```

Client side code using Request module. What is wrong in this code?

```<code>var request = require('request')
request('http:/localhost:11146/base/bigFile.zip', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});
</code>```

error for above client side code is below -

```<code>error: Error: Invalid protocol
    at Request.init (/Users/air/Projects/node_modules/request/request.js:338:51)
    at new Request (/Users/air/Projects//node_modules/request/request.js:105:8)
    at request (/Users/air/Projects/Vertico/Vertico-CLI/node_modules/request/index.js:53:11)
    at Object.<anonymous> (/Users/air/Projects/req.js:2:1)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
statusCode: undefined
body: undefined
</code>```

I revised client side to use wget shell process instead of request package, that code is below, the problem is - I am not able to see nice download progress of wget, any work around for this code, such that I can see the progress bar in child process.

```<code>const fs = require('fs');
   const child_process = require('child_process');

   var workerProcess = child_process.spawn('wget', ['-O','fdsf.zip', 'http://localhost:11146/base/bigFile.zip']);

   workerProcess.stdout.on('data', function (data) {
     console.log('stdout: ' + data);
   });

   workerProcess.stderr.on('data', function (data) {
     //console.log('stderr: ' + data);
   });

   workerProcess.on('close', function (code) {
      console.log('Download Completed' + code);
   });
</code>```

So finally I want to know how to download a file using client side code written in nodejs?

答:
UPDATE:

request module is deprecated

It is recommended to use active modules. My personal preference is got
Please refer got streams for examples.
Another alternative is node-fetch

Easiest way is to use request module

Here you are trying to store entire result in memory and console log it. 5GB is pretty much large, either you must increase Node.js memory limit (not recommended) or you must use streams. See the streaming example below from request npm documentation:

```<code>const fs = require('fs');
const request = require('request');
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
</code>```

You must pipe the response, so that whether is 1MB or 1GB or 1TB, only a fraction of the file will be in memory and it will be written to disk as soon as possible. You can use the same approach using Node.js built in functions, but implementation will be difficult and be like re-inventing the wheel when request module is there.

For download with progress you can use request-progress module along with request module, see the example below (taken from their documentation):

```<code>var fs = require('fs');
var request = require('request');
var progress = require('request-progress');

// The options argument is optional so you can omit it
progress(request('https://az412801.vo.msecnd.net/vhd/VMBuild_20141027/VirtualBox/IE11/Windows/IE11.Win8.1.For.Windows.VirtualBox.zip'), {
    // throttle: 2000,                    // Throttle the progress event to 2000ms, defaults to 1000ms
    // delay: 1000,                       // Only start to emit after 1000ms delay, defaults to 0ms
    // lengthHeader: 'x-transfer-length'  // Length header to use, defaults to content-length
})
.on('progress', function (state) {
    // The state is an object that looks like this:
    // {
    //     percent: 0.5,               // Overall percent (between 0 to 1)
    //     speed: 554732,              // The download speed in bytes/sec
    //     size: {
    //         total: 90044871,        // The total payload size in bytes
    //         transferred: 27610959   // The transferred payload size in bytes
    //     },
    //     time: {
    //         elapsed: 36.235,        // The total elapsed seconds since the start (3 decimals)
    //         remaining: 81.403       // The remaining seconds to finish (3 decimals)
    //     }
    // }
    console.log('progress', state);
})
.on('error', function (err) {
    // Do something with err
})
.on('end', function () {
    // Do something after request finishes
})
.pipe(fs.createWriteStream('IE11.Win8.1.For.Windows.VirtualBox.zip'));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The below server code is working fine for 5GB file using
 wget http://localhost:11146/base/bigFile.zip but not using client side code.

Server side code.

var http = require("http");
var fs = require("fs");
var filename = "base/bigFile.zip";

var serv = http.createServer(function (req, res) {
    var stat = fs.statSync(filename);
    res.writeHeader(200, {"Content-Length": stat.size});
    var fReadStream = fs.createReadStream(filename);
    fReadStream.on('data', function (chunk) {
       if(!res.write(chunk)){
           fReadStream.pause();
       }
   });
   fReadStream.on('end', function () {
      res.end();
   });
   res.on("drain", function () {
      fReadStream.resume();
   });
});

serv.listen(1114);

Client side code using Request module. What is wrong in this code?

var request = require('request')
request('http:/localhost:11146/base/bigFile.zip', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

error for above client side code is below -

error: Error: Invalid protocol
    at Request.init (/Users/air/Projects/node_modules/request/request.js:338:51)
    at new Request (/Users/air/Projects//node_modules/request/request.js:105:8)
    at request (/Users/air/Projects/Vertico/Vertico-CLI/node_modules/request/index.js:53:11)
    at Object.<anonymous> (/Users/air/Projects/req.js:2:1)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
statusCode: undefined
body: undefined

I revised client side to use wget shell process instead of request package, that code is below, the problem is - I am not able to see nice download progress of wget, any work around for this code, such that I can see the progress bar in child process.

const fs = require('fs');
   const child_process = require('child_process');

   var workerProcess = child_process.spawn('wget', ['-O','fdsf.zip', 'http://localhost:11146/base/bigFile.zip']);

   workerProcess.stdout.on('data', function (data) {
     console.log('stdout: ' + data);
   });

   workerProcess.stderr.on('data', function (data) {
     //console.log('stderr: ' + data);
   });

   workerProcess.on('close', function (code) {
      console.log('Download Completed' + code);
   });

So finally I want to know how to download a file using client side code written in nodejs?

Body:
UPDATE:

request module is deprecated

It is recommended to use active modules. My personal preference is got
Please refer got streams for examples.
Another alternative is node-fetch

Easiest way is to use request module

Here you are trying to store entire result in memory and console log it. 5GB is pretty much large, either you must increase Node.js memory limit (not recommended) or you must use streams. See the streaming example below from request npm documentation:

const fs = require('fs');
const request = require('request');
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))

You must pipe the response, so that whether is 1MB or 1GB or 1TB, only a fraction of the file will be in memory and it will be written to disk as soon as possible. You can use the same approach using Node.js built in functions, but implementation will be difficult and be like re-inventing the wheel when request module is there.

For download with progress you can use request-progress module along with request module, see the example below (taken from their documentation):

var fs = require('fs');
var request = require('request');
var progress = require('request-progress');

// The options argument is optional so you can omit it
progress(request('https://az412801.vo.msecnd.net/vhd/VMBuild_20141027/VirtualBox/IE11/Windows/IE11.Win8.1.For.Windows.VirtualBox.zip'), {
    // throttle: 2000,                    // Throttle the progress event to 2000ms, defaults to 1000ms
    // delay: 1000,                       // Only start to emit after 1000ms delay, defaults to 0ms
    // lengthHeader: 'x-transfer-length'  // Length header to use, defaults to content-length
})
.on('progress', function (state) {
    // The state is an object that looks like this:
    // {
    //     percent: 0.5,               // Overall percent (between 0 to 1)
    //     speed: 554732,              // The download speed in bytes/sec
    //     size: {
    //         total: 90044871,        // The total payload size in bytes
    //         transferred: 27610959   // The transferred payload size in bytes
    //     },
    //     time: {
    //         elapsed: 36.235,        // The total elapsed seconds since the start (3 decimals)
    //         remaining: 81.403       // The remaining seconds to finish (3 decimals)
    //     }
    // }
    console.log('progress', state);
})
.on('error', function (err) {
    // Do something with err
})
.on('end', function () {
    // Do something after request finishes
})
.pipe(fs.createWriteStream('IE11.Win8.1.For.Windows.VirtualBox.zip'));


来源: stackexchange

问:
YII2 Dropdownlist from JSON link
How to populate json data to dropdownlist

this is the json link : http://localhost/data

this the json format :

```<code>[{"inst_id":"1","inst_code":"001","inst_name":"HARVARD"},{"inst_id":"2","inst_code":"002","inst_name":"UCLA"}]
</code>```

this the view :

```<code><?= $form->field($model, 'institusi')->dropDownList(); ?>
</code>```

the dropdown value from "inst_id" and text from "inst_name"

i have the code but it isn't Active form

```<code>$url = 'http://localhost/data';
        $content = file_get_contents($url);
        $json = json_decode($content, true);
        $inst=array();
        echo "<select>";
        foreach($json as $item) {

            echo "<option value='".$item['inst_id']."'>".$item['inst_name']."</option>";

        }
        echo "</select>";
</code>```

so how to populate the json data into Activeform Dropdownlist

答:
The easiest way would be to prepare the array for dropDownList just before it

```<code><?php
        $url = 'http://localhost/data';
        $content = file_get_contents($url);
        $json = json_decode($content, true);
        $instArray = ArrayHelper::map($json,'inst_id','inst_name');
        echo $form->field($model, 'institusi')->dropDownList($instArray);
?>
</code>```

You could also prepare the the same array from controller and pass it to view from render method.

Other options would be to create a component or add a static method to the model. Both should return the array format of your json data.

ContentLicense: CC BY-SA 3.0

Title: YII2 Dropdownlist from JSON link

Body:
How to populate json data to dropdownlist

this is the json link : http://localhost/data

this the json format :

[{"inst_id":"1","inst_code":"001","inst_name":"HARVARD"},{"inst_id":"2","inst_code":"002","inst_name":"UCLA"}]

this the view :

<?= $form->field($model, 'institusi')->dropDownList(); ?>

the dropdown value from "inst_id" and text from "inst_name"

i have the code but it isn't Active form

$url = 'http://localhost/data';
        $content = file_get_contents($url);
        $json = json_decode($content, true);
        $inst=array();
        echo "<select>";
        foreach($json as $item) {

            echo "<option value='".$item['inst_id']."'>".$item['inst_name']."</option>";

        }
        echo "</select>";

so how to populate the json data into Activeform Dropdownlist

Body:
The easiest way would be to prepare the array for dropDownList just before it

<?php
        $url = 'http://localhost/data';
        $content = file_get_contents($url);
        $json = json_decode($content, true);
        $instArray = ArrayHelper::map($json,'inst_id','inst_name');
        echo $form->field($model, 'institusi')->dropDownList($instArray);
?>

You could also prepare the the same array from controller and pass it to view from render method.

Other options would be to create a component or add a static method to the model. Both should return the array format of your json data.


问:
Selenium HtmlUnitDriver clicking on checkbox
I'm trying to get my checkbox clicked while running using selenium.

I have no issue running my test when using chromedriver.
But when I switch to HtmlUnitDriver, it will throw error when it reaches the clicking of checkbox action. The error thrown is

org.openga.selenium.ElementNotVisibleException: You may only interact with visible elements

I've tried multiple methods like:

```<code>driver.findElement(By.xpath("//*[@id=\"chkConfirm\"]")).sendKeys(Keys.SPACE);
driver.findElement(By.xpath("//*[@id=\"chkConfirm\"]")).click();
</code>```

But none of it works. Can someone help me out?

答:
```<code>WebElement checkBox = driver.findElement(By.xpath("//*[@id='chkConfirm']"))
checkBox.isDisplayed();
if(!checkBox.isSelected())
checkBox.click();
</code>```

Try this block.

Body:
I'm trying to get my checkbox clicked while running using selenium.

I have no issue running my test when using chromedriver.
But when I switch to HtmlUnitDriver, it will throw error when it reaches the clicking of checkbox action. The error thrown is

org.openga.selenium.ElementNotVisibleException: You may only interact with visible elements

I've tried multiple methods like:

driver.findElement(By.xpath("//*[@id=\"chkConfirm\"]")).sendKeys(Keys.SPACE);
driver.findElement(By.xpath("//*[@id=\"chkConfirm\"]")).click();

But none of it works. Can someone help me out?

Body:
WebElement checkBox = driver.findElement(By.xpath("//*[@id='chkConfirm']"))
checkBox.isDisplayed();
if(!checkBox.isSelected())
checkBox.click();

Try this block.


问:
Bluetooth data update notifications not getting fired
I am facing some issue while reading data from bluetooth peripheral. We have a bluetooth device with the following gatt details.

```<code><service uuid="service id" advertise="true">
    <description>XXXX service</description>
    <characteristic uuid="characteristic id" id="xgatt_data">
        <description>Data</description>
        <properties write="true" indicate="true" />
        <value variable_length="true" length="20" type="user" />
    </characteristic>
</service>
</code>```

What i am doing is

Search for the peripheral who is having "service id"

Connect to the peripheral once found and keeping a strong reference to it.

After connecting setting delegate and searching for all the services
it providing

loop all services and scan for characteristics once we discover
service

after i found desired characteristic i am enabling notification

On button click i am writing data to characteristic

I am able to connect to the device. and i can send commands(data) to peripheral also. Once we send any command to device it will send some data in response. I can see logs at the device, it is sending some data back once it receive any command. But in my iOS device i am not able to read the data by using either notification or normal read functions. What i am missing here?

答: I found the issue. Actually issue is with the emulator. And now i can get data update indications and able to write data to BLE with only "read" and "indicate" properties. </p>

Body:
I am facing some issue while reading data from bluetooth peripheral. We have a bluetooth device with the following gatt details.

<service uuid="service id" advertise="true">
    <description>XXXX service</description>
    <characteristic uuid="characteristic id" id="xgatt_data">
        <description>Data</description>
        <properties write="true" indicate="true" />
        <value variable_length="true" length="20" type="user" />
    </characteristic>
</service>

What i am doing is

Search for the peripheral who is having "service id"

Connect to the peripheral once found and keeping a strong reference to it.

After connecting setting delegate and searching for all the services
it providing

loop all services and scan for characteristics once we discover
service

after i found desired characteristic i am enabling notification

On button click i am writing data to characteristic

I am able to connect to the device. and i can send commands(data) to peripheral also. Once we send any command to device it will send some data in response. I can see logs at the device, it is sending some data back once it receive any command. But in my iOS device i am not able to read the data by using either notification or normal read functions. What i am missing here?


答:
This is in reference to MySQL and MariaDB databases:

```<code>SELECT SUM(Connection)
       FROM Connection
       WHERE Member_ID = ALL (SELECT ID FROM Member WHERE Status = 1);
</code>```

OR

```<code>SELECT SUM(Connection)
       FROM Connection
       WHERE Member_ID IN (SELECT ID FROM Member WHERE Status = 1);
</code>```

Title: sql select sum with condition 2 tables?

Body:
I have 2 table

Table Connection
----------------------------------------
|  ID       |  Member_ID  |  Connection|
----------------------------------------
|  1        |  100        |  22        |
----------------------------------------
|  2        |  101        |  15        |
----------------------------------------
|  3        |  102        |  19        |
----------------------------------------
|  4        |  103        |  21        |

Table Member
---------------------------
|  ID         |  Status     |
---------------------------
|  100        |  0          |
----------------------------
|  101        |  1          |
----------------------------
|  102        |  1          |
---------------------------
|  103        |  0          |

I want to get sum of Connection has status =1.
The result in example should be 15+19 = 34.

Body:
This is in reference to MySQL and MariaDB databases:

SELECT SUM(Connection)
       FROM Connection
       WHERE Member_ID = ALL (SELECT ID FROM Member WHERE Status = 1);

OR

SELECT SUM(Connection)
       FROM Connection
       WHERE Member_ID IN (SELECT ID FROM Member WHERE Status = 1);


问:
Getting the handler inside on() method

$( document ).ready(function() {

  $('#handler').on('click', '.selector', function(){
    alert( $(this).text());
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="handler">
  handler content
  selector content
</div></code>```

How do I get the #handler inside the on method without explicitly specifying it?

答:
Use the event "delegateTarget" property

```<code>$( document ).ready(function() {
    $('#handler').on('click', '.selector', function(e){
        console.log(e.delegateTarget);
    });
});
</code>```

Working example:-

$( document ).ready(function() {
  $('#handler').on('click', '.selector', function(e){
      console.log(e.delegateTarget);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="handler">
  handler content
  child
  <div>
    grand child
  </div>
  <div>
    <div>
      great grand child
    </div>
  </div>
</div></code>```

Title: Getting the handler inside on() method

Body:
$( document ).ready(function() {

  $('#handler').on('click', '.selector', function(){
    alert( $(this).text());
  });

});

  handler content
  selector content

How do I get the #handler inside the on method without explicitly specifying it?

Body:
Use the event "delegateTarget" property

$( document ).ready(function() {
    $('#handler').on('click', '.selector', function(e){
        console.log(e.delegateTarget);
    });
});

Working example:-

$( document ).ready(function() {
  $('#handler').on('click', '.selector', function(e){
      console.log(e.delegateTarget);
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="handler">
  handler content
  <a href="#" class="selector">child</a>
  <div>
    <a href="#" class="selector">grand child</a>
  </div>
  <div>
    <div>
      <a href="#" class="selector">great grand child</a>
    </div>
  </div>
</div>


问:
android: How to increase long press time for listview items in android?
I have a custom listview, in which items are scroll horizontal. I want to perform single touch and longpress for items for 5 sec for listview items. How to do this. How can i increase longpress time interval for listview items to 5 sec.

答:
This replicates onLongPress more accurately because it does not wait for the user to lift their finger before executing. Was written specifically for ViewPager, but should be able to apply similar logic.</p>

```<code>// long press duration in milliseconds
public static final int LONG_PRESS_DURATION = 2000;

private boolean mIsTouching = false;

@Override
public boolean onTouchEvent(MotionEvent event) {

    if (event.getAction() == event.ACTION_DOWN) {
        mIsTouching = true;
    } else if (event.getAction() == event.ACTION_UP) {
        mIsTouching = false;
    }

    return super.onTouchEvent(event);
}

@Override
public void onLongPress(MotionEvent event) {

    // subtracts the system set timeout since that time has already occured at this point
    int duration = LONG_PRESS_DURATION - getLongPressTimeout();

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (mIsTouching) {
                do something...
            }
        }
    }, duration > 0 ? duration : 0);
}
</code>```

Body:
This replicates onLongPress more accurately because it does not wait for the user to lift their finger before executing. Was written specifically for ViewPager, but should be able to apply similar logic.

// long press duration in milliseconds
public static final int LONG_PRESS_DURATION = 2000;

private boolean mIsTouching = false;

@Override
public boolean onTouchEvent(MotionEvent event) {

    if (event.getAction() == event.ACTION_DOWN) {
        mIsTouching = true;
    } else if (event.getAction() == event.ACTION_UP) {
        mIsTouching = false;
    }

    return super.onTouchEvent(event);
}

@Override
public void onLongPress(MotionEvent event) {

    // subtracts the system set timeout since that time has already occured at this point
    int duration = LONG_PRESS_DURATION - getLongPressTimeout();

    Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (mIsTouching) {
                do something...
            }
        }
    }, duration > 0 ? duration : 0);
}


问:
open webpage in firefox
i am not sure..is there any chance to open my webpage in firefox. for example i am browsing mywebsite using IE. when ever i click link of the page then automatically it will open in firefox. this option is not for all pages only for specified page.

thanks.

答:
If this were the case, ie6 would have gone out long ago. The best you can do here, would be to check which browser they are using (get_browser if you are using php) and refuse to show content to people using browsers other than firefox.

Instead you could redirect them to a page explaining why they need to be using firefox to access your websites services (I guess a link to the firefox download page would be nice too)

ContentLicense: CC BY-SA 2.5

Title: open webpage in firefox


问:
Android Test: how to test if a "synchronized static" method could block itself in multi-thread?
i've got a simple class to test in Android environment

```<code>public class ClassToTest {
    public synchronized static void func1() {....}
}
</code>```

i should test: func1() can run in ONLY ONE thread, and in other threads its calls should be blocked.

how to write this JUNIT test case?

many thanks!

答:
"Two threads cannot execute static synchronized methods of the same class at the same time, just as two threads cannot execute synchronized methods on the same object at the same time." -- The Java Programming Language, 4th Edition, Section 14.3.2

If I understand what you're asking, I don't think you should bother to write that unit test.

Also see this SO Question

Body:
i've got a simple class to test in Android environment

public class ClassToTest {
    public synchronized static void func1() {....}
}

i should test: func1() can run in ONLY ONE thread, and in other threads its calls should be blocked.

how to write this JUNIT test case?

many thanks!


问:
how to insert html, css and php in mail function in php
I am confused to use this function when my coding is too long and there is "php" function in email. Can you give me an example? I want to send an email according to this code that I created this from  to  * end     </p>

```<code>  <!doctype html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Wherco</title>

        <!-- Latest compiled and minified css -->
           <link rel="stylesheet" href="../view/css/bootstrap.min.css">
        <!-- optional theme-->
           <link rel="stylesheet" href="../view/css/bootstrap-theme.min.css">
        <!--my custom css-->
           <link rel="stylesheet" href="../view/css/style.css">
        <!--font-awesome-->
           <link rel="stylesheet" href="../view/font-awesome/css/font-awesome.min.css">

        <style>
        .invoice-box{
            max-width:800px;
            margin:auto;
            padding:30px;
            border:1px solid #eee;
            box-shadow:0 0 10px rgba(0, 0, 0, .15);
            font-size:16px;
            line-height:24px;
            font-family:'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif;
            color:#555;
        }

        .invoice-box table{
            width:100%;
            line-height:inherit;
            text-align:left;
        }

        .invoice-box table td{
            padding:5px;
            vertical-align:top;
        }

        .invoice-box table tr td:nth-child(2){
            text-align:right;
        }

        .invoice-box table tr.top table td{
            padding-bottom:20px;
        }

        .invoice-box table tr.top table td.title{
            font-size:45px;
            line-height:45px;
            color:#333;
        }

        .invoice-box table tr.information table td{
            padding-bottom:40px;
        }

        .invoice-box table tr.heading td{
            background:#eee;
            border-bottom:1px solid #ddd;
            font-weight:bold;
        }

        .invoice-box table tr.details td{
            padding-bottom:20px;
        }

        .invoice-box table tr.item td{
            border-bottom:1px solid #eee;
        }

        .invoice-box table tr.item.last td{
            border-bottom:none;
        }

        .invoice-box table tr.total td:nth-child(2){
            border-top:2px solid #eee;
            font-weight:bold;
        }

        @media only screen and (max-width: 600px) {
            .invoice-box table tr.top table td{
                width:100%;
                display:block;
                text-align:center;
            }

            .invoice-box table tr.information table td{
                width:100%;
                display:block;
                text-align:center;
            }
        }
        </style>
    </head>

    <?php $result = tampil_per_id_order($_GET['id']);
    while($row = mysqli_fetch_assoc($result)) { ?>

    <body>
        <div class="invoice-box">
            <table cellpadding="0" cellspacing="0">
                <tr class="top">
                    <td colspan="2">
                        <table>
                            <tr>
                                <td class="title">
                                    <h7> Wherco </h7>
                                </td>

                                <td>
                                    Invoice order #: <?php echo $row['id_order']?><br>
                                    Created: <?php echo date("Y-m-d"); ?><br>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>

                <tr class="information">
                    <td colspan="2">
                        <table>
                            <tr>
                                <td>
                                    Wherco.<br>
                                    12345 Seminyak<br>
                                    -
                                </td>

                                <td>
                                    <?php echo $row['username']?><br>
                                      <?php echo $row['email']?><br>
                                      <?php echo $row['telp']?>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>

                <tr class="heading">
                    <td>
                        Deskripsi Project
                    </td>

                    <td>
                        Tanggal Transfer
                    </td>
                </tr>

                <tr class="details">
                    <td>
                          <?php echo $row['deskripsi']?>
                    </td>

                    <td>
                      <?php echo $row['tanggal_konfirmasi']?>
                    </td>
                </tr>

                <tr class="heading">
                    <td>
                        Jenis Package
                    </td>

                    <td>
                        Biaya
                    </td>
                </tr>

                <tr class="item">
                    <td>
                      <?php echo $row['jenis_package']?>
                    </td>

                    <td>
                        Rp.<?php echo number_format($row['jumlah_transfer']); ?>
                    </td>
                </tr>

                <tr class="item last">
                    <td>

                    </td>

                    <td>

                    </td>
                </tr>

                <tr class="total">
                    <td>Total</td>

                    <td>
                      Rp.<?php echo number_format($row['jumlah_transfer']); ?> <br> <br>
                  <form class="" action="" method="post">
                      <div class="btn-group" role="group" aria-label="...">
                          <button type="submit" class="btn btn-success">Kirim Email</button>
                      </div>
                </form>
                    </td>
                </tr>
            </table>
        </div>
    </body>
      <?php }?>
    </html>
</code>```

答:
You can do this with the help of output buffer and use PHPMailer with authentication.

First save this code to 1 file and use this file as mail template. check below code.

```<code><?php

include("/phpMailer/class.phpmailer.php"); // Include php mailer file
ob_start(); // start buffering
include("mail_template.php"); // mail template file
$msg = ob_get_contents();
ob_end_clean(); // clear buffering
$mail = new PHPMailer(); // defaults to using php "mail()"
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true;
$mail->Username = "emailaddress"; // SMTP account username
$mail->Password = "password"; // SMTP account password

$mail->Port = "MAIL_PORT";
$mail->Host = "MAIL_HOST";

$body = $msg;
$mail->From = "From email address";
$mail->FromName = "From Name";
$mail->Subject = "Subject";
$mail->MsgHTML($body);
$mail->AddAddress("email address");

if (!$mail->Send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
}
?>
</code>```

Body:
I am confused to use this function when my coding is too long and there is "php" function in email. Can you give me an example? I want to send an email according to this code that I created this from  to  * end

  <!doctype html>

        <meta charset="utf-8">
        <title>Wherco</title>

           <link rel="stylesheet" href="../view/css/bootstrap.min.css">

           <link rel="stylesheet" href="../view/css/bootstrap-theme.min.css">

           <link rel="stylesheet" href="../view/css/style.css">

           <link rel="stylesheet" href="../view/font-awesome/css/font-awesome.min.css">

    <?php $result = tampil_per_id_order($_GET['id']);
    while($row = mysqli_fetch_assoc($result)) { ?>

                                    <h7> Wherco </h7>

                                    Invoice order #: <?php echo $row['id_order']?>

                                    Created: <?php echo date("Y-m-d"); ?>

                                    Wherco.

                                    12345 Seminyak

                                    -

                                    <?php echo $row['username']?>

                                      <?php echo $row['email']?>

                                      <?php echo $row['telp']?>

                        Deskripsi Project

                        Tanggal Transfer

                          <?php echo $row['deskripsi']?>

                      <?php echo $row['tanggal_konfirmasi']?>

                        Jenis Package

                        Biaya

                      <?php echo $row['jenis_package']?>

                        Rp.<?php echo number_format($row['jumlah_transfer']); ?>

                    Total

                      Rp.<?php echo number_format($row['jumlah_transfer']); ?>

                  <form class="" action="" method="post">

                          <button type="submit" class="btn btn-success">Kirim Email</button>

                </form>

      <?php }?>

Body:
You can do this with the help of output buffer and use PHPMailer with authentication.

First save this code to 1 file and use this file as mail template. check below code.

<?php

include("/phpMailer/class.phpmailer.php"); // Include php mailer file
ob_start(); // start buffering
include("mail_template.php"); // mail template file
$msg = ob_get_contents();
ob_end_clean(); // clear buffering
$mail = new PHPMailer(); // defaults to using php "mail()"
$mail->IsSMTP(); // telling the class to use SMTP
$mail->SMTPAuth = true;
$mail->Username = "emailaddress"; // SMTP account username
$mail->Password = "password"; // SMTP account password

$mail->Port = "MAIL_PORT";
$mail->Host = "MAIL_HOST";

$body = $msg;
$mail->From = "From email address";
$mail->FromName = "From Name";
$mail->Subject = "Subject";
$mail->MsgHTML($body);
$mail->AddAddress("email address");

if (!$mail->Send()) {
    echo "Mailer Error: " . $mail->ErrorInfo;
}
?>


问:
" TypeError: unsupported operand type(s) for -=: 'Retry' and 'int' " during PIP upgrade
I'm using Ubuntu 16.04.2 LTS in an Acer Laptop and I'm trying to update my pip installation (current version: 8.1.1). When I run the command

pip install --upgrade pip

I get the following output:

```<code>Exception:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 209, in main
    status = self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 328, in run
    wb.build(autobuilding=True)
File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 748, in build
    self.requirement_set.prepare_files(self.finder)
File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 360, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 512, in _prepare_file
    finder, self.upgrade, require_hashes)
File "/usr/lib/python2.7/dist-packages/pip/req/req_install.py", line 273, in populate_link
    self.link = finder.find_requirement(self, upgrade)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 442, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 400, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 545, in _get_pages
    page = self._get_page(location)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 648, in _get_page
    return HTMLPage.get_page(link, session=self.session)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 757, in get_page
    "Cache-Control": "max-age=600",
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 480, in get
    return self.request('GET', url, **kwargs)
File "/usr/lib/python2.7/dist-packages/pip/download.py", line 378, in request
    return super(PipSession, self).request(method, url, *args, **kwargs)
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
File "/usr/share/python-wheels/CacheControl-0.11.5-py2.py3-none-any.whl/cachecontrol/adapter.py", line 46, in send
    resp = super(CacheControlAdapter, self).send(request, **kw)
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/adapters.py", line 376, in send
    timeout=timeout
File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/connectionpool.py", line 610, in urlopen
    _stacktrace=sys.exc_info()[2])
File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/util/retry.py", line 228, in increment
    total -= 1
TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'
</code>```

I have read the messages in the following pages:

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

https://github.com/pypa/pip/issues/3943

https://github.com/pypa/pip/issues/4133

I'm not using any proxy or firewall (unless you count my router as both, idk).

答:
This happens to me when I am behind a corporate proxy. To fix that, run with --proxy=urlOfYourProxy.

For example:

```<code>pip install --proxy user:password@http://localproxy:8080
</code>```

Body:
I'm using Ubuntu 16.04.2 LTS in an Acer Laptop and I'm trying to update my pip installation (current version: 8.1.1). When I run the command

pip install --upgrade pip

I get the following output:

Exception:
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 209, in main
    status = self.run(options, args)
File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 328, in run
    wb.build(autobuilding=True)
File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 748, in build
    self.requirement_set.prepare_files(self.finder)
File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 360, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
File "/usr/lib/python2.7/dist-packages/pip/req/req_set.py", line 512, in _prepare_file
    finder, self.upgrade, require_hashes)
File "/usr/lib/python2.7/dist-packages/pip/req/req_install.py", line 273, in populate_link
    self.link = finder.find_requirement(self, upgrade)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 442, in find_requirement
    all_candidates = self.find_all_candidates(req.name)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 400, in find_all_candidates
    for page in self._get_pages(url_locations, project_name):
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 545, in _get_pages
    page = self._get_page(location)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 648, in _get_page
    return HTMLPage.get_page(link, session=self.session)
File "/usr/lib/python2.7/dist-packages/pip/index.py", line 757, in get_page
    "Cache-Control": "max-age=600",
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 480, in get
    return self.request('GET', url, **kwargs)
File "/usr/lib/python2.7/dist-packages/pip/download.py", line 378, in request
    return super(PipSession, self).request(method, url, *args, **kwargs)
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 468, in request
    resp = self.send(prep, **send_kwargs)
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 576, in send
    r = adapter.send(request, **kwargs)
File "/usr/share/python-wheels/CacheControl-0.11.5-py2.py3-none-any.whl/cachecontrol/adapter.py", line 46, in send
    resp = super(CacheControlAdapter, self).send(request, **kw)
File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/adapters.py", line 376, in send
    timeout=timeout
File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/connectionpool.py", line 610, in urlopen
    _stacktrace=sys.exc_info()[2])
File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/util/retry.py", line 228, in increment
    total -= 1
TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

I have read the messages in the following pages:

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

https://github.com/pypa/pip/issues/3943

https://github.com/pypa/pip/issues/4133

I'm not using any proxy or firewall (unless you count my router as both, idk).

Body:
This happens to me when I am behind a corporate proxy. To fix that, run with --proxy=urlOfYourProxy.

For example:

pip install --proxy user:password@http://localproxy:8080


问:
How to add DELETE method inside 'do' keyword in config/routes.rb?
I know I can add a new DELETE method on http://localhost:3000/students by editing config/routes.rb:

```<code>resources :students
delete '/students',:to => 'students#destroymany'
</code>```

Note: it is different from DELETE http://localhost:3000/students/1 because  the default DELETE supports deleting 1 student only, while I also want to support DELETE on http://localhost:3000/students/ (without specific student id)

but it has a disadvantage: I need to repeat typing 'students'. Is there any syntax that changes the routing statement to become

```<code>resources :students do
    xxx
end
</code>```

but have the same effect as the beginning version? I tried:

```<code>resources :students do
  delete '',:to => 'students#destroymany'
end
</code>```

but the error occurs:

```<code>No route matches [DELETE] "/students"
</code>```

because it adds the routing to

```<code>/students/:student_id
</code>```

instead of

```<code>/students
</code>```

答:
You could do this instead, for what you are trying to accomplish :</p>

```<code>resource :students do
  collection do
    delete '', to: 'students#destroymany'
  end
end
</code>```

Body:
I know I can add a new DELETE method on http://localhost:3000/students by editing config/routes.rb:

resources :students
delete '/students',:to => 'students#destroymany'

Note: it is different from DELETE http://localhost:3000/students/1 because  the default DELETE supports deleting 1 student only, while I also want to support DELETE on http://localhost:3000/students/ (without specific student id)

but it has a disadvantage: I need to repeat typing 'students'. Is there any syntax that changes the routing statement to become

resources :students do
    xxx
end

but have the same effect as the beginning version? I tried:

resources :students do
  delete '',:to => 'students#destroymany'
end

but the error occurs:

No route matches [DELETE] "/students"

because it adds the routing to

/students/:student_id

instead of

/students

Body:
You could do this instead, for what you are trying to accomplish :

resource :students do
  collection do
    delete '', to: 'students#destroymany'
  end
end


问:
Unfortunately MyApp has stopped. How can I solve this?
I am developing an application, and everytime I run it, I get the message:

Unfortunately, MyApp has stopped.

What can I do to solve this?

About this question - obviously inspired by What is a stack trace, and how can I use it to debug my application errors?, there are lots of questions stating that their application has crashed, without any further detail. This question aims to instruct novice Android programmers on how to try and fix their problems themselves, or ask the right questions.

答:
This popup shows only when you get a fatal exception in your code which stops the execution of the app. It could be any exception NullPointerException, OutOfMemoryException etc.

Best way to check is through Logcat if you are still developing the app in Android studio which is quick way to read stack trace and check the cause of the app.

If your app is already live, then you can not use logcat. So, for that you can implement Crashlytics to provide you bug reports of any exception that occurs.


问:
AdomdConnectionException was unhandled - The connection string is not valid
```<code>     public static void connect()
     {
        try
        {
            string connectionStringStaging = @"Data Source=<server_name>;Catalog=<catalog_name>;User ID=<user_name>;Password=<my_password>";
            string commandText = @"SELECT NON EMPTY { [Measures].[# Opptys moved to Committed] } ON COLUMNS FROM [Model]
                                    CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS";
            AdomdConnection connection = new AdomdConnection(connectionStringStaging);
            connection.Open();
            AdomdCommand cmd = new AdomdCommand(commandText);
            cmd.Connection = connection;
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    Console.WriteLine(reader[0]);
                }
            }
        }
        catch (AdomdConnectionException ex)
        {
            Console.WriteLine("Error : " + ex.ToString());
        }
     }
</code>```

I am using the above code to connect to server and then I am further running MDX queries using this.The problem is the error I am getting - "The connection string is not valid" at line

```<code>connection.open();
</code>```

Are the settings name incorrect which I am using in my connection string?Can someone help me figure out what is wrong in my connection string ?

The stack trace is as follows:

答: I found my answer here. The unofficial package worked just fine . So I installed the reference Unofficial.Microsoft.AnalysisServices.AdomdClient and so the problem was not in the connection string but in the package.

Body:
     public static void connect()
     {
        try
        {
            string connectionStringStaging = @"Data Source=<server_name>;Catalog=<catalog_name>;User ID=<user_name>;Password=<my_password>";
            string commandText = @"SELECT NON EMPTY { [Measures].[# Opptys moved to Committed] } ON COLUMNS FROM [Model]
                                    CELL PROPERTIES VALUE, BACK_COLOR, FORE_COLOR, FORMATTED_VALUE, FORMAT_STRING, FONT_NAME, FONT_SIZE, FONT_FLAGS";
            AdomdConnection connection = new AdomdConnection(connectionStringStaging);
            connection.Open();
            AdomdCommand cmd = new AdomdCommand(commandText);
            cmd.Connection = connection;
            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    Console.WriteLine(reader[0]);
                }
            }
        }
        catch (AdomdConnectionException ex)
        {
            Console.WriteLine("Error : " + ex.ToString());
        }
     }

I am using the above code to connect to server and then I am further running MDX queries using this.The problem is the error I am getting - "The connection string is not valid" at line

connection.open();

Are the settings name incorrect which I am using in my connection string?Can someone help me figure out what is wrong in my connection string ?

The stack trace is as follows:


问:
trigger click on element loaded by ajax
how can i trigger click method of an element loaded by ajax runs on click event of a parent element?

i want it happen of page load time.

答:
I had faced same problem in my experience.

My solution is this.

```<code>jQuery(document).ready(function($){
$("#element_id").bind('click',function(){
alert('click event is triggered');
});

$("#element_id").trigger('click');
});
</code>```

Title: trigger click on element loaded by ajax

Body:
I had faced same problem in my experience.

My solution is this.

jQuery(document).ready(function($){
$("#element_id").bind('click',function(){
alert('click event is triggered');
});

$("#element_id").trigger('click');
});


问:
How to render a template from a folder which does not contain express.static?
I have my loginController as

var User = require('./../models/User.js');

var loginController = {};

loginController.match = function(req, res){

    var username = req.body.username;
    var password = req.body.password;

    User.findOne({username : username, password : password})
    .then(function(user){
        if(user){
            res.render('profile',{
                title : 'Profile',
                user : user
            });
            /*return res.status(200).json({
                success : true,
                data : user
            });*/
        }
        else{
            return res.status(200).json({
                message : "Either username or password is wrong"
            });
        }
    })
    .catch(function(err){
        return res.status(500).json({
            message : err
        })
    });
}

module.exports = loginController;```
</div>
</div>
</p>

<p>which runs as soon as i submit the login credintals.If on correct validation i want to render profile.handlebars and i am able to render it also but i am unable to consume the css which is using served using express.static and is present in a seperate file which is my app.js.</p>

<p>My app.js</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var hbs = require('express-handlebars');
var Path = require('path');

var routes = require('./routes.js');
var app = express();

/*View Engine*/
app.engine('handlebars',hbs({defaultLayout : 'layouts.handlebars', layoutsDir : __dirname + './../views/layouts'}));
app.set('views', Path.join(__dirname, './../views'));
app.set('view engine', 'handlebars');

/*Serve Static files*/
app.use(express.static(__dirname+'./../public'));

mongoose.connect('mongodb://localhost/tournament', function(){
    console.log('connected to tournament..');
});

/*Template Routes*/
/*Login*/
app.get('/', function(req,res,next){
    res.render('login',{
        title : 'Login'
    });
})
/*Profile
app.get('/profile',function(req,res,next){
    res.render('profile',options)
});
*/

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret : "asdasdvbvc234234sdfsdf23213123", resave : false, saveUninitialized : true}));
app.use('/api', routes);

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

My profile.handlebars

            Hello, {{user.username}}
            <button class="btn btn-md btn-danger">Logout</button>

```

答: try changing app.use(express.static(__dirname+'./../public')); to app.use(express.static(Path.join(__dirname, './../public')));

Body:
I have my loginController as

var User = require('./../models/User.js');

var loginController = {};

loginController.match = function(req, res){

    var username = req.body.username;
    var password = req.body.password;

    User.findOne({username : username, password : password})
    .then(function(user){
        if(user){
            res.render('profile',{
                title : 'Profile',
                user : user
            });
            /*return res.status(200).json({
                success : true,
                data : user
            });*/
        }
        else{
            return res.status(200).json({
                message : "Either username or password is wrong"
            });
        }
    })
    .catch(function(err){
        return res.status(500).json({
            message : err
        })
    });
}

module.exports = loginController;

which runs as soon as i submit the login credintals.If on correct validation i want to render profile.handlebars and i am able to render it also but i am unable to consume the css which is using served using express.static and is present in a seperate file which is my app.js.

My app.js

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var hbs = require('express-handlebars');
var Path = require('path');

var routes = require('./routes.js');
var app = express();

/*View Engine*/
app.engine('handlebars',hbs({defaultLayout : 'layouts.handlebars', layoutsDir : __dirname + './../views/layouts'}));
app.set('views', Path.join(__dirname, './../views'));
app.set('view engine', 'handlebars');

/*Serve Static files*/
app.use(express.static(__dirname+'./../public'));

mongoose.connect('mongodb://localhost/tournament', function(){
    console.log('connected to tournament..');
});

/*Template Routes*/
/*Login*/
app.get('/', function(req,res,next){
    res.render('login',{
        title : 'Login'
    });
})
/*Profile
app.get('/profile',function(req,res,next){
    res.render('profile',options)
});
*/

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({secret : "asdasdvbvc234234sdfsdf23213123", resave : false, saveUninitialized : true}));
app.use('/api', routes);

module.exports = app;

My profile.handlebars

            Hello, {{user.username}}
            <button class="btn btn-md btn-danger">Logout</button>


问:
Microsoft Bot Framework WebChat: Add bot image
How to add image of the bot with some welcome text in the middle in Microsoft Bot Framework Web Chat. Seems like quite common functionality and I see images which indicates that is possible.

Anyone knows how to add it?

答:
ok, here is what we end up doing:

```<code><script>
    $(document).ready(function () {
        $(".wc-header").append("<div class='wc-header-welcome'><img src='/Images/bot.png'/><div>Hello! I am your bot</div>");
    });
</script>
</code>```

Hope it will help save time to someone else.

Body:
ok, here is what we end up doing:

<script>
    $(document).ready(function () {
        $(".wc-header").append("<div class='wc-header-welcome'><img src='/Images/bot.png'/><div>Hello! I am your bot</div>");
    });
</script>

Hope it will help save time to someone else.


答:
```<code>var request = require('request')
request('http://localhost:11146/base/bigFile.zip', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});
</code>```

Title: What is the best way to download a big file in NodeJS?

Body:
The below server code is working fine for 5GB file using
 wget http://localhost:11146/base/bigFile.zip but not using client side code.

Server side code.

var http = require("http");
var fs = require("fs");
var filename = "base/bigFile.zip";

var serv = http.createServer(function (req, res) {
    var stat = fs.statSync(filename);
    res.writeHeader(200, {"Content-Length": stat.size});
    var fReadStream = fs.createReadStream(filename);
    fReadStream.on('data', function (chunk) {
       if(!res.write(chunk)){
           fReadStream.pause();
       }
   });
   fReadStream.on('end', function () {
      res.end();
   });
   res.on("drain", function () {
      fReadStream.resume();
   });
});

serv.listen(1114);

Client side code using Request module. What is wrong in this code?

var request = require('request')
request('http:/localhost:11146/base/bigFile.zip', function (error, response, body) {
  console.log('error:', error); // Print the error if one occurred
  console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
  console.log('body:', body); // Print the HTML for the Google homepage.
});

error for above client side code is below -

error: Error: Invalid protocol
    at Request.init (/Users/air/Projects/node_modules/request/request.js:338:51)
    at new Request (/Users/air/Projects//node_modules/request/request.js:105:8)
    at request (/Users/air/Projects/Vertico/Vertico-CLI/node_modules/request/index.js:53:11)
    at Object.<anonymous> (/Users/air/Projects/req.js:2:1)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Function.Module.runMain (module.js:605:10)
statusCode: undefined
body: undefined

I revised client side to use wget shell process instead of request package, that code is below, the problem is - I am not able to see nice download progress of wget, any work around for this code, such that I can see the progress bar in child process.

const fs = require('fs');
   const child_process = require('child_process');

   var workerProcess = child_process.spawn('wget', ['-O','fdsf.zip', 'http://localhost:11146/base/bigFile.zip']);

   workerProcess.stdout.on('data', function (data) {
     console.log('stdout: ' + data);
   });

   workerProcess.stderr.on('data', function (data) {
     //console.log('stderr: ' + data);
   });

   workerProcess.on('close', function (code) {
      console.log('Download Completed' + code);
   });

So finally I want to know how to download a file using client side code written in nodejs?


问:
iText 7.0.2 Destination error
I am learning how to generate pdfs using java code but it seems I can't seem to understand why this error is appearing.

```<code>PdfWriter writer = new PdfWriter(new FileOutputStream("D:/t.pdf"));
PdfDocument pdf = new PdfDocument(writer);
Document doc = new Document(pdf);
doc.add(new Paragraph("Hello World!"));
doc.close();
</code>```

When I try to state a destination folder to output the pdf file to, it constantly shows me an error as shown below. I am not sure why it is doing this. Please provide me with some guidance on how to resolve this. I tried to also not use FileOutputStream and just use the string location instead but it shows the same error.

wait.Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
      at com.itextpdf.io.font.FontRegisterProvider.(FontRegisterProvider.java:65)
      at com.itextpdf.io.font.FontProgramFactory.(FontProgramFactory.java:61)
      at com.itextpdf.kernel.font.PdfFontFactory.createFont(PdfFontFactory.java:215)
      at com.itextpdf.kernel.font.PdfFontFactory.createFont(PdfFontFactory.java:201)
      at com.itextpdf.kernel.font.PdfFontFactory.createFont(PdfFontFactory.java:143)
      at com.itextpdf.kernel.font.PdfFontFactory.createFont(PdfFontFactory.java:92)
      at com.itextpdf.layout.RootElement.getDefaultProperty(RootElement.java:180)
      at com.itextpdf.layout.renderer.AbstractRenderer.getProperty(AbstractRenderer.java:289)
      at com.itextpdf.layout.renderer.AbstractRenderer.getProperty(AbstractRenderer.java:282)
      at com.itextpdf.layout.renderer.AbstractRenderer.getProperty(AbstractRenderer.java:282)
      at com.itextpdf.layout.renderer.AbstractRenderer.getProperty(AbstractRenderer.java:282)
      at com.itextpdf.layout.renderer.TextRenderer.resolveFonts(TextRenderer.java:1045)
      at com.itextpdf.layout.renderer.LineRenderer.resolveChildrenFonts(LineRenderer.java:706)
      at com.itextpdf.layout.renderer.LineRenderer.layout(LineRenderer.java:94)
      at com.itextpdf.layout.renderer.ParagraphRenderer.layout(ParagraphRenderer.java:171)
      at com.itextpdf.layout.renderer.RootRenderer.addChild(RootRenderer.java:111)
      at com.itextpdf.layout.RootElement.add(RootElement.java:108)
      at com.itextpdf.layout.Document.add(Document.java:143)
      at report.GenerateReport.GeneratePDF(GenerateReport.java:136)
      at report.GenerateReport.main(GenerateReport.java:87)
      Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
      at java.net.URLClassLoader.findClass(Unknown Source)
      at java.lang.ClassLoader.loadClass(Unknown Source)
      at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
      at java.lang.ClassLoader.loadClass(Unknown Source)
      ... 20 more

答:
java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory

The error message states that it cannot find the simple logging facade for Java LoggerFactory class.

I.e. you did not add all required JAR files to your code. In particular you seem to have missed the slf4j-api.jar.

Title: iText 7.0.2 Destination error

Body:
I am learning how to generate pdfs using java code but it seems I can't seem to understand why this error is appearing.

PdfWriter writer = new PdfWriter(new FileOutputStream("D:/t.pdf"));
PdfDocument pdf = new PdfDocument(writer);
Document doc = new Document(pdf);
doc.add(new Paragraph("Hello World!"));
doc.close();

When I try to state a destination folder to output the pdf file to, it constantly shows me an error as shown below. I am not sure why it is doing this. Please provide me with some guidance on how to resolve this. I tried to also not use FileOutputStream and just use the string location instead but it shows the same error.

wait.Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
      at com.itextpdf.io.font.FontRegisterProvider.(FontRegisterProvider.java:65)
      at com.itextpdf.io.font.FontProgramFactory.(FontProgramFactory.java:61)
      at com.itextpdf.kernel.font.PdfFontFactory.createFont(PdfFontFactory.java:215)
      at com.itextpdf.kernel.font.PdfFontFactory.createFont(PdfFontFactory.java:201)
      at com.itextpdf.kernel.font.PdfFontFactory.createFont(PdfFontFactory.java:143)
      at com.itextpdf.kernel.font.PdfFontFactory.createFont(PdfFontFactory.java:92)
      at com.itextpdf.layout.RootElement.getDefaultProperty(RootElement.java:180)
      at com.itextpdf.layout.renderer.AbstractRenderer.getProperty(AbstractRenderer.java:289)
      at com.itextpdf.layout.renderer.AbstractRenderer.getProperty(AbstractRenderer.java:282)
      at com.itextpdf.layout.renderer.AbstractRenderer.getProperty(AbstractRenderer.java:282)
      at com.itextpdf.layout.renderer.AbstractRenderer.getProperty(AbstractRenderer.java:282)
      at com.itextpdf.layout.renderer.TextRenderer.resolveFonts(TextRenderer.java:1045)
      at com.itextpdf.layout.renderer.LineRenderer.resolveChildrenFonts(LineRenderer.java:706)
      at com.itextpdf.layout.renderer.LineRenderer.layout(LineRenderer.java:94)
      at com.itextpdf.layout.renderer.ParagraphRenderer.layout(ParagraphRenderer.java:171)
      at com.itextpdf.layout.renderer.RootRenderer.addChild(RootRenderer.java:111)
      at com.itextpdf.layout.RootElement.add(RootElement.java:108)
      at com.itextpdf.layout.Document.add(Document.java:143)
      at report.GenerateReport.GeneratePDF(GenerateReport.java:136)
      at report.GenerateReport.main(GenerateReport.java:87)
      Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
      at java.net.URLClassLoader.findClass(Unknown Source)
      at java.lang.ClassLoader.loadClass(Unknown Source)
      at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
      at java.lang.ClassLoader.loadClass(Unknown Source)
      ... 20 more


问:
GCP: Import data into CloudSQL from local drive
If I need to import sql file from my local drive to GCP's CloudSQL Postgres DB, it seems there is no way to do that.

The docs only talk about importing from Google Cloud Storage. Do I have to buy bucket storage just to import data to CloudSQL, or is there another way?

答:
You can just connect to your Cloud SQL database using a postgres CLI locally and pipe in your local sql file. It will be slower than importing from a GCS bucket if your data is already, but (probably) faster than uploading to GCS and then importing to Cloud SQL from there.

Although, depending on how large the dump is, it's possible that the local CLI's connection may break in the middle of the upload. This can happen for any number of reasons, and the re-connects implemented in the GCS upload and GCS->Cloud SQL import would prevent this from being a problem. So if your import is larger then tens of GBs, depending on your Internet speed, it might better to temporarily put the dump on GCS and then import it to the database.


问:
How to install nodejs 6.x version on centos 6?
I use centos release 6.9

current nodejs version v0.10.48

I want install nodejs 6.x version

and I try

```<code>yum install -y gcc-c++ make
curl -sL https://rpm.nodesource.com/setup_6.x | sudo -E bash -
yum install nodejs
</code>```

but occur error
enter image description here

how to install nodejs 6.x version on centos 6?

答:
The easiest way is use n to switch the node version

To avoid some issue after version changed, please run this command.

npm cache clean -f

Then install n

npm i -g  n

Now, use n install node version you want. (I suggest you lts one.)

n lts

here is n documentation https://github.com/tj/n

Body:
I use centos release 6.9

current nodejs version v0.10.48

I want install nodejs 6.x version

and I try

yum install -y gcc-c++ make
curl -sL https://rpm.nodesource.com/setup_6.x | sudo -E bash -
yum install nodejs

but occur error
enter image description here

how to install nodejs 6.x version on centos 6?


问:
Selenium HtmlUnitDriver clicking on checkbox
I'm trying to get my checkbox clicked while running using selenium.

I have no issue running my test when using chromedriver.
But when I switch to HtmlUnitDriver, it will throw error when it reaches the clicking of checkbox action. The error thrown is

org.openga.selenium.ElementNotVisibleException: You may only interact with visible elements

I've tried multiple methods like:

```<code>driver.findElement(By.xpath("//*[@id=\"chkConfirm\"]")).sendKeys(Keys.SPACE);
driver.findElement(By.xpath("//*[@id=\"chkConfirm\"]")).click();
</code>```

But none of it works. Can someone help me out?

答:
Could you add wait before clicking on the element? See an example below.</p>

```<code>WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\"chkConfirm\"]")));
driver.findElement(By.xpath("//*[@id=\"chkConfirm\"]")).click();
</code>```

Body:
I'm trying to get my checkbox clicked while running using selenium.

I have no issue running my test when using chromedriver.
But when I switch to HtmlUnitDriver, it will throw error when it reaches the clicking of checkbox action. The error thrown is

org.openga.selenium.ElementNotVisibleException: You may only interact with visible elements

I've tried multiple methods like:

driver.findElement(By.xpath("//*[@id=\"chkConfirm\"]")).sendKeys(Keys.SPACE);
driver.findElement(By.xpath("//*[@id=\"chkConfirm\"]")).click();

But none of it works. Can someone help me out?

Body:
Could you add wait before clicking on the element? See an example below.

WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id=\"chkConfirm\"]")));
driver.findElement(By.xpath("//*[@id=\"chkConfirm\"]")).click();


答:
It is different from DELETE http://localhost:3000/students/1, because
  the default DELETE supports deleting 1 student only, while I also want
  to support DELETE on http://localhost:3000/students/ (without specific
  student id)

Well add it on a collection then

```<code>resources :students do
  delete '', :to => 'students#destroymany', on: :collection
end
</code>```

This will give the below route

```<code>DELETE /students(.:format)  students#destroymany
</code>```

So, you can call /students with method: :delete

Title: How to add DELETE method inside 'do' keyword in config/routes.rb?

Body:
It is different from DELETE http://localhost:3000/students/1, because
  the default DELETE supports deleting 1 student only, while I also want
  to support DELETE on http://localhost:3000/students/ (without specific
  student id)

Well add it on a collection then

resources :students do
  delete '', :to => 'students#destroymany', on: :collection
end

This will give the below route

DELETE /students(.:format)  students#destroymany

So, you can call /students with method: :delete


问:
Multiple Threads accessing the database: one with long transaction, one with short transactions
Let's say I have a desktop app that acts as a garage for a bunch of cars:

```<code>@Entity
public class Garage {
    private List<Car> cars = new ArrayList<Car>();
    ...
}
</code>```

The desktop app has a "simulation" button that starts a new thread and starts calling methods on the Garage, Car, Wheel, etc etc.  This simulation can take as long as 10 minutes to run.  At the moment I have a class that looks like this:

```<code>beginTransaction();
Garage garage = garageDao.findGarage(1);
List<Car> cars = garage.getCars();
for (Car car : cars) {
    // call methods on the car to lazily fetch other things like wheels...
}
commitTransaction();
</code>```

This code only does "reads" and never "writes"

So the above can take a long time depending on how badly the cars need a service.  While the above is happening, the user may continue working using the desktop app.  They may choose to change the color of a car that is being used in the above transaction.

My question is whether the above long transaction is going to prevent the changing of the car color?  i.e. the user changing the color of the car in the desktop app will be prevented from committing the change until the long transaction is finished?

答:
As above:

Normally, read-only operations should not block write operations in a database.
So your long, reading thread should not block the short write operations.

I suppose it is possible to configure an isolation level for your database and connection that writes can be blocked by long reading statements but this is NOT the default on any of the database types I know.

Body:
Let's say I have a desktop app that acts as a garage for a bunch of cars:

@Entity
public class Garage {
    private List<Car> cars = new ArrayList<Car>();
    ...
}

The desktop app has a "simulation" button that starts a new thread and starts calling methods on the Garage, Car, Wheel, etc etc.  This simulation can take as long as 10 minutes to run.  At the moment I have a class that looks like this:

beginTransaction();
Garage garage = garageDao.findGarage(1);
List<Car> cars = garage.getCars();
for (Car car : cars) {
    // call methods on the car to lazily fetch other things like wheels...
}
commitTransaction();

This code only does "reads" and never "writes"

So the above can take a long time depending on how badly the cars need a service.  While the above is happening, the user may continue working using the desktop app.  They may choose to change the color of a car that is being used in the above transaction.

My question is whether the above long transaction is going to prevent the changing of the car color?  i.e. the user changing the color of the car in the desktop app will be prevented from committing the change until the long transaction is finished?


问:
How to read column one by one in python pandas?
I have read file from URL as follows :

```<code>    url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"

    names = ['sepal length', 'sepal width', 'petal length', 'petal width',  'class']

    data = pd.read_csv(url, names=names)

    print(data.shape)

    print(data)
</code>```

Now, I want to read one column and do some processing (may be min, max, or std dev, r score etc) and then again read another column and do some processing.

Is there any way to do it in scikit learn/pandas/python?

Body:
I have read file from URL as follows :

    url = "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"

    names = ['sepal length', 'sepal width', 'petal length', 'petal width',  'class']

    data = pd.read_csv(url, names=names)

    print(data.shape)

    print(data)

Now, I want to read one column and do some processing (may be min, max, or std dev, r score etc) and then again read another column and do some processing.

Is there any way to do it in scikit learn/pandas/python?

Body:
You can use describe:

data.describe()

Output:

       sepal length  sepal width  petal length  petal width
count    150.000000   150.000000    150.000000   150.000000
mean       5.843333     3.054000      3.758667     1.198667
std        0.828066     0.433594      1.764420     0.763161
min        4.300000     2.000000      1.000000     0.100000
25%        5.100000     2.800000      1.600000     0.300000
50%        5.800000     3.000000      4.350000     1.300000
75%        6.400000     3.300000      5.100000     1.800000
max        7.900000     4.400000      6.900000     2.500000

Or a single column:

data['petal length'].describe()

Output:

count    150.000000
mean       3.758667
std        1.764420
min        1.000000
25%        1.600000
50%        4.350000
75%        5.100000
max        6.900000
Name: petal length, dtype: float64

Or you can use apply with lambda to do some custom processing by columns.

data.apply(lambda x: x.describe())

Output:

        sepal length  sepal width  petal length  petal width        class
25%         5.100000     2.800000      1.600000     0.300000          NaN
50%         5.800000     3.000000      4.350000     1.300000          NaN
75%         6.400000     3.300000      5.100000     1.800000          NaN
count     150.000000   150.000000    150.000000   150.000000          150
freq             NaN          NaN           NaN          NaN           50
max         7.900000     4.400000      6.900000     2.500000          NaN
mean        5.843333     3.054000      3.758667     1.198667          NaN
min         4.300000     2.000000      1.000000     0.100000          NaN
std         0.828066     0.433594      1.764420     0.763161          NaN
top              NaN          NaN           NaN          NaN  Iris-setosa
unique           NaN          NaN           NaN          NaN            3


问:
Create Azure Service Bus with ACS (for PHP Integration)
I have been trying to setup an ACS namespace to enable access from a PHP integration app. This was an option in the portal but has now been removed, so I'm trying to create the namespace through powershell. As you can see from the commented out lines I have been trying several approaches. The azure environment was setup in the last few weeks.

```<code>#Add-AzureRMAccount
Login-AzureRmAccount -SubscriptionId "my-guid"
#Select-AzureRMSubscription -SubscriptionId "my-guid" | Select-AzureRmSubscription
Get-AzureRmSubscription -SubscriptionId "my-guid" | Select-AzureRmSubscription
New-AzureSBNamespace -Name "myservicebus.servicebus.windows.net" -Location "UK South" -CreateACSNamespace $true -NamespaceType Messaging
</code>```

I have tried several combinations but I keep getting the same error when I call the New-AzureSBNamespace method which is as follows "No Default subscription has been designated"

EDIT: I can now create the namespace / service bus via power shell but don't seem to have  away of creating ACS for it.

```<code>Login-AzureRmAccount -SubscriptionId "2a428947-cc0e-4fa5-aef2-a7ad0fe7a26e"
Get-AzureRmSubscription -SubscriptionId "2a428947-cc0e-4fa5-aef2-a7ad0fe7a26e" | Select-AzureRmSubscription
New-AzureRmServiceBusNamespace -ResourceGroup StevenStone-Shop -NamespaceName my-service-bus -Location UKSouth -SkuName "Basic"
</code>```

The reason why I am trying to do this is so that I can connect via PHP with a connection as shown below:

"Endpoint=[yourEndpoint];SharedSecretIssuer=[Default Issuer];SharedSecretValue=[Default Key]"

https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-php-how-to-use-queues

答:
You may need to add -CreateACSNamespace $true to the command to create a new ACS Service Bus namespace.

```<code>Add-AzureAccount # this will sign you in
New-AzureSBNamespace -CreateACSNamespace $true -Name 'mytestbusname' -Location 'West US' -NamespaceType 'Messaging'
</code>```

If it is successful, you will get the connection string in the PowerShell output. If you get connection errors with it and the connection string looks like Endpoint=sb://..., change it to Endpoint=https://....

For more details, please refer to this post.

Body:
I have been trying to setup an ACS namespace to enable access from a PHP integration app. This was an option in the portal but has now been removed, so I'm trying to create the namespace through powershell. As you can see from the commented out lines I have been trying several approaches. The azure environment was setup in the last few weeks.

#Add-AzureRMAccount
Login-AzureRmAccount -SubscriptionId "my-guid"
#Select-AzureRMSubscription -SubscriptionId "my-guid" | Select-AzureRmSubscription
Get-AzureRmSubscription -SubscriptionId "my-guid" | Select-AzureRmSubscription
New-AzureSBNamespace -Name "myservicebus.servicebus.windows.net" -Location "UK South" -CreateACSNamespace $true -NamespaceType Messaging

I have tried several combinations but I keep getting the same error when I call the New-AzureSBNamespace method which is as follows "No Default subscription has been designated"

EDIT: I can now create the namespace / service bus via power shell but don't seem to have  away of creating ACS for it.

Login-AzureRmAccount -SubscriptionId "2a428947-cc0e-4fa5-aef2-a7ad0fe7a26e"
Get-AzureRmSubscription -SubscriptionId "2a428947-cc0e-4fa5-aef2-a7ad0fe7a26e" | Select-AzureRmSubscription
New-AzureRmServiceBusNamespace -ResourceGroup StevenStone-Shop -NamespaceName my-service-bus -Location UKSouth -SkuName "Basic"

The reason why I am trying to do this is so that I can connect via PHP with a connection as shown below:

"Endpoint=[yourEndpoint];SharedSecretIssuer=[Default Issuer];SharedSecretValue=[Default Key]"

https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-php-how-to-use-queues

Body:
You may need to add -CreateACSNamespace $true to the command to create a new ACS Service Bus namespace.

Add-AzureAccount # this will sign you in
New-AzureSBNamespace -CreateACSNamespace $true -Name 'mytestbusname' -Location 'West US' -NamespaceType 'Messaging'

If it is successful, you will get the connection string in the PowerShell output. If you get connection errors with it and the connection string looks like Endpoint=sb://..., change it to Endpoint=https://....

For more details, please refer to this post.


问:
How to convert Base64 data and NSData into string
i am new in IOS and i am making a project in which i receive Base64 data from web service. how to convert Base64 data into string and how to open a pdf view in swift and also check that is there any pdf owner application install or not in iPhone .and i want to know that how to convert NSDATA in string swift.Help me
example like this is Base64 data
JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nLVcza8ct5GH1rK9ejIU24lkO5GtJ8vWm5E87eY3uXtbYLHAYi8JdItySrABAjhA8v8fUuwmu35kF2fmxbsWDMxjk8VisapYX+TfbudJ6ds5/6s//vj

Like this is nsdata
<25504446 2d312e34 0a25c7ec 8fa20a35 2030206f 626a0a3c 3c2f4c65 6e677468 20362030 20522f46 696c7465 72202f46 6c617465 4465636f 64653e3e 0a737472 65616d0a 789cb55c cdaf1cb7 9187d6b2 bd7a3214 db89643b 91ad27cb d69b913c

答:
From Base64 to Data to String.

```<code>let base64String = "dGhpcyBpcyBmb3IgdGVzdGluZw=="
if let data = Data(base64Encoded: base64String) {
    if let string = String(data: data, encoding: .utf8) {
        print(string)
    }
}
</code>```

From Base64 to NSData to String.

```<code>let data = NSData(base64Encoded: base64String, options: .ignoreUnknownCharacters)
    var string = String(data: data, encoding: .utf8)
}
</code>```

Body:
From Base64 to Data to String.

let base64String = "dGhpcyBpcyBmb3IgdGVzdGluZw=="
if let data = Data(base64Encoded: base64String) {
    if let string = String(data: data, encoding: .utf8) {
        print(string)
    }
}

From Base64 to NSData to String.

let data = NSData(base64Encoded: base64String, options: .ignoreUnknownCharacters)
    var string = String(data: data, encoding: .utf8)
}


问:
Bootstrap Tabs or Alternatives?
Is it possible to have tabs like bootstrap .nav-tabs but instead of an anchor tag it will change the content below it?

Im looking for something like this:

Home

Menu 1

Menu 2

Menu 3

```

But without the anchor tags but will just change the active tab and change the content below it.

If bootstrap is not the best option let me know

答:
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

    <link rel="stylesheet" href="CSS/style.css">
    <title>Template</title>

Home

Menu 1

test

Menu 2

test

Menu 3

test

Title: Bootstrap Tabs or Alternatives?

Body:
Is it possible to have tabs like bootstrap .nav-tabs but instead of an anchor tag it will change the content below it?

Im looking for something like this:

Home

Menu 1

Menu 2

Menu 3

But without the anchor tags but will just change the active tab and change the content below it.

If bootstrap is not the best option let me know

Body:
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <!--<link href="CSS/bootstrap.css" rel="stylesheet">-->
    <link rel="stylesheet" href="CSS/style.css">
    <title>Template</title>
</head>
<body>
<ul class="nav nav-tabs">
    <li><a href="#">Home</a></li>
    <li><a href="#" id="1">Menu 1</a>
    <div class="1">
        <h1>test</h1>
    </div>
    </li>
    <li><a href="#" id="2">Menu 2</a>
    <div class="2">
        <h1>test</h1>
    </div>
    </li>
    <li><a href="#" id="3">Menu 3</a>
        <div class="3">
            <h1>test</h1>
        </div>
    </li>
</ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
    $(function() {
        $('.2, .3')
            .hide();
    });
    $(document).ready(function(){
        $("#1").click(function(){
            $(".2, .3").hide();
            $(".1").show();
        });
        $("#2").click(function(){
            $(".1, .3").hide();
            $(".2").show();
        });
        $("#3").click(function(){
            $(".2, .1").hide();
            $(".3").show();
        });
    });

Ended up using this code Thx @amit


问:
Can you search github network commit messages?
Upon brief Google and SO search, I couldn't find any info on this. I am looking at this Github repo which hasn't been updated for years, but there are many forks that are still being developed actively. Is there any way to search through commit messages from different forks of this Github repo network?</p>

答:
Beside the Google search already mentioned, another more precise alternative, if that repo is not too big, is to:

list all the forks with this API GET /repos/:owner/:repo/forks

clone them, and do a git grep in each of those local clones.

That way, you are sure to have a complete search.

See also the python frost-nzcr4/find_forks script.


问:
UPDATED: How can I Insert a Json object inside a Json Array to SQLite
Good day, How to fetch this Json Response and insert it in Android SQLite.
Hope you will guide me how to fetch this Json object inside a Json Array inside a Object

```<code>{
  "error": false,
  "sl_summ": [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}
</code>```

This my whole JSON response. the 1st Json Object(user) was successfully parse and inserted to database but the 2nd Json response(sl_summ) was unsuccessfully parse and was not inserted. and thats my problem.

```<code>{
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}
{
  "error": false,
  "sl_summ":
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}
</code>```

This is the Logcat message

```<code>D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}
07-05 16:19:15.068 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/ViewRootImpl@dd06ab4[LoginActivity]: dispatchDetachedFromWindow
07-05 16:19:15.083 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/InputTransport: Input channel destroyed: fd=76
07-05 16:19:15.084 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/RegisterActivity: Checking JSON Object{"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
07-05 16:19:15.085 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/TEST: -error attribute             : false
07-05 16:19:15.094 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SessionManager: User login session modified!
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -user object     : {"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -br_code         : 12
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -mem_id          : 13
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -username        : novalyn
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -email           : gsac_tabaco@yahoo.com
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -created at      : 2016-07-22 09:05:21
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: New member was inserted into table members: 13
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: BR CODE: 12
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Member ID: 13
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Username: novalyn
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Email: gsac_tabaco@yahoo.com
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Created at: 2016-07-22 09:05:21
07-05 16:19:15.118 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/sl_summ: JSON String                  : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
07-05 16:19:15.118 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/sl_summ: -error attribute             : false
07-05 16:19:15.119 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/TEST: org.json.JSONException: No value for sl_summ
</code>```

I noticed that only the 1st response was returned

```<code>D/sl_summ: JSON String : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute             : false
D/TEST: org.json.JSONException: No value for sl_summ
</code>```

答:
Here the parsing is called(Passing the response)

```<code>getParsing(response.body().string());
</code>```

Parsing method is here

```<code>public void getParsing(String jsonresponse) {

        try {
            JSONArray responseArray = new JSONArray(jsonresponse);
            for (int i = 0; i < responseArray.length(); i++) {
                JSONObject responseObject = responseArray.getJSONObject(i);
                String mId = responseArray.optString("KEY_TAG to get value ID");
                String mName = responseArray.optString("KEY_TAG to get value Name");
                .
                .

                loginDataBaseAdapter = loginDataBaseAdapter.open();
                loginDataBaseAdapter.insertRole(mId, mName);

                loginDataBaseAdapter.close();

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
</code>```

And your insert query be like

```<code>public void insertRole(String id, String name) {
        String selectQuery = "SELECT  * FROM " + DATABASE_ROLES + " WHERE id = '" + name + "'";
        db = dbHelper.getWritableDatabase();

        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.getCount() > 0) {
            ContentValues newValues = new ContentValues();
            // Assign values for each row.
            newValues.put("id", id);
            newValues.put("name", name);

            int rowsUpdated = db.update(DATABASE_ROLES, newValues, "id= '" + id+ "'", null);
            Log.v("resultState", "resultState==" + rowsUpdated);

        } else {
            ContentValues newValues = new ContentValues();
            // Assign values for each row.
            newValues.put("id", id);
            newValues.put("name", name);

            long result = db.insert(DATABASE_ROLES, null, newValues);
            Log.v("resultState", "resultState==" + result);

        }
        cursor.close();

    }
</code>```

Body:
Good day, How to fetch this Json Response and insert it in Android SQLite.
Hope you will guide me how to fetch this Json object inside a Json Array inside a Object

{
  "error": false,
  "sl_summ": [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}

This my whole JSON response. the 1st Json Object(user) was successfully parse and inserted to database but the 2nd Json response(sl_summ) was unsuccessfully parse and was not inserted. and thats my problem.

{
  "error": false,
  "user": {
    "br_code": 12,
    "mem_id": 13,
    "username": "novalyn",
    "email": "gsac_tabaco@yahoo.com",
    "created_at": "2016-07-22 09:05:21"
  }
}
{
  "error": false,
  "sl_summ":
  [
    {
      "sl_desc": "PA : Savings Account",
      "tr_date": "2015-08-17",
      "actual_balance": "483.67",
      "available_balance": "483.67"
    },
    {
      "sl_desc": "PA : Savings - Cash Bond",
      "tr_date": "2015-08-28",
      "actual_balance": "10129.43",
      "available_balance": "10129.43"
    }
  ]
}

This is the Logcat message

D/RegisterActivity: Login Response: {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}{"error":false,"sl_summ":[{"sl_desc":"PA : Savings Account","tr_date":"2015-08-17","actual_balance":"483.67","available_balance":"483.67"},{"sl_desc":"PA : Savings - Cash Bond","tr_date":"2015-08-28","actual_balance":"10129.43","available_balance":"10129.43"}]}
07-05 16:19:15.068 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/ViewRootImpl@dd06ab4[LoginActivity]: dispatchDetachedFromWindow
07-05 16:19:15.083 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/InputTransport: Input channel destroyed: fd=76
07-05 16:19:15.084 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/RegisterActivity: Checking JSON Object{"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
07-05 16:19:15.085 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/TEST: -error attribute             : false
07-05 16:19:15.094 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SessionManager: User login session modified!
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -user object     : {"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -br_code         : 12
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -mem_id          : 13
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -username        : novalyn
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -email           : gsac_tabaco@yahoo.com
07-05 16:19:15.095 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/USER: -created at      : 2016-07-22 09:05:21
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: New member was inserted into table members: 13
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: BR CODE: 12
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Member ID: 13
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Username: novalyn
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Email: gsac_tabaco@yahoo.com
07-05 16:19:15.117 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/SQLiteHandler: Created at: 2016-07-22 09:05:21
07-05 16:19:15.118 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/sl_summ: JSON String                  : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
07-05 16:19:15.118 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/sl_summ: -error attribute             : false
07-05 16:19:15.119 20514-20514/ph.coredev.johnjessbayutas.gsacmobileportal D/TEST: org.json.JSONException: No value for sl_summ

I noticed that only the 1st response was returned

D/sl_summ: JSON String : {"error":false,"user":{"br_code":12,"mem_id":13,"username":"novalyn","email":"gsac_tabaco@yahoo.com","created_at":"2016-07-22 09:05:21"}}
D/sl_summ: -error attribute             : false
D/TEST: org.json.JSONException: No value for sl_summ

Body:
Here the parsing is called(Passing the response)

getParsing(response.body().string());

Parsing method is here

public void getParsing(String jsonresponse) {

        try {
            JSONArray responseArray = new JSONArray(jsonresponse);
            for (int i = 0; i < responseArray.length(); i++) {
                JSONObject responseObject = responseArray.getJSONObject(i);
                String mId = responseArray.optString("KEY_TAG to get value ID");
                String mName = responseArray.optString("KEY_TAG to get value Name");
                .
                .

                loginDataBaseAdapter = loginDataBaseAdapter.open();
                loginDataBaseAdapter.insertRole(mId, mName);

                loginDataBaseAdapter.close();

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

And your insert query be like

public void insertRole(String id, String name) {
        String selectQuery = "SELECT  * FROM " + DATABASE_ROLES + " WHERE id = '" + name + "'";
        db = dbHelper.getWritableDatabase();

        Cursor cursor = db.rawQuery(selectQuery, null);
        if (cursor.getCount() > 0) {
            ContentValues newValues = new ContentValues();
            // Assign values for each row.
            newValues.put("id", id);
            newValues.put("name", name);

            int rowsUpdated = db.update(DATABASE_ROLES, newValues, "id= '" + id+ "'", null);
            Log.v("resultState", "resultState==" + rowsUpdated);

        } else {
            ContentValues newValues = new ContentValues();
            // Assign values for each row.
            newValues.put("id", id);
            newValues.put("name", name);

            long result = db.insert(DATABASE_ROLES, null, newValues);
            Log.v("resultState", "resultState==" + result);

        }
        cursor.close();

    }