问:
Image path not convert to url in swift3
I have post response i want to download image from image_path

```<code>let fileUrl = NSURL(fileURLWithPath: (posts.value(forKey: "image_path") as! [String])[indexPath.row])
        print(fileUrl as Any) // here i can get path

        if FileManager.default.fileExists(atPath: (fileUrl)// nil value {
            let url = NSURL(string: (posts.value(forKey: "image_path") as! [String])[indexPath.row]) // Here url found nil
            let data = NSData(contentsOf: url! as URL)
            cell.LocationImage?.image = UIImage(data: data! as Data)
        }
</code>```

UPDATE:

S9.png

答:
That URL is not a local file path URL, nor a valid URL accoridng to my browser.

The URL you have provided above returns a server error in the browser and does not return an image. See screenshot

You would need to ensure that the image is accessible and the URL actually returns an image response firstly. Then you would need to download the image. Not sure if you are using any libraries or not so I will post an example without.

```<code>//: Playground - noun: a place where people can play

import UIKit
import XCPlayground
import PlaygroundSupport

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

// random image from images.google.com
let urlString = "https://files.allaboutbirds.net/wp-content/uploads/2015/06/prow-featured-240x135.jpg"

let url = URL(string: urlString)
let session = URLSession.shared

let task = session.dataTask(with: url!) { data, response, error in
    guard error == nil else {
        print("[ERROR] - Failed to download image")
        return
    }

    if let data = data {
        let image = UIImage(data: data)
        DispatchQueue.main.async {
            imageView.image = image
        }
    }
}

let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.addSubview(imageView)

task.resume()
PlaygroundPage.current.liveView = view
</code>```

UPDATE:

Title: Image path not convert to url in swift3

Body:
I have post response i want to download image from image_path

let fileUrl = NSURL(fileURLWithPath: (posts.value(forKey: "image_path") as! [String])[indexPath.row])
        print(fileUrl as Any) // here i can get path

        if FileManager.default.fileExists(atPath: (fileUrl)// nil value {
            let url = NSURL(string: (posts.value(forKey: "image_path") as! [String])[indexPath.row]) // Here url found nil
            let data = NSData(contentsOf: url! as URL)
            cell.LocationImage?.image = UIImage(data: data! as Data)
        }

UPDATE:

S9.png

Body:
That URL is not a local file path URL, nor a valid URL accoridng to my browser.

The URL you have provided above returns a server error in the browser and does not return an image. See screenshot

You would need to ensure that the image is accessible and the URL actually returns an image response firstly. Then you would need to download the image. Not sure if you are using any libraries or not so I will post an example without.

//: Playground - noun: a place where people can play

import UIKit
import XCPlayground
import PlaygroundSupport

let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))

// random image from images.google.com
let urlString = "https://files.allaboutbirds.net/wp-content/uploads/2015/06/prow-featured-240x135.jpg"

let url = URL(string: urlString)
let session = URLSession.shared

let task = session.dataTask(with: url!) { data, response, error in
    guard error == nil else {
        print("[ERROR] - Failed to download image")
        return
    }

    if let data = data {
        let image = UIImage(data: data)
        DispatchQueue.main.async {
            imageView.image = image
        }
    }
}

let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.addSubview(imageView)

task.resume()
PlaygroundPage.current.liveView = view

UPDATE:


来源: stackexchange

问:
how to set path for File Input Stream
i was trying to use a txt file but i got this eror "FileNotFoundException"
but it was readable and it exist but on line FileInputStream i got that error
whats the matter?</p>

```<code>        System.out.println(Files.isReadable(Paths.get("I:/Code/Coding/src/Files/" + path + ".txt")));
        System.out.println(Files.exists(Paths.get("I:/Code/Coding/src/Files/" + path + ".txt")));
        FileInputStream f1=new FileInputStream("I:/Code/Coding/src/Files/" + path + ".txt");
        reader = new ObjectInputStream(f1);

java.io.FileNotFoundException: I:\Code\Coding\src\Files\Artists.txt (The system cannot find the path specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at sample.Datebase.Server.readFiles(Server.java:70)
    at sample.Datebase.Server.run(Server.java:99)
    at sample.Datebase.Server.main(Server.java:54)
Exception in thread "main" java.lang.NullPointerException
    at sample.Datebase.Server.readFiles(Server.java:94)
    at sample.Datebase.Server.run(Server.java:99)
    at sample.Datebase.Server.main(Server.java:54)
</code>```

答:
I had the same problem and i solved it by using File class. Please try this code. maybe your problem will be solved :

```<code>File file = new File("I:/Code/coding/src/Files/" + path + ".txt");
reader = new ObjectInputStream(new FileInputStream(file));
Object o = reader.readObject();
</code>```

ContentLicense: CC BY-SA 3.0

Title: how to set path for File Input Stream

Body:
i was trying to use a txt file but i got this eror "FileNotFoundException"
but it was readable and it exist but on line FileInputStream i got that error
whats the matter?

        System.out.println(Files.isReadable(Paths.get("I:/Code/Coding/src/Files/" + path + ".txt")));
        System.out.println(Files.exists(Paths.get("I:/Code/Coding/src/Files/" + path + ".txt")));
        FileInputStream f1=new FileInputStream("I:/Code/Coding/src/Files/" + path + ".txt");
        reader = new ObjectInputStream(f1);

java.io.FileNotFoundException: I:\Code\Coding\src\Files\Artists.txt (The system cannot find the path specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at java.io.FileInputStream.<init>(FileInputStream.java:93)
    at sample.Datebase.Server.readFiles(Server.java:70)
    at sample.Datebase.Server.run(Server.java:99)
    at sample.Datebase.Server.main(Server.java:54)
Exception in thread "main" java.lang.NullPointerException
    at sample.Datebase.Server.readFiles(Server.java:94)
    at sample.Datebase.Server.run(Server.java:99)
    at sample.Datebase.Server.main(Server.java:54)

Body:
I had the same problem and i solved it by using File class. Please try this code. maybe your problem will be solved :

File file = new File("I:/Code/coding/src/Files/" + path + ".txt");
reader = new ObjectInputStream(new FileInputStream(file));
Object o = reader.readObject();

ContentLicense: CC BY-SA 4.0


问:
Arduino Adafruit Neonpixel returns 0 pixels
I am working on a project where I am required to work with a WS2812B LED strip that has 360 LEDs. I am using Adafruit_NeoPixel.h library to drive the LED strip. I have a class called lights which are responsible for driving the LEDs.

Here is a snippet of my code:

//---- in Lights.h
private:

   Adafruit_NeoPixel m_LedStrip;
//----------------------------------------

//--- in Lights.cpp

Lights::Lights()
{
   m_LedStrip = Adafruit_NeoPixel(360, m_LedPin, NEO_GRB + NEO_KHZ800);

   #if defined (__AVR_ATtiny85__)
      if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
   #endif

   m_LedStrip.begin();

   Serial.print("m_LedStrip.numPixels() is ");
   Serial.println(m_LedStrip.numPixels());
}

//----------------------------------------
```

<p>I am working on Arduino Nano w/ATmega328 by the way.</p>

<p>Now, <code>m_LedStrips.numPixels()</code> shows that it have 0 pixels. Strangely it works when I put the number of pixels to something smaller. 360 also works on my prototype code that only has lights control. I suspect that this might be a memory issue but my Arduino memory is not even full. Here are the memory usage stats.</p>

```Program size: 9,186 bytes (used 30% of a 30,720 byte maximum) (1.64 secs)
Minimum Memory Usage: 928 bytes (45% of a 2048 byte maximum)
```

Can someone give some advice as to how I can fix this issue?

答:
360 LEDs with 3 bytes per pixel takes 1080 bytes of memory.

The Adafruit_NeoPixel library dynamically allocates memory, that's why you don't see that memory usage during compile time.

Together with your 928 bytes at compile time, it uses 2008 bytes of memory. At 2048 bytes being the maximum, that is 98% of your memory used. And you would still need memory for the stack.

You will either need to reduce the memory usage of your other code or get a MCU with more memory.

Body:
I am working on a project where I am required to work with a WS2812B LED strip that has 360 LEDs. I am using Adafruit_NeoPixel.h library to drive the LED strip. I have a class called lights which are responsible for driving the LEDs.

Here is a snippet of my code:

//---- in Lights.h
private:

   Adafruit_NeoPixel m_LedStrip;
//----------------------------------------

//--- in Lights.cpp

Lights::Lights()
{
   m_LedStrip = Adafruit_NeoPixel(360, m_LedPin, NEO_GRB + NEO_KHZ800);

   #if defined (__AVR_ATtiny85__)
      if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
   #endif

   m_LedStrip.begin();

   Serial.print("m_LedStrip.numPixels() is ");
   Serial.println(m_LedStrip.numPixels());
}

//----------------------------------------

I am working on Arduino Nano w/ATmega328 by the way.

Now, m_LedStrips.numPixels() shows that it have 0 pixels. Strangely it works when I put the number of pixels to something smaller. 360 also works on my prototype code that only has lights control. I suspect that this might be a memory issue but my Arduino memory is not even full. Here are the memory usage stats.

Program size: 9,186 bytes (used 30% of a 30,720 byte maximum) (1.64 secs)
Minimum Memory Usage: 928 bytes (45% of a 2048 byte maximum)

Can someone give some advice as to how I can fix this issue?


问:
can the caller function close the xml reader resource
I have the following function which takes url path and gets the reader. As i cannot close the reader and return it. Can the caller close the returned reader object.  </p>

```<code>public  XmlReader GetXMLContent(string Path)
        {
         XmlTextReader responseReader= new XmlTextReader(XmlUrlPath);
         return responseReader;
        }

 XmlTextReader myReader =  GetXMLContent("http://sample.xml");
 while() // loop through all the elements
 {
 }

 myReader.close(); // close the reader
</code>```

答:
You should not use the XmlTextReader constructor. You should use the facrory method in XmlReader. As described in the docs:

In the .NET Framework version 2.0
  release, the recommended practice is
  to create XmlReader instances using
  the XmlReader.Create method. This
  allows you to take full advantage of
  the new features introduced in this
  release.

Unless your method was simplified for this post, this would also make you method obsolete.

```<code>using (XmlReader r = XmlReader.Create("http://sample.xml"))
{
   // read
}
</code>```

In case you need that method, you'd do it this way:

```<code>public XmlReader GetXMLContent(string path)
{
    XmlReader responseReader = XmlReader.Create(path);
    // do something special
    return responseReader;
}

using(XmlReader r = this.GetXMLContent("http://sample.xml"))
{
    // read
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following function which takes url path and gets the reader. As i cannot close the reader and return it. Can the caller close the returned reader object.

public  XmlReader GetXMLContent(string Path)
        {
         XmlTextReader responseReader= new XmlTextReader(XmlUrlPath);
         return responseReader;
        }

 XmlTextReader myReader =  GetXMLContent("http://sample.xml");
 while() // loop through all the elements
 {
 }

 myReader.close(); // close the reader

Body:
You should not use the XmlTextReader constructor. You should use the facrory method in XmlReader. As described in the docs:

In the .NET Framework version 2.0
  release, the recommended practice is
  to create XmlReader instances using
  the XmlReader.Create method. This
  allows you to take full advantage of
  the new features introduced in this
  release.

Unless your method was simplified for this post, this would also make you method obsolete.

using (XmlReader r = XmlReader.Create("http://sample.xml"))
{
   // read
}

In case you need that method, you'd do it this way:

public XmlReader GetXMLContent(string path)
{
    XmlReader responseReader = XmlReader.Create(path);
    // do something special
    return responseReader;
}

using(XmlReader r = this.GetXMLContent("http://sample.xml"))
{
    // read
}


问:
Access to network usage history and statistics before Marshmallow
Using Neworkstats manager i am able to access to network usage history and statistics from marshmallow devices.If that app runs in below marshmallow unfortunately stopping with the below error.

Caused by: java.lang.ClassNotFoundException: Didn't find class "android.app.usage.NetworkStatsManager" on path

My app shoul work below and after marshmallow devices.How can i achieve this.Any help appreciated...

Thanks in advance.....

答: As you can see here https://developer.android.com/reference/android/app/usage/NetworkStatsManager.html this class was added in API 23. Meaning you can't access that data prior to 6.0. What you can try to do for < 6.0 is count traffic for your application using this class: https://developer.android.com/reference/android/net/TrafficStats.html</p>


问:
Disable output of hardcoded HTML tags in a PHP file
I am working with a software written in PHP that I have no control over. Some of the PHP files have hardcoded HTML tags in them that I'd like to suppress or exchange with my own code.

Fortunately there is a plugin-system that allows me to execute my own code at certain points, here's an example of the files I'm dealing with:

```<code><!DOCTYPE html>
<html>
  <?php
    execute_plugin_code_1()
  ?>
  <head>
  <!-- some additional tags -->
  </head>
  <?php
    execute_plugin_code_2()
  ?>
  <body>
  </body>
</html>
</code>```

What I want to do here is generate my own  tag. I don't want to alter the file itself so I'd like to suppress the hardcoded tag and its children.

Is there any way to disable the output of hardcoded HTML between execute_plugin_code_1() and execute_plugin_code_2()?

答:
Do you want to avoid jquery? If not, then

```<code>$(document).ready(function(){
    $('head').remove();
)};
</code>```

https://api.jquery.com/remove/

Then you'd need to also use jquery to insert your new head tag's html. I'd be very wary, though. Seems like it'd be pretty easy to break the page altogether.

Body:
I am working with a software written in PHP that I have no control over. Some of the PHP files have hardcoded HTML tags in them that I'd like to suppress or exchange with my own code.

Fortunately there is a plugin-system that allows me to execute my own code at certain points, here's an example of the files I'm dealing with:

<!DOCTYPE html>

  <?php
    execute_plugin_code_1()
  ?>

  <?php
    execute_plugin_code_2()
  ?>

What I want to do here is generate my own  tag. I don't want to alter the file itself so I'd like to suppress the hardcoded tag and its children.

Is there any way to disable the output of hardcoded HTML between execute_plugin_code_1() and execute_plugin_code_2()?

Body:
Do you want to avoid jquery? If not, then

$(document).ready(function(){
    $('head').remove();
)};

https://api.jquery.com/remove/

Then you'd need to also use jquery to insert your new head tag's html. I'd be very wary, though. Seems like it'd be pretty easy to break the page altogether.


问:
Upload APK not working
I have a problem when I'm publishing my app in play Store, and I'm having a huge problem: it stops at 40% and I don't know the reason!?

答: Upload signed APK replace of build APK.</p>

Title: Upload APK not working

Body: Upload signed APK replace of build APK.


问:
How do I know how many partitions a DynamoDB table is spread over?
Amazon's DynamoDB in designed for guaranteed performances. A customer must provision throughput for each of it's tables.

To achieve this performances, tables are transparently spread over multiple "servers" AKA "partitions".

Amazon provides us with a "best practice" guide for dimensioning and optimizing the throughput. In this guide, we are told that the provisioned throughput is evenly divided over the partitions. In other words, If the requests are not evenly distributed over the partitions, only a fraction of the reserved (and paid) throughput will be available to the application.

In the worst case scenario, it will be:

```<code>worst_throughput = provisioned_and_paid_throughput / partitions
</code>```

To estimate this "worst_throughput", I need to know the total number of partitions. Where can I find it or how do I estimate it ?

答:
See this page: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GuidelinesForTables.html#GuidelinesForTables.Partitions

Which has some simple calculations you can carry out based on the amount of read and write capacity you provision.  Note that this is only for initial capacity.  As your usage of dynamodb continues, these calculations will have less and less relevance.

A single partition can hold approximately 10 GB of data, and can support a maximum of 3,000 read capacity units or 1,000 write capacity units.

Body:
Amazon's DynamoDB in designed for guaranteed performances. A customer must provision throughput for each of it's tables.

To achieve this performances, tables are transparently spread over multiple "servers" AKA "partitions".

Amazon provides us with a "best practice" guide for dimensioning and optimizing the throughput. In this guide, we are told that the provisioned throughput is evenly divided over the partitions. In other words, If the requests are not evenly distributed over the partitions, only a fraction of the reserved (and paid) throughput will be available to the application.

In the worst case scenario, it will be:

worst_throughput = provisioned_and_paid_throughput / partitions

To estimate this "worst_throughput", I need to know the total number of partitions. Where can I find it or how do I estimate it ?


问:
jQuery selector for li whose first child is a span
here is an HTML structure I can't change:

I successfully attached a click event handler for those li's, like so:

```<code>$(document).on("click", "#menu li.top-level", function (e) {

     // whatever code

});
</code>```

However, I don't want the clicks on li's that have the z-index: auto to be caught by the handler. I tried this:

```<code>$(document).on("click", "#menu li.top-level[style='z-index: auto;']", function (e) {
</code>```

and

```<code>$(document).on("click", "#menu li[style='z-index: auto;'].top-level", function (e) {
</code>```

but no luck.

Also, the li's I want to catch in the handler have a  as first child, while the others have a . Maybe this can be used to help?

EDIT

Here is the HTML structure: I want to catch the upper li, not the other one

答:
If the first child of the li elements you want is guaranteed to be an a while that of the ones you don't is always a span, you're better off selecting based on that condition instead since matching elements by their styles is often fragile:

```<code>$(document).on("click", "#menu li.top-level:has(> a:first-child)", function (e) {
</code>```

Body:
here is an HTML structure I can't change:

I successfully attached a click event handler for those li's, like so:

$(document).on("click", "#menu li.top-level", function (e) {

     // whatever code

});

However, I don't want the clicks on li's that have the z-index: auto to be caught by the handler. I tried this:

$(document).on("click", "#menu li.top-level[style='z-index: auto;']", function (e) {

and

$(document).on("click", "#menu li[style='z-index: auto;'].top-level", function (e) {

but no luck.

Also, the li's I want to catch in the handler have a  as first child, while the others have a . Maybe this can be used to help?

EDIT

Here is the HTML structure: I want to catch the upper li, not the other one

Body:
If the first child of the li elements you want is guaranteed to be an a while that of the ones you don't is always a span, you're better off selecting based on that condition instead since matching elements by their styles is often fragile:

$(document).on("click", "#menu li.top-level:has(> a:first-child)", function (e) {


问:
Prevent decorView background from blinking while in transition
I'm creating transitions for my activities. I already set to exclude Navigation and Status Bar from transition:

```<code>    <targets>
        <target android:excludeId="@android:id/statusBarBackground"/>
        <target android:excludeId="@android:id/navigationBarBackground"/>
    </targets>
</code>```

My problem is that I set the app background using:

```<code>    getWindow().getDecorView().setBackgroundColor(COLOR);
</code>```

And because of that, when my transition starts or finishes, this color I set before, blinks on screen between transitions. How could I prevent that? Is there any id I could put inside targets?

答:
From Transition#getTargets():

Returns the list of target views that this transition limits itself to tracking and animating. If the list is null or empty for getTargetIds(), getTargets(), getTargetNames(), and getTargetTypes() then this transition is not limited to specific views, and will handle changes to any views in the hierarchy of a scene change.

Transitions API will use getTargets() of the specified Transition in order to find out which Views need to be obtained. And as long as you have not explicitly specified a target view for the transition, then the whole view hierarchy would be obtained for changes. Hence, decorView will also participate in transition. Instead, you can specify as target the root of your view hierarchy, thus eliminating decorView from transition:

```<code><fade xmlns:android="http://schemas.android.com/apk/res/android">

  <targets>
    <target android:excludeId="@android:id/statusBarBackground"/>
    <target android:excludeId="@android:id/navigationBarBackground"/>
    <target android:targetId="@id/root"/>
  </targets>

</fade>
</code>```

Is there any id I could put inside targets?

decorView has no id associated with it, that's why it's not possible to do via xml. You can inflate/acquire the Transition for the current window and add/exclude targets programmatically:

```
<code>
    Transition t = new Fade();

    // Inflating a transition from /transition/my_transition.xml
    // t = TransitionInflater.from(this).inflateTransition(R.transition.my_transition);

    // If transition is set through theme via `android:windowExitTransition`
    // t = getWindow().getExitTransition();

    // Adding a target
    // t.addTarget(rootView);

    // Excluding decorView, which will exclude all children too
    t.excludeTarget(getWindow().getDecorView(), true);
    t.excludeTarget(android.R.id.statusBarBackground, true);
    t.excludeTarget(android.R.id.navigationBarBackground, true);

    getWindow().setExitTransition(t);
</code>
```

Body:
I'm creating transitions for my activities. I already set to exclude Navigation and Status Bar from transition:

    <targets>
        <target android:excludeId="@android:id/statusBarBackground"/>
        <target android:excludeId="@android:id/navigationBarBackground"/>
    </targets>

My problem is that I set the app background using:

    getWindow().getDecorView().setBackgroundColor(COLOR);

And because of that, when my transition starts or finishes, this color I set before, blinks on screen between transitions. How could I prevent that? Is there any id I could put inside targets?

Body:
From Transition#getTargets():

Returns the list of target views that this transition limits itself to tracking and animating. If the list is null or empty for getTargetIds(), getTargets(), getTargetNames(), and getTargetTypes() then this transition is not limited to specific views, and will handle changes to any views in the hierarchy of a scene change.

Transitions API will use getTargets() of the specified Transition in order to find out which Views need to be obtained. And as long as you have not explicitly specified a target view for the transition, then the whole view hierarchy would be obtained for changes. Hence, decorView will also participate in transition. Instead, you can specify as target the root of your view hierarchy, thus eliminating decorView from transition:

<fade xmlns:android="http://schemas.android.com/apk/res/android">

  <targets>
    <target android:excludeId="@android:id/statusBarBackground"/>
    <target android:excludeId="@android:id/navigationBarBackground"/>
    <target android:targetId="@id/root"/>
  </targets>

</fade>

Is there any id I could put inside targets?

decorView has no id associated with it, that's why it's not possible to do via xml. You can inflate/acquire the Transition for the current window and add/exclude targets programmatically:

    Transition t = new Fade();

    // Inflating a transition from /transition/my_transition.xml
    // t = TransitionInflater.from(this).inflateTransition(R.transition.my_transition);

    // If transition is set through theme via `android:windowExitTransition`
    // t = getWindow().getExitTransition();

    // Adding a target
    // t.addTarget(rootView);

    // Excluding decorView, which will exclude all children too
    t.excludeTarget(getWindow().getDecorView(), true);
    t.excludeTarget(android.R.id.statusBarBackground, true);
    t.excludeTarget(android.R.id.navigationBarBackground, true);

    getWindow().setExitTransition(t);


问:
unable to click on Image Button

how do i click on the mage button
i tried with xpath and id below are the mentioned code that i had tried
    driver.findElementById("btn_google").click();
//      driver.findElementByName("Login with Google+").click();
        //driver.findElementByXPath("//android.widget.ImageButton[@content-desc='Login with Google+',@resource-id,'btn_google']").click();
    //  driver.findElementByXPath("//android.widget.Button[contains(@resource-id,'btn_google') and @content-desc,'Login with Google+']").click();

```<code>//  driver.findElementByXPath("//*[@class='android.widget.ImageButton' and @resource-id='btn_google']").click();

    //driver.findElementByName("Login with Google+").click();;
     WebElement element=driver.findElementByXPath("//*[@class='android.widget.ImageButton' and @resource-id='btn_google']");
    TouchAction action = new TouchAction(driver);
    action.longPress(element).release().perform();

    //driver.findElement(By.xpath("//android.widget.ImageButton[@content-desct='Login with Google+']")).click();
</code>```

//      WebElement googlebutton= driver.findElementByXPath("//android.widget.ImageButton[@resource-id='com.zipgo.customer:id/btn_google']");
//      googlebutton.click();

答:
You can simply find the id of that imagebutton like:

```<code>googleImageButton=(ImageButton)findViewById(R.id.googleImageButton);
</code>```

And now you can call a listener method for any operation, for eg:

```<code>googleImageButton.setOnClickListener(googleImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //action
            }
        });)
</code>```

Title: unable to click on Image Button

Body:
how do i click on the mage button
i tried with xpath and id below are the mentioned code that i had tried
    driver.findElementById("btn_google").click();
//      driver.findElementByName("Login with Google+").click();
        //driver.findElementByXPath("//android.widget.ImageButton[@content-desc='Login with Google+',@resource-id,'btn_google']").click();
    //  driver.findElementByXPath("//android.widget.Button[contains(@resource-id,'btn_google') and @content-desc,'Login with Google+']").click();

//  driver.findElementByXPath("//*[@class='android.widget.ImageButton' and @resource-id='btn_google']").click();

    //driver.findElementByName("Login with Google+").click();;
     WebElement element=driver.findElementByXPath("//*[@class='android.widget.ImageButton' and @resource-id='btn_google']");
    TouchAction action = new TouchAction(driver);
    action.longPress(element).release().perform();

    //driver.findElement(By.xpath("//android.widget.ImageButton[@content-desct='Login with Google+']")).click();

//      WebElement googlebutton= driver.findElementByXPath("//android.widget.ImageButton[@resource-id='com.zipgo.customer:id/btn_google']");
//      googlebutton.click();

Body:
You can simply find the id of that imagebutton like:

googleImageButton=(ImageButton)findViewById(R.id.googleImageButton);

And now you can call a listener method for any operation, for eg:

googleImageButton.setOnClickListener(googleImageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               //action
            }
        });)


问:
First and last value of window function in one row in PostgreSQL
I'd like to have first value of one column and last value of second column in one row for a specified partition. For that I created this query:

```<code>SELECT DISTINCT
b.machine_id,
batch,
timestamp_sta,
timestamp_stp,
FIRST_VALUE(timestamp_sta) OVER w AS batch_start,
LAST_VALUE(timestamp_stp) OVER w AS batch_end
FROM db_data.sta_stp AS a
JOIN db_data.ll_lu AS b
ON a.ll_lu_id=b.id
WINDOW w AS (PARTITION BY batch, machine_id ORDER BY timestamp_sta)
ORDER BY timestamp_sta, batch, machine_id;
</code>```

But as you can see in the image, returned data in batch_end column are not correct.

batch_start column has correct first value of timestamp_sta column. However batch_end should be "2012-09-17 10:49:45" and it equals timestamp_stp from same row.

Why is it so?

答:
The explanations given by @Łukasz Kamiński solve the core of the issue.

However, the last_value should be replaced by max(). You are sorting by timestamp_sta so the last value is the one having the greatest timestamp_sta, which may or may not be related to timestamp_stp. Also I would sort by the two fields.

```<code>SELECT DISTINCT
  b.machine_id,
  batch,
  timestamp_sta,
  timestamp_stp,
  FIRST_VALUE(timestamp_sta) OVER w AS batch_start,
  MAX(timestamp_stp) OVER w AS batch_end
FROM db_data.sta_stp AS a
JOIN db_data.ll_lu AS b
ON a.ll_lu_id=b.id
WINDOW w AS (PARTITION BY batch, machine_id
             ORDER BY timestamp_sta,timestamp_stp
             RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
ORDER BY timestamp_sta, batch, machine_id;
</code>```

http://rextester.com/UTDE60342

Body:
I'd like to have first value of one column and last value of second column in one row for a specified partition. For that I created this query:

SELECT DISTINCT
b.machine_id,
batch,
timestamp_sta,
timestamp_stp,
FIRST_VALUE(timestamp_sta) OVER w AS batch_start,
LAST_VALUE(timestamp_stp) OVER w AS batch_end
FROM db_data.sta_stp AS a
JOIN db_data.ll_lu AS b
ON a.ll_lu_id=b.id
WINDOW w AS (PARTITION BY batch, machine_id ORDER BY timestamp_sta)
ORDER BY timestamp_sta, batch, machine_id;

But as you can see in the image, returned data in batch_end column are not correct.

batch_start column has correct first value of timestamp_sta column. However batch_end should be "2012-09-17 10:49:45" and it equals timestamp_stp from same row.

Why is it so?

Body:
The explanations given by @Łukasz Kamiński solve the core of the issue.

However, the last_value should be replaced by max(). You are sorting by timestamp_sta so the last value is the one having the greatest timestamp_sta, which may or may not be related to timestamp_stp. Also I would sort by the two fields.

SELECT DISTINCT
  b.machine_id,
  batch,
  timestamp_sta,
  timestamp_stp,
  FIRST_VALUE(timestamp_sta) OVER w AS batch_start,
  MAX(timestamp_stp) OVER w AS batch_end
FROM db_data.sta_stp AS a
JOIN db_data.ll_lu AS b
ON a.ll_lu_id=b.id
WINDOW w AS (PARTITION BY batch, machine_id
             ORDER BY timestamp_sta,timestamp_stp
             RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
ORDER BY timestamp_sta, batch, machine_id;

http://rextester.com/UTDE60342


问:
Key Value Pair in C Language
I am new to C programming and I am trying to create a key value structure as in Perl Programming. I saw one solution like :-

```<code>struct key_value
{
   int key;
   char* value;
};

struct key_value kv;

kv.key = 1;
kv.value = "foo";
</code>```

But I don't know how to access these values from this structure. Can someone enlight on this ?

答:
What you are missing is a collection. Most languages have a data type called a dictionary or a map or an associative array or some variation thereof. C does not have a data structure of this type; in fact, the only collection type you have built in to C is the array. So, if you want something where you can supply a key and get the value, you have to roll your own or find one on the Internet. The latter is probably preferable because you are likely to make mistakes and produce a slow data structure if you roll your own (especially if you are a beginner).

To give you a flavour of what you'll end up with, here's a simple example:

You'll need something to represent the collection; call it a ListMap for now:

```<code>struct ListMap;
</code>```

The above is called an incomplete type. For now, we are not concerned with what's in it. You can't do anything with it except pass pointers to instances around.

You need a function to insert items into your collection. Its prototype would look something like this:

```<code>bool listMapInsert(struct ListMap* collection, int key, const char* value);
// Returns true if insert is successful, false if the map is full in some way.
</code>```

And you need a function to retrieve the value for any one key.

```<code>const char* listMapValueForKey(struct ListMap* collection, int key);
</code>```

You also need a function to initialise the collection:

```<code>struct ListMap* newListMap();
</code>```

and to throw it away:

```<code>void freeListMap(struct ListMap* listMap);
</code>```

The hard bit is implementing how those functions do what they do. Anyway, here's how you would use them:

```<code>struct ListMap* myMap = newListMap();
listMapInsert(myMap, 1, "foo");
listMapInsert(myMap, 1729, "taxi");
listMapInsert(myMap, 28, "perfect");

char* value = listMapValueForKey(myMap, 28); // perfect
freeListMap(myMap);
</code>```

Here's a simple implementation. This is just for illustration because I haven't tested it and searching for entries increases linearly with the number of entries (you can do much better than that with hash tables and other structures).

```<code>enum
{
    listMapCapacity = 20
};
struct ListMap
{
    struct key_value kvPairs[listMapCapacity];
    size_t count;
};

struct ListMap* newListMap()
{
    struct ListMap* ret = calloc(1, sizeof *ret);
    ret->count = 0; // not strictly necessary because of calloc
    return ret;
}

bool listMapInsert(struct ListMap* collection, int key, const char* value)
{
    if (collection->count == listMapCapacity)
    {
        return false;
    }
    collection->kvPairs[count].key = key;
    collection->kvPairs[count].value = strdup(value);
    count++;
    return true;
}

const char* listMapValueForKey(struct ListMap* collection, int key)
{
    const char* ret = NULL;
    for (size_t i = 0 ; i < collection->count && ret == NULL ; ++i)
    {
        if (collection->kvPairs[i].key == key)
        {
            ret = kvPairs[i].value;
        }
    }
    return ret;
}

void freeListMap(struct ListMap* listMap)
{
    if (listMap == NULL)
    {
        return;
    }
    for (size_t i = 0 ; i < listMap->count ; ++i)
    {
        free(listMap->kvPair[i].value);
    }
    free(listMap);
}
</code>```

Title: Key Value Pair in C Language

Body:
I am new to C programming and I am trying to create a key value structure as in Perl Programming. I saw one solution like :-

struct key_value
{
   int key;
   char* value;
};

struct key_value kv;

kv.key = 1;
kv.value = "foo";

But I don't know how to access these values from this structure. Can someone enlight on this ?

Body:
What you are missing is a collection. Most languages have a data type called a dictionary or a map or an associative array or some variation thereof. C does not have a data structure of this type; in fact, the only collection type you have built in to C is the array. So, if you want something where you can supply a key and get the value, you have to roll your own or find one on the Internet. The latter is probably preferable because you are likely to make mistakes and produce a slow data structure if you roll your own (especially if you are a beginner).

To give you a flavour of what you'll end up with, here's a simple example:

You'll need something to represent the collection; call it a ListMap for now:

struct ListMap;

The above is called an incomplete type. For now, we are not concerned with what's in it. You can't do anything with it except pass pointers to instances around.

You need a function to insert items into your collection. Its prototype would look something like this:

bool listMapInsert(struct ListMap* collection, int key, const char* value);
// Returns true if insert is successful, false if the map is full in some way.

And you need a function to retrieve the value for any one key.

const char* listMapValueForKey(struct ListMap* collection, int key);

You also need a function to initialise the collection:

struct ListMap* newListMap();

and to throw it away:

void freeListMap(struct ListMap* listMap);

The hard bit is implementing how those functions do what they do. Anyway, here's how you would use them:

struct ListMap* myMap = newListMap();
listMapInsert(myMap, 1, "foo");
listMapInsert(myMap, 1729, "taxi");
listMapInsert(myMap, 28, "perfect");

char* value = listMapValueForKey(myMap, 28); // perfect
freeListMap(myMap);

Here's a simple implementation. This is just for illustration because I haven't tested it and searching for entries increases linearly with the number of entries (you can do much better than that with hash tables and other structures).

enum
{
    listMapCapacity = 20
};
struct ListMap
{
    struct key_value kvPairs[listMapCapacity];
    size_t count;
};

struct ListMap* newListMap()
{
    struct ListMap* ret = calloc(1, sizeof *ret);
    ret->count = 0; // not strictly necessary because of calloc
    return ret;
}

bool listMapInsert(struct ListMap* collection, int key, const char* value)
{
    if (collection->count == listMapCapacity)
    {
        return false;
    }
    collection->kvPairs[count].key = key;
    collection->kvPairs[count].value = strdup(value);
    count++;
    return true;
}

const char* listMapValueForKey(struct ListMap* collection, int key)
{
    const char* ret = NULL;
    for (size_t i = 0 ; i < collection->count && ret == NULL ; ++i)
    {
        if (collection->kvPairs[i].key == key)
        {
            ret = kvPairs[i].value;
        }
    }
    return ret;
}

void freeListMap(struct ListMap* listMap)
{
    if (listMap == NULL)
    {
        return;
    }
    for (size_t i = 0 ; i < listMap->count ; ++i)
    {
        free(listMap->kvPair[i].value);
    }
    free(listMap);
}


问:
Convert JSONObject to JSONArray in Android JAVA?
I am trying to prepare JSON data for an ArrayAdapter to add to a listView.

A breakdown of the JSON I am digesting from a server is such:

```<code>{
"friends": {
            "mufasa3": "false",
            "jenkins": "false"
           }
}
</code>```

I convert this JSON to a java JSONObject like:

```<code>try {
                JSONObject obj = new JSONObject(jsonDigest);

                Object thelist = obj.get("friends");

                }

            }catch(JSONException e){
                throw new RuntimeException(e);
            }
</code>```

How do I convert Object thelist to an Array so that I can use it with a my custom ArrayAdapter?
I've tried JSONArray arr = obj.toJSONArray("friends"); but errors because there is no existing array in the JSONObject.

答:
Don't

```<code>  Object thelist = obj.get("friends");
</code>```

I've tried JSONArray arr = obj.toJSONArray("friends");

Why you using toJSONArray ? .JSON ARRAY is not present there.

Do

```<code> JSONObject sys  = obj.getJSONObject("friends");
</code>```

Finally

```<code>JSONObject obj = new JSONObject(jsonDigest);
JSONObject sys  = obj.getJSONObject("friends");
String str_MUFA = sys.getString("mufasa3");
String str_JENK = sys.getString("jenkins");
</code>```

Body:
I am trying to prepare JSON data for an ArrayAdapter to add to a listView.

A breakdown of the JSON I am digesting from a server is such:

{
"friends": {
            "mufasa3": "false",
            "jenkins": "false"
           }
}

I convert this JSON to a java JSONObject like:

try {
                JSONObject obj = new JSONObject(jsonDigest);

                Object thelist = obj.get("friends");

                }

            }catch(JSONException e){
                throw new RuntimeException(e);
            }

How do I convert Object thelist to an Array so that I can use it with a my custom ArrayAdapter?
I've tried JSONArray arr = obj.toJSONArray("friends"); but errors because there is no existing array in the JSONObject.

Body:
Don't

  Object thelist = obj.get("friends");

I've tried JSONArray arr = obj.toJSONArray("friends");

Why you using toJSONArray ? .JSON ARRAY is not present there.

Do

 JSONObject sys  = obj.getJSONObject("friends");

Finally

JSONObject obj = new JSONObject(jsonDigest);
JSONObject sys  = obj.getJSONObject("friends");
String str_MUFA = sys.getString("mufasa3");
String str_JENK = sys.getString("jenkins");


答:
As you don't want to select element having style='z-index: auto;' then use :not() selector and :has() to target element having anchor as first child

```<code>$(document).on("click", "#menu li.top-level:not([style='z-index: auto;']):has(> a:first-child)", handler);
</code>```

$(document).on("click", "#menu li.top-level:not([style='z-index: auto;']):has(> a:first-child)", function() {
  console.log($(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>
<ul id="menu">
  <li class="top-level">1</li>
  <li class="top-level"><span>2</span></li>
  <li class="top-level" style='z-index: auto;'>3</li>
</ul></code>```

Title: jQuery selector for li whose first child is a span

Body:
As you don't want to select element having style='z-index: auto;' then use :not() selector and :has() to target element having anchor as first child

$(document).on("click", "#menu li.top-level:not([style='z-index: auto;']):has(> a:first-child)", handler);

$(document).on("click", "#menu li.top-level:not([style='z-index: auto;']):has(> a:first-child)", function() {
  console.log($(this).text());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu">
  <li class="top-level"><a href="#">1</a></li>
  <li class="top-level"><span>2</span></li>
  <li class="top-level" style='z-index: auto;'><a href="#">3</a></li>
</ul>


问:
How to increase slider values in whole numbers when starting value is 2 decimals
I have a price slider that submits and works as it should. The only thing it doesn't do is increase the values of the slider in whole numbers when the starting value is a 2 decimal number.
It also doesn't display the initial 2 decimal number. Just to show what I mean here is the code:

```<code> $Deposit= '12.85';
<script>
   Deposit_increase = <?php echo (isset($_GET['Deposit_increase'])) ?
   $_GET['Deposit_increase'] : 0 ?>;

   $(document).ready(function() {
   $( "#slider-range-min" ).slider({
      range: "min",
      value: <?php echo $Deposit ?>,
      min: <?php echo $Deposit ?>,
      max: 3000,

      values : [Deposit_increase],
                slide : function(event, ui) {
                    $("#Deposit_increase").val(ui.values[0]);
                },
        change: function() {
            $("#increase_form").submit();
        }
    });
    $("#Deposit_increase").val($("#slider-range-min").slider("values", 0));
});
  </script>
</code>```

The form:

```<code> <form action="" id="increase_form" method="get">

           <p  style="margin-left:12%; color:#2872bd; font-weight:bold; text-align:left">
  Change your Depost<br><br>
Deposit: £
  <input type="text" id="Deposit_increase" name="Deposit_increase"  style="border:0; color:#2872bd; font-weight:bold; text-align:left"  value="<?php echo $_GET['Deposit_increase']; ?>">

</p>
        <div id="slider-range-min"></div></form>
</code>```

Here it displays as follows:
Deposit: £12.9  (instead of £12.85)

The slider uses increments of 1 so all values will be shown as 13.9, 14.9. 15.9 etc.

What I want the slider to show is:
14, 15, 16 etc.

Is there a way to achieve this? Any help welcome

答:
You can replace the following line

```<code>$("#Deposit_increase").val(ui.values[0]);
</code>```

with

```<code>$("#Deposit_increase").val(Math.floor(ui.values[0]+0.5));
</code>```

This will always round off to the nearest integer.

Body:
I have a price slider that submits and works as it should. The only thing it doesn't do is increase the values of the slider in whole numbers when the starting value is a 2 decimal number.
It also doesn't display the initial 2 decimal number. Just to show what I mean here is the code:

 $Deposit= '12.85';

The form:

 <form action="" id="increase_form" method="get">

  Change your Depost

Deposit: £
  <input type="text" id="Deposit_increase" name="Deposit_increase"  style="border:0; color:#2872bd; font-weight:bold; text-align:left"  value="<?php echo $_GET['Deposit_increase']; ?>">

</form>

Here it displays as follows:
Deposit: £12.9  (instead of £12.85)

The slider uses increments of 1 so all values will be shown as 13.9, 14.9. 15.9 etc.

What I want the slider to show is:
14, 15, 16 etc.

Is there a way to achieve this? Any help welcome

Body:
You can replace the following line

$("#Deposit_increase").val(ui.values[0]);

with

$("#Deposit_increase").val(Math.floor(ui.values[0]+0.5));

This will always round off to the nearest integer.


问:
what is typeof((c) + 1) in C
I came across an expression in C like

```<code>typeof((c) + 1) _tmp = c;
</code>```

What exactly does this mean?

Thanks for the reply.

Just one doubt? What if the type of c is struct instead of the primitive types, then what will +1 do?

答:
The typeof operator in plain C (not C++) is a GCC addition to the standard. It tells the compiler you want to use the type of the expression enclosed in parenthesis.

Using typeof as above, you can declare variables of types unknown to you or in that context, using another variable's type as reference. It can also be used for casting.

The + operation inside typeof has a peculiar effect. typeof((c) + 1) means "the type of c, or the type of 1, whichever would remain after promotion". Remember that, for example, chars are promoted to ints when used in operations involving ints, ints are promoted to floats, floats to doubles, etc.

So, typeof(int_variable + char_variable) is int, since the char would be promoted to int to perform the operation.

Note that only the compiler can resolve this: typeof doesn't evaluate, it has no value, nothing happens at run-time.

The full description of typeof can be found here.

Title: what is typeof((c) + 1) in C

Body:
I came across an expression in C like

typeof((c) + 1) _tmp = c;

What exactly does this mean?

Thanks for the reply.

Just one doubt? What if the type of c is struct instead of the primitive types, then what will +1 do?


问:
creating a panel kind of functionality in xcode like it is present in bootstrap
I am looking to create panel kind of functionality in my app. I am using iOS 10 and swift 3.
It should look like

Login       +

  Register    -

Like it is shown down.

I would like to have functionality like when I touch login or that row till + sign then sign becomes - and it drop down fields which is holding username and password text box. Means login box gets expanded with login fields and at same time register bar minimizes its fields, And vice versa. I am confused how to approach this design problem. I don't know their is direct way like it is in bootstrap. If not kindly suggest me little approach to solve this problem.

答: You can take tableView and Put login label and + button on header programmatically.Take textField inside the cell and make toggle after click on + button.


问:
Employing parallelism in pipelined execution
I am trying to develop a pipeline in which data is first read and processed, manipulated once, manipulated in a different way, and then displayed. I have a design in mind in which the data IO feeds into a buffer that is read by the first manipulator. Subsequently that first manipulator writes to another buffer which is read when possible by the second manipulator. Lastly, the output of the second manipulator is written to a display buffer which is read by the visualizer and displayed using OpenGL.

In my mind this is a fairly straightforward parallel problem in which each task has its own thread and they communicate via data buffers. However, all the tutorials I've come across for threaded programs seem to suggest that multithreading is something to be left up to some middleware (like OpenMP) that decides how to divide the workload.

I'm new to developing multithreaded applications, so this may be a dumb question, but is what I've described feasible and can it be done with middleware like OpenMP? I realize the obvious answer is "try it," and I want to, but the tutorials don't shed any light on *how* to try it.

答:
To solve this particular problem Intel® Threading Building Blocks library includes special constructions. Intel® TBB is cross-platform library that aids in multithreading programming.
We could look at the entities involved in your application as at four different task providers. One type of tasks is input tasks - those that provide input data, another type of tasks is provided by the first manipulation routine, and so on.

Thus, the only thing the user needs to do is to provide the body for those tasks. There are several APIs in the library for specifying what bodies to be processed and how to do it in parallel. Everything else (here I mean thread creation, synchronization between task execution, work balancing, etc.) is done by the library.

The simplest variant of the solution that came to my mind is the using of parallel_pipeline function. Here is the prototype:

#include "tbb/pipeline.h"
using namespace tbb;

int main() {
    parallel_pipeline(/*specify max number of bodies executed in parallel, e.g.*/16,
        make_filter<void, input_data_type>(
            filter::serial_in_order, // read data sequentially
            [](flow_control& fc) -> input_data_type {
                if ( /*check some stop condition: EOF, etc.*/ ) {
                    fc.stop();
                    return input_data_type(); // return dummy value
                }
                auto input_data = read_data();
                return input_data;
            }
        ) &
        make_filter<input_data_type, manipulator1_output_type>(
            filter::parallel, // process data in parallel by the first manipulator
            [](input_data_type elem) -> manipulator1_output_type {
                auto processed_elem = manipulator1::process(elem);
                return processed_elem;
            }
        ) &
        make_filter<manipulator1_output_type, manipulator2_output_type>(
            filter::parallel, // process data in parallel by the second manipulator
            [](manipulator1_output_type elem) -> manipulator2_output_type {
                auto processed_elem = manipulator2::process(elem);
                return processed_elem;
            }
        ) &
        make_filter<manipulator2_output_type, void>(
            filter::serial_in_order, // visualize frame by frame
            [](manipulator2_output_type elem) {
                visualize(elem);
            }
        )
    );
    return 0;
}
```

provided that necessary functions (read_data, visualize) are implemented. Here input_data_type, manipulator1_output_type, etc. are the types that are passed between pipeline stages, and manipulator's process functions do necessary computation on the passed arguments.

BTW, to avoid working with locks and other synchronization primitives, you can use concurrent_bounded_queue from the library and put your input data into this queue, by possibly different thread (e.g. dedicated to IO operations), as simple as concurrent_bounded_queue_instance.push(elem), and then read it via input_data_type elem; concurrent_bounded_queue_instance.pop(elem). Note that popping an item is a blocking operation here. concurrent_queue provides non-blocking try_pop alternative.

The other possibility is to use tbb::flow_graph and its nodes for organizing the same pipelining scheme. Take a look at two examples that describe dependency and data flow graphs. You might need to use sequencer_node for correct ordering of items execution (if necessary).

It is worth reading the SO questions marked by tbb tag to see how other people use this library.

Body:
To solve this particular problem Intel® Threading Building Blocks library includes special constructions. Intel® TBB is cross-platform library that aids in multithreading programming.
We could look at the entities involved in your application as at four different task providers. One type of tasks is input tasks - those that provide input data, another type of tasks is provided by the first manipulation routine, and so on.

Thus, the only thing the user needs to do is to provide the body for those tasks. There are several APIs in the library for specifying what bodies to be processed and how to do it in parallel. Everything else (here I mean thread creation, synchronization between task execution, work balancing, etc.) is done by the library.

The simplest variant of the solution that came to my mind is the using of parallel_pipeline function. Here is the prototype:

#include "tbb/pipeline.h"
using namespace tbb;

int main() {
    parallel_pipeline(/*specify max number of bodies executed in parallel, e.g.*/16,
        make_filter<void, input_data_type>(
            filter::serial_in_order, // read data sequentially
            [](flow_control& fc) -> input_data_type {
                if ( /*check some stop condition: EOF, etc.*/ ) {
                    fc.stop();
                    return input_data_type(); // return dummy value
                }
                auto input_data = read_data();
                return input_data;
            }
        ) &
        make_filter<input_data_type, manipulator1_output_type>(
            filter::parallel, // process data in parallel by the first manipulator
            [](input_data_type elem) -> manipulator1_output_type {
                auto processed_elem = manipulator1::process(elem);
                return processed_elem;
            }
        ) &
        make_filter<manipulator1_output_type, manipulator2_output_type>(
            filter::parallel, // process data in parallel by the second manipulator
            [](manipulator1_output_type elem) -> manipulator2_output_type {
                auto processed_elem = manipulator2::process(elem);
                return processed_elem;
            }
        ) &
        make_filter<manipulator2_output_type, void>(
            filter::serial_in_order, // visualize frame by frame
            [](manipulator2_output_type elem) {
                visualize(elem);
            }
        )
    );
    return 0;
}

provided that necessary functions (read_data, visualize) are implemented. Here input_data_type, manipulator1_output_type, etc. are the types that are passed between pipeline stages, and manipulator's process functions do necessary computation on the passed arguments.

BTW, to avoid working with locks and other synchronization primitives, you can use concurrent_bounded_queue from the library and put your input data into this queue, by possibly different thread (e.g. dedicated to IO operations), as simple as concurrent_bounded_queue_instance.push(elem), and then read it via input_data_type elem; concurrent_bounded_queue_instance.pop(elem). Note that popping an item is a blocking operation here. concurrent_queue provides non-blocking try_pop alternative.

The other possibility is to use tbb::flow_graph and its nodes for organizing the same pipelining scheme. Take a look at two examples that describe dependency and data flow graphs. You might need to use sequencer_node for correct ordering of items execution (if necessary).

It is worth reading the SO questions marked by tbb tag to see how other people use this library.


问:
Why app crashes when i set image to ImageView and run it on android 7.1.1
I am new to Android. I want to know why my app crashes on Android 7.1.1 while setting the image to imageView using explicit intent, as it totally runs fine on other versions of Android. I have tried to understand and solve the issue but unable to do.

Can anyone please help me to understand why this is happening and what's the reason behind this?

Thanks.

This is what it showing :

```<code>eAnimators on 0x97c5ee80 (RippleDrawable) with handle 0x9affd880
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.himanshu.imageviewintent, PID: 5049
                  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/41 }} to activity {com.example.himanshu.imageviewintent/com.example.himanshu.imageviewintent.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/41 from pid=5049, uid=10073 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4089)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                      at android.app.ActivityThread.-wrap20(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                   Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/41 from pid=5049, uid=10073 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                      at android.os.Parcel.readException(Parcel.java:1684)
                      at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
                      at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:146)
                      at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:692)
                      at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1147)
                      at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:984)
                      at android.content.ContentResolver.openInputStream(ContentResolver.java:704)
                      at com.example.himanshu.imageviewintent.MainActivity.onActivityResult(MainActivity.java:44)
                      at android.app.Activity.dispatchActivityResult(Activity.java:6932)
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                      at android.app.ActivityThread.-wrap20(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Application terminated.
</code>```

And this is my code :

Java :

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

    final static int ImageIntentRequest = 1;

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

    public void setImage(View view) {

        Intent intent = new Intent(Intent.ACTION_PICK);
        File imageViewPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        String path =  imageViewPath.getPath();
        intent.setDataAndType(Uri.parse(path),"image/*");
        startActivityForResult(intent,ImageIntentRequest);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == RESULT_OK && requestCode == ImageIntentRequest) {

            InputStream stream;
            ImageView imageView = (ImageView)findViewById(R.id.imageView);
            try {
             stream = getContentResolver().openInputStream(data.getData());
                Bitmap bitmap = BitmapFactory.decodeStream(stream);
                imageView.setImageBitmap(bitmap);

            } catch (FileNotFoundException e) {
                Toast.makeText(this,"There is no File Present",Toast.LENGTH_SHORT).show();;
                e.printStackTrace();
            }
        }
    }
}
</code>```

XML :

```<code>   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.himanshu.imageviewintent.MainActivity"
>

<Button
    android:text="@string/set_image_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn_set_image"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:onClick="setImage"
    />

<ImageView
    android:src="@mipmap/ic_launcher"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/imageView"
    android:contentDescription="@null"
    android:layout_above="@+id/btn_set_image"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="10dp"
    />
</RelativeLayout>
</code>```

I found an easy fix for this :

I just replaced,

```<code>Intent.ACTION_PICK by -

Intent intent = Intent(Intent.ACTION_GET_CONTENT);
</code>```

and now the app runs totally fine on old and latest releases of Android.

But still have doubts:

Why ACTION_PICK works on old versions of Android but not on new Releases?
Why ACTION_GET_CONTENT works on all releases?

I will be thankful if someone clarify this?

答:
You have either not added Storage permissions to the manifest or you do not ask the user to accept them before using them.

```<code><manifest ...>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    ...
</manifest>
</code>```

You can ask user for permission using this function

```<code>    public  boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                Log.v(TAG,"Permission is granted");
                return true;
            } else {

                Log.v(TAG,"Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        }
        else { //permission is automatically granted on sdk<23 upon installation
            Log.v(TAG,"Permission is granted");
            return true;
        }

}
</code>```

Body:
I am new to Android. I want to know why my app crashes on Android 7.1.1 while setting the image to imageView using explicit intent, as it totally runs fine on other versions of Android. I have tried to understand and solve the issue but unable to do.

Can anyone please help me to understand why this is happening and what's the reason behind this?

Thanks.

This is what it showing :

eAnimators on 0x97c5ee80 (RippleDrawable) with handle 0x9affd880
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.himanshu.imageviewintent, PID: 5049
                  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/41 }} to activity {com.example.himanshu.imageviewintent/com.example.himanshu.imageviewintent.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/41 from pid=5049, uid=10073 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4089)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                      at android.app.ActivityThread.-wrap20(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                   Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/41 from pid=5049, uid=10073 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                      at android.os.Parcel.readException(Parcel.java:1684)
                      at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
                      at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:146)
                      at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:692)
                      at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1147)
                      at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:984)
                      at android.content.ContentResolver.openInputStream(ContentResolver.java:704)
                      at com.example.himanshu.imageviewintent.MainActivity.onActivityResult(MainActivity.java:44)
                      at android.app.Activity.dispatchActivityResult(Activity.java:6932)
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
                      at android.app.ActivityThread.-wrap20(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6119)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Application terminated.

And this is my code :

Java :

public class MainActivity extends Activity {

    final static int ImageIntentRequest = 1;

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

    public void setImage(View view) {

        Intent intent = new Intent(Intent.ACTION_PICK);
        File imageViewPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        String path =  imageViewPath.getPath();
        intent.setDataAndType(Uri.parse(path),"image/*");
        startActivityForResult(intent,ImageIntentRequest);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if(resultCode == RESULT_OK && requestCode == ImageIntentRequest) {

            InputStream stream;
            ImageView imageView = (ImageView)findViewById(R.id.imageView);
            try {
             stream = getContentResolver().openInputStream(data.getData());
                Bitmap bitmap = BitmapFactory.decodeStream(stream);
                imageView.setImageBitmap(bitmap);

            } catch (FileNotFoundException e) {
                Toast.makeText(this,"There is no File Present",Toast.LENGTH_SHORT).show();;
                e.printStackTrace();
            }
        }
    }
}

XML :

   <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.himanshu.imageviewintent.MainActivity"
>

<Button
    android:text="@string/set_image_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn_set_image"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:onClick="setImage"
    />

<ImageView
    android:src="@mipmap/ic_launcher"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/imageView"
    android:contentDescription="@null"
    android:layout_above="@+id/btn_set_image"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="10dp"
    />
</RelativeLayout>

I found an easy fix for this :

I just replaced,

Intent.ACTION_PICK by -

Intent intent = Intent(Intent.ACTION_GET_CONTENT);

and now the app runs totally fine on old and latest releases of Android.

But still have doubts:

Why ACTION_PICK works on old versions of Android but not on new Releases?
Why ACTION_GET_CONTENT works on all releases?

I will be thankful if someone clarify this?

Body:
You have either not added Storage permissions to the manifest or you do not ask the user to accept them before using them.

<manifest ...>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    ...
</manifest>

You can ask user for permission using this function

    public  boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                Log.v(TAG,"Permission is granted");
                return true;
            } else {

                Log.v(TAG,"Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        }
        else { //permission is automatically granted on sdk<23 upon installation
            Log.v(TAG,"Permission is granted");
            return true;
        }

}


问:
javascript library not loaded in ionic
Im including the google cast external javascript library. When I run with ionic serve it works good, but when I run the app in the phone, the library is not loaded. Debugging can see that :

https://cdn-enterprise.discourse.org/ionicframework/uploads/default/original/3X/a/d/ad4c985f45c1c538bdfbfbb02d10141b6929e1d5.png

The "http" is replaced by "file"!
I tried to include the libraries with that code:

script src="//www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1">

and with type="text/javascript" added; but all codes replaces http by file, and the library is not loaded.

Any suggestions?

Title: javascript library not loaded in ionic

Body:
When you run the app do not add cdn files starting with "//:", add them like "http://".

If its possible download those files and keep them in directory, after that give directory path to file.

e.g. <script type="text/javascript" src="assets/js/library.js">


问:
How to get diff for specified user between two dates from git?
How to get diff for specified user between two dates from git? Or, how to use git whatchanged command to list commits for specified user?

Is there any none-scripting way (builtin git command)?

答:
```<code>git log --since "MAY 1 2017" --until "MAY 31 2017" -p --author="Jack" > diffJackMay.patch
</code>```


问:
SSRS 2008 date formatting and exporting to excel confusion
Suppose I have a field with a date value in a Reporting Services template, e.g. =CDate("2010.12.03"), I apply the "d" format to this cell, which, according to the description, "will reflect the regional settings of the report". I generate the report using the English language, the date is displayed as 12/03/2010, which is fine. Now when I export this report to excel, I have no idea what the __ happens.

First scenario: the regional settings of the computer are set to English (United States). When I open the excel document, the value seen in the cell is 12/03/2010, as expected. When I click on it, I can see that the actual value stored in the cell is 2010.12.03, which also seems reasonable - some formatting is applied to the cell, it's not simply exported as text. But when I try to figure out what type of formatting is applied, by right clicking and checking Format Cells, I see that the format is "General", i.e. none! How can this be ? This is Excel 2010 by the way, but the file itself is .xls, of course.

Second scenario, where it gets more interesting: now the region of the computer is set to e.g. Lithuania, where the date format is 2010.12.03. I open the same document and see 12.03.2010. Now that simply does not make any sense. Exporting many times I've encountered that sometimes the cell is formatted as [$-10409]m.d.yyyy in excel (under the Custom section). What is this, what does the 10409 mean ? The weirdest part of all: if I close the document without saving, change the computer region back to English (United States), reopen the document, the format is now [$-10409]m/d/yyyy ! HOW is this possible !??

Basically the same thing happens with numbers and with thousand/decimal separators - excel uses the region of the computer to format these, but the actual format of the cell can be something like [$-10409]#,##0.00;-#,##0.00 or General - again, depending on the region of the computer, direction of wind and the temperature outside.

My question is then, first of all, what the __ is going on ? Second, how should the excel document behave according to the specs, i.e. what does the statement that a format "will reflect the regional settings of the report" in the BIDS designed, where I chose the "d" format for the date textbox, mean ? Does it mean, that the format will be determined by the language of the report and the result will look the same on all computers in the world (which makes sense, since this is how other formats behave, i.e. if you export the date to a pdf, it stays the same always) ? If not, which appears to be partially the case in excel, why doesn't the exported date cell have the regional date format, i.e. the one that you normally use in excel, the one which formats the date according to the region of the computer ?

Are these some kind of limitations of excel or what ? Why can't we have consistent behavior, i.e. either make everything sensitive to the culture of the computer viewing the document or don't, why is the actual behavior somewhere in between ?

答:
Excel uses a custom encoding for the date, and uses the machine regional settings as a hint on how to format the contents. The encoding is archaic, and has lots of specific, historic gotchas.

This means that the kinds of bugs that you see often do happen - you'll have data that's been exported to Excel, which then has its formatting and contents mangled once opened for the first time by the actual Excel application. The problem can be anywhere along the line - maybe the library that exports the data to Excel doesn't deal with some of the more esoteric historic cases well, or maybe Excel is confusing itself along the way.

I've had some success in the past with exporting dates as a strings to a CSV file, stripped of formatting, and then importing them into Excel/opening them with Excel.


问:
How do I store first control in flowLayoutPanel c#?
I am new to C# and I am using windows forms.

I have flowLayoutPanel and I programmatically add some buttons to it .
What I am trying to do is: I want to save the first button located in the flowLayoutPanel into ButtonToSave object.

```<code>   flowLayoutPanel1.FlowDirection= FlowDirection.LeftToRight

   private void AddButtons_Click(object sender, EventArgs e)
    {
       Button btn = new Button();

       flowLayoutPanel1.Controls.Add(btn);
    }

 private void StoreTheFirstButton_Click(object sender, EventArgs e)
    {

          Button ButtonToSave = new Button();
          ButtonToSave = "First button in flowLayoutPanel1"
    }
</code>```

Anyone knows how to save the first button located in flowLayoutPanel1 into ButtonToSave when StoreTheFirstButton event is raised?

Thank you

答:
Try code below.  You may want to look at my response at following posting (How to (create and) add components to a Table Layout?) :

        private void AddButtons_Click(object sender, EventArgs e)
        {
            Button btn = new Button();
            btn.Click += new EventHandler(StoreTheFirstButton_Click);

            flowLayoutPanel1.Controls.Add(btn);
        }

        private void StoreTheFirstButton_Click(object sender, EventArgs e)
        {
            Button button = sender as Button;

            Button ButtonToSave = button;
            //ButtonToSave = "First button in flowLayoutPanel1";
        }```

Body:
I am new to C# and I am using windows forms.

I have flowLayoutPanel and I programmatically add some buttons to it .
What I am trying to do is: I want to save the first button located in the flowLayoutPanel into ButtonToSave object.

   flowLayoutPanel1.FlowDirection= FlowDirection.LeftToRight

   private void AddButtons_Click(object sender, EventArgs e)
    {
       Button btn = new Button();

       flowLayoutPanel1.Controls.Add(btn);
    }

 private void StoreTheFirstButton_Click(object sender, EventArgs e)
    {

          Button ButtonToSave = new Button();
          ButtonToSave = "First button in flowLayoutPanel1"
    }

Anyone knows how to save the first button located in flowLayoutPanel1 into ButtonToSave when StoreTheFirstButton event is raised?

Thank you


问:
Server side route to download file
I've got a server side route I'm using to download a file. This is called from a client side button click and everything is working fine. However, once the button has been clicked once it will not work again until another route is loaded and you go back. How can I code it so that the button can be clicked multiple times and the server side route be fired each time?

My button code looks like this...

```<code>'click #view_document_download': function (event, tmpl) {
   Router.go('/download_document/' + this._id);
}
</code>```

And my server side route looks like this...

```<code>Router.route('/download_document/:_id', function () {

  //Get the file record to download
  var file = files.findOne({_id: this.params._id});

  //Function to take a cfs file and return a base64 string
  var getBase64Data = function(file2, callback) {
    var readStream = file2.createReadStream();
    var buffer = [];
    readStream.on('data', function(chunk) {
      buffer.push(chunk);
    });
    readStream.on('error', function(err) {
      callback(err, null);
    });
    readStream.on('end', function() {
      callback(null, buffer.concat()[0].toString('base64'));
    });
  };

  //Wrap it to make it sync
  var getBase64DataSync = Meteor.wrapAsync(getBase64Data);

  //Get the base64 string
  var base64str = getBase64DataSync(file);

  //Get the buffer from the string
  var buffer = new Buffer(base64str, 'base64');

  //Create the headers
  var headers = {
    'Content-type': file.original.type,
    'Content-Disposition': 'attachment; filename=' + file.original.name
  };

  this.response.writeHead(200, headers);
  this.response.end(buffer, 'binary');

}, { where: 'server' });
</code>```

答:
use a element instead of js 'click' event

page html

```<code><a href="/download_document/{{_id}}" download="true" target="_blank"></a>
</code>```

page js in server

```<code>Router.route("/download_document/:fileId", function(){
    var file = files.findOne({_id: this.params.fileId});
    var contentFile = //file text
    let headers = {
      'Content-Type': 'text/plain',
      'Content-Disposition': "attachment; filename=file.txt"
    };
    this.response.writeHead(200, headers);
    this.response.end(contentFile);
  },
  {where: "server", name: "download"}
);
</code>```

Title: Server side route to download file

Body:
I've got a server side route I'm using to download a file. This is called from a client side button click and everything is working fine. However, once the button has been clicked once it will not work again until another route is loaded and you go back. How can I code it so that the button can be clicked multiple times and the server side route be fired each time?

My button code looks like this...

'click #view_document_download': function (event, tmpl) {
   Router.go('/download_document/' + this._id);
}

And my server side route looks like this...

Router.route('/download_document/:_id', function () {

  //Get the file record to download
  var file = files.findOne({_id: this.params._id});

  //Function to take a cfs file and return a base64 string
  var getBase64Data = function(file2, callback) {
    var readStream = file2.createReadStream();
    var buffer = [];
    readStream.on('data', function(chunk) {
      buffer.push(chunk);
    });
    readStream.on('error', function(err) {
      callback(err, null);
    });
    readStream.on('end', function() {
      callback(null, buffer.concat()[0].toString('base64'));
    });
  };

  //Wrap it to make it sync
  var getBase64DataSync = Meteor.wrapAsync(getBase64Data);

  //Get the base64 string
  var base64str = getBase64DataSync(file);

  //Get the buffer from the string
  var buffer = new Buffer(base64str, 'base64');

  //Create the headers
  var headers = {
    'Content-type': file.original.type,
    'Content-Disposition': 'attachment; filename=' + file.original.name
  };

  this.response.writeHead(200, headers);
  this.response.end(buffer, 'binary');

}, { where: 'server' });

Body:
use a element instead of js 'click' event

page html

<a href="/download_document/{{_id}}" download="true" target="_blank"></a>

page js in server

Router.route("/download_document/:fileId", function(){
    var file = files.findOne({_id: this.params.fileId});
    var contentFile = //file text
    let headers = {
      'Content-Type': 'text/plain',
      'Content-Disposition': "attachment; filename=file.txt"
    };
    this.response.writeHead(200, headers);
    this.response.end(contentFile);
  },
  {where: "server", name: "download"}
);


问:
Pexpect and Terminal Resizing
I'm using pexpect to automate ssh-ing into a remote server that prompts for a password. The process is very simple, and works great:

```<code>child = pexpect.spawn("ssh -Y remote.server")
child.expect(re.compile(b".*password.*"))
child.sendline(password)
child.interact()
</code>```

This works great, however, I notice one quite annoying quirk I have not been able to figure out. When I use vim in this terminal, it seems to not resize correctly. When ssh-ing directly, and using a program such as vim, I can resize my terminal window (locally), and the remote program automatically/interactively fixes the columns and lines. My pexpect instance does not. There are a few other minor quirks that I can lvie with, but this one is quite annoying.

I'm hoping to find a way I can get my pexpect ssh session to behave the same way a native ssh session does, or at the very least understand the reason the two behave differently.

答:
There's actually an example for this under the interact() function in pexpect's doc. Just like writing C code, it requires a SIGWINCH handler.

```<code>import pexpect, struct, fcntl, termios, signal, sys

def sigwinch_passthrough (sig, data):
    s = struct.pack("HHHH", 0, 0, 0, 0)
    a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
                                          termios.TIOCGWINSZ , s) )
    global p
    p.setwinsize(a[0], a[1])

# Note this 'p' global and used in sigwinch_passthrough.
p = pexpect.spawn('/bin/bash')
signal.signal(signal.SIGWINCH, sigwinch_passthrough)

p.interact()
</code>```

Title: Pexpect and Terminal Resizing

Body:
I'm using pexpect to automate ssh-ing into a remote server that prompts for a password. The process is very simple, and works great:

child = pexpect.spawn("ssh -Y remote.server")
child.expect(re.compile(b".*password.*"))
child.sendline(password)
child.interact()

This works great, however, I notice one quite annoying quirk I have not been able to figure out. When I use vim in this terminal, it seems to not resize correctly. When ssh-ing directly, and using a program such as vim, I can resize my terminal window (locally), and the remote program automatically/interactively fixes the columns and lines. My pexpect instance does not. There are a few other minor quirks that I can lvie with, but this one is quite annoying.

I'm hoping to find a way I can get my pexpect ssh session to behave the same way a native ssh session does, or at the very least understand the reason the two behave differently.

Body:
There's actually an example for this under the interact() function in pexpect's doc. Just like writing C code, it requires a SIGWINCH handler.

import pexpect, struct, fcntl, termios, signal, sys

def sigwinch_passthrough (sig, data):
    s = struct.pack("HHHH", 0, 0, 0, 0)
    a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
                                          termios.TIOCGWINSZ , s) )
    global p
    p.setwinsize(a[0], a[1])

# Note this 'p' global and used in sigwinch_passthrough.
p = pexpect.spawn('/bin/bash')
signal.signal(signal.SIGWINCH, sigwinch_passthrough)

p.interact()


问:
SQL Server query (create rule)

Create a rule called Makedata to allow only the following values to the make of the data: txt, excel, word, rar, and powerpoint.

You must attach the rule to column Make in the datatype table

What does this question mean? I don't want a solution just an explanation.

Thank you

答:
You are asked to filter the values that can be stored in that data column. For this you can use enum data type if were using MySQL. To fit your case take a look at: SQL Server equivalent to MySQL enum data type?

Alter your table with:

```<code>column_name VARCHAR(255) NOT NULL CHECK (column_name IN('txt', 'excel', 'word', 'rar', 'powerpoint'))
</code>```

Title: SQL Server query (create rule)

Body:
You are asked to filter the values that can be stored in that data column. For this you can use enum data type if were using MySQL. To fit your case take a look at: SQL Server equivalent to MySQL enum data type?

Alter your table with:

column_name VARCHAR(255) NOT NULL CHECK (column_name IN('txt', 'excel', 'word', 'rar', 'powerpoint'))


问:
Access denied for user ''@'localhost' (using password: NO) with MySQL in JavaFX
Im using my root account to login to mysql from a javafx app but im denied with
 Acces Denied ''@'localhost' (using password: NO).
This is my code:

```<code>    public void ConnnectClicked(ActionEvent e) throws SQLException {
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException ex) {
        System.out.println("Error: unable to load driver class!");
        System.exit(1);
    }
    String URL = "jdbc:mysql://localhost:3306/world";
    String name = username.getSelectedText();
    String pass = password.getSelectedText();

    Connection conn = DriverManager.getConnection(URL, name, pass);
    primaryStage.setScene(country);
}
</code>```

As you can see its just a basic connection scheme in javafx. Doenst "password no" means theres something worng with my user account?

答:
It's just a guess, but if those are text boxes:

```<code>String name = username.getSelectedText();
String pass = password.getSelectedText();
</code>```

Then you should propably use username.getText(), because selectedText is the text you marked with your mouse. If you didnt mark it (blue highlighting), then it's empty.

Body:
Im using my root account to login to mysql from a javafx app but im denied with
 Acces Denied ''@'localhost' (using password: NO).
This is my code:

    public void ConnnectClicked(ActionEvent e) throws SQLException {
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException ex) {
        System.out.println("Error: unable to load driver class!");
        System.exit(1);
    }
    String URL = "jdbc:mysql://localhost:3306/world";
    String name = username.getSelectedText();
    String pass = password.getSelectedText();

    Connection conn = DriverManager.getConnection(URL, name, pass);
    primaryStage.setScene(country);
}

As you can see its just a basic connection scheme in javafx. Doenst "password no" means theres something worng with my user account?

Body:
It's just a guess, but if those are text boxes:

String name = username.getSelectedText();
String pass = password.getSelectedText();

Then you should propably use username.getText(), because selectedText is the text you marked with your mouse. If you didnt mark it (blue highlighting), then it's empty.


问:
How to debug a SQL Server table insertion that hangs?
On my SQL Server, I have a query which does not produce any rows and this select statement runs for about a minute. Now I don't understand why the insert would not finish forever. The destination table has only 48k rows. I don't have rights to run any kinds of tracing or any other diagnostic queries that can help this. What else can I try?</p>

答: Turn your insert into a select so you can see what you're trying to insert.  Then take parts away from your SQL statement (joins, sub queries, etc.) until it starts running quickly.  The last thing you removed was the cause of the slowness.  Without an example we can't give you more specific help that.  The process of writing a https://stackoverflow.com/help/mcve will probably help you answer this yourself.</p>


问:
How to iterate over Table in Jquery to change the content
I have this fiddle

where I have an input type with two buttons + and - , I want to add the value of the input to all the units value in the table .

JS Fiddle

The JQuery looks like thi s

```<code>$(".commission").TouchSpin({
  min: 0,
  max: 2,
  step: 0.0001,
  decimals: 4,
  boostat: 5,
  maxboostedstep: 10,
  buttondown_class: 'btn btn-white',
  buttonup_class: 'btn btn-white'
});
$(".commission").on('touchspin.on.startupspin', function() {
  var table = $(this).parent().parent().parent().prev().find('table');
  console.log(table.rows);
})
</code>```

and the HTML you can see in the fiddle itself

答:
I don't know the plugin you are using, so I'll put my function inside a .change() but put this code inside the function called at each input change :

```<code>$('body').on('change','.commission',function(){
  var $this = $(this);
  $('.unit').each(function(){
    $(this).text(+$(this).text()+$this.val());
  });
});
</code>```

Body:
I have this fiddle

where I have an input type with two buttons + and - , I want to add the value of the input to all the units value in the table .

JS Fiddle

The JQuery looks like thi s

$(".commission").TouchSpin({
  min: 0,
  max: 2,
  step: 0.0001,
  decimals: 4,
  boostat: 5,
  maxboostedstep: 10,
  buttondown_class: 'btn btn-white',
  buttonup_class: 'btn btn-white'
});
$(".commission").on('touchspin.on.startupspin', function() {
  var table = $(this).parent().parent().parent().prev().find('table');
  console.log(table.rows);
})

and the HTML you can see in the fiddle itself

Body:
I don't know the plugin you are using, so I'll put my function inside a .change() but put this code inside the function called at each input change :

$('body').on('change','.commission',function(){
  var $this = $(this);
  $('.unit').each(function(){
    $(this).text(+$(this).text()+$this.val());
  });
});