问:
Double Colon confusions
Why can I use double colons in functions and classes not defined but I can't use in variables ??

Example:

```<code>#include <iostream>

using namespace std;

class Person{

    public:
        int age;
        string name();
};

int Person::age = 10; //It outputs an error

string Person::name(){ //It doesn't
    return "n";
}
</code>```

答:
Why can I use double colons in functions and classes not defined but I can't use in variables ??

age is an instance field, it exists in multiple places in memory - one for each Person that exists.

I'll now expand in detail about what the :: operator does, how to use it, and how static class members compare to instance members:

The :: operator:

The :: (the scope-resolution operator) has multiple uses in C++:

If you're familiar with Java, C# or JavaScript then it can be likened to the dot dereference or "navigation operator" . (e.g. namespace.Class.Method().Result) - except C++ uses a different operators for different kinds of navigation and dereferencing:

. is the member-access operator, similar to C - it's only applicable for "object values" and references (foo&), not pointers (foo*).

-> is another member-access operator for pointer types, note that this operator can be overridden but . cannot (overridin -> is risky but it improves the ergonomics of smart-pointer libraries when done correctly).

:: is the scope-resolution operator - it has a few different uses:

Namespace navigation - whereas Java and C# use . to navigate packages and namespaces, C++ uses ::, for example: using std::time.

When unqualified, it's also used to reference the global namespace, e.g. ::std which is handy if you're writing code which is already in a namespace.

It's also used to access static members of types - typically an actual static member (a static method or field) but also items like enum class (scoped enumeration) values (e.g. SomeEnumClass::value_name)

Finally, it's also used to select a specific base method when dealing with virtual method implementations: it's used when an overridden method needs to call a base implementation in a superclass - C++ does not have the singular base or super keywords that C# and Java have (respectively) because C++ allows multiple inheritance, so you must specify the specific parent class name: How to call a parent class function from derived class function?

Anyway, in your case, it looks like you're confused about what instance and static members actually mean, so here is an illustration:

```<code>class Person {
public:
    int height; // each Person has their own height, so this is an instance member
    static int averageHeight; // but an individual Person doesn't have an "average height" - but a single average-height value can be used for all Persons, so this is a shared ("static") value.

    int getAverageHeight() { // this is an instance method, btw
        return Person::averageHeight; // use `Person::` to unambiguously reference a static member of `Person`
    }

    Person()
    : height(0) {
        // instance members should be initialized in the constructor!
    }
}

// This will create an array of 10 people (10 different object instances).
// Each Person object (an instance) will have its own `height` in memory
Person* multiplePeople = new Person[10];

// btw, you probably should use `std::array` with an initializer instead:
// array<Person,10> multiplePeople{}; // <-- like this

// This sets a value to the `staticField` member, which exists only once in memory, that is, all Person instances share the same value for this member...
Person::averageHeight = 175; // 175cm

// ...for example:
assert( 175 == multiplePeople[3]->getAverageHeight() );
assert( 175 == multiplePeople[6]->getAverageHeight() );

// However instance members can have different values for each instance:
multiplePeople[3]->height = 170;
multiplePeople[6]->height = 180;

// Btw `height` is initialized to 0 in each Person's constructor.
assert( 170 != multiplePeople[0]->height );
assert( 180 != multiplePeople[7]->height );
</code>```

Title: Double Colon confusions

Body:
Why can I use double colons in functions and classes not defined but I can't use in variables ??

Example:

#include <iostream>

using namespace std;

class Person{

    public:
        int age;
        string name();
};

int Person::age = 10; //It outputs an error

string Person::name(){ //It doesn't
    return "n";
}

Body:
Why can I use double colons in functions and classes not defined but I can't use in variables ??

age is an instance field, it exists in multiple places in memory - one for each Person that exists.

I'll now expand in detail about what the :: operator does, how to use it, and how static class members compare to instance members:

The :: operator:

The :: (the scope-resolution operator) has multiple uses in C++:

If you're familiar with Java, C# or JavaScript then it can be likened to the dot dereference or "navigation operator" . (e.g. namespace.Class.Method().Result) - except C++ uses a different operators for different kinds of navigation and dereferencing:

. is the member-access operator, similar to C - it's only applicable for "object values" and references (foo&), not pointers (foo*).

-> is another member-access operator for pointer types, note that this operator can be overridden but . cannot (overridin -> is risky but it improves the ergonomics of smart-pointer libraries when done correctly).

:: is the scope-resolution operator - it has a few different uses:

Namespace navigation - whereas Java and C# use . to navigate packages and namespaces, C++ uses ::, for example: using std::time.

When unqualified, it's also used to reference the global namespace, e.g. ::std which is handy if you're writing code which is already in a namespace.

It's also used to access static members of types - typically an actual static member (a static method or field) but also items like enum class (scoped enumeration) values (e.g. SomeEnumClass::value_name)

Finally, it's also used to select a specific base method when dealing with virtual method implementations: it's used when an overridden method needs to call a base implementation in a superclass - C++ does not have the singular base or super keywords that C# and Java have (respectively) because C++ allows multiple inheritance, so you must specify the specific parent class name: How to call a parent class function from derived class function?

Anyway, in your case, it looks like you're confused about what instance and static members actually mean, so here is an illustration:

class Person {
public:
    int height; // each Person has their own height, so this is an instance member
    static int averageHeight; // but an individual Person doesn't have an "average height" - but a single average-height value can be used for all Persons, so this is a shared ("static") value.

    int getAverageHeight() { // this is an instance method, btw
        return Person::averageHeight; // use `Person::` to unambiguously reference a static member of `Person`
    }

    Person()
    : height(0) {
        // instance members should be initialized in the constructor!
    }
}

// This will create an array of 10 people (10 different object instances).
// Each Person object (an instance) will have its own `height` in memory
Person* multiplePeople = new Person[10];

// btw, you probably should use `std::array` with an initializer instead:
// array<Person,10> multiplePeople{}; // <-- like this

// This sets a value to the `staticField` member, which exists only once in memory, that is, all Person instances share the same value for this member...
Person::averageHeight = 175; // 175cm

// ...for example:
assert( 175 == multiplePeople[3]->getAverageHeight() );
assert( 175 == multiplePeople[6]->getAverageHeight() );

// However instance members can have different values for each instance:
multiplePeople[3]->height = 170;
multiplePeople[6]->height = 180;

// Btw `height` is initialized to 0 in each Person's constructor.
assert( 170 != multiplePeople[0]->height );
assert( 180 != multiplePeople[7]->height );


来源: stackexchange

问:
How to make a certain number be counted rather than the length of the actual number?
What I want to happen is if the number is over 500 for the console to print something, but right now it counts how long the number is not how high its numerical value is. </p>

```<code>print ("What Is The Current Distance  In Meters?")
distance = input ()

if len (distance) >= 500:
    (print) ("Thanks")
</code>```

答: input() is always a string - you likely want distance = int(input())

ContentLicense: CC BY-SA 3.0

Body:
What I want to happen is if the number is over 500 for the console to print something, but right now it counts how long the number is not how high its numerical value is.

print ("What Is The Current Distance  In Meters?")
distance = input ()

if len (distance) >= 500:
    (print) ("Thanks")


问:
Determining if a squence is true
How would I determine if a sequence is true?
Lets say I have this code

```<code>int a = random.nextInt(10);
int b = random.nextInt(10);
int c = random.nextInt(10);
</code>```

How would I use an if statement or a loop to determine if/when a = 1, b = 2, and c = 3 (or any combination of a,b, and c being only one number apart. Like 4,5,6 or 7,8,9) is in a sequence such as stated?

答:
```<code>int min = Math.min(a, Math.min(b, c));
boolean isSequence = Arrays.equals(IntStream.range(min, min+3).toArray(), new int[]{a,b,c});
</code>```

Populate array as sequence (range) and compare with original values(as array)

Title: Determining if a squence is true

Body:
How would I determine if a sequence is true?
Lets say I have this code

int a = random.nextInt(10);
int b = random.nextInt(10);
int c = random.nextInt(10);

How would I use an if statement or a loop to determine if/when a = 1, b = 2, and c = 3 (or any combination of a,b, and c being only one number apart. Like 4,5,6 or 7,8,9) is in a sequence such as stated?

Body:
int min = Math.min(a, Math.min(b, c));
boolean isSequence = Arrays.equals(IntStream.range(min, min+3).toArray(), new int[]{a,b,c});

Populate array as sequence (range) and compare with original values(as array)


问:
how to change button background colour in tableview cell swift3
I have one UITableViewCell. In TableViewCell, I have 7 buttons in single row. I want to play music. When i press button1, its background colour should be changed. If I pressed button2, its background colour should be changed, and button1 would be deselect. I also set the tag for each button in row, but i don't understand, how to do? Sound is playing fine but i am unable to select and deselect buttons. I am using swift3. Thanks in advance.

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> tableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell") as! tableViewCell

     cell.Btn_one.addTarget(self, action: #selector(TableViewController.BtnAction_One), for: .touchUpInside)

     //For example
       if (cell.Btn_one.tag == 1){

        cell.Btn_one.backgroundColor = .white
    }else if (cell.Btn_two.tag == 2){
               cell.Btn_two.backgroundColor = .red
    }
 }

 @IBAction func BtnAction_One(_ sender: UIButton) {
    self.play()
 }
</code>```

答:
You'll want to subclass the button as CustomButton or whatever you would like to call it. And you'll need to create a delegate to let your viewcontroller know whats up.

Create a func that takes in an integer. This will be the code that'll take in your button's tag and preform some code. @Gabs had the right idea there.

```<code>func select(index: Int) {
  switch sender.tag {
        case 0: //do something
        case 1: //do something
        }
}
</code>```

Create a single IBAction then link all your buttons to it. Inside, call the method created above

```<code> @IBAction func buttonTapped(_ sender: Any) {
  select(index: sender.tag)
}
</code>```

all that's missing is the viewController being informed on which button has been tapped. Set a delegate for it in your CustomCell view file and have it capture the sender.tag in your IBAction. Be sure to conform your viewcontroller too so the delegation works.

Body:
I have one UITableViewCell. In TableViewCell, I have 7 buttons in single row. I want to play music. When i press button1, its background colour should be changed. If I pressed button2, its background colour should be changed, and button1 would be deselect. I also set the tag for each button in row, but i don't understand, how to do? Sound is playing fine but i am unable to select and deselect buttons. I am using swift3. Thanks in advance.

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> tableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "PlayerCell") as! tableViewCell

     cell.Btn_one.addTarget(self, action: #selector(TableViewController.BtnAction_One), for: .touchUpInside)

     //For example
       if (cell.Btn_one.tag == 1){

        cell.Btn_one.backgroundColor = .white
    }else if (cell.Btn_two.tag == 2){
               cell.Btn_two.backgroundColor = .red
    }
 }

 @IBAction func BtnAction_One(_ sender: UIButton) {
    self.play()
 }

Body:
You'll want to subclass the button as CustomButton or whatever you would like to call it. And you'll need to create a delegate to let your viewcontroller know whats up.

Create a func that takes in an integer. This will be the code that'll take in your button's tag and preform some code. @Gabs had the right idea there.

func select(index: Int) {
  switch sender.tag {
        case 0: //do something
        case 1: //do something
        }
}

Create a single IBAction then link all your buttons to it. Inside, call the method created above

 @IBAction func buttonTapped(_ sender: Any) {
  select(index: sender.tag)
}

all that's missing is the viewController being informed on which button has been tapped. Set a delegate for it in your CustomCell view file and have it capture the sender.tag in your IBAction. Be sure to conform your viewcontroller too so the delegation works.


问:
Trigger Infinite Scroll based on target position
I am trying to trigger / allow a new set of images to be loaded when the bottom of the window scroll bar has reached the position of a target div.

Here is the formula for triggering when scrollbar reaches the bottom of the page with a slight offset, 50, and works flawlessly.

```<code>$(window).scroll( function() {
    // Page height
    var pageHeight  = $(document).height();
    // Window height
    var winH = $(window).height();
    // Scrollbar position
    var scrollPos = $(this).scrollTop();
    // Formula
    var dist = pageHeight - (scrollPos + winH);
    // When to load new images with a slight offset
    var load = dist < 50;
    if (load) {
        addItems();
    }
});
</code>```

But, instead if I want to use the position of a target div.infinite-scroll what is the calculation / formula needed? I thought that I could substitute the target div's offset in place of, 50, but did not work for me.

```<code>var targetPos = $(Infinite_Scroll.container).offset().top;
var load = dist < targetPos;
</code>```

答:
This seems to work for my needs and could help others. If you substitute the target container for the pageHeightin the calculation than Infinite Scroll will be triggered as the window scrollbar reaches the position of the target instead of the bottom of the page.

```<code>// Before
var dist = pageHeight - (scrollPos + winH);
// Change
var dist = $(Infinite_Scroll.container).offset().top - (scrollPos + winH);

$(window).scroll( function() {
    // Page height
    var pageHeight  = $(document).height();
    // Window height
    var winH = $(window).height();
    // Scrollbar position
    var scrollPos = $(this).scrollTop();
    // Formula
    var dist = $(Infinite_Scroll.container).offset().top - (scrollPos + winH);
    // When to load new images with a slight offset
    var load = dist < 50;
    if (load) {
        addItems();
    }
});
</code>```

Body:
I am trying to trigger / allow a new set of images to be loaded when the bottom of the window scroll bar has reached the position of a target div.

Here is the formula for triggering when scrollbar reaches the bottom of the page with a slight offset, 50, and works flawlessly.

$(window).scroll( function() {
    // Page height
    var pageHeight  = $(document).height();
    // Window height
    var winH = $(window).height();
    // Scrollbar position
    var scrollPos = $(this).scrollTop();
    // Formula
    var dist = pageHeight - (scrollPos + winH);
    // When to load new images with a slight offset
    var load = dist < 50;
    if (load) {
        addItems();
    }
});

But, instead if I want to use the position of a target div.infinite-scroll what is the calculation / formula needed? I thought that I could substitute the target div's offset in place of, 50, but did not work for me.

var targetPos = $(Infinite_Scroll.container).offset().top;
var load = dist < targetPos;

Body:
This seems to work for my needs and could help others. If you substitute the target container for the pageHeightin the calculation than Infinite Scroll will be triggered as the window scrollbar reaches the position of the target instead of the bottom of the page.

// Before
var dist = pageHeight - (scrollPos + winH);
// Change
var dist = $(Infinite_Scroll.container).offset().top - (scrollPos + winH);

$(window).scroll( function() {
    // Page height
    var pageHeight  = $(document).height();
    // Window height
    var winH = $(window).height();
    // Scrollbar position
    var scrollPos = $(this).scrollTop();
    // Formula
    var dist = $(Infinite_Scroll.container).offset().top - (scrollPos + winH);
    // When to load new images with a slight offset
    var load = dist < 50;
    if (load) {
        addItems();
    }
});


问:
Best performance for tags in mysql/php
I have one table with items and one table with tags that can be linked to the items. Should I create a table where I store the relations between them or can I store the tag ids right in the item table like a column with "1,52,375" (tag ids).

I would in most cases lean towards a relation table, but I will mostly add one single tag per item and at the most 10 so I wonder if it's worth it.

If going with the relation table will I need a "loop-in-loop" where I make one query per item to fetch the tags. It seems like a lot of queries or is there a different solution?

I could also fetch all the items and tags separately in two queries and link them with php. Also loop in loop, but less database queries.

What do you think? Thanks!

答: I've had this issue before and my current best solution is to have the tag table and a column for the tags separated by spaces (spaces in actual tags are replaced with #). Then use MySQL MATCH AGAINST to perform a natural language search for the tag you need in the tag column, the # character will be ignored by match against so it's not an issue. This has worked very well for me so far.</p>

Title: Best performance for tags in mysql/php


问:
Make a jquery ajax POST inside a loop
I have a bunch of data inside a loop I'd like to POST to the server via jQuery.

My code is similar to the following:

```<code>var patients = [] // contains an array of patient objects I want to POST to server

var post = function(theUrl, theData, callback){
    $.ajax({
        type: "POST",
        url: theUrl,
        data: theData,
        success: callback,
        contentType: "application/json"
    });
}

var createdPatient = function(patient){
    //patient was created
}

$('#saveAll').click(function(event) {
    for (var i = 0;i < patients.length;i++) {
        var json = JSON.stringify(patients[i]);
        post("/openmrs/ws/rest/v1/patient", json, createdPatient);
    }
});
</code>```

When I run the code only the last patient has been saved to the server. How may I correct this erroneous outcome?

答:
Taking advantage of the promise returned by jQuery.ajax(), you can write something more like this (see comments for detail) :

```<code>var patients = [...] // contains an array of patient objects to be POSTed to the server

$('#saveAll').click(function(event) {
    // first, map the `patients` array to an array of jqXHR promises as returned by $.ajax().
    var promises = patients.map(function(patient) {
        return $.ajax({
            type: 'POST',
            url: '/openmrs/ws/rest/v1/patient',
            data: patient, // jQuery.jax will handle js plain objects here. You may need to stringify here if patient is not a plain object.
            contentType: "application/json"
        }).then(function(data, textStatus, jqXHR) {
            return textStatus; // report successes in the form of the "textStatus" message (or anything you like).
        }, function(jqXHR, textStatus, errorThrown) {
            return $.when(textStatus || errorThrown); // report error on the success path, otherwise `$.when()` will bail out at the first error.
        });
    });
    // Now aggregate the `promises` array with `$.when()`
    $.when.apply(null, promises).then(function(results) {
        console.log(results);
    }, function(error) {
        // due to error handling above, you should never get here.
        console.log(error);
    });
});
</code>```

For more detail, see jQuery.ajax() and jQuery.when()

Title: Make a jquery ajax POST inside a loop

Body:
I have a bunch of data inside a loop I'd like to POST to the server via jQuery.

My code is similar to the following:

var patients = [] // contains an array of patient objects I want to POST to server

var post = function(theUrl, theData, callback){
    $.ajax({
        type: "POST",
        url: theUrl,
        data: theData,
        success: callback,
        contentType: "application/json"
    });
}

var createdPatient = function(patient){
    //patient was created
}

$('#saveAll').click(function(event) {
    for (var i = 0;i < patients.length;i++) {
        var json = JSON.stringify(patients[i]);
        post("/openmrs/ws/rest/v1/patient", json, createdPatient);
    }
});

When I run the code only the last patient has been saved to the server. How may I correct this erroneous outcome?

Body:
Taking advantage of the promise returned by jQuery.ajax(), you can write something more like this (see comments for detail) :

var patients = [...] // contains an array of patient objects to be POSTed to the server

$('#saveAll').click(function(event) {
    // first, map the `patients` array to an array of jqXHR promises as returned by $.ajax().
    var promises = patients.map(function(patient) {
        return $.ajax({
            type: 'POST',
            url: '/openmrs/ws/rest/v1/patient',
            data: patient, // jQuery.jax will handle js plain objects here. You may need to stringify here if patient is not a plain object.
            contentType: "application/json"
        }).then(function(data, textStatus, jqXHR) {
            return textStatus; // report successes in the form of the "textStatus" message (or anything you like).
        }, function(jqXHR, textStatus, errorThrown) {
            return $.when(textStatus || errorThrown); // report error on the success path, otherwise `$.when()` will bail out at the first error.
        });
    });
    // Now aggregate the `promises` array with `$.when()`
    $.when.apply(null, promises).then(function(results) {
        console.log(results);
    }, function(error) {
        // due to error handling above, you should never get here.
        console.log(error);
    });
});

For more detail, see jQuery.ajax() and jQuery.when()


问:
replace NA with groups mean in a non specified number of columns
I want to replace the NA with mean of each single group collembola and mite in multiple columns. Here it is an example with 3 columns however I want to apply this a data frame with 5000 columns

```<code>dat <- read.table(text =
                  "id    ID        length  width    extra
                  101   collembola  2.1     0.9     1
                  102   mite        NA      0.7     NA
                  103   mite        1.1     0.8     2
                  104   collembola  1       NA      3
                  105   collembola  1.5     0.5     4
                  106   mite        NA      NA      NA
                  106   mite        1.9     NA      4",
                  header=TRUE)
</code>```

It works if I enter each column

```<code>library(plyr)
impute.mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
data2 <- ddply(dat, ~ ID, transform, length = impute.mean(length))
</code>```

I want to apply the function that calculates the mean of each single group ID collembola and mite across multiple columns, below is what I tried (it does not work):

```<code>dat2 <- ddply(dat, ~ ID, transform,  impute.mean(dat[,3:ncol(dat)]))
</code>```

答:
Try</p>

```<code>library(plyr)
impute.mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
dat2 <- ddply(dat, ~ ID, transform, length = impute.mean(length),
          width = impute.mean(width), extra = impute.mean(extra))
</code>```

Body:
I want to replace the NA with mean of each single group collembola and mite in multiple columns. Here it is an example with 3 columns however I want to apply this a data frame with 5000 columns

dat <- read.table(text =
                  "id    ID        length  width    extra
                  101   collembola  2.1     0.9     1
                  102   mite        NA      0.7     NA
                  103   mite        1.1     0.8     2
                  104   collembola  1       NA      3
                  105   collembola  1.5     0.5     4
                  106   mite        NA      NA      NA
                  106   mite        1.9     NA      4",
                  header=TRUE)

It works if I enter each column

library(plyr)
impute.mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
data2 <- ddply(dat, ~ ID, transform, length = impute.mean(length))

I want to apply the function that calculates the mean of each single group ID collembola and mite across multiple columns, below is what I tried (it does not work):

dat2 <- ddply(dat, ~ ID, transform,  impute.mean(dat[,3:ncol(dat)]))

Body:
Try

library(plyr)
impute.mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
dat2 <- ddply(dat, ~ ID, transform, length = impute.mean(length),
          width = impute.mean(width), extra = impute.mean(extra))


问:
React JS onChange Event is not triggered
I am implementing a Markdown Previewer from Freecodecamp, but I am having some problem. The onChange event on the input component is not being triggered and I can't figure out why!

Any ideas?

class MarkDownPreviewer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputText: this.props.text
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    alert("a");
    this.setState({inputText: event.target.value});
  }

  render() {
    return (

        <MarkDownInput text={this.state.inputText} onChange={this.handleChange}/>
        <MarkDownOutput output={this.state.inputText}/>

    );
  }
}

class MarkDownInput extends React.Component {
  render() {
    return (
      <textarea className="input">{this.props.text}</textarea>
    );
  }
}

class MarkDownOutput extends React.Component {
  parseMarkup(rawInput) {
    var rawMarkup = marked(rawInput, {gfm: true, sanitize: true});
    return {__html: rawMarkup};
  }

  render() {
    return (

    );
  }
}

var previewText = '# Heading\n\n ## Sub-heading\n \n### Another deeper heading\n \nParagraphs are separated\nby a blank line.\n\nLeave 2 spaces at the end of a line to do a  \nline break\n\nText attributes *italic*, **bold**, \n`monospace`, ~~strikethrough~~ .\n\nShopping list:\n\n  * apples\n  * oranges\n  * pears\n\nNumbered list:\n\n  1. apples\n  2. oranges\n  3. pears\n\nThe rain---not the reign---in\nSpain.\n\n *[Herman Fassett](https://freecodecamp.com/hermanfassett)*';

ReactDOM.render(
  <MarkDownPreviewer text={previewText} />,
  document.getElementById('markpreview')
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body {
  height: 100%;
}

#markpreview {
  height: 100%;
}

#wrapper {
  display:flex;
  height: 100%;
}

.input {
  width: 50%;
  background-color: #e3e3e3;
  margin-right: 10px;
  padding: 10px;
}

.output {
  width: 50%;
  background-color: #f3f3f3;
  white-space: pre;
  padding: 10px;
}</code>```

```

答:
You're not passing the onChange function to the textarea component in MarkDownInput, so it's never being called.

Change this:

```<code><textarea className="input">{this.props.text}</textarea>
</code>```

To this:

```<code><textarea className="input" onChange={this.props.onChange}>{this.props.text}</textarea>
</code>```

Body:
I am implementing a Markdown Previewer from Freecodecamp, but I am having some problem. The onChange event on the input component is not being triggered and I can't figure out why!

Any ideas?

class MarkDownPreviewer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputText: this.props.text
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
    alert("a");
    this.setState({inputText: event.target.value});
  }

  render() {
    return (

        <MarkDownInput text={this.state.inputText} onChange={this.handleChange}/>
        <MarkDownOutput output={this.state.inputText}/>

    );
  }
}

class MarkDownInput extends React.Component {
  render() {
    return (
      <textarea className="input">{this.props.text}</textarea>
    );
  }
}

class MarkDownOutput extends React.Component {
  parseMarkup(rawInput) {
    var rawMarkup = marked(rawInput, {gfm: true, sanitize: true});
    return {__html: rawMarkup};
  }

  render() {
    return (

    );
  }
}

var previewText = '# Heading\n\n ## Sub-heading\n \n### Another deeper heading\n \nParagraphs are separated\nby a blank line.\n\nLeave 2 spaces at the end of a line to do a  \nline break\n\nText attributes *italic*, **bold**, \n`monospace`, ~~strikethrough~~ .\n\nShopping list:\n\n  * apples\n  * oranges\n  * pears\n\nNumbered list:\n\n  1. apples\n  2. oranges\n  3. pears\n\nThe rain---not the reign---in\nSpain.\n\n *[Herman Fassett](https://freecodecamp.com/hermanfassett)*';

ReactDOM.render(
  <MarkDownPreviewer text={previewText} />,
  document.getElementById('markpreview')
);

html, body {
  height: 100%;
}

#markpreview {
  height: 100%;
}

#wrapper {
  display:flex;
  height: 100%;
}

.input {
  width: 50%;
  background-color: #e3e3e3;
  margin-right: 10px;
  padding: 10px;
}

.output {
  width: 50%;
  background-color: #f3f3f3;
  white-space: pre;
  padding: 10px;
}

Body:
You're not passing the onChange function to the textarea component in MarkDownInput, so it's never being called.

Change this:

<textarea className="input">{this.props.text}</textarea>

To this:

<textarea className="input" onChange={this.props.onChange}>{this.props.text}</textarea>


问:
Unexplained Subversion directory status after checkout
I am working in an SVN repo with a huge branches area.  As a result, I did a shallow (--depth empty) checkout on my branches folder.

Example: C:\svn\branches

Has no subfolders in my working copy.

Suppose I have a branch called MyBranch that I want to checkout.

I run:

svn checkout http://svn/ThisProject/branches/MyBranch C:\svn\branches\MyBranch --depth infinity

Coolio.  I get all the files.  However, svn status looks a little strange:

```
C:\svn\branches> svn status
?       MyBranch
```

Let's check info...

```
C:\svn\branches> svn info .
Path: .
URL: http://svn/ThisProject/branches
Repository Root: http://svn
Repository UUID: 3facc57d-2901-0010-8249-59daf7a806c1
Revision: 1733
Node Kind: directory
Schedule: normal
Depth: empty
Last Changed Author: e467443
Last Changed Rev: 1733
Last Changed Date: 2010-12-14 21:42:31 +0800 (Tue, 14 Dec 2010)
```

```
C:\svn\branches> svn info MyBranch
Path: ARPE-TEST2
URL: http://svn/ThisProject/branches/MyBranch
Repository Root: http://svn
Repository UUID: 3facc57d-2901-0010-8249-59daf7a806c1
Revision: 1733
Node Kind: directory
Schedule: normal
Last Changed Author: v094424
Last Changed Rev: 1624
Last Changed Date: 2010-12-13 22:46:21 +0800 (Mon, 13 Dec 2010)
```

That's weird.  Let's try an add:

```
C:\svn\branches> svn add MyBranch
svn: warning: 'MyBranch' is already under version control
```

My guess is that branches has Depth: empty so SVN is confused.

Can anyone explain and provide a fix?  Maybe I can ignore.

I am using CollabNet command line tools on Windows.

```
C:\svn\branches> svn --version
svn, version 1.6.12 (r955767)
   compiled Jun 21 2010, 16:00:59
```

答:
To fetch MyBranch as part of the same working copy use</p>

```<code>cd \svn\branches
svn update --set-depth infinity MyBranch
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am working in an SVN repo with a huge branches area.  As a result, I did a shallow (--depth empty) checkout on my branches folder.

Example: C:\svn\branches

Has no subfolders in my working copy.

Suppose I have a branch called MyBranch that I want to checkout.

I run:

svn checkout http://svn/ThisProject/branches/MyBranch C:\svn\branches\MyBranch --depth infinity

Coolio.  I get all the files.  However, svn status looks a little strange:

C:\svn\branches> svn status
?       MyBranch

Let's check info...

C:\svn\branches> svn info .
Path: .
URL: http://svn/ThisProject/branches
Repository Root: http://svn
Repository UUID: 3facc57d-2901-0010-8249-59daf7a806c1
Revision: 1733
Node Kind: directory
Schedule: normal
Depth: empty
Last Changed Author: e467443
Last Changed Rev: 1733
Last Changed Date: 2010-12-14 21:42:31 +0800 (Tue, 14 Dec 2010)

C:\svn\branches> svn info MyBranch
Path: ARPE-TEST2
URL: http://svn/ThisProject/branches/MyBranch
Repository Root: http://svn
Repository UUID: 3facc57d-2901-0010-8249-59daf7a806c1
Revision: 1733
Node Kind: directory
Schedule: normal
Last Changed Author: v094424
Last Changed Rev: 1624
Last Changed Date: 2010-12-13 22:46:21 +0800 (Mon, 13 Dec 2010)

That's weird.  Let's try an add:

C:\svn\branches> svn add MyBranch
svn: warning: 'MyBranch' is already under version control

My guess is that branches has Depth: empty so SVN is confused.

Can anyone explain and provide a fix?  Maybe I can ignore.

I am using CollabNet command line tools on Windows.

C:\svn\branches> svn --version
svn, version 1.6.12 (r955767)
   compiled Jun 21 2010, 16:00:59

Body:
To fetch MyBranch as part of the same working copy use

cd \svn\branches
svn update --set-depth infinity MyBranch


问:
Linking 3rd Party Libraries with VS Cross-Platform C++ Mobile App Project
I need some general guidance regarding the correct way to link either static or dynamic libraries in a Visual Studio Cross-Platform C++ Mobile App project.

Specifically, I'm trying to link my project with a libpng build, but I doubt this is specific to that library.

I have built libpng (and zlib) successfully.  The Universal Windows App project in the solution runs and uses the libpng API just fine.  The Android project, however, is giving me undefined reference errors to the libpng functions and very high blood pressure.

The various libpng types defined in headers are not causing errors, only the function definitions.  I'm also fairly sure the compiler(s)/linker can find the files in the first place, since when I remove references to them from the project options, I get file not found errors instead of undefined references.  I have little experience with Clang or GCC, and have never attempted to build with them from Visual Studio before.

I have already examined this SO question, but the accepted answer actually contains misinformation.  I've also seen this other SO question, which seems to describe the same problem, but that question is concerned with Eclipse; its solution involves makefiles, which isn't applicable in my case.

I have tried every permutation I could come up with modifying various project settings in both the native activity and static library projects: adding various directories to project settings, forward-slashes-vs-backslashes, manually specifying -l commands on the command line to ensure the link order was correct, all for naught.

Clearly, I'm missing something (probably basic) to getting Clang or GCC to link with a third-party library in a Visual Studio project.  I appreciate any thoughts anyone might offer me.  Thank you.

答:
Instead of banging my head on this any longer, I decided to build the libraries myself within the solution rather than link to them externally.  (The provided Visual Studio templates make it trivial to drop in existing and have it work across all your projects right out of the box.)

This is less of an answer then an alternate solution, but it was the route I ended up taking, and in the end I think it was perhaps the better choice.  (To state the obvious, if I end up needing those libraries for multiple projects, then this isn't the most efficient approach.  But for now it wasn't worth the headache for me.)

Should anyone ever come across this question in the future and have an answer I would still very much appreciate hearing their input!


答:
Well, you need to parse this line by line if you want to extract your data, the algorithm should roughly be:

Scan the file line by line

if empty line, skip

if the line starts with 'Origin' capture the number after it (origin_no)

else break apart the line by semi-colon and for each element:

split by a colon

the first element is the second dict key number (element_no)

the second element is the value (value_no)

store in your result dictionary as (origin_no, element_no): value_no

Which is quite trivial to implement:

```<code>result = {}  # we'll store our result in this dict
origin_no = 0  # our starting Origin number in case the file doesn't begin with one
with open("trips.txt", "r") as f:
    for line in f:
        line = line.rstrip()  # we're not interested in the newline at the end
        if not line:  # empty line, skip
            continue
        if line.startswith("Origin"):
            origin_no = int(line[7:].strip())  # grab the integer following Origin
        else:
            elements = line.split(";")  # get our elements by splitting by semi-colon
            for element in elements:  # loop through each of them:
                if not element:  # we're not interested in the last element
                    continue
                element_no, element_value = element.split(":")  # get our pair
                # beware, these two are now most likely padded strings!
                # that's why we'll strip them from whitespace and convert to integer/float
                result[(origin_no, int(element_no.strip()))] = float(element_value.strip())
# Done!
</code>```

Title: Converting a text file into a dictionary

Body:
I have the following text file for demand in a network.

Origin  1
    1 :      0.0;     2 :    100.0;     3 :    100.0;     4 :    500.0;     5 :    200.0;
    6 :    300.0;     7 :    500.0;     8 :    800.0;     9 :    500.0;    10 :   1300.0;
   11 :    500.0;    12 :    200.0;    13 :    500.0;    14 :    300.0;    15 :    500.0;
   16 :    500.0;    17 :    400.0;    18 :    100.0;    19 :    300.0;    20 :    300.0;
   21 :    100.0;    22 :    400.0;    23 :    300.0;    24 :    100.0;

Origin  2
    1 :    100.0;     2 :      0.0;     3 :    100.0;     4 :    200.0;     5 :    100.0;
    6 :    400.0;     7 :    200.0;     8 :    400.0;     9 :    200.0;    10 :    600.0;
   11 :    200.0;    12 :    100.0;    13 :    300.0;    14 :    100.0;    15 :    100.0;
   16 :    400.0;    17 :    200.0;    18 :      0.0;    19 :    100.0;    20 :    100.0;
   21 :      0.0;    22 :    100.0;    23 :      0.0;    24 :      0.0;

Origin  3
    1 :    100.0;     2 :    100.0;     3 :      0.0;     4 :    200.0;     5 :    100.0;
    6 :    300.0;     7 :    100.0;     8 :    200.0;     9 :    100.0;    10 :    300.0;
   11 :    300.0;    12 :    200.0;    13 :    100.0;    14 :    100.0;    15 :    100.0;
   16 :    200.0;    17 :    100.0;    18 :      0.0;    19 :      0.0;    20 :      0.0;
   21 :      0.0;    22 :    100.0;    23 :    100.0;    24 :      0.0;

... records 4-23 elided ...

Origin  24
    1 :    100.0;     2 :      0.0;     3 :      0.0;     4 :    200.0;     5 :      0.0;
    6 :    100.0;     7 :    100.0;     8 :    200.0;     9 :    200.0;    10 :    800.0;
   11 :    600.0;    12 :    500.0;    13 :    700.0;    14 :    400.0;    15 :    400.0;
   16 :    300.0;    17 :    300.0;    18 :      0.0;    19 :    100.0;    20 :    400.0;
   21 :    500.0;    22 :   1100.0;    23 :    700.0;    24 :      0.0;

Now I need to create a dictionary, which should look something like:

{(1,1):0.0, (1,2):100.0, (1, 3):100.0, .......
 (2, 1):100.0, (2,2):0, ......}

Where the tuple elements e.g. (1, 2) represent the origin and destination, and the value represents the demand (which is 100.0 for the (1, 2) key).

I tried the following:

with open("trips.txt", "r") as f:
     line = f.readline()
     line = f.readline()
     ind = 0
     while len(line):
         line = line.strip(';')
         l = line.split()
         print l

         ind = ind + 1
         if(ind == 5):
             line = f.readline()
             line = f.readline()
             line = f.readline()
             ind = 0
             node = node + 1
         else:
             line = f.readline()

But I don't think I am going anywhere with this...

Body:
Well, you need to parse this line by line if you want to extract your data, the algorithm should roughly be:

Scan the file line by line

if empty line, skip

if the line starts with 'Origin' capture the number after it (origin_no)

else break apart the line by semi-colon and for each element:

split by a colon

the first element is the second dict key number (element_no)

the second element is the value (value_no)

store in your result dictionary as (origin_no, element_no): value_no

Which is quite trivial to implement:

result = {}  # we'll store our result in this dict
origin_no = 0  # our starting Origin number in case the file doesn't begin with one
with open("trips.txt", "r") as f:
    for line in f:
        line = line.rstrip()  # we're not interested in the newline at the end
        if not line:  # empty line, skip
            continue
        if line.startswith("Origin"):
            origin_no = int(line[7:].strip())  # grab the integer following Origin
        else:
            elements = line.split(";")  # get our elements by splitting by semi-colon
            for element in elements:  # loop through each of them:
                if not element:  # we're not interested in the last element
                    continue
                element_no, element_value = element.split(":")  # get our pair
                # beware, these two are now most likely padded strings!
                # that's why we'll strip them from whitespace and convert to integer/float
                result[(origin_no, int(element_no.strip()))] = float(element_value.strip())
# Done!


问:
Is there a way to have an alias contain $(!!) that is expanded when it's run?
Or a function, or anything else, for that matter.

My use case is that I have a command that I run which will find a branch name in a git repository for me, and the only output of the command is that branch name, passable to git checkout.  I then type git checkout $(!!) in order to actually perform the checkout.  What I'd like is an alias (don't care whether it's a "real" alias) for git checkout $(!!) that actually works.

I don't want a single command that finds the branch and checks it out, as it's possible that the command I use to find the branch outputs more than one branch name, in which case I rerun it with more specific arguments.  (It's an alias for git branch -r | cut -d '/' -f 2- | grep.)

答:
The fc built-in extracts (and by default, lets you edit) your previous command from your bash history.  Using fc -nl -1 -1 gets back the previous command (as standard output).  Hence:

```<code>alias again='eval $(fc -nl -1 -1)'
</code>```

makes the command again do whatever you just did again, just like !!.  Modifying this slightly, we get (fixed, from R. Woods):

```<code>alias xxx='git checkout $(eval $(fc -nl -1 -1))'
</code>```

<s>which should do the trick (not that I have tested it).</s>  Note that this is, and must be, a bash alias, not a Git alias: Git has no access to the shell's history (except by reading the file, but that is not guaranteed to be up to date—or perhaps I should say, guaranteed not to be up to date, at least from the bash documentation I just checked).

Body:
The fc built-in extracts (and by default, lets you edit) your previous command from your bash history.  Using fc -nl -1 -1 gets back the previous command (as standard output).  Hence:

alias again='eval $(fc -nl -1 -1)'

makes the command again do whatever you just did again, just like !!.  Modifying this slightly, we get (fixed, from R. Woods):

alias xxx='git checkout $(eval $(fc -nl -1 -1))'

<s>which should do the trick (not that I have tested it).</s>  Note that this is, and must be, a bash alias, not a Git alias: Git has no access to the shell's history (except by reading the file, but that is not guaranteed to be up to date—or perhaps I should say, guaranteed not to be up to date, at least from the bash documentation I just checked).


问:
Embedded Stylesheet in external assembly for asp.net Core 1.1
I am using VS.2017 Community Edition with 15.2 update (26430.12) and in my solution I have a main ASP.NET Core 1.1 web application and a separate assembly which is a .NET Core class library which I have rigged so that it is the Web SDK as class library and from where I provide view components to the main web application. That works fine.

However, I have just added a couple of partial views (perhaps view components later on) but these two in particular do need a stylesheet (CSS) file to be included. Since I want everything self contained like the visual components, I created a wwwroot\css folder and therein I put my CSS and made it an embedded resource.

The question is.... in my main web application how do I go about streaming that stylesheet in the ASP.NET Core _Layout file given the stylesheet is embedded in the external assembly?

答:
Well, so far for me this .NET Core thing is complicating my life rather than making it easier. Anyway, I managed to get the CSS file residing in the same external assembly where the (external) view components are embedded served in my _Layout.

For one thing, I added a new API method to the SampleAPI API controller of the main web application. This API method retrieves the embedded resource in the external assembly and gets its stream.

Let us say the full namespace of the external assembly where the view component requiring a custom CSS is embedded has a namespace ExternalAssembly and there I defined my component and its CSS file. I am omitting the full view component for clarity.

```<code>ExternalAssembly.proj
     css\
        my-view-component.css
     ViewComponents\
        MyViewComponent.cs
     Views\
        Shared\
           Components\
              MyViewComponent\
                  Default.cshtml
</code>```

The Default.cshtml file and the CSS files are marked in the project as embedded resources.

The API method on the API controller looks like this, my application is an ASP.NET Core 1.1 MVC but has an API as well. The API method takes care of returning the CSS file as a stream for use in your layout page:

```<code>[HttpGet("cssMyViewComponent")]
public IActionResult GetCss(string id) {
    var stream = typeof(ExternalAssembly.ViewComponents.MyViewComponent)
 .GetTypeInfo().Assembly
 .GetManifestResourceStream("ExternalAssembly.css.my-view-component.css");
}
</code>```

Make sure to get the actual name of the embedded resource, notice the css folder name is part of the full namespace of that resource. If unsure you can open up the external assembly with ILDASM and look up the name of the resource.

Last but not least I reference the CSS in the _Layout.cshtml like this using the name of the API method and the route defined for it:

```<code><link rel="stylesheet" href="~/api/SampleAPI/cssMyViewComponent" />
</code>```

Body:
Well, so far for me this .NET Core thing is complicating my life rather than making it easier. Anyway, I managed to get the CSS file residing in the same external assembly where the (external) view components are embedded served in my _Layout.

For one thing, I added a new API method to the SampleAPI API controller of the main web application. This API method retrieves the embedded resource in the external assembly and gets its stream.

Let us say the full namespace of the external assembly where the view component requiring a custom CSS is embedded has a namespace ExternalAssembly and there I defined my component and its CSS file. I am omitting the full view component for clarity.

ExternalAssembly.proj
     css\
        my-view-component.css
     ViewComponents\
        MyViewComponent.cs
     Views\
        Shared\
           Components\
              MyViewComponent\
                  Default.cshtml

The Default.cshtml file and the CSS files are marked in the project as embedded resources.

The API method on the API controller looks like this, my application is an ASP.NET Core 1.1 MVC but has an API as well. The API method takes care of returning the CSS file as a stream for use in your layout page:

[HttpGet("cssMyViewComponent")]
public IActionResult GetCss(string id) {
    var stream = typeof(ExternalAssembly.ViewComponents.MyViewComponent)
 .GetTypeInfo().Assembly
 .GetManifestResourceStream("ExternalAssembly.css.my-view-component.css");
}

Make sure to get the actual name of the embedded resource, notice the css folder name is part of the full namespace of that resource. If unsure you can open up the external assembly with ILDASM and look up the name of the resource.

Last but not least I reference the CSS in the _Layout.cshtml like this using the name of the API method and the route defined for it:

<link rel="stylesheet" href="~/api/SampleAPI/cssMyViewComponent" />


问:
Data Store for a Mac/iPhone Hybrid App
I've been doing iPhone development for the last 5 months or so, and have been using Gus Mueller's FMDB for database interaction. My next project will have both a Mac and an iPhone application, and they will share data between them, although in the end, the iPhone will be mostly a viewer app, with some minor editing capabilities.

My question is this: Will Core Data make my life easy enough on the Mac side, that it would be worth it to write my data model twice, using Core Data on the Mac, and FMDB on the iPhone? Or should I just use FMDB for both so that I can reuse the same code for both the Mac and iPhone?

I've poked at Core Data a little, but not much (mostly just the examples in the Hillegas book), so any specific examples in favor of Core Data would be greatly appreciated. For the record, I really like FMDB, I'm just wondering if Core Data would make my life that much easier in this situation.

Edit:
I understand the core differences between FMDB and Core Data, I'm mostly looking to find out if what Core Data provides "for free" makes it worth coding my data model twice.

答: Code sharing is good, but depending on how similar your model and model controller classes are, you may not want to totally discount Core Data. For example, in addition to object persistence you also get really good undo/redo support "for free". You may want to do a quick prototype to judge how much code you might end up rewriting between the two applications.</p>

OwnerDisplayName: shauber

Title: Data Store for a Mac/iPhone Hybrid App

LastEditorDisplayName: shauber

OwnerDisplayName: Marc Charbonneau


问:
How to chop off characters after a space?
I have a variable - 2 words separated by a single space : $var = "xxxx yyyy". In perl, how do i use regular expressions to make $var = "xxxx"

Thanks,
Trinity

Body:
$var = (split / /, $var, 2)[0];

Or

($var) = $var =~ /^(\S+)/;


问:
"missing required keys" - Ruby on Rails
I have the following Controller called Login:

```<code>class LoginController < ApplicationController
  skip_before_action :verify_authenticity_token
  protect_from_forgery
  before_action :require_user
  helper_method :current_user

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
    rescue ActiveRecord::RecordNotFound
  end

  def require_user
    redirect_to login_path unless current_user
  end

  def show

  end

  def new
    if session[:user]
      @user = User.find(session[:user])
    end
  end

  def destroy
    reset_session
    redirect_to "/login/acesso", notice: "Você foi deslogado"
  end

  def create
    user = User.validate(login_params[:email], login_params[:senha])
    if user
      session[:user] = user.id
      redirect_to "/home/inicio", notice: "login feito com sucesso"
    else
      redirect_to "/login/acesso", notice: "Dados incorretos"
    end
  end

  private

  def login_params
    params.require(:login).permit(:email, :senha)
  end
end
</code>```

and this is my routes:

```<code>Rails.application.routes.draw do

  root 'login#new'
  get '/home/inicio', to: 'home#index'

  scope '/login' do
    get '/acesso', to:'login#new'
    post '/acessorecebendo', to:'login#create'
    get '/sair', to:'login#destroy'
  end

  resources :login
  resources :home
  resources :produtos
  resources :fornecedors
end
</code>```

and the error:

No route matches {:action=>"show", :controller=>"login"}, missing
  required keys: [:id]

at the lines:

```<code>def require_user
  redirect_to login_path unless current_user
end
</code>```

the point is: if I delete the line "before_action :..." found in Login controller, I got this error:

Couldn't find User with 'id'=2

the new.html.erb (the login's view):

```<code><% if flash[:notice] %>
  <div class="notice"><%= flash[:notice] %></div>
<% end %>

<div class="login-page">
  <div class="form">
    <form class="register-form" action="/login/acessorecebendo" method="post">
      <input type="text" name="login[email]" placeholder="Email"/>
      <input type="password" name="login[senha]" placeholder="Senha"/>
      <button>Cadastrar</button>
      <p class="message">Já é registrado? <a href="#">Login</a></p>
    </form>
    <form class="login-form" action="/login/acessorecebendo" method="post">
      <input type="text" name="login[email]" placeholder="email"/>
      <input type="password" name="login[senha]" placeholder="password"/>
      <button>login</button>
      <p class="message">Não está registrado <a href="#">Criar uma conta</a></p>
    </form>
    <% if session[:user] %>
      <a href="/login/sair">Sair sessão <%= @user.nome %> </a>
    <% end %>
  </div>
</div>
</code>```

So, to try solve this, I need to do a way to check if are someone logged or not and redirect to the proper view. I'm trying do something like that with this before action...

can someone explain this to me, please? :\

I tried to follow this solutions: Couldn't find User with id=1

But it didn't work..

答:
The problem with this:

```<code>redirect_to login_path unless current_user
</code>```

Is that login_path requires and id, which you can see by running rake routes in the console:

```<code>           acesso GET    /login/acesso(.:format)          login#new
  acessorecebendo POST   /login/acessorecebendo(.:format) login#create
             sair GET    /login/sair(.:format)            login#destroy
      login_index GET    /login(.:format)                 login#index
                  POST   /login(.:format)                 login#create
        new_login GET    /login/new(.:format)             login#new
       edit_login GET    /login/:id/edit(.:format)        login#edit
            login GET    /login/:id(.:format)             login#show
                  PATCH  /login/:id(.:format)             login#update
                  PUT    /login/:id(.:format)             login#update
                  DELETE /login/:id(.:format)             login#destroy
       home_index GET    /home(.:format)                  home#index
                  POST   /home(.:format)                  home#create
         new_home GET    /home/new(.:format)              home#new
        edit_home GET    /home/:id/edit(.:format)         home#edit
                  GET    /home/:id(.:format)              home#show
                  PATCH  /home/:id(.:format)              home#update
                  PUT    /home/:id(.:format)              home#update
                  DELETE /home/:id(.:format)              home#destroy
</code>```

(I removed some for brevity's sake.)

I'm guessing you probably want to do:

```<code>redirect_to accesso_path unless current_user
</code>```

Or, possibly:

```<code>redirect_to new_login_path unless current_user
</code>```

They both point to the same place, by the way, so you probably can get rid of accesso_path and replace it with login_new.

So, the other problem is sounds like you are likely having (from your comments), is that you have a invalid id in session[:user_id]. When you remove before_action :require_user, then, you're getting to:

```<code>def new
  if session[:user]
    @user = User.find(session[:user])
  end
end
</code>```

Which is then raising the exception:

Couldn't find User with 'id'=2

So, here's probably what you should do:

```<code>class LoginController < ApplicationController
  skip_before_action :verify_authenticity_token
  protect_from_forgery
  before_action :go_home_if_signed_in
  helper_method :current_user
  # ^^^
  # I don't know what this is

  def go_home_if_signed_in
    if session[:user_id]
      # there was a session[:user_id]
      # use find_by instead of find because it won't raise an exception
      if User.find_by(id: session[:user_id])
        # the session[:user_id] resulted in a valid user, so
        # send the user to their home page.
        redirect_to home_index_path
      else
        # if the User wasn't found, then you'll be in here, without
        # raising an exception.
        # So now you want to set the session[:user_id] to nil
        # because it's invalid.
        session[:user_id] = nil
      end
    end
  end

  # you should be able to get rid of this.
  # def require_user
  #   redirect_to new_login_path unless current_user # or wherever, but not login_path
  # end

  def show

  end

  def new
    # This seems wrong. What is session[:user] and how do you
    # expect User to find it?
    # if session[:user]
    #   @user = User.find(session[:user])
    # end
  end

  def destroy
    # Make sure you set session[:user] = nil somewhere!!!
    reset_session
    # ^^^
    # I don't know what this is.
    # redirect_to "/login/acesso", notice: "Você foi deslogado"
    redirect_to :acesso_path, notice: "Você foi deslogado"
    # ^^^
    # Why not use the path you generated in routes? You went through
    # the trouble of defining it.
  end

  def create
    user = User.validate(login_params[:email], login_params[:senha])
    if user
      session[:user] = user.id
      redirect_to "/home/inicio", notice: "login feito com sucesso"
    else
      redirect_to "/login/acesso", notice: "Dados incorretos"
    end
  end

  private

  def login_params
    params.require(:login).permit(:email, :senha)
  end
end
</code>```

Title: "missing required keys" - Ruby on Rails

Body:
I have the following Controller called Login:

class LoginController < ApplicationController
  skip_before_action :verify_authenticity_token
  protect_from_forgery
  before_action :require_user
  helper_method :current_user

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
    rescue ActiveRecord::RecordNotFound
  end

  def require_user
    redirect_to login_path unless current_user
  end

  def show

  end

  def new
    if session[:user]
      @user = User.find(session[:user])
    end
  end

  def destroy
    reset_session
    redirect_to "/login/acesso", notice: "Você foi deslogado"
  end

  def create
    user = User.validate(login_params[:email], login_params[:senha])
    if user
      session[:user] = user.id
      redirect_to "/home/inicio", notice: "login feito com sucesso"
    else
      redirect_to "/login/acesso", notice: "Dados incorretos"
    end
  end

  private

  def login_params
    params.require(:login).permit(:email, :senha)
  end
end

and this is my routes:

Rails.application.routes.draw do

  root 'login#new'
  get '/home/inicio', to: 'home#index'

  scope '/login' do
    get '/acesso', to:'login#new'
    post '/acessorecebendo', to:'login#create'
    get '/sair', to:'login#destroy'
  end

  resources :login
  resources :home
  resources :produtos
  resources :fornecedors
end

and the error:

No route matches {:action=>"show", :controller=>"login"}, missing
  required keys: [:id]

at the lines:

def require_user
  redirect_to login_path unless current_user
end

the point is: if I delete the line "before_action :..." found in Login controller, I got this error:

Couldn't find User with 'id'=2

the new.html.erb (the login's view):

<% if flash[:notice] %>

<%= flash[:notice] %>

<% end %>

    <form class="register-form" action="/login/acessorecebendo" method="post">
      <input type="text" name="login[email]" placeholder="Email"/>
      <input type="password" name="login[senha]" placeholder="Senha"/>
      <button>Cadastrar</button>

Já é registrado? Login

    </form>
    <form class="login-form" action="/login/acessorecebendo" method="post">
      <input type="text" name="login[email]" placeholder="email"/>
      <input type="password" name="login[senha]" placeholder="password"/>
      <button>login</button>

Não está registrado Criar uma conta

    </form>
    <% if session[:user] %>
      Sair sessão <%= @user.nome %>
    <% end %>

So, to try solve this, I need to do a way to check if are someone logged or not and redirect to the proper view. I'm trying do something like that with this before action...

can someone explain this to me, please? :\

I tried to follow this solutions: Couldn't find User with id=1

But it didn't work..

Body:
The problem with this:

redirect_to login_path unless current_user

Is that login_path requires and id, which you can see by running rake routes in the console:

           acesso GET    /login/acesso(.:format)          login#new
  acessorecebendo POST   /login/acessorecebendo(.:format) login#create
             sair GET    /login/sair(.:format)            login#destroy
      login_index GET    /login(.:format)                 login#index
                  POST   /login(.:format)                 login#create
        new_login GET    /login/new(.:format)             login#new
       edit_login GET    /login/:id/edit(.:format)        login#edit
            login GET    /login/:id(.:format)             login#show
                  PATCH  /login/:id(.:format)             login#update
                  PUT    /login/:id(.:format)             login#update
                  DELETE /login/:id(.:format)             login#destroy
       home_index GET    /home(.:format)                  home#index
                  POST   /home(.:format)                  home#create
         new_home GET    /home/new(.:format)              home#new
        edit_home GET    /home/:id/edit(.:format)         home#edit
                  GET    /home/:id(.:format)              home#show
                  PATCH  /home/:id(.:format)              home#update
                  PUT    /home/:id(.:format)              home#update
                  DELETE /home/:id(.:format)              home#destroy

(I removed some for brevity's sake.)

I'm guessing you probably want to do:

redirect_to accesso_path unless current_user

Or, possibly:

redirect_to new_login_path unless current_user

They both point to the same place, by the way, so you probably can get rid of accesso_path and replace it with login_new.

So, the other problem is sounds like you are likely having (from your comments), is that you have a invalid id in session[:user_id]. When you remove before_action :require_user, then, you're getting to:

def new
  if session[:user]
    @user = User.find(session[:user])
  end
end

Which is then raising the exception:

Couldn't find User with 'id'=2

So, here's probably what you should do:

class LoginController < ApplicationController
  skip_before_action :verify_authenticity_token
  protect_from_forgery
  before_action :go_home_if_signed_in
  helper_method :current_user
  # ^^^
  # I don't know what this is

  def go_home_if_signed_in
    if session[:user_id]
      # there was a session[:user_id]
      # use find_by instead of find because it won't raise an exception
      if User.find_by(id: session[:user_id])
        # the session[:user_id] resulted in a valid user, so
        # send the user to their home page.
        redirect_to home_index_path
      else
        # if the User wasn't found, then you'll be in here, without
        # raising an exception.
        # So now you want to set the session[:user_id] to nil
        # because it's invalid.
        session[:user_id] = nil
      end
    end
  end

  # you should be able to get rid of this.
  # def require_user
  #   redirect_to new_login_path unless current_user # or wherever, but not login_path
  # end

  def show

  end

  def new
    # This seems wrong. What is session[:user] and how do you
    # expect User to find it?
    # if session[:user]
    #   @user = User.find(session[:user])
    # end
  end

  def destroy
    # Make sure you set session[:user] = nil somewhere!!!
    reset_session
    # ^^^
    # I don't know what this is.
    # redirect_to "/login/acesso", notice: "Você foi deslogado"
    redirect_to :acesso_path, notice: "Você foi deslogado"
    # ^^^
    # Why not use the path you generated in routes? You went through
    # the trouble of defining it.
  end

  def create
    user = User.validate(login_params[:email], login_params[:senha])
    if user
      session[:user] = user.id
      redirect_to "/home/inicio", notice: "login feito com sucesso"
    else
      redirect_to "/login/acesso", notice: "Dados incorretos"
    end
  end

  private

  def login_params
    params.require(:login).permit(:email, :senha)
  end
end


问:
how to close child of other components?
enter image description here

When I open one of three copmonent A child open,I want to close two others child if they are open.

答:
The gist of it is

```<code>// where openChild is just the index of the child that should be open
// fetched from redux
// you should use an id here instead of an index
const Parent = ({ openChild }) => {
    return [0, 1, 2].map((index) => (
        <Child key={index} index={index} closed={openChild !== index}/>
    ))
}

const Child = ({ index, closed }) => {
    return <div className={closed ? 'closed' : 'open'}>{index}</div>
}
</code>```

use .open and .closed on the child to control whether or not it's being shown or you can just conditionally render the whole thing like

```<code>const Parent = ({ openChild }) => {
    return [0, 1, 2].map((index) => (
        openChild !== index
            ? <Child key={index} index={index} />
            : null
    )).filter(child => !!child)
    /* you don't really need the above line */
}
</code>```

Title: how to close child of other components?

Body:
The gist of it is

// where openChild is just the index of the child that should be open
// fetched from redux
// you should use an id here instead of an index
const Parent = ({ openChild }) => {
    return [0, 1, 2].map((index) => (
        <Child key={index} index={index} closed={openChild !== index}/>
    ))
}

const Child = ({ index, closed }) => {
    return <div className={closed ? 'closed' : 'open'}>{index}</div>
}

use .open and .closed on the child to control whether or not it's being shown or you can just conditionally render the whole thing like

const Parent = ({ openChild }) => {
    return [0, 1, 2].map((index) => (
        openChild !== index
            ? <Child key={index} index={index} />
            : null
    )).filter(child => !!child)
    /* you don't really need the above line */
}


问:
How to use UIBlurEffect with modal View Controllers?
I have a UIViewController that presents another UIViewController modally. I want the modal view controller to have the blur/transparency that iOS 7 introduced. I tried using the new UIVisualEffect but it seems like that only works with UIViews, and not UIViewControllers?

Here is the code I've written, all the views I've added as subviews are what I want to be in the user interface above the blurred out view below it.

In the presenting view controller, I take a screenshot of the screen that I pass to the modal view controller before applying the blur.

In Presenting View Controller:

```<code>- (UIImage *)viewImage {
    CGSize size = CGSizeMake(self.view.frame.size.width,self.view.frame.size.height);
    UIGraphicsBeginImageContext(size);
    [self.view drawViewHierarchyInRect:(CGRect){CGPointZero, self.view.frame.size.width, self.view.frame.size.height} afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}
</code>```

In Modal View Controller:

```<code>- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:[[UIImageView alloc] initWithImage:self.backgroundImage]];
    //self.backgroundImage is the image that the method above returns, it's a screenshot of the presenting view controller.
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    [blurEffectView setFrame:self.view.bounds];
    [self.view addSubview:blurEffectView];

    [self.view bringSubviewToFront:self.cancelButton];
    [self.view bringSubviewToFront:self.titleLabel];
    [self.view bringSubviewToFront:self.tableView];
}
</code>```

答:
the easiest way is just copy and paste this code in viewDidLoad :)</p>

```<code>UIVisualEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];

visualEffectView.frame = self.view.bounds;
self.view insertSubview:visualEffectView atIndex:0];
</code>```

Body:
I have a UIViewController that presents another UIViewController modally. I want the modal view controller to have the blur/transparency that iOS 7 introduced. I tried using the new UIVisualEffect but it seems like that only works with UIViews, and not UIViewControllers?

Here is the code I've written, all the views I've added as subviews are what I want to be in the user interface above the blurred out view below it.

In the presenting view controller, I take a screenshot of the screen that I pass to the modal view controller before applying the blur.

In Presenting View Controller:

- (UIImage *)viewImage {
    CGSize size = CGSizeMake(self.view.frame.size.width,self.view.frame.size.height);
    UIGraphicsBeginImageContext(size);
    [self.view drawViewHierarchyInRect:(CGRect){CGPointZero, self.view.frame.size.width, self.view.frame.size.height} afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

In Modal View Controller:

- (void)viewDidLoad {
    [super viewDidLoad];

    [self.view addSubview:[[UIImageView alloc] initWithImage:self.backgroundImage]];
    //self.backgroundImage is the image that the method above returns, it's a screenshot of the presenting view controller.
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    [blurEffectView setFrame:self.view.bounds];
    [self.view addSubview:blurEffectView];

    [self.view bringSubviewToFront:self.cancelButton];
    [self.view bringSubviewToFront:self.titleLabel];
    [self.view bringSubviewToFront:self.tableView];
}

Body:
the easiest way is just copy and paste this code in viewDidLoad :)

UIVisualEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];

visualEffectView.frame = self.view.bounds;
self.view insertSubview:visualEffectView atIndex:0];


答: It looks liked you checked out a branch within an already existing working copy. That's not the correct way, since it created a new (unrelated) working copy withing your working copy.</p>

Title: Unexplained Subversion directory status after checkout


问:
Jasmine Mock for nested Object in Angulartics
I have an Angular 2 project. In that project I have imported the Angulartics npm package and injected it into one of my components.
In my component I am making a single call that I need to mock for an existing unit test.

```<code>this.angulartics2.eventTrack.next({ action: 'Track my event'});
</code>```

In my test spec file I have done the following:

Added this in beforeEach:

```<code>mockAngulartics2 = jasmine.createSpyObj<Angulartics2>('angulartics2', ['eventTrack']);
</code>```

Added this to providers:

```<code>{ provide: Angulartics2, useValue: mockAngulartics2 },
</code>```

When I run my test, I get the following error back. What is the correct way to mock the angulartics2.eventTrack.next object?

TypeError: undefined is not a constructor (evaluating 'this.angulartics2.eventTrack.next({ action: 'Track my event' })') in config/spec-bundle.js (line 145931)

答:
It's complaining about the call to next only.
You correctly created a spy object for eventTrack but not for next. So in between 1) and 2), you can do:

mockAngulartics2.eventTrack = jasmine.createSpyObj('angulartics2', ['next']);

I had an issue mocking Angulartics2 and you lead me on the right way, so, thanks!

Body:
I have an Angular 2 project. In that project I have imported the Angulartics npm package and injected it into one of my components.
In my component I am making a single call that I need to mock for an existing unit test.

this.angulartics2.eventTrack.next({ action: 'Track my event'});

In my test spec file I have done the following:

Added this in beforeEach:

mockAngulartics2 = jasmine.createSpyObj<Angulartics2>('angulartics2', ['eventTrack']);

Added this to providers:

{ provide: Angulartics2, useValue: mockAngulartics2 },

When I run my test, I get the following error back. What is the correct way to mock the angulartics2.eventTrack.next object?

TypeError: undefined is not a constructor (evaluating 'this.angulartics2.eventTrack.next({ action: 'Track my event' })') in config/spec-bundle.js (line 145931)


问:
Multiple Tomcat instances: Port already in use: 8086 (tried checking server.xml)
I have to run multiple Tomcat instance on app server (Apache Tomcat 7.0.33 and 7.0.42). Everything was working until last week. Now when I start one instance, another throws following error and couldn't start tomcat instance, and vice-a-versa. I thought of changing the port from 8086 to other, but there is no mention of port 8086 in both instance's config (conf/server.xml) files. How can I keep both instances running, without killing another instance?

Error:
2017-06-06 11:09:17 Commons Daemon procrun stderr initialized
Error: Exception thrown by the agent : java.rmi.server.ExportException: Port already in use: 8086; nested exception is:
    java.net.BindException: Address already in use: JVM_Bind

答: ensure the ports at file server.conf under tomcatdir/conf/  different than your other tomcat instance.</p>


问:
Android Studio - Drawable folders
I have three general questions regarding android's drawable folders.

Do i put different sized images in each of these folders, or will the images automatically scale themselves? As in, does android decrease the quality of the .bmp files automatically if placed in these folders?

When using the android design preview screen, will the appropriate image from the appropriate drawable folder be shown? If I have to make different sized images for each folder, I want to ensure that what i'm seeing in the design preview matches what is shown on other devices.

Lastly, do the drawable folders, if used, help to avoid the issue with failing to allocate memory for drawables on devices? I have had to scale my images down, and yet my college's phone still cannot allocate enough resources.

I couldn't find answers to these specific questions anywhere, so i'd really appreciate the help with these!

答:
1) You don't need the different folders if you will put the same things in those folders. The designer/developer puts the resources that most adapt to that configuration.

2) You can select what kind of device you're previewing the design with (resolution and dpi), on the design tools. It will attempt to load the appropriate resource for that configuration.

3) Loading smaller images into memory may be helpful, as well as resizing them before displaying them (libraries like Picasso can do this out of the box), or you could be looking at a leak of some sort.

Title: Android Studio - Drawable folders


Body:
You can try:

with open('trips.txt', 'r') as f:
    dic = {}
    try:
        while True:
            num = int(f.next().split()[1])
            lst = []
            for _ in xrange(5):
                lst.append(f.next().strip().split(';'))
            f.next()
            for n in lst:
                for l in n:
                    if l != '':
                        tmp = l.strip().split(':')
                        dic[(num, int(tmp[0]))] = float(tmp[1])
    except StopIteration:
        print dic

output:

{(1, 21): 100.0, (1, 3): 100.0, (2, 18): 0.0, (2, 8): 400.0, (1, 17): 400.0, (2, 1): 100.0, (1, 15): 500.0, (2, 22): 100.0....etc}


问:
get the dates of specific day of week
How to be able to know the date of a specific day in next month in java

for example if I enter Friday I need the output to be as following

Friday 9 Jun 2017
Friday 16 Jun 2017
Friday 23 Jun 2017
Friday 30 Jun 2017

答:
```<code>LocalDate.of( 2017 , Month.JUNE , 9 )
     .with( TemporalAdjusters.next( DayOfWeek.FRIDAY ) )
</code>```

You can use java.time.LocalDate and java.time.TemporalAdjusters

java.time API

For Android library to do this code, use the ThreeTenABP project, an adaptation of the ThreeTen-Backport project. See How to use ThreeTenABP.

Title: get the dates of specific day of week

Body:
LocalDate.of( 2017 , Month.JUNE , 9 )
     .with( TemporalAdjusters.next( DayOfWeek.FRIDAY ) )

You can use java.time.LocalDate and java.time.TemporalAdjusters

java.time API

For Android library to do this code, use the ThreeTenABP project, an adaptation of the ThreeTen-Backport project. See How to use ThreeTenABP.


问:
ArrayList updated inserting one row but Jtable still not refresh
I've to create a java swing app that allows the user to menage some Oracle tables.

I've implemented the JTable in this way:

```<code>public class TableModel extends AbstractTableModel{
        .
        .
        .

  public List <List <String> > result = null;
        .
        .
        .
  public void createTable(ResultSet r) throws SQLException {
    rs = r;
    numcols = getColumnCount();
    result = new ArrayList();
    while (rs.next()) {
      List <String> row = new ArrayList<>(numcols);
      for (int i=1; i<= numcols; i++)
          row.add(rs.getString(i).replace("00:00:00.0", "")); //just managing stuffs .. nothing important. Don't care of this replace.
      result.add(row);
     }
     fireTableStructureChanged();
   }

  public void addRow(){
    List <String> row = new ArrayList<>();
    for(int i=1;i<=getColumnCount();i++)
        row.add("");
    result.add(row);
    fireTableStructureChanged();
  }

  public Object getValueAt(int row, int col) {
    return result.get(row).get(col);
  }

  public int getColumnCount() {
  if (rs == null) {
     return 0;
  }
  try {
     return rs.getMetaData().getColumnCount();
  } catch (SQLException e) {
     System.err.println("error in colcount");
     return 0;
  }
 }

  public int getRowCount() {
  int totalRows = 0;
  try {
    rs.last();
    totalRows = rs.getRow();
    rs.beforeFirst();
  } catch(Exception ex)  {
        return 0;
  }
    return totalRows ;
  }
}
</code>```

so, I store database data into the arraylist and then I print the table using the arraylist.
Now in the addRow() function I add to that arraylist an empty record (in my mind an empty record is a record composed of all null ("") strings).
Finally using the fireTableStructureChanged() method I expect the table to refresh itself.. but this will never occur and I don't understand why.

I've already checked that the new row is successfully loaded into the arraylist:
I got all the data stored in the table of the Database into the arraylist and the new row is successfully loaded in the arraylist.
so I swear the problem is about that fireTableStructureChanged() method.

Thanks :3

答:
I found the solution.
That's quite embarassing..

@tsolakp you helped me a lot!

Since before using ArrayList I was working on ResultSet directly, I forgot to update getrowcount.
So, since the inserting was only "client side" on the arraylist, the rows displayed were only "n" (where n was the number of rows on the database). So I would never displayed my new row since it was not loaded into the database.

That's all :)

Maybe working hard on coding, makes these errors invisible :X

Body:
I've to create a java swing app that allows the user to menage some Oracle tables.

I've implemented the JTable in this way:

public class TableModel extends AbstractTableModel{
        .
        .
        .

  public List <List <String> > result = null;
        .
        .
        .
  public void createTable(ResultSet r) throws SQLException {
    rs = r;
    numcols = getColumnCount();
    result = new ArrayList();
    while (rs.next()) {
      List <String> row = new ArrayList<>(numcols);
      for (int i=1; i<= numcols; i++)
          row.add(rs.getString(i).replace("00:00:00.0", "")); //just managing stuffs .. nothing important. Don't care of this replace.
      result.add(row);
     }
     fireTableStructureChanged();
   }

  public void addRow(){
    List <String> row = new ArrayList<>();
    for(int i=1;i<=getColumnCount();i++)
        row.add("");
    result.add(row);
    fireTableStructureChanged();
  }

  public Object getValueAt(int row, int col) {
    return result.get(row).get(col);
  }

  public int getColumnCount() {
  if (rs == null) {
     return 0;
  }
  try {
     return rs.getMetaData().getColumnCount();
  } catch (SQLException e) {
     System.err.println("error in colcount");
     return 0;
  }
 }

  public int getRowCount() {
  int totalRows = 0;
  try {
    rs.last();
    totalRows = rs.getRow();
    rs.beforeFirst();
  } catch(Exception ex)  {
        return 0;
  }
    return totalRows ;
  }
}

so, I store database data into the arraylist and then I print the table using the arraylist.
Now in the addRow() function I add to that arraylist an empty record (in my mind an empty record is a record composed of all null ("") strings).
Finally using the fireTableStructureChanged() method I expect the table to refresh itself.. but this will never occur and I don't understand why.

I've already checked that the new row is successfully loaded into the arraylist:
I got all the data stored in the table of the Database into the arraylist and the new row is successfully loaded in the arraylist.
so I swear the problem is about that fireTableStructureChanged() method.

Thanks :3


问:
Am I writing this code wrong?
This looks wrong to me, am i right? This is the code that I am using:

```<code>_editButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                               style:UIBarButtonItemStylePlain
                                              target:self
                                              action:@selector(editButtonPressed:)];

// If we have no threads we don't have the edit button
self.navigationItem.leftBarButtonItem = _editButton ; nil;
</code>```

Mainly I am concerned with self.navigationItem.leftBarButtonItem = _editButton ; nil; the _editButton ; nil; looks wrong to me.

Should the code look like this? self.navigationItem.leftBarButtonItem = _editButton;

答: I've never used this particular type before, but your main indicator is prooobably if it works as intended (+ if it shows up on a debugger as correct, but that's a given).</p>

Title: Am I writing this code wrong?

Body:
This looks wrong to me, am i right? This is the code that I am using:

_editButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                               style:UIBarButtonItemStylePlain
                                              target:self
                                              action:@selector(editButtonPressed:)];

// If we have no threads we don't have the edit button
self.navigationItem.leftBarButtonItem = _editButton ; nil;

Mainly I am concerned with self.navigationItem.leftBarButtonItem = _editButton ; nil; the _editButton ; nil; looks wrong to me.

Should the code look like this? self.navigationItem.leftBarButtonItem = _editButton;


问:
I18N Using Django/Python
Im looking to optimize our translation workflow for a django/python based project.
Currently we run a command to export our gettext files, send it to the translators, receive it back. Well you get the drill.

What in your opinion is the best way to optimize this workflow. Tools which integrate nicely and allow translations to be pushed and pulled from and to the system?

Options i've seen so far:

http://trac.transifex.org/ (supported in django 1.3)

答: Transifex was designed for pretty much this. It doesn't pull the strings from the project/app automatically yet, but it can be extended to do so if desired.</p>

Title: I18N Using Django/Python


问:
Makefile where target names unknown
I'm trying to write a Makefile where multiple source files (in my case they are markdown) create multiple target files (pdfs). However, the target files generated have extra characters in the file name that can't be predicted (it happens to be a version number encoded in the source), but ideally the Makefile would not have to read the source itself.

So, for example:

```<code>file1.md => file1-v1.pdf
file2.md => file2-v2.pdf
...
</code>```

I can calculate source name given a target name (by excluding anything after the hyphen and adding .md), but cannot calculate target name given the source.

Is it possible to write a Makefile that builds only the targets where the source have been updated?

答:
@Beta's answer is informative and helpful, but I needed a solution (using GNU Make 4.1) that worked when the destination filename bears no resemblance to the input filename, for example, if it is generated from its content. I came up with the following, which takes every file matching *.in, and creates a file by reading the contents of the source file, appending a .txt, and using it as a filename to create. (For example, if test.in exists and contains foo, the makefile will create a foo.txt file.)

```<code>SRCS := $(wildcard *.in)
.PHONY: all

all: all_s

define TXT_template =
$(2).txt: $(1)
    touch $$@
ALL += $(2).txt
endef

$(foreach src,$(SRCS),$(eval $(call TXT_template, $(src), $(shell cat $(src)))))

.SECONDARY_EXPANSION:
all_s: $(ALL)
</code>```

The explanation:

The define block defines the recipe needed to make the text file from the .in file. It's a function that takes two parameters; $(1) is the .in. file and $(2) is the contents of it, or the base of the output filename. Replace touch with whatever makes the output. We have to use $$@ because eval will expand everything once, but we want $@ to left after this expansion. Since we have to collect all the generated targets so we known what all the make, the ALL line accumulates the targets into one variable. The foreach line goes through each source file, calls the function with the source filename and the contents of the file (i.e. what we want to be the name of the target, here you'd normally use whatever script generates the desired filename), and then evaluates the resulting block, dynamically adding the recipe to make. Thanks to Beta for explaining .SECONDARY_EXPANSION; I needed it for reasons not entirely clear to me, but it works (putting all: $(ALL) at the top doesn't work).  The all: at the top depends on the secondary expansion of all_s: at the bottom and somehow this magic makes it work. Comments welcome.

Title: Makefile where target names unknown

Body:
I'm trying to write a Makefile where multiple source files (in my case they are markdown) create multiple target files (pdfs). However, the target files generated have extra characters in the file name that can't be predicted (it happens to be a version number encoded in the source), but ideally the Makefile would not have to read the source itself.

So, for example:

file1.md => file1-v1.pdf
file2.md => file2-v2.pdf
...

I can calculate source name given a target name (by excluding anything after the hyphen and adding .md), but cannot calculate target name given the source.

Is it possible to write a Makefile that builds only the targets where the source have been updated?

Body:
@Beta's answer is informative and helpful, but I needed a solution (using GNU Make 4.1) that worked when the destination filename bears no resemblance to the input filename, for example, if it is generated from its content. I came up with the following, which takes every file matching *.in, and creates a file by reading the contents of the source file, appending a .txt, and using it as a filename to create. (For example, if test.in exists and contains foo, the makefile will create a foo.txt file.)

SRCS := $(wildcard *.in)
.PHONY: all

all: all_s

define TXT_template =
$(2).txt: $(1)
    touch $$@
ALL += $(2).txt
endef

$(foreach src,$(SRCS),$(eval $(call TXT_template, $(src), $(shell cat $(src)))))

.SECONDARY_EXPANSION:
all_s: $(ALL)

The explanation:

The define block defines the recipe needed to make the text file from the .in file. It's a function that takes two parameters; $(1) is the .in. file and $(2) is the contents of it, or the base of the output filename. Replace touch with whatever makes the output. We have to use $$@ because eval will expand everything once, but we want $@ to left after this expansion. Since we have to collect all the generated targets so we known what all the make, the ALL line accumulates the targets into one variable. The foreach line goes through each source file, calls the function with the source filename and the contents of the file (i.e. what we want to be the name of the target, here you'd normally use whatever script generates the desired filename), and then evaluates the resulting block, dynamically adding the recipe to make. Thanks to Beta for explaining .SECONDARY_EXPANSION; I needed it for reasons not entirely clear to me, but it works (putting all: $(ALL) at the top doesn't work).  The all: at the top depends on the secondary expansion of all_s: at the bottom and somehow this magic makes it work. Comments welcome.


问:
Must declare the scalar variable @DateField2
```<code>protected void Button2_Click(object sender, EventArgs e)
{
    string dateType = DateFieldDropDown.SelectedItem.ToString();
    string DateField1 = DateTextBox.Text;
    string DateField2 = dateSelection2Text.Text;
    string DateFiled = "DateFiled";

    if (dateType == "DateFiled")
    {
        SqlDataSource1.SelectParameters.Add(new Parameter("DateFiled", TypeCode.String, DateFiled));
        SqlDataSource1.SelectParameters.Add(new Parameter("DateField1", TypeCode.String, DateField1));
        SqlDataSource1.SelectParameters.Add(new Parameter("DateFie1d2", TypeCode.String, DateField2));

        SqlDataSource1.SelectCommand = "SELECT * FROM tbl_repopulate WHERE CONVERT(VARCHAR, @DateFiled) BETWEEN " +
            "CONVERT(VARCHAR, @DateField1) AND CONVERT(VARCHAR, @DateField2)";
        SqlDataSource1.DataBind();
        GridView1.DataBind();
    }
</code>```

I'm trying to perform a SQL query on a database.  I was getting an error indicating that the types DateFiled and DateField1 were incompatible even though all the elements are text. I went in and tried to fix that with the CONVERT(VARCHAR... but now it's coming up with a new error on @DateField2, that it is not declared.  To me, it looks like it is set up exactly the same as the other two parameters.  Am I missing something?

答:
spelling issue..

```<code>SqlDataSource1.SelectParameters.Add(new Parameter("DateFie1d2", TypeCode.String, DateField2));
</code>```

DateFie1d2 instead of DateField2

Body:
protected void Button2_Click(object sender, EventArgs e)
{
    string dateType = DateFieldDropDown.SelectedItem.ToString();
    string DateField1 = DateTextBox.Text;
    string DateField2 = dateSelection2Text.Text;
    string DateFiled = "DateFiled";

    if (dateType == "DateFiled")
    {
        SqlDataSource1.SelectParameters.Add(new Parameter("DateFiled", TypeCode.String, DateFiled));
        SqlDataSource1.SelectParameters.Add(new Parameter("DateField1", TypeCode.String, DateField1));
        SqlDataSource1.SelectParameters.Add(new Parameter("DateFie1d2", TypeCode.String, DateField2));

        SqlDataSource1.SelectCommand = "SELECT * FROM tbl_repopulate WHERE CONVERT(VARCHAR, @DateFiled) BETWEEN " +
            "CONVERT(VARCHAR, @DateField1) AND CONVERT(VARCHAR, @DateField2)";
        SqlDataSource1.DataBind();
        GridView1.DataBind();
    }

I'm trying to perform a SQL query on a database.  I was getting an error indicating that the types DateFiled and DateField1 were incompatible even though all the elements are text. I went in and tried to fix that with the CONVERT(VARCHAR... but now it's coming up with a new error on @DateField2, that it is not declared.  To me, it looks like it is set up exactly the same as the other two parameters.  Am I missing something?

Body:
spelling issue..

SqlDataSource1.SelectParameters.Add(new Parameter("DateFie1d2", TypeCode.String, DateField2));

DateFie1d2 instead of DateField2


问:
node.js require() cache - possible to invalidate?
From the node.js documentation:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Is there a way to invalidate this cache? i.e. for unit testing, I'd like each test to be working on a fresh object.

答: If it's for unit tests, another good tool to use is proxyquire. Everytime you proxyquire the module, it will invalidate the module cache and cache a new one. It also allows you to modify the modules required by the file that you are testing.</p>


问:
Branch by cloning - Must I make modification on default in order to see the branch?
I am coming from CVS background.

I try to perform branch by cloning.

The current default tree looks like this from hello project.

I try to clone a project out from 'hello' to 'hello-branch-by-clone'.

I did modification on 'hello-branch-by-clone' and commit.

I did not do any modification on 'hello'.

I perform push from 'hello-branch-by-clone' to 'hello'.

I expect to see a branch but I didn't.

This time, I try another way around.

I did modification on 'hello-branch-by-clone' and commit.

I did modification on 'hello' and commit.

I need to pull from 'hello' to 'hello-branch-by-clone', and merge.

I perform push from 'hello-branch-by-clone' to 'hello'.

This time, then only I can see the branch

By applying cloning technique, is there any way I can have a branch view, without having explicitly modify the default repository (hello)

答:
There's no fork because no two changesets share a parent.

A cloned repository isn't special in any way. It's identical to the original. Commits to it are identical to commits in the original repo. They aren't notionally tagged as being on a branch. A clone is just a nice way of having another work area that you can do some work (including commits) without effecting the original.

A fork occurs when two or more commits have the same parent. Often this happens when using clones, but it may not. If there's only one changeset with the same parent, there is no fork.

After your first sequence you've introduced just one changeset (4) which is which has the old tip (3) as it's parent, so it's still a straight line. Only when you introduce a second changeset parented by (3) will you see a fork.

Now remember, even though you 'push'ed the changeset back, and the original "Hello" repo contains all 4 changesets, it's working directory is still pointing to changeset (3). It will stay that way until you run 'hg update' inside it. This means that if you were to make a commit in "Hello" it will be based upon (3), and then a fork will appear. It doesn't matter when this commit is made.

This is what you did in your second sequence.

Hope that helps.

I've tried to use the term 'fork' in this, because 'branch' has lots of meanings, including the 'hg branch' command which does some slightly different things.


问:
Regex match cookie value and remove hyphens
I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens.  I would like to replace the hyphens with a space and set to a variable.  Javascript or jQuery.

As an example, the larger string has a name and value like this within it:

```<code>facility=34222%7CConner-Department-Store;
</code>```

(notice the leading "C")

So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex.  Then break it down to "Conner Department Store"

var cookie = document.cookie;
var facilityValue = cookie.match( REGEX );  ??

答:
var test = "store=874635%7Csomethingelse;facility=34222%7CConner-Department-Store;store=874635%7Csomethingelse;";

var test2 = test.replace(/^(.*)facility=([^;]+)(.*)$/, function(matchedString, match1, match2, match3){
    return decodeURIComponent(match2);
});

console.log( test2 );
console.log( test2.split('|')[1].replace(/[-]/g, ' ') );```

Body:
I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens.  I would like to replace the hyphens with a space and set to a variable.  Javascript or jQuery.

As an example, the larger string has a name and value like this within it:

facility=34222%7CConner-Department-Store;

(notice the leading "C")

So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex.  Then break it down to "Conner Department Store"

var cookie = document.cookie;
var facilityValue = cookie.match( REGEX );  ??