问:
react slidetoggle with this
I'm trying to get slideToggle to work with React like I did with jQuery, but I'm unable to figure out how to do it.
I have a list of different recipes, and not to make the page incredibly long, I want to hide the content and only show the heading of each recipe. When the user clicks the heading, it will show the content for that particular recipe. If the heading is clicked again, it will hide that particular content.
I want to use same className ('content') for each recipe content, so I would need "this" to determine which content I want to show. How can I do this in React?

In jQuery I got it work like this

```<code> $("h2").click(function(){
    $(this).siblings('.content').slideToggle('slow');
});
</code>```

but after several tests in React the best I got was hiding the last content with the example from this page (React jQuery slideToggle)

I wasn't able to get this one work, probably the way to get this working..?
react using jquery to slideToggle
I think this is bit out of date and could be done better nowadays?

答:
The accepted answer here will work well:

Implementing a Read More link in React.js

Alternatively, you could expand the text using React Router Page Transition

Demo

Title: react slidetoggle with this

Body:
I'm trying to get slideToggle to work with React like I did with jQuery, but I'm unable to figure out how to do it.
I have a list of different recipes, and not to make the page incredibly long, I want to hide the content and only show the heading of each recipe. When the user clicks the heading, it will show the content for that particular recipe. If the heading is clicked again, it will hide that particular content.
I want to use same className ('content') for each recipe content, so I would need "this" to determine which content I want to show. How can I do this in React?

In jQuery I got it work like this

 $("h2").click(function(){
    $(this).siblings('.content').slideToggle('slow');
});

but after several tests in React the best I got was hiding the last content with the example from this page (React jQuery slideToggle)

I wasn't able to get this one work, probably the way to get this working..?
react using jquery to slideToggle
I think this is bit out of date and could be done better nowadays?


来源: stackexchange

问:
Segmentation fault when non-capitalized input is given due to toupper used in a condition which inturn is used inside a for loop [C]
I'm trying to write a program for the course CS50, where I need to get the initial of full names of people (and make sure it's all capitalized).

Therefore, I ended up writing this:

```<code>#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>

int main(void)
{
    //Asks user for input and checks for it's length
    printf("What's your name?\n");
    string full_name = get_string();
    int name_length = strlen(full_name);
    //Program to select the intitials of each word
    for(int i=0; i<name_length; i++)
    {
        char selectedchar = full_name[i]; //determines the currently selected character from the string on the basis of how many times the loop has run
        if(selectedchar != ' ')          //Makes the program ignore any spaces before the name
        {
            if(selectedchar>='A' && selectedchar<='z')
            {
                printf("%c", toupper(full_name[i]));
            }
            else
            {
                printf("ERROR: INVALID INITIALS. (Check the characters used.)");
                return 1;
            }
        }

        //To skip printing of non-initials
        while(selectedchar != ' ')
        {
            i++;
            selectedchar=full_name[i];
        }

        if(i>=name_length)       //print a linebreak on the end of each run
        {
            printf("\n");
            return 0;
        }
    }
}
</code>```

Now, whenver I input something, I get a segment fault. E:

Input Damien Chazelle Result: DCSegmentation fault (and line break)

Input Dam!en Chazelle Result: DCSegmentation fault (and line break)

Input Damien          Result: DSegmentation fault (and line break)

Input !Damien         Result: Segmentation fault  (and line break)

Now, I am a beginner! I have absolutely no idea of what's causing the problem or how to properly write this question. (Please pardon me for that!)

答:
Your while-loop that shall set the pointer to the next blank will run out of bounds every time when a space is not the last character in the string:

```<code>    while(selectedchar != ' ')
    {
        i++;
        selectedchar=full_name[i];
    }
</code>```

Suppose a string like "Damien Chazelle", and suppose that i points to character C: Then, as the string does not contain any more space from this position onwards, i will run out of bounds of the string. Note that string termination character '\0' is not equal ' ', so the loop will step over.

Without interpreting the rest of your code to much, write

```<code>while(i < name_length && selectedchar != ' ')
</code>```

instead.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to write a program for the course CS50, where I need to get the initial of full names of people (and make sure it's all capitalized).

Therefore, I ended up writing this:

#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>

int main(void)
{
    //Asks user for input and checks for it's length
    printf("What's your name?\n");
    string full_name = get_string();
    int name_length = strlen(full_name);
    //Program to select the intitials of each word
    for(int i=0; i<name_length; i++)
    {
        char selectedchar = full_name[i]; //determines the currently selected character from the string on the basis of how many times the loop has run
        if(selectedchar != ' ')          //Makes the program ignore any spaces before the name
        {
            if(selectedchar>='A' && selectedchar<='z')
            {
                printf("%c", toupper(full_name[i]));
            }
            else
            {
                printf("ERROR: INVALID INITIALS. (Check the characters used.)");
                return 1;
            }
        }

        //To skip printing of non-initials
        while(selectedchar != ' ')
        {
            i++;
            selectedchar=full_name[i];
        }

        if(i>=name_length)       //print a linebreak on the end of each run
        {
            printf("\n");
            return 0;
        }
    }
}

Now, whenver I input something, I get a segment fault. E:

Input Damien Chazelle Result: DCSegmentation fault (and line break)

Input Dam!en Chazelle Result: DCSegmentation fault (and line break)

Input Damien          Result: DSegmentation fault (and line break)

Input !Damien         Result: Segmentation fault  (and line break)

Now, I am a beginner! I have absolutely no idea of what's causing the problem or how to properly write this question. (Please pardon me for that!)

Body:
Your while-loop that shall set the pointer to the next blank will run out of bounds every time when a space is not the last character in the string:

    while(selectedchar != ' ')
    {
        i++;
        selectedchar=full_name[i];
    }

Suppose a string like "Damien Chazelle", and suppose that i points to character C: Then, as the string does not contain any more space from this position onwards, i will run out of bounds of the string. Note that string termination character '\0' is not equal ' ', so the loop will step over.

Without interpreting the rest of your code to much, write

while(i < name_length && selectedchar != ' ')

instead.


问:
From a shell script, determine if firefox has rendered a page
I need to run firefox from a bash script to load a url

Example

firefox -url www.google.ie

The problem is I need to know when firefox has rendered the page on the browser. Does anyone know how this could be done? There doesn't seem to be anything about this in the firefox documentation.

My goal is automated tests, Basically I have a proxy type server that sits between a browser and the web, it performs optimizations on webpages before returning them to the browser (I have a good reason for doing this). Currently I just want to know how long it takes between requesting the page and loading it in the browser.

答: Not sure if this will be helpful for you, but for alternatives - Selenium (an open source testing tool, seleniumhq.org) has a way to interact with firefox where you can write some sorts of scripts and run them with the selenium test runner. You run a local 'selenium server' that you can then send requests to. If this is what you're trying to accomplish, all of it can be done through a shell script.</p>

ContentLicense: CC BY-SA 2.5


问:
IBoutlet Collection Button - setTitle

I have a number of buttons that all have the same action so I’ve used a collection View

```<code>@IBOutlet var playerButtons: [UIButton]!
</code>```

I was hoping that using a picker view would allow me to select a name and then set the title of the button, however I cant seem to find out how to achieve this in a collection view.

The function I’m trying to use docent seem to work though

```<code>open func setTitle(_ title: String?, for state: UIControlState)
</code>```

My full code is

```<code>import UIKit
import Firebase

class TeamSelection: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    //IBOutlets Collection for Player Names
    @IBOutlet var playerButtons: [UIButton]!
    @IBOutlet var Player: [UIView]!
    @IBOutlet weak var homeTeamLabel: UILabel!
    @IBOutlet weak var pickerView: UIPickerView!

    var player = [Players]()
    var club: Clubs!
    var clubName = String()
    var playerFirstName = String()
    var playerLastName = String()

    // Will be removed and Firebase used in place
    var players = ["player 1", "player 2", "player 3", "and so on"]

    override func viewDidLoad() {
        super.viewDidLoad()

        pickerView.dataSource = self
        pickerView.delegate = self

        CLUB_KEY = ""
        CLUB_KEY = club.clubKey

        self.navigationItem.title = club.clubName

        DataService.ds.REF_PLAYERS.queryOrdered(byChild: "clubKey").queryEqual(toValue: club.clubKey).observe(.value, with: { (snapshot) in

            print("PLAYERS_COUNT: \(snapshot.childrenCount)")
            print("PLAYERS_SNAPSHOT: \(snapshot)")

            self.player = []
            if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {

                for snap in snapshots {
                    if let playerDict = snap.value as? Dictionary<String, AnyObject> {
                        let key = snap.key

                        let players = Players(playerKey: key, dictionary: playerDict)
                        self.player.append(players)

                    }
                }
            }
//            self.tableView.reloadData()
        }) { (error) in
            print(error.localizedDescription)
            print("CHET: local error")
        }
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {

        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        return players.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        return players[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

//        self.pickerView.isHidden = true

        // Missing command
           playerButtons.setTitle
    }

    //IBActions Collection for Player Names
    @IBAction func playerSelectionAction(_ sender: UIButton) {

        sender.setTitle("buttonName", for: .normal)

        let sender = sender.tag
        print(sender)

    }
}
</code>```

答:
Sorted with the following</p>

```<code>@IBAction func playerSelectionAction(_ sender: UIButton) {

        let senderINT = sender.tag

        let selectedBtn = self.view.viewWithTag(senderINT) as! UIButton

        selectedBtn.setTitle("", for: .normal)

        print(sender)

    }
</code>```

Title: IBoutlet Collection Button - setTitle

Body:
I have a number of buttons that all have the same action so I’ve used a collection View

@IBOutlet var playerButtons: [UIButton]!

I was hoping that using a picker view would allow me to select a name and then set the title of the button, however I cant seem to find out how to achieve this in a collection view.

The function I’m trying to use docent seem to work though

open func setTitle(_ title: String?, for state: UIControlState)

My full code is

import UIKit
import Firebase

class TeamSelection: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {

    //IBOutlets Collection for Player Names
    @IBOutlet var playerButtons: [UIButton]!
    @IBOutlet var Player: [UIView]!
    @IBOutlet weak var homeTeamLabel: UILabel!
    @IBOutlet weak var pickerView: UIPickerView!

    var player = [Players]()
    var club: Clubs!
    var clubName = String()
    var playerFirstName = String()
    var playerLastName = String()

    // Will be removed and Firebase used in place
    var players = ["player 1", "player 2", "player 3", "and so on"]

    override func viewDidLoad() {
        super.viewDidLoad()

        pickerView.dataSource = self
        pickerView.delegate = self

        CLUB_KEY = ""
        CLUB_KEY = club.clubKey

        self.navigationItem.title = club.clubName

        DataService.ds.REF_PLAYERS.queryOrdered(byChild: "clubKey").queryEqual(toValue: club.clubKey).observe(.value, with: { (snapshot) in

            print("PLAYERS_COUNT: \(snapshot.childrenCount)")
            print("PLAYERS_SNAPSHOT: \(snapshot)")

            self.player = []
            if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {

                for snap in snapshots {
                    if let playerDict = snap.value as? Dictionary<String, AnyObject> {
                        let key = snap.key

                        let players = Players(playerKey: key, dictionary: playerDict)
                        self.player.append(players)

                    }
                }
            }
//            self.tableView.reloadData()
        }) { (error) in
            print(error.localizedDescription)
            print("CHET: local error")
        }
    }

    func numberOfComponents(in pickerView: UIPickerView) -> Int {

        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

        return players.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {

        return players[row]
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

//        self.pickerView.isHidden = true

        // Missing command
           playerButtons.setTitle
    }

    //IBActions Collection for Player Names
    @IBAction func playerSelectionAction(_ sender: UIButton) {

        sender.setTitle("buttonName", for: .normal)

        let sender = sender.tag
        print(sender)

    }
}

Body:
Sorted with the following

@IBAction func playerSelectionAction(_ sender: UIButton) {

        let senderINT = sender.tag

        let selectedBtn = self.view.viewWithTag(senderINT) as! UIButton

        selectedBtn.setTitle("", for: .normal)

        print(sender)

    }


问:
how can i achieve FibonacciSecret in php
I'm trying to get all the characters in that message at positions that are present in the Fibonacci sequence (a sequence formed by the the Fibonacci number sorted in ascending order). Please ignore whitespace characters and use the extended Fibonacci.

Return the obtained characters capitalized and connected by the '-' character.

Example

For message = "The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown",

the output should be

FibonacciSecret(message) = "T-H-H-E-D-V-C-E-M-T".

The first Fibonacci is 0 then the first letter is T

The second Fibonacci is 1 then the second letter is H

The third Fibonacci is 1 then the third letter is H ... and so on.

Thus, the answer should be "T-H-H-E-D-V-C-E-M-T".

Tried Code

```<code><?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split($message);

$x = 0;
$y = 1;

for($i=0;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       echo $str_split[$fvalue]."-";
}

?>
</code>```

Output

```<code>h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-h-h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-
</code>```

Expected Output

the answer should be "T-H-H-E-D-V-C-E-M-T".

Can anyone tell me. Where im going wrong in this one ?

答:
Your code was almost correct.

You would delete spaces and add two start element of array.

```<code>    $message   = str_replace( ' ', '', 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown' );
    $str_split = str_split( $message );

    $x = 0;
    $y = 1;

    $farray[] = $x;
    $farray[] = $y;

    for ( $i = 2; $i <= 10; $i ++ ) {
        $z        = $x + $y;
        $farray[] = $z;
        $x        = $y;
        $y        = $z;
    }

    foreach ( $farray as $key => $fvalue ) {
        echo $str_split[ $fvalue ] . "-";
    }
</code>```

Body:
I'm trying to get all the characters in that message at positions that are present in the Fibonacci sequence (a sequence formed by the the Fibonacci number sorted in ascending order). Please ignore whitespace characters and use the extended Fibonacci.

Return the obtained characters capitalized and connected by the '-' character.

Example

For message = "The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown",

the output should be

FibonacciSecret(message) = "T-H-H-E-D-V-C-E-M-T".

The first Fibonacci is 0 then the first letter is T

The second Fibonacci is 1 then the second letter is H

The third Fibonacci is 1 then the third letter is H ... and so on.

Thus, the answer should be "T-H-H-E-D-V-C-E-M-T".

Tried Code

<?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split($message);

$x = 0;
$y = 1;

for($i=0;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       echo $str_split[$fvalue]."-";
}

?>

Output

h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-h-h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-

Expected Output

the answer should be "T-H-H-E-D-V-C-E-M-T".

Can anyone tell me. Where im going wrong in this one ?

Body:
Your code was almost correct.

You would delete spaces and add two start element of array.

    $message   = str_replace( ' ', '', 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown' );
    $str_split = str_split( $message );

    $x = 0;
    $y = 1;

    $farray[] = $x;
    $farray[] = $y;

    for ( $i = 2; $i <= 10; $i ++ ) {
        $z        = $x + $y;
        $farray[] = $z;
        $x        = $y;
        $y        = $z;
    }

    foreach ( $farray as $key => $fvalue ) {
        echo $str_split[ $fvalue ] . "-";
    }


问:
SQL Server - find absence date occurrences
I have the following dataset:

enter image description here

Here is script for this data:

;with dataset AS (
    select 'EMP01' AS EMP_ID,CAST('2018-01-01' AS DATE) AS PERIOD_START,CAST('2018-01-31' AS DATE) AS PERIOD_END,CAST('2018-01-07' AS DATE) AS CUT_DATE
    UNION
    select 'EMP01' AS EMP_ID,CAST('2018-01-01' AS DATE) AS PERIOD_START,CAST('2018-01-31' AS DATE) AS PERIOD_END,CAST('2018-01-15' AS DATE) AS CUT_DATE
    UNION
    select 'EMP02' AS EMP_ID,CAST('2018-01-01' AS DATE) AS PERIOD_START,CAST('2018-01-31' AS DATE) AS PERIOD_END,CAST('2018-01-09' AS DATE) AS CUT_DATE
)
select *
from dataset
I need to divide these periods (PERIOD_START and PERIOD_END) by CUT_DATE (exclude cut dates from that periods) The number of cut dates could be any (3,5,8 etc).

Expecting result for the dataset above is:

答:
You  would use the LAG function.
If you order by something, the LAG function gives the previous value;

a full description can be found at: http://www.sqlservercentral.com/articles/T-SQL/106783/

Take a look at vkp's answer for a full query

ContentLicense: CC BY-SA 4.0


问:
How to change the opacity of background without changing the content of it?
I don't know how to make background-image opacity 0.5 and the content full opacity.

.about-section {
  height: 100%;
  padding-top: 50px;
  text-align: center;
  /*background: #eee;*/
  background: url(../images/about.jpg);
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
  opacity: 0.3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="about" class="about-section">
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
        <h1 class="head">About Us</h1>

      </div>
    </div>
  </div>
</section></code>```

答:
Is this the sort of thing you're after?

  .about-section {
    height: 100%;
    padding-top: 50px;
    text-align: center;
  }

  .background {
    height: 100%;
    width: 100%;
    position: absolute;
    background: url(https://ichef-1.bbci.co.uk/news/976/media/images/83351000/jpg/_83351965_explorer273lincolnshirewoldssouthpicturebynicholassilkstone.jpg);
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
    opacity: 0.3;

  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="about" class="about-section">
  <div class="background">
  </div>
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
        <h1 class="head">About Us</h1>
      </div>
    </div>
  </div>
</section></code>```

Body:
I don't know how to make background-image opacity 0.5 and the content full opacity.

.about-section {
  height: 100%;
  padding-top: 50px;
  text-align: center;
  /*background: #eee;*/
  background: url(../images/about.jpg);
  background-repeat: no-repeat;
  background-size: contain;
  background-position: center;
  opacity: 0.3;
}

About Us

Body:
Is this the sort of thing you're after?

  .about-section {
    height: 100%;
    padding-top: 50px;
    text-align: center;
  }

  .background {
    height: 100%;
    width: 100%;
    position: absolute;
    background: url(https://ichef-1.bbci.co.uk/news/976/media/images/83351000/jpg/_83351965_explorer273lincolnshirewoldssouthpicturebynicholassilkstone.jpg);
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
    opacity: 0.3;

  }

<section id="about" class="about-section">
  <div class="background">
  </div>
  <div class="container">
    <div class="row">
      <div class="col-lg-12">
        <h1 class="head">About Us</h1>
      </div>
    </div>
  </div>
</section>


问:
text file inside class folder, yet cannot find it

As you can see, the file is right inside the same folder where the class file is. While I tried to have it print the path to it, that is a bummer because no matter what name I type it will always type a full path to that invented file name. The file is comma separated, that I copied pasted into gedit and tried all kinds of extensions, csv, txt and no extension.

What I am trying to do is import it into an array, but the error is clear, no such file or directory.

答:
You should place files that are needed by your program in the classpath of your application so that they will get packaged in your JAR file. You can then read them with getResourceAsStream() Here's an idea of how that would work.

```<code>public class ArrayMain {

public static void main(String[] args) {
    Scanner in = new Scanner(ArrayMain.class.getResourceAsStream("numbers.txt"));
    String[] numbers = in.nextLine().split(",");
    for (int i = 0; i < numbers.length; i++) {
        System.out.println(numbers[i]);
    }
}
</code>```

}

The file numbers.txt is a simple file that looks like this:

1,2,3,4,5,6,7,8,9

Body:
You should place files that are needed by your program in the classpath of your application so that they will get packaged in your JAR file. You can then read them with getResourceAsStream() Here's an idea of how that would work.

public class ArrayMain {

public static void main(String[] args) {
    Scanner in = new Scanner(ArrayMain.class.getResourceAsStream("numbers.txt"));
    String[] numbers = in.nextLine().split(",");
    for (int i = 0; i < numbers.length; i++) {
        System.out.println(numbers[i]);
    }
}

}

The file numbers.txt is a simple file that looks like this:

1,2,3,4,5,6,7,8,9


问:
How to apply WPF stype to children of button template
I'm new to WPF and I would like to change to color of the text and icon of a button template. But it seems I can only change the opacity.
I guess I should apply the style to the children of the button but I don't know how.

Here is the template:

```<code><Button x:Name="btnApp1" Width="56" Height="66" Margin="0,0,0,0" Style="{StaticResource AppButton}">
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <Grid>
                    <iconPacks:PackIconMaterial Kind="StarOutline"  Width="48" Height="48" VerticalAlignment="Top" HorizontalAlignment="Center" Foreground="#FFFFFFFF" />
                    <TextBlock x:Name="tButton" HorizontalAlignment="Center" VerticalAlignment="Bottom" Foreground="#FFFFFFFF" FontWeight="Bold">PVIE</TextBlock>
                </Grid>
            </ControlTemplate>
        </Button.Template>
    </Button>
</code>```

And here is the style:

```<code><Style x:Key="AppButton" TargetType="{x:Type Button}">

    <Setter Property="Opacity" Value="0.25" />
    <Setter Property="Foreground" Value="#FFFF9966" />

    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Trigger.EnterActions>
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetProperty="Opacity" To="1" Duration="0:0:0:0.3" />
                        <!--<ColorAnimation Storyboard.TargetProperty="(Foreground).(SolidColorBrush.Color)" To="Green" Duration="0:0:0:0.3" />-->

                        <ColorAnimationUsingKeyFrames Storyboard.Target="{Binding RelativeSource={RelativeSource TemplatedParent}}"
                                                        Storyboard.TargetProperty="(TextBox.Foreground).(SolidColorBrush.Color)">
                            <EasingColorKeyFrame KeyTime="0" Value="Green" />
                        </ColorAnimationUsingKeyFrames>

                    </Storyboard>
                </BeginStoryboard>
            </Trigger.EnterActions>
            <Trigger.ExitActions>
                <BeginStoryboard>
                    <Storyboard>
                        <DoubleAnimation Storyboard.TargetProperty="Opacity" To="0.25" Duration="0:0:0:0.3" />
                        <!--<ColorAnimation Storyboard.TargetProperty="(Foreground).(SolidColorBrush.Color)" To="White" Duration="0:0:0:0.3" />-->

                        <ColorAnimationUsingKeyFrames Storyboard.Target="{Binding RelativeSource={RelativeSource TemplatedParent}}"
                                                        Storyboard.TargetProperty="(TextBox.Foreground).(SolidColorBrush.Color)">
                            <EasingColorKeyFrame KeyTime="0" Value="White" />
                        </ColorAnimationUsingKeyFrames>

                    </Storyboard>
                </BeginStoryboard>
            </Trigger.ExitActions>
        </Trigger>
    </Style.Triggers>

</Style>
</code>```

Thanks for your help.

答:
Bind the Foreground property of the TextBlock and the Icon in the ControlTemplate using a {TemplateBinding}:

```<code><Button x:Name="btnApp1" Width="56" Height="66" Margin="0,0,0,0" Style="{StaticResource AppButton}">
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Grid>
                <iconPacks:PackIconMaterial Kind="StarOutline"  Width="48" Height="48" VerticalAlignment="Top" HorizontalAlignment="Center"
                                Foreground="{TemplateBinding Foreground}" />
                <TextBlock x:Name="tButton" HorizontalAlignment="Center" VerticalAlignment="Bottom"
                           Foreground="{TemplateBinding Foreground}" FontWeight="Bold">PVIE</TextBlock>
            </Grid>
        </ControlTemplate>
    </Button.Template>
</Button>
</code>```

Body:
I'm new to WPF and I would like to change to color of the text and icon of a button template. But it seems I can only change the opacity.
I guess I should apply the style to the children of the button but I don't know how.

Here is the template:

<Button x:Name="btnApp1" Width="56" Height="66" Margin="0,0,0,0" Style="{StaticResource AppButton}">
        <Button.Template>
            <ControlTemplate TargetType="Button">
                <Grid>
                    <iconPacks:PackIconMaterial Kind="StarOutline"  Width="48" Height="48" VerticalAlignment="Top" HorizontalAlignment="Center" Foreground="#FFFFFFFF" />
                    <TextBlock x:Name="tButton" HorizontalAlignment="Center" VerticalAlignment="Bottom" Foreground="#FFFFFFFF" FontWeight="Bold">PVIE</TextBlock>
                </Grid>
            </ControlTemplate>
        </Button.Template>
    </Button>

And here is the style:

</Style>

Thanks for your help.

Body:
Bind the Foreground property of the TextBlock and the Icon in the ControlTemplate using a {TemplateBinding}:

<Button x:Name="btnApp1" Width="56" Height="66" Margin="0,0,0,0" Style="{StaticResource AppButton}">
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Grid>
                <iconPacks:PackIconMaterial Kind="StarOutline"  Width="48" Height="48" VerticalAlignment="Top" HorizontalAlignment="Center"
                                Foreground="{TemplateBinding Foreground}" />
                <TextBlock x:Name="tButton" HorizontalAlignment="Center" VerticalAlignment="Bottom"
                           Foreground="{TemplateBinding Foreground}" FontWeight="Bold">PVIE</TextBlock>
            </Grid>
        </ControlTemplate>
    </Button.Template>
</Button>


问:
Show trailing whitespace on emacs only on non-empty lines
Right now I'm using:

```<code>(setq show-trailing-whitespace t)
</code>```

In my .emacs to show trailing whitespace for my CC mode. I can't seem to figure out how to have it not show the whitespace font for whitespace only lines.

Empty lines separating indenting code are sometimes indented at the code level and sometimes not indented at all, and I don't want to draw my attention to a line I don't care to change.

I'd like to stick to built-in emacs modules, but I'm willing to use whitespace.el but it's not clear how to configure it to do this.

答:
With

"\\b.*\\(\\(\t\\| \\|\xA0\\|\x8A0\\|\x920\\|\xE20\\|\xF20\\)+\\)$"

the word does not need to be directly in front of the trailing whitespaces but there can be e.g. punctuation characters between them (i.e. this also highlights trailing whitespaces behind non-word characters).

Edit:

Using

"\\b.*?\\(\\(\t\\| \\|\xA0\\|\x8A0\\|\x920\\|\xE20\\|\xF20\\)+\\)$")

highlights all the trailing whitespaces and thus eliminates the drawback mentioned in comment #1.

Body:
Right now I'm using:

(setq show-trailing-whitespace t)

In my .emacs to show trailing whitespace for my CC mode. I can't seem to figure out how to have it not show the whitespace font for whitespace only lines.

Empty lines separating indenting code are sometimes indented at the code level and sometimes not indented at all, and I don't want to draw my attention to a line I don't care to change.

I'd like to stick to built-in emacs modules, but I'm willing to use whitespace.el but it's not clear how to configure it to do this.


问:
How to change a 1 line output to multiple lines
I have this line in a .txt file:

```<code>I just got home.\nDid you make lunch?\nOh, I see...
</code>```

It's just one line, it's formatted like this for a game, so it is exactly like this, with the \n's.

What I need is that when I print this, after I store it into a variable or list, to print it on multiple lines, respecting the \n. Like this:

```<code>I just got home.\n
Did you make lunch?\n
Oh, I see...
</code>```

I can't think of a way to modify the output to make a new line after the program displays each \n. How would I do this?

答:
Using of str.replace() function would be enough:

```<code>s="I just got home.\nDid you make lunch?\nOh, I see..."
print(s.replace("\n", "\\n\n"))
</code>```

The output:

```<code>I just got home.\n
Did you make lunch?\n
Oh, I see...
</code>```

Body:
I have this line in a .txt file:

I just got home.\nDid you make lunch?\nOh, I see...

It's just one line, it's formatted like this for a game, so it is exactly like this, with the \n's.

What I need is that when I print this, after I store it into a variable or list, to print it on multiple lines, respecting the \n. Like this:

I just got home.\n
Did you make lunch?\n
Oh, I see...

I can't think of a way to modify the output to make a new line after the program displays each \n. How would I do this?

Body:
Using of str.replace() function would be enough:

s="I just got home.\nDid you make lunch?\nOh, I see..."
print(s.replace("\n", "\\n\n"))

The output:

I just got home.\n
Did you make lunch?\n
Oh, I see...


问:
Compare two pandas dataframe with different size
I have one massive pandas dataframe with this structure:

```<code>df1:
    A   B
0   0  12
1   0  15
2   0  17
3   0  18
4   1  45
5   1  78
6   1  96
7   1  32
8   2  45
9   2  78
10  2  44
11  2  10
</code>```

And a second one, smaller like this:

```<code>df2
   G   H
0  0  15
1  1  45
2  2  31
</code>```

I want to add a column to my first dataframe following this rule: column df1.C = df2.H when df1.A == df2.G

I manage to do it with for loops, but the database is massive and the code run really slowly so I am looking for a Pandas-way or numpy to do it.

Many thanks,

Boris

答:
You probably want to use a merge:

```<code>df=df1.merge(df2,left_on="A",right_on="G")
</code>```

will give you a dataframe with 3 columns, but the third one's name will be H

```<code>df.columns=["A","B","C"]
</code>```

will then give you the column names you want

Body:
I have one massive pandas dataframe with this structure:

df1:
    A   B
0   0  12
1   0  15
2   0  17
3   0  18
4   1  45
5   1  78
6   1  96
7   1  32
8   2  45
9   2  78
10  2  44
11  2  10

And a second one, smaller like this:

df2
   G   H
0  0  15
1  1  45
2  2  31

I want to add a column to my first dataframe following this rule: column df1.C = df2.H when df1.A == df2.G

I manage to do it with for loops, but the database is massive and the code run really slowly so I am looking for a Pandas-way or numpy to do it.

Many thanks,

Boris

Body:
You probably want to use a merge:

df=df1.merge(df2,left_on="A",right_on="G")

will give you a dataframe with 3 columns, but the third one's name will be H

df.columns=["A","B","C"]

will then give you the column names you want


问:
Spark - Is it possible to control placement of partitions to nodes?
In Spark, custom Partitioners can be supplied for RDD's. Normally, the produced partitions are randomly distributed to set of workers. For example if we have 20 partitions and 4 workers, each worker will (approximately) get 5 partitions. However the placement of partitions to workers (nodes) seems random like in the table below.

```<code>          trial 1    trial 2
worker 1: [10-14]    [15-19]
worker 2: [5-9]      [5-9]
worker 3: [0-4]      [10-14]
worker 4: [15-19]    [0-4]
</code>```

This is fine for operations on a single RDD, but when you are using join() or cogroup() operations that span multiple RDD's, the communication between those nodes becomes a bottleneck. I would use the same partitioner for multiple RDDs and want to be sure they will end up on the same node so the subsequent join() would not be costly. Is it possible to control the placement of partitions to workers (nodes)?

```<code>          desired
worker 1: [0-4]
worker 2: [5-9]
worker 3: [10-14]
worker 4: [15-19]
</code>```

答:
I would use the same partitioner for multiple RDDs and want to be sure
  they will end up on the same node so the subsequent join() would not
  be costly.

This is the right way to handle joins between RDDs so that records to be joined are ensured to be in the same partition/executor.

Is it possible to control the placement of partitions to workers
  (nodes)

It is not possible to explicitly specify the worker node for each partition. This would break the abstractions of parallel computation defined for Spark or any other parallel computation frameworks like Map-Reduce/Tez etc.

Spark and other parallel computation frameworks are designed to fault tolerant. So this means if a small subset of worker nodes fail, then are replaced with other worker nodes and this process occurs transparently to the user application.

These abstractions would break if a user is allowed to explicitly refer a worker-node in the application. The only means of governing the placement of a partition of RDD is by specifying your own partitions for the RDD partitioner.

Body:
In Spark, custom Partitioners can be supplied for RDD's. Normally, the produced partitions are randomly distributed to set of workers. For example if we have 20 partitions and 4 workers, each worker will (approximately) get 5 partitions. However the placement of partitions to workers (nodes) seems random like in the table below.

          trial 1    trial 2
worker 1: [10-14]    [15-19]
worker 2: [5-9]      [5-9]
worker 3: [0-4]      [10-14]
worker 4: [15-19]    [0-4]

This is fine for operations on a single RDD, but when you are using join() or cogroup() operations that span multiple RDD's, the communication between those nodes becomes a bottleneck. I would use the same partitioner for multiple RDDs and want to be sure they will end up on the same node so the subsequent join() would not be costly. Is it possible to control the placement of partitions to workers (nodes)?

          desired
worker 1: [0-4]
worker 2: [5-9]
worker 3: [10-14]
worker 4: [15-19]


问:
How to properly give argument to docker entrypoint when building a container (docker run ...)?
My goal is to share properly an docker image between 2 servers.
I need to give the name of the hostname when creating my containers. </p>

<p>How can I give an arg to docker run command that will take account by the entrypoint script. </p>

答:
You can use the option e of docker run command like this :

```<code>docker run -it -e ARG1=foo -e ARG2=bar ubuntu
</code>```

It the previous example, we define 2 args called ARG1 and ARG2.

For the hostname, when you specify option --hostname of Docker run, it will set a variable in env HOSTNAME which can be used.

Body:
My goal is to share properly an docker image between 2 servers.
I need to give the name of the hostname when creating my containers.

How can I give an arg to docker run command that will take account by the entrypoint script.

Body:
You can use the option e of docker run command like this :

docker run -it -e ARG1=foo -e ARG2=bar ubuntu

It the previous example, we define 2 args called ARG1 and ARG2.

For the hostname, when you specify option --hostname of Docker run, it will set a variable in env HOSTNAME which can be used.


问:
The service certificate is not provided for target '###' Specify a service certificate in ClientCredentials
I have implemented a test Client / Server that implements UserName message authentication over WCF.  It almost all works however I have fallen at the last hurdle.

I get an InvalidOperationException that reads

The service certificate is not provided for target 'http://localhost:8732/Design_Time_Addresses/EvalServiceLibrary/Service1/'. Specify a service certificate in ClientCredentials.

Can anyone shed any light?

Thanks

答:
Your client needs to be able to authenticate the service by reference to an X509certificate, the public key of which it will use to encrypt messages sent to the service.

The service certificate is identified on the client side by the ServiceCertificate property of the ClientCredentials. The error message is telling you that your configuration/code hasn't set this up correctly. If you post your code/config we may be able to tell you what's wrong.


问:
sqlite3 c++ function: INSERT statement not executed when it comes as an argument
I am implementing a function that receives any SQL statement and then executes it.

```<code>void dbExec(std::string str, bool vertical)
{
   sqlite3 *db; // Create db object
   char *zErrMsg = 0;
   int rc;
   const char *sql = str.c_str(); // Convert string to char
   sqlite3_stmt *stmt = NULL; // SQL statement

   /* Open Database */
   rc = sqlite3_open("db/survey.db",&db);
   if (rc)
   {
      fprintf(stderr, "DBOPEN_ERR: %s\n", sqlite3_errmsg(db));
   }

   /* Execute SQL statement */
   rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL); // Prepare statement

   if (rc != SQLITE_OK )
   { // Check error
      fprintf(stderr, "DB error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }

   int cols = sqlite3_column_count(stmt); // Number of columns
   const char *data = NULL; // data char pointer

   if (vertical)
   {
      sqlite3_step( stmt );
      for (int i = 0; i < cols; i++)
      {
         // Print column name and info
         data = (const char*)sqlite3_column_text( stmt, i );
         std::cout << std::setw(20) << sqlite3_column_name(stmt,i)
                   << std::setw(30) << (data ? data : "[NULL]" );
         printf("\n");
      }
   }
   else
   {
      for (int i = 0; i < cols; i++)
      {
         // Print column name
         std::cout << std::setw(15) << sqlite3_column_name(stmt,i);
      }
      printf("\n");

      while ( sqlite3_step( stmt ) == SQLITE_ROW )
      {
         // print each row
         for (int i = 0; i < cols; i++)
         {
            data = (const char*)sqlite3_column_text( stmt, i );
            std::cout << std::setw(15) << (data ? data : "[NULL]" );
         }
         printf("\n");
      }
   }

   /* Close Database */
   sqlite3_close(db);
}
</code>```

When the str argument is:

```<code>SELECT * FROM TABLE
</code>```

it works perfect. If the str argument is:

```<code>INSERT INTO TABLE (COL1) VALUES(100)
</code>```

it doesn't work.

However, if inside of the function I add the following line:

```<code>str = "INSERT INTO TABLE (COL1) VALUES(100)";
</code>```

it works perfect. I tried many things but I still can't figure out what's going on... Any ideas?

Thanks!

EDIT:
The function dbExec is being called in this way:

```<code>void addBorehole()
{
   std::string statement;
   statement = "INSERT INTO BOREHOLE (TOTAL_DEPTH) VALUES (45)";

   dbExec(statement, false);
}
</code>```

答:
OK, the problem was solved by writing the following line before closing the database:

```<code>sqlite3_finalize( stmt );
</code>```

Info: https://sqlite.org/c3ref/close.html

If the database connection is associated with unfinalized prepared
  statements or unfinished sqlite3_backup objects then sqlite3_close()
  will leave the database connection open and return SQLITE_BUSY.

However, I still didn't get why it worked when I hardcoded the statement inside of the function.

Thank you!

Body:
I am implementing a function that receives any SQL statement and then executes it.

void dbExec(std::string str, bool vertical)
{
   sqlite3 *db; // Create db object
   char *zErrMsg = 0;
   int rc;
   const char *sql = str.c_str(); // Convert string to char
   sqlite3_stmt *stmt = NULL; // SQL statement

   /* Open Database */
   rc = sqlite3_open("db/survey.db",&db);
   if (rc)
   {
      fprintf(stderr, "DBOPEN_ERR: %s\n", sqlite3_errmsg(db));
   }

   /* Execute SQL statement */
   rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL); // Prepare statement

   if (rc != SQLITE_OK )
   { // Check error
      fprintf(stderr, "DB error: %s\n", zErrMsg);
      sqlite3_free(zErrMsg);
   }

   int cols = sqlite3_column_count(stmt); // Number of columns
   const char *data = NULL; // data char pointer

   if (vertical)
   {
      sqlite3_step( stmt );
      for (int i = 0; i < cols; i++)
      {
         // Print column name and info
         data = (const char*)sqlite3_column_text( stmt, i );
         std::cout << std::setw(20) << sqlite3_column_name(stmt,i)
                   << std::setw(30) << (data ? data : "[NULL]" );
         printf("\n");
      }
   }
   else
   {
      for (int i = 0; i < cols; i++)
      {
         // Print column name
         std::cout << std::setw(15) << sqlite3_column_name(stmt,i);
      }
      printf("\n");

      while ( sqlite3_step( stmt ) == SQLITE_ROW )
      {
         // print each row
         for (int i = 0; i < cols; i++)
         {
            data = (const char*)sqlite3_column_text( stmt, i );
            std::cout << std::setw(15) << (data ? data : "[NULL]" );
         }
         printf("\n");
      }
   }

   /* Close Database */
   sqlite3_close(db);
}

When the str argument is:

SELECT * FROM TABLE

it works perfect. If the str argument is:

INSERT INTO TABLE (COL1) VALUES(100)

it doesn't work.

However, if inside of the function I add the following line:

str = "INSERT INTO TABLE (COL1) VALUES(100)";

it works perfect. I tried many things but I still can't figure out what's going on... Any ideas?

Thanks!

EDIT:
The function dbExec is being called in this way:

void addBorehole()
{
   std::string statement;
   statement = "INSERT INTO BOREHOLE (TOTAL_DEPTH) VALUES (45)";

   dbExec(statement, false);
}

Body:
OK, the problem was solved by writing the following line before closing the database:

sqlite3_finalize( stmt );

Info: https://sqlite.org/c3ref/close.html

If the database connection is associated with unfinalized prepared
  statements or unfinished sqlite3_backup objects then sqlite3_close()
  will leave the database connection open and return SQLITE_BUSY.

However, I still didn't get why it worked when I hardcoded the statement inside of the function.

Thank you!


问:
clojure definition of list in source code
I was browsing the clojure source code this morning, and near the top of clojure/core.clj I found this:

```<code>(def
    ^{:arglists '([& items])
      :doc "Creates a new list containing the items."
      :added "1.0"}
    list (. clojure.lang.PersistentList creator))
</code>```

The thing that looks odd to me is the symbol creator. It doesn't appear anywhere in the file above it. Why is that not a problem?

答:
The dot special form is used for java interop. Since clojure.lang.PersistentList is a class name symbol,

```<code>(. clojure.lang.PersistentList creator)
</code>```

is an access of the static creator field.

https://github.com/clojure/clojure/blob/clojure-1.8.0/src/jvm/clojure/lang/PersistentList.java#L66

Body:
I was browsing the clojure source code this morning, and near the top of clojure/core.clj I found this:

(def
    ^{:arglists '([& items])
      :doc "Creates a new list containing the items."
      :added "1.0"}
    list (. clojure.lang.PersistentList creator))

The thing that looks odd to me is the symbol creator. It doesn't appear anywhere in the file above it. Why is that not a problem?

Body:
The dot special form is used for java interop. Since clojure.lang.PersistentList is a class name symbol,

(. clojure.lang.PersistentList creator)

is an access of the static creator field.

https://github.com/clojure/clojure/blob/clojure-1.8.0/src/jvm/clojure/lang/PersistentList.java#L66


问:
Automate Save As File with IUIAutomation in Internet Explorer 9+
There are 63 entries on Stack Overflow related to "IE VBA Save-as" topic.

That is to automate the Download Notification Bar of IE 9+.

Several methods are recommended to automate this process.

Method 1. using XMLHttp   (example link, applied to sites that show the direct url of to-be-downloaded file)

Method 2. using autoitx.dll to send hotkeys (example link, not so stable based on my experience)

Method 3. using IUIAutomation (blogspot link )

I think Method 3 is suitable for most of these situations.
However, I have NOT successfully tried this method, because
1) I can't add reference to  UIAutomationCore.dll
   I get this dll under C:\Windows\SysWOW64 and the project(*.xlsm) folder

   Question1:Please tell me how to add reference to  UIAutomationCore.dll.

2) Subroutine Download_Save_As in the page (blogspot link ) uses sending shortkeys to navigate to the save-as window.

    I don't thinks this is stable enough as I tried the AutoitX way.

    Question2:Is it possible to click the save-as option by using purely IUIAutomation way? and how to?

答: You have to find the file in reference library and move it where it is looking. You can hover on a reference to see where they are kept. I don't know why this particular reference's location is different. </p>


问:
Using gpu for tensorflow's calculation on raspberry pi
I am developing robot with computer vision on Raspberry Pi 3 with Tensorflow. Can I use gpu for deep learning on raspberry pi 3? </p>

答:
UPDATE :

Here is an alternative backend for Keras called plaidml that is not Tensorflow. The major selling feature is a speedup on non-Nvidia graphics cards.  It still isn't Tensorflow, but it may be a viable option.

HERE IS MY OLD ANSER PRIOR TO 2018-09 :

The short answer is no, it isn't possible at this time since Tensorflow leverages Nvidia drivers to power Nvidia GPUs and Raspberry Pi does not have Nvidia hardware.

One of two things have to change for you to have access to GPUs for a small form computing, Tensorflow has to support OpenCl (tracked here), or you have to switch platforms to something that has a Nvidia GPU like this

Sorry to be the bringer of bad news.


问:
Understanding behavior of cout.operator<<()
According to the top answer to this question, cout << expr is equivalent to cout.operator<<(expr).

According to responses to this question, the statement above is untrue.

According to my own testing, cout.operator<<() is the same as cout << when given an integer.  When given a float, cout.operator<<() coerces it to an integer.  When given a string literal, as in cout.operator<<("hello world"), it outputs what appears to be a memory address.  And when given a variable holding a std::string, it gives a compiler error.

Could anyone give a beginner-to-intermediate-level explanation of what's going on?

答:
It depends on expr.

The answers to both questions are speaking to that specific case, not a blanket guarantee.

In fact, some of the operator<<s are free functions, and some are member functions.

Consult your favourite C++ reference to find out which.


问:
LINQ to SQL: Reusing DataContext
I have a number of static methods that perform simple operations like insert or delete a record. All these methods follow this template of using:

```<code>public static UserDataModel FromEmail(string email)
{
    using (var db = new MyWebAppDataContext())
    {
        db.ObjectTrackingEnabled = false;
        return (from u in db.UserDataModels
                where u.Email == email
                select u).Single();
    }
}
</code>```

I also have a few methods that need to perform multiple operations that use a DataContext:

```<code>public static UserPreferencesDataModel Preferences(string email)
{
    return UserDataModel.Preferences(UserDataModel.FromEmail(email));
}

private static UserPreferencesViewModel Preferences(UserDataModel user)
{
    using(var db = new MyWebAppDataContext())
    {
        var preferences = (from u in db.UserDataModels
                          where u == user
                          select u.Preferences).Single();

        return new UserPreferencesViewModel(preferences);
    }
}
</code>```

I like that I can divide simple operations into faux-stored procedures in my data models with static methods like FromEmail(), but I'm concerned about the cost of having Preferences() invoking two connections (right?) via the two using DataContext statements.

Do I need to be? Is what I'm doing less efficient than using a single using(var db = new MyWebAppDataContext()) statement?

答:
Of cause there is some overhead in creating a new DataContext each time. But its a good practice to do as Ludwig stated: One context per unit of work.

Its using connection pooling so its not a too expensive operation.

Title: LINQ to SQL: Reusing DataContext

Body:
I have a number of static methods that perform simple operations like insert or delete a record. All these methods follow this template of using:

public static UserDataModel FromEmail(string email)
{
    using (var db = new MyWebAppDataContext())
    {
        db.ObjectTrackingEnabled = false;
        return (from u in db.UserDataModels
                where u.Email == email
                select u).Single();
    }
}

I also have a few methods that need to perform multiple operations that use a DataContext:

public static UserPreferencesDataModel Preferences(string email)
{
    return UserDataModel.Preferences(UserDataModel.FromEmail(email));
}

private static UserPreferencesViewModel Preferences(UserDataModel user)
{
    using(var db = new MyWebAppDataContext())
    {
        var preferences = (from u in db.UserDataModels
                          where u == user
                          select u.Preferences).Single();

        return new UserPreferencesViewModel(preferences);
    }
}

I like that I can divide simple operations into faux-stored procedures in my data models with static methods like FromEmail(), but I'm concerned about the cost of having Preferences() invoking two connections (right?) via the two using DataContext statements.

Do I need to be? Is what I'm doing less efficient than using a single using(var db = new MyWebAppDataContext()) statement?


问:
Save CURL result in a variable PHP
I'm new to the whole CURL library in PHP and managed to sucesfully get post data from a website using the following code:

```<code> <?php
    $postcode="6942GJ";
    $huisnummer="8";
    $marktsegment="27";
    $aansluiting="-";
    $url="http://notimportantforstackoverflow.com";
    $postdata = "postcode=".$postcode."&huisnummer=".$huisnummer."&marktsegment=".$marktsegment."&aansluiting=".$aansluiting;
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $result = curl_exec ($ch);
    curl_close($ch);
    ?>
</code>```

Wich returns the following table:

    Ean code aansluiting

    Straatnaam

    Huisnr.

    Huisnr. toev.

    Woonplaats

    Postcode

    Bijzondere aansluiting

    Markt segment

    Naam Netbeheerder

    Ean Netbeheerder

    871687140007253845

    Pittelderstraat

    8

    DIDAM

    6942GJ

    NEE

         GAS

    Liander NB

    8716871000002

```

I want to work with the resulting data specifically the resulting string "Liander NB" I want to make a var out of this result like so $beheerder ="Liander NB"; But I don't know how to make a variable out of the resulting CURL data.

答:
Thanks Barmar, I've added the returntransfer.
used a slightly diffrent approach with the PHPSimpleDOM parser but the result is the same, I just find it easier to work with as opposed to DomDocument.</p>

```<code><?php
$postcode     = ($_POST['postcode']);
$huisnummer   = ($_POST['huisnummer']);
$marktsegment = "27";
$aansluiting  = "-";
$url          = "xxxxxxxxx";
include('simple_html_dom.php');

$postdata = "postcode=" . $postcode . "&huisnummer=" . $huisnummer . "&marktsegment=" . $marktsegment . "&aansluiting=" . $aansluiting;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

// Create a DOM object
$dom = new simple_html_dom();
// Load HTML from a string
$dom->load(curl_exec($ch));

$gasleverancier = $dom->find('td', 38)->plaintext; // zero based index selector

$gasleverancier = trim($gasleverancier);
</code>```

Title: Save CURL result in a variable PHP

Body:
I'm new to the whole CURL library in PHP and managed to sucesfully get post data from a website using the following code:

 <?php
    $postcode="6942GJ";
    $huisnummer="8";
    $marktsegment="27";
    $aansluiting="-";
    $url="http://notimportantforstackoverflow.com";
    $postdata = "postcode=".$postcode."&huisnummer=".$huisnummer."&marktsegment=".$marktsegment."&aansluiting=".$aansluiting;
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $result = curl_exec ($ch);
    curl_close($ch);
    ?>

Wich returns the following table:

    Ean code aansluiting

    Straatnaam

    Huisnr.

    Huisnr. toev.

    Woonplaats

    Postcode

    Bijzondere aansluiting

    Markt segment

    Naam Netbeheerder

    Ean Netbeheerder

    871687140007253845

    Pittelderstraat

    8

    DIDAM

    6942GJ

    NEE

         GAS

    Liander NB

    8716871000002

I want to work with the resulting data specifically the resulting string "Liander NB" I want to make a var out of this result like so $beheerder ="Liander NB"; But I don't know how to make a variable out of the resulting CURL data.

Body:
Thanks Barmar, I've added the returntransfer.
used a slightly diffrent approach with the PHPSimpleDOM parser but the result is the same, I just find it easier to work with as opposed to DomDocument.

<?php
$postcode     = ($_POST['postcode']);
$huisnummer   = ($_POST['huisnummer']);
$marktsegment = "27";
$aansluiting  = "-";
$url          = "xxxxxxxxx";
include('simple_html_dom.php');

$postdata = "postcode=" . $postcode . "&huisnummer=" . $huisnummer . "&marktsegment=" . $marktsegment . "&aansluiting=" . $aansluiting;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

// Create a DOM object
$dom = new simple_html_dom();
// Load HTML from a string
$dom->load(curl_exec($ch));

$gasleverancier = $dom->find('td', 38)->plaintext; // zero based index selector

$gasleverancier = trim($gasleverancier);


问:
logback in spring-OSGI with pax-runner
We are running OSGI bundles with pax-runner. We are logging using logback over slf4j.

The problem is logback tries to look for logback.xml in classpath, but in pax-runner where should I place logback.xml so that pax-runner configure logback accordingly?

I have tried with JoranConfigurator to load logback.xml which is included in bundle classpath, but it assumes classpath as the container in which the bundle is running (in my case it is runner folder where all the bundle jars are placed).

Any help would be appreciated.

Thanks in advace.

答:
Another solution would be to configure logback to read the configuration
file from outside the classpath.

This can be done by setting VM options -Dlogback.configurationFile=/dir/conf/logback.xml

Title: logback in spring-OSGI with pax-runner


问:
BASH. Does not work correctly search and replace of word combination from array in a loop
i want to write script of mass searching and replacing of word combinations using bash.
I have a script:

```<code>#!/bin/bash
text="cm punk, dolph ziggler, duke nukem"
IFS=", "
my=( $text )
echo ${my[@]}

text2="the undertaker, john cena, the rock"
IFS=", "
my2=( $text2 )
echo ${my2[@]}

for ((i=0;i<${#my[@]};++i)); do
       sed -i "s/${my[i]}/${my2[i]}/g" text.txt
done
</code>```

For the first look, it works. I saw in a result, script changed word combinations.
But, i decided to see in debug:

```<code>+ (( i=0 ))
+ (( i<6 ))
+ sed -i s/cm/the/g text.txt
+ (( ++i ))
+ (( i<6 ))
+ sed -i s/punk/undertaker/g text.txt
+ (( ++i ))
+ (( i<6 ))
+ sed -i s/dolph/john/g text.txt
+ (( ++i ))
+ (( i<6 ))
+ sed -i s/ziggler/cena/g text.txt
+ (( ++i ))
+ (( i<6 ))
+ sed -i s/duke/the/g text.txt
+ (( ++i ))
+ (( i<6 ))
+ sed -i s/nukem/rock/g text.txt
+ (( ++i ))
+ (( i<6 ))
</code>```

How you can see, it makes search and replace word by word. But i need swearch and replace word combination. for example, i tried to do it with using only one word combinations in variables (in debug):

```<code>sed -i 's/cm punk/the undertaker/g' text.txt
</code>```

How you think, where i have error ?

答:
IFS variable is not a patter to split string into tokens, but list of characters acting as a separator. So, by setting IFS=", " you declare you want to have either comma as space as a token delimiter. So, either you will initialize array directly, like:

```<code>my=("cm punk", "dolph ziggler", "duke nukem")
</code>```

or modify the text/text2 variables and use sole comma as a separator:

```<code>text="cm punk,dolph ziggler,duke nukem"
IFS=","
my=( $text )
</code>```

Body:
i want to write script of mass searching and replacing of word combinations using bash.
I have a script:

#!/bin/bash
text="cm punk, dolph ziggler, duke nukem"
IFS=", "
my=( $text )
echo ${my[@]}

text2="the undertaker, john cena, the rock"
IFS=", "
my2=( $text2 )
echo ${my2[@]}

for ((i=0;i<${#my[@]};++i)); do
       sed -i "s/${my[i]}/${my2[i]}/g" text.txt
done

For the first look, it works. I saw in a result, script changed word combinations.
But, i decided to see in debug:

+ (( i=0 ))
+ (( i<6 ))
+ sed -i s/cm/the/g text.txt
+ (( ++i ))
+ (( i<6 ))
+ sed -i s/punk/undertaker/g text.txt
+ (( ++i ))
+ (( i<6 ))
+ sed -i s/dolph/john/g text.txt
+ (( ++i ))
+ (( i<6 ))
+ sed -i s/ziggler/cena/g text.txt
+ (( ++i ))
+ (( i<6 ))
+ sed -i s/duke/the/g text.txt
+ (( ++i ))
+ (( i<6 ))
+ sed -i s/nukem/rock/g text.txt
+ (( ++i ))
+ (( i<6 ))

How you can see, it makes search and replace word by word. But i need swearch and replace word combination. for example, i tried to do it with using only one word combinations in variables (in debug):

sed -i 's/cm punk/the undertaker/g' text.txt

How you think, where i have error ?

Body:
IFS variable is not a patter to split string into tokens, but list of characters acting as a separator. So, by setting IFS=", " you declare you want to have either comma as space as a token delimiter. So, either you will initialize array directly, like:

my=("cm punk", "dolph ziggler", "duke nukem")

or modify the text/text2 variables and use sole comma as a separator:

text="cm punk,dolph ziggler,duke nukem"
IFS=","
my=( $text )


问:
Issue with this xsl template to calculate max for node list
The below for-each loop is only picking up first value for X.. and not actually finding maximum could you please let me know the issue here.</p>

```<code><xsl:for-each select=".//X">
     <xsl:choose>
        <xsl:when test="position() = 1">
           <xsl:value-of select="abc:set_variable($_XDOCTX, 'v1t1', abc:normalize_string($_XDOCTX, (.//.)[1]))"/>
        </xsl:when>
        <xsl:when test="abc:nOne(abc:normalize_string($_XDOCTX, (.//.)[1])) > number(abc:get_variable($_XDOCTX, 'v1t1'))">
           <xsl:value-of select="abc:set_variable($_XDOCTX, 'v1t1', abc:normalize_string($_XDOCTX, (.//.)[1]))"/>
        </xsl:when>
     </xsl:choose>
  </xsl:for-each>
</code>```

答:
To sort such large sequences of digits numerically, you can split them into substrings and sort by each substring individually - for example:

XML

```<code><input>
    <item>123456789.0123456780</item>
    <item>123456789.0123456781</item>
    <item>123456789.0123456782</item>
    <item>123456789.0123456783</item>
    <item>123456789.0123456784</item>
    <item>123456789.0123456785</item>
    <item>123456789.0123456786</item>
    <item>123456789.0123456787</item>
    <item>123456789.0123456788</item>
    <item>123456789.0123456789</item>
    <item>123456789.012344</item>
    <item>123456789.012346</item>
</input>
</code>```

XSLT 1.0

```<code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/input">
    <output>
        <xsl:for-each select="item">
            <xsl:sort select="substring-before(., '.')" data-type="number" order="descending"/>
            <xsl:sort select="concat('0.', substring-after(., '.'))" data-type="number" order="descending"/>
            <xsl:copy-of select="."/>
        </xsl:for-each>
    </output>
</xsl:template>

</xsl:stylesheet>
</code>```

Result

```<code><?xml version="1.0" encoding="UTF-8"?>
<output>
  <item>123456789.012346</item>
  <item>123456789.0123456789</item>
  <item>123456789.0123456788</item>
  <item>123456789.0123456787</item>
  <item>123456789.0123456786</item>
  <item>123456789.0123456785</item>
  <item>123456789.0123456784</item>
  <item>123456789.0123456783</item>
  <item>123456789.0123456782</item>
  <item>123456789.0123456781</item>
  <item>123456789.0123456780</item>
  <item>123456789.012344</item>
</output>
</code>```

Note that the limitation is processor-dependent: I could not reproduce the problem using either Xalan or Saxon.

Body:
The below for-each loop is only picking up first value for X.. and not actually finding maximum could you please let me know the issue here.

<xsl:for-each select=".//X">
     <xsl:choose>
        <xsl:when test="position() = 1">
           <xsl:value-of select="abc:set_variable($_XDOCTX, 'v1t1', abc:normalize_string($_XDOCTX, (.//.)[1]))"/>
        </xsl:when>
        <xsl:when test="abc:nOne(abc:normalize_string($_XDOCTX, (.//.)[1])) > number(abc:get_variable($_XDOCTX, 'v1t1'))">
           <xsl:value-of select="abc:set_variable($_XDOCTX, 'v1t1', abc:normalize_string($_XDOCTX, (.//.)[1]))"/>
        </xsl:when>
     </xsl:choose>
  </xsl:for-each>

Body:
To sort such large sequences of digits numerically, you can split them into substrings and sort by each substring individually - for example:

XML

<input>
    <item>123456789.0123456780</item>
    <item>123456789.0123456781</item>
    <item>123456789.0123456782</item>
    <item>123456789.0123456783</item>
    <item>123456789.0123456784</item>
    <item>123456789.0123456785</item>
    <item>123456789.0123456786</item>
    <item>123456789.0123456787</item>
    <item>123456789.0123456788</item>
    <item>123456789.0123456789</item>
    <item>123456789.012344</item>
    <item>123456789.012346</item>
</input>

XSLT 1.0

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="/input">
    <output>
        <xsl:for-each select="item">
            <xsl:sort select="substring-before(., '.')" data-type="number" order="descending"/>
            <xsl:sort select="concat('0.', substring-after(., '.'))" data-type="number" order="descending"/>
            <xsl:copy-of select="."/>
        </xsl:for-each>
    </output>
</xsl:template>

</xsl:stylesheet>

Result

<?xml version="1.0" encoding="UTF-8"?>
<output>
  <item>123456789.012346</item>
  <item>123456789.0123456789</item>
  <item>123456789.0123456788</item>
  <item>123456789.0123456787</item>
  <item>123456789.0123456786</item>
  <item>123456789.0123456785</item>
  <item>123456789.0123456784</item>
  <item>123456789.0123456783</item>
  <item>123456789.0123456782</item>
  <item>123456789.0123456781</item>
  <item>123456789.0123456780</item>
  <item>123456789.012344</item>
</output>

Note that the limitation is processor-dependent: I could not reproduce the problem using either Xalan or Saxon.


Title: Compare two pandas dataframe with different size

Body:
You can use map by Series created by set_index:

df1['C'] = df1['A'].map(df2.set_index('G')['H'])
print (df1)
    A   B   C
0   0  12  15
1   0  15  15
2   0  17  15
3   0  18  15
4   1  45  45
5   1  78  45
6   1  96  45
7   1  32  45
8   2  45  31
9   2  78  31
10  2  44  31
11  2  10  31

Or merge with drop and rename:

df = df1.merge(df2,left_on="A",right_on="G", how='left')
        .drop('G', axis=1)
        .rename(columns={'H':'C'})
print (df)
    A   B   C
0   0  12  15
1   0  15  15
2   0  17  15
3   0  18  15
4   1  45  45
5   1  78  45
6   1  96  45
7   1  32  45
8   2  45  31
9   2  78  31
10  2  44  31
11  2  10  31


问:
Difference between !! and ! in JavaScript
I have encountered those operators that are checking for user.rank property:

```<code><div ng-show="!!user.rank">
    {{user.rank}}
</div>
<button ng-show="!user.rank"  ng-click="addRank(user)">Add Rank</button>
</code>```

How are they different and what can we use instead?

答:
A single bang (!) is used to negate a boolean.

Double bang (!!) is used to coerce a truthy/falsey value to a boolean true or false.

for example

var x = 0; // a falsey value
console.log(x); // logs 0
console.log(!x)// logs true
console.log(!!x)// logs false

var y = "Hello world"; // a truthy value
console.log(y); // logs "Hello world"
console.log(!y)// logs false
console.log(!!y)// logs true```
</div>
</div>
</p>

<p>Applied to your specific case</p>

```ng-show="!!user.rank"
```

ng-show is no doubt expecting an actual boolean, and user.rank is obviously either truthy or falsey - coercing it to a boolean satisfies your angular directive appropriately.

Body:
I have encountered those operators that are checking for user.rank property:

    {{user.rank}}

<button ng-show="!user.rank"  ng-click="addRank(user)">Add Rank</button>

How are they different and what can we use instead?

Body:
A single bang (!) is used to negate a boolean.

Double bang (!!) is used to coerce a truthy/falsey value to a boolean true or false.

for example

var x = 0; // a falsey value
console.log(x); // logs 0
console.log(!x)// logs true
console.log(!!x)// logs false

var y = "Hello world"; // a truthy value
console.log(y); // logs "Hello world"
console.log(!y)// logs false
console.log(!!y)// logs true

Applied to your specific case

ng-show="!!user.rank"

ng-show is no doubt expecting an actual boolean, and user.rank is obviously either truthy or falsey - coercing it to a boolean satisfies your angular directive appropriately.


问:
java stop people from closing
hi i have a full screen program which i dont want people to close unless they have a password i have this code at the moment

```<code>public void windowClosing(WindowEvent arg0)
{
    System.out.println("HERE");
    String inputValue = JOptionPane.showInputDialog("Please input the closeword");

    if (inputValue != "closeplz")
    {

    }
}
</code>```

in the if statement i want it to stop the method so that the program doesent close. any help would be greatly aprecheated thanks ste

答:
You have to call

```<code>setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
</code>```

on (or within) the JFrame instance. Then the frame will not close unless you do it manually, though windowClosing() will still be called. Inside it, you can then conditionally call

```<code>System.exit(1);
</code>```

which will end the application. Be sure to do any necessary cleanup first.

Title: java stop people from closing

Body:
hi i have a full screen program which i dont want people to close unless they have a password i have this code at the moment

public void windowClosing(WindowEvent arg0)
{
    System.out.println("HERE");
    String inputValue = JOptionPane.showInputDialog("Please input the closeword");

    if (inputValue != "closeplz")
    {

    }
}

in the if statement i want it to stop the method so that the program doesent close. any help would be greatly aprecheated thanks ste

Body:
You have to call

setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

on (or within) the JFrame instance. Then the frame will not close unless you do it manually, though windowClosing() will still be called. Inside it, you can then conditionally call

System.exit(1);

which will end the application. Be sure to do any necessary cleanup first.


问:
Scrolling in all directions
I've been trying to implement an activity where I can scroll horizontally and vertically in all directions, I've tried out using gesturelistener and the "scrollby" method in View, however the screen is still static. I've also done a nested horizontal and vertical scroll in xml, however this only gives me scrolling to the right of the screen and bottom. It seems i cant move in the negative x direction.

Thanks.

答:
Customize ViewGroup

Override OnTouchEvent

Detect MotionEvents

Track Finger Points

Calculate Distance Moved

Modify the X and Y of the canvas Content Rectangle.

Finally in your layout add child views you want to scroll inside this ViewGroup

Source code: https://gist.github.com/jayakrishnan-pm/ScrollingLayout.java

Title: Scrolling in all directions


问:
Grabbing all values from 3rd level in multi-dimensional array
In a PHP script that I'm writing I need to extract some massive JSON files and parse through them to retrieve a single value for each top level object.

My JSON file looks something like this:

```<code>[
    {
        "SOMEDATA": "SOMEVALUE",
        "MOREDATA": "MOREVALUES",
        "METADATA": {
            "CUSTOM": {
                "TYPE": "THE VALUE THAT I NEED",
                //...more irrelevant data
            },
            //...more irrelevant data
        },
        //...more irrelevant data
    },
    ... Repeats several thousand times.
]
</code>```

The only piece of data that I want right now is the TYPE, which is buried several layers down. What I want to know is if there's a way that I can extract all of those TYPEs into an array using some built in PHP functionality. I've been doing it the long way of just looping through every top level index in the JSON file, but I feel like there's probably a better way to do this. Right now I'm bench marking at over a minute for execution, which is a little painful since this is for a small web application that will be getting accessed frequently.

If there is no built in functions that I can use to achieve this result of:

```<code>[
    0 => "TYPE1",
    1 => "TYPE2",
    2 => "TYPE3",
    3 => "TYPE4",
    ...
]
</code>```

is there some internal pointers or anything to PHP objects I can use to do this faster than just looping through the array?

I would normally just write the parsed array to a new file as a cron job every so often, and just grab data from the already parsed file, which would be much faster, but the JSON file changes too frequently to be able to justify this approach.

Note: I could do this with array_walk and form the new array in the callback, as suggested by some other answers, but internally that's still a loop. I want to know if there's a way to do this that in the backend takes advantage of pointer and array internals to optimize the performance. Unless in an interpreted language that isn't possible, I don't know how much PHP is able to optimize code on the fly. I'm relatively new to PHP, so I'm unsure what it's capable of.

答:
Assuming you're taking your JSON, running it through json_decode($json) and then using foreach on the output, that's really the best you can do. Foreach is faster than for when dealing with an array, it's just a question of how optimised the loop itself is and the hardware you're running it on at that point.

For a simple loop like this one

```<code>foreach($json as $val){
    $output[] = $val['metadata']['custom']['type'];
}
</code>```

is about as efficient as a loop can ever be.

OwnerDisplayName: anon

Body:
In a PHP script that I'm writing I need to extract some massive JSON files and parse through them to retrieve a single value for each top level object.

My JSON file looks something like this:

[
    {
        "SOMEDATA": "SOMEVALUE",
        "MOREDATA": "MOREVALUES",
        "METADATA": {
            "CUSTOM": {
                "TYPE": "THE VALUE THAT I NEED",
                //...more irrelevant data
            },
            //...more irrelevant data
        },
        //...more irrelevant data
    },
    ... Repeats several thousand times.
]

The only piece of data that I want right now is the TYPE, which is buried several layers down. What I want to know is if there's a way that I can extract all of those TYPEs into an array using some built in PHP functionality. I've been doing it the long way of just looping through every top level index in the JSON file, but I feel like there's probably a better way to do this. Right now I'm bench marking at over a minute for execution, which is a little painful since this is for a small web application that will be getting accessed frequently.

If there is no built in functions that I can use to achieve this result of:

[
    0 => "TYPE1",
    1 => "TYPE2",
    2 => "TYPE3",
    3 => "TYPE4",
    ...
]

is there some internal pointers or anything to PHP objects I can use to do this faster than just looping through the array?

I would normally just write the parsed array to a new file as a cron job every so often, and just grab data from the already parsed file, which would be much faster, but the JSON file changes too frequently to be able to justify this approach.

Note: I could do this with array_walk and form the new array in the callback, as suggested by some other answers, but internally that's still a loop. I want to know if there's a way to do this that in the backend takes advantage of pointer and array internals to optimize the performance. Unless in an interpreted language that isn't possible, I don't know how much PHP is able to optimize code on the fly. I'm relatively new to PHP, so I'm unsure what it's capable of.

Body:
Assuming you're taking your JSON, running it through json_decode($json) and then using foreach on the output, that's really the best you can do. Foreach is faster than for when dealing with an array, it's just a question of how optimised the loop itself is and the hardware you're running it on at that point.

For a simple loop like this one

foreach($json as $val){
    $output[] = $val['metadata']['custom']['type'];
}

is about as efficient as a loop can ever be.


问:
Xamarin whitelabel apps
I'm investigating Xamarin solution for my project.

Project requirements are:

IOS app,

Android app,

MacOS app,

Windows 7,8,10 app.

I already build test solution based on MvvmCross and it works fine.

My question is, how can I build whitelabel apps for all platforms that will be based on my test solution?
In those apps I will change only resources, such as Strings, icons, fonts...and so on, but logic, views and UI will be the same.

Is there any way to do it like gradle in android (build variants) ?

答:
MSBuild has a lot of features and can certainly achieve something similar to what gradle has with build variants. However, it is complicated to dive into that stuff if you don't have a background with MSBuild.

I think this might be the easier approach (and what I would do):

Use projects to organize everything

Keep all your cross-platform code in a Shared project (or PCL)

Keep all Windows, iOS, Android-specific code in a Shared project for each platform

Make a startup project for each flavor/platform of your app, referencing the shared projects. If you wish, include preprocessor defines for each flavor of your app.

In the startup projects you can include different string resources, images, etc. Also look into how to use "file-linking" in Visual Studio/Xamarin Studio, as it will help you out of tight spots here--especially if the different flavors of your app vary in different ways.

Title: Xamarin whitelabel apps


答:
The equivalency of cout << expr and cout.operator<<(expr) depends on what expr is.

If it lands up being a "built in" type, that cout "knows" about, then yes, it is equivalent to cout.operator<<(expr) (a member function).

If it is a "user type" (and std::string counts here), then it is an overloaded non-member method with a signature akin to std::ostream& operator<<(std::ostream&, const std::string&); etc.

Why does cout.operator<<("hello world") print a memory address?

The best member method overload to the above (since it is being forced to use the member method, is ostream& operator<<(const void* value); which outputs the value of the pointer (not what is being pointed to).

By contrast, cout << "hello world" calls the non-member overload ostream& operator<<(ostream&, const char*) and this in-turn inserts each character into the output.

Title: Understanding behavior of cout.operator<<()

Body:
According to the top answer to this question, cout << expr is equivalent to cout.operator<<(expr).

According to responses to this question, the statement above is untrue.

According to my own testing, cout.operator<<() is the same as cout << when given an integer.  When given a float, cout.operator<<() coerces it to an integer.  When given a string literal, as in cout.operator<<("hello world"), it outputs what appears to be a memory address.  And when given a variable holding a std::string, it gives a compiler error.

Could anyone give a beginner-to-intermediate-level explanation of what's going on?


问:
How to implement file operations to otg using JNI?
I need to perform file operations to a usb device connected to my android phone. The permission should be granted by android java code and file operations should be performed using JNI. Currently i'm not able to grant permissions to perform file operations - I'm getting an EACCESS:Permission denied error

I've attached my code here :

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

private UsbAccessory accessory;
private String TAG = "TAG";
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private PendingIntent mPermissionIntent;
private UsbManager manager;
private UsbDeviceConnection connection;
private HashMap<Integer, Integer> connectedDevices;
TextView tv;

// Used to load the 'native-lib' library on application startup.
static {
    System.loadLibrary("native-lib");
}

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

    // Example of a call to a native method
    tv = (TextView) findViewById(R.id.sample_text);
   // tv.setText(stringFromJNI());

    connectedDevices = new HashMap<Integer, Integer>();

    manager = (UsbManager) getSystemService(Context.USB_SERVICE);

    registerReceiver(usbManagerBroadcastReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED));
    registerReceiver(usbManagerBroadcastReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED));
    registerReceiver(usbManagerBroadcastReceiver, new IntentFilter(ACTION_USB_PERMISSION));

    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

    /*String str = ndkopenfile();
    tv.setText(str);*/

    final Handler handler = new Handler();

    handler.postDelayed(new Runnable()
    {
        @Override
        public void run()
        {
            checkForDevices();
        }
    }, 1000);
}

/**
 * A native method that is implemented by the 'native-lib' native library,
 * which is packaged with this application.
 */
</code>```

// public native String stringFromJNI();

```<code>@Override
public void onDestroy()
{
    super.onDestroy();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
}

// private static native void notifyDeviceAttached(int fd);
 //private static native void notifyDeviceDetached(int fd);

public  native String ndkopenfile();

private final BroadcastReceiver usbManagerBroadcastReceiver = new BroadcastReceiver()
{
    public void onReceive(Context context, Intent intent)
    {
        try
        {
            String action = intent.getAction();

            Log.d(TAG, "INTENT ACTION: " + action);

            if (ACTION_USB_PERMISSION.equals(action))
            {
                Log.d(TAG, "onUsbPermission");

                synchronized (this)
                {
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
                    {
                        if(device != null)
                        {

                          /*  int fd = connectToDevice(device);
                            Log.d(TAG,"device file descriptor: " + fd);
                           // notifyDeviceAttached(fd);
                            String str = ndkopenfile();
                            tv.setText(str);*/

                          writetofile();
                        }
                    }
                    else
                    {
                        Log.d(TAG, "permission denied for device " + device);
                    }
                }
            }

            if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action))
            {
                Log.d(TAG, "onDeviceConnected");

                synchronized(this)
                {
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    if (device != null)
                    {
                        manager.requestPermission(device, mPermissionIntent);
                    }
                }
            }

            if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action))
            {
                Log.d(TAG, "onDeviceDisconnected");

                synchronized(this)
                {
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    int fd = connectedDevices.get(device.getDeviceId());

                    Log.d(TAG, "device: " + device.getDeviceId() + " disconnected. fd: " + fd);

                   // notifyDeviceDetached(fd);

                    connectedDevices.remove(device.getDeviceId());
                }
            }
        }
        catch(Exception e)
        {
            Log.d(TAG, "Exception: " + e);
        }
    }

};

private void writetofile() {

   // File file = new File("/storage/9E6D-8A07/COMMWR");

    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("/storage/9E6D-8A07/COMMWR", Context.MODE_PRIVATE));
        outputStreamWriter.write("Hello");
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }

}

private int connectToDevice(UsbDevice device)
{
    connection = manager.openDevice(device);
    // if we make this, kernel driver will be disconnected
    connection.claimInterface(device.getInterface(0), true);

    Log.d(TAG, "inserting device with id: " + device.getDeviceId() + " and file descriptor: " + connection.getFileDescriptor());
    connectedDevices.put(device.getDeviceId(), connection.getFileDescriptor());

    return connection.getFileDescriptor();
}

private void checkForDevices()
{
    HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();

    while(deviceIterator.hasNext())
    {
        UsbDevice device = deviceIterator.next();

           /* if (device.getVendorId()==VID && device.getProductId()==PID)
            {
                Log.d(TAG, "Found a device: " + device);

                manager.requestPermission(device, mPermissionIntent);
            }*/

        Log.d(TAG, "Found a device: " + device);

        manager.requestPermission(device, mPermissionIntent);
    }
}
</code>```

}

JNI Code :

```<code>#include <jni.h>
#include <string.h>
#include <stdio.h>

extern "C"
JNIEXPORT jstring JNICALL
Java_nrrsmdm_com_myapplication_MainActivity_ndkopenfile
        (JNIEnv *env, jobject obj)
{
    int errno = 0;
    char myStr[20];
    FILE* fp = fopen("/storage/9E6D-8A07/COMMWR","w+");
    if(fp!=NULL)
    {
        fputs("HELLO WORLD!\n", fp);
        fflush(fp);
        fclose(fp);
        return env->NewStringUTF(myStr);
    }
    else
    { sprintf("error","errno = %d",errno);
        fclose(fp);
        return env->NewStringUTF("Error opening file!");
    }

   /* std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());*/

}
</code>```

答:
Try adding the permission to your manifest:

```<code><manifest>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    ...
    <application>
        ...
        <activity>
            ...
        </activity>
    </application>
</manifest>
</code>```

To support marshmallow be sure that your activity implements OnRequestPermissionResult and add code to request permission if not already granted (code take from an answer to this question):

```<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>```

Permission result callback:

```<code>@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }
}
</code>```

Body:
I need to perform file operations to a usb device connected to my android phone. The permission should be granted by android java code and file operations should be performed using JNI. Currently i'm not able to grant permissions to perform file operations - I'm getting an EACCESS:Permission denied error

I've attached my code here :

public class MainActivity extends AppCompatActivity {

private UsbAccessory accessory;
private String TAG = "TAG";
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
private PendingIntent mPermissionIntent;
private UsbManager manager;
private UsbDeviceConnection connection;
private HashMap<Integer, Integer> connectedDevices;
TextView tv;

// Used to load the 'native-lib' library on application startup.
static {
    System.loadLibrary("native-lib");
}

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

    // Example of a call to a native method
    tv = (TextView) findViewById(R.id.sample_text);
   // tv.setText(stringFromJNI());

    connectedDevices = new HashMap<Integer, Integer>();

    manager = (UsbManager) getSystemService(Context.USB_SERVICE);

    registerReceiver(usbManagerBroadcastReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED));
    registerReceiver(usbManagerBroadcastReceiver, new IntentFilter(UsbManager.ACTION_USB_DEVICE_DETACHED));
    registerReceiver(usbManagerBroadcastReceiver, new IntentFilter(ACTION_USB_PERMISSION));

    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);

    /*String str = ndkopenfile();
    tv.setText(str);*/

    final Handler handler = new Handler();

    handler.postDelayed(new Runnable()
    {
        @Override
        public void run()
        {
            checkForDevices();
        }
    }, 1000);
}

/**
 * A native method that is implemented by the 'native-lib' native library,
 * which is packaged with this application.
 */

// public native String stringFromJNI();

@Override
public void onDestroy()
{
    super.onDestroy();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
}

// private static native void notifyDeviceAttached(int fd);
 //private static native void notifyDeviceDetached(int fd);

public  native String ndkopenfile();

private final BroadcastReceiver usbManagerBroadcastReceiver = new BroadcastReceiver()
{
    public void onReceive(Context context, Intent intent)
    {
        try
        {
            String action = intent.getAction();

            Log.d(TAG, "INTENT ACTION: " + action);

            if (ACTION_USB_PERMISSION.equals(action))
            {
                Log.d(TAG, "onUsbPermission");

                synchronized (this)
                {
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
                    {
                        if(device != null)
                        {

                          /*  int fd = connectToDevice(device);
                            Log.d(TAG,"device file descriptor: " + fd);
                           // notifyDeviceAttached(fd);
                            String str = ndkopenfile();
                            tv.setText(str);*/

                          writetofile();
                        }
                    }
                    else
                    {
                        Log.d(TAG, "permission denied for device " + device);
                    }
                }
            }

            if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action))
            {
                Log.d(TAG, "onDeviceConnected");

                synchronized(this)
                {
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    if (device != null)
                    {
                        manager.requestPermission(device, mPermissionIntent);
                    }
                }
            }

            if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action))
            {
                Log.d(TAG, "onDeviceDisconnected");

                synchronized(this)
                {
                    UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

                    int fd = connectedDevices.get(device.getDeviceId());

                    Log.d(TAG, "device: " + device.getDeviceId() + " disconnected. fd: " + fd);

                   // notifyDeviceDetached(fd);

                    connectedDevices.remove(device.getDeviceId());
                }
            }
        }
        catch(Exception e)
        {
            Log.d(TAG, "Exception: " + e);
        }
    }

};

private void writetofile() {

   // File file = new File("/storage/9E6D-8A07/COMMWR");

    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("/storage/9E6D-8A07/COMMWR", Context.MODE_PRIVATE));
        outputStreamWriter.write("Hello");
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }

}

private int connectToDevice(UsbDevice device)
{
    connection = manager.openDevice(device);
    // if we make this, kernel driver will be disconnected
    connection.claimInterface(device.getInterface(0), true);

    Log.d(TAG, "inserting device with id: " + device.getDeviceId() + " and file descriptor: " + connection.getFileDescriptor());
    connectedDevices.put(device.getDeviceId(), connection.getFileDescriptor());

    return connection.getFileDescriptor();
}

private void checkForDevices()
{
    HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
    Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();

    while(deviceIterator.hasNext())
    {
        UsbDevice device = deviceIterator.next();

           /* if (device.getVendorId()==VID && device.getProductId()==PID)
            {
                Log.d(TAG, "Found a device: " + device);

                manager.requestPermission(device, mPermissionIntent);
            }*/

        Log.d(TAG, "Found a device: " + device);

        manager.requestPermission(device, mPermissionIntent);
    }
}

}

JNI Code :

#include <jni.h>
#include <string.h>
#include <stdio.h>

extern "C"
JNIEXPORT jstring JNICALL
Java_nrrsmdm_com_myapplication_MainActivity_ndkopenfile
        (JNIEnv *env, jobject obj)
{
    int errno = 0;
    char myStr[20];
    FILE* fp = fopen("/storage/9E6D-8A07/COMMWR","w+");
    if(fp!=NULL)
    {
        fputs("HELLO WORLD!\n", fp);
        fflush(fp);
        fclose(fp);
        return env->NewStringUTF(myStr);
    }
    else
    { sprintf("error","errno = %d",errno);
        fclose(fp);
        return env->NewStringUTF("Error opening file!");
    }

   /* std::string hello = "Hello from C++";
    return env->NewStringUTF(hello.c_str());*/

}

Body:
Try adding the permission to your manifest:

<manifest>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    ...
    <application>
        ...
        <activity>
            ...
        </activity>
    </application>
</manifest>

To support marshmallow be sure that your activity implements OnRequestPermissionResult and add code to request permission if not already granted (code take from an answer to this question):

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;
    }
}

Permission result callback:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
        Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        //resume tasks needing this permission
    }
}


问:
How to remove hover effect from <md-button>?
when I move mouse over md-button it highlights and when I click it remains highlighted but I don't want that I want remove hover effect  how can I do this?

答:
You can try md-no-ink attribute for md-button

More: https://material.angularjs.org/1.0.9/demo/button