问:
C# delete dynamically added textbox and move all other textboxes down
I have really been struggling with this question for a long time.

I add a textbox and a button on tab press . I put text inside the textboxes:

Now, my question, how do I remove the textbox next to the button I click and move all the textboxes down, so I won't get any open space. If I press on the button next to the 7th textbox, I want it to look like this:

here's my code:

```<code>private void Form1_Load(object sender, EventArgs e)
    {
        //creates a textbox(t0) and a button(b0) on load
        TextBox t0 = new TextBox();
        t0.Name = "t0";
        t0.Location = new Point(16, 12);
        t0.Width = 200;
        t0.PreviewKeyDown += new PreviewKeyDownEventHandler(PreviewKeyDown);

        Button b0 = new Button();
        b0.TabStop = false;
        b0.Text = "x";
        b0.Location = new Point(216, 11);
        b0.Size = new System.Drawing.Size(20, 22);
        b0.Click += new EventHandler(buttonclicked);

        panel1.Controls.Add(t0);
        panel1.Controls.Add(b0);
    }

    private new void PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        //if I press tab in the last textbox it creates a new textbox(t + amount of textboxes) and button(b + amount of textboxes)
        if (e.KeyData == Keys.Tab)
        {
            int counter2 = 0;
            foreach (TextBox box in panel1.Controls.OfType<TextBox>())
            {
                counter2++;
            }

            counter2 = counter2 - 1;
            string Name = "t" + Convert.ToString(counter2);
            counter2++;
            foreach (TextBox box in panel1.Controls.OfType<TextBox>())
            {
                if (Name == box.Name && box.Focused)
                {
                    TextBox t0 = new TextBox();
                    Button b0 = new Button();

                    t0.Location = new Point(16, 12 + counter - panel1.VerticalScroll.Value);
                    t0.Width = 200;
                    t0.Name = "t" + Convert.ToString(counter2);
                    t0.PreviewKeyDown += new PreviewKeyDownEventHandler(PreviewKeyDown);

                    b0.TabStop = false;
                    b0.Text = "x";
                    b0.Name = "b" + Convert.ToString(counter2);
                    b0.Location = new Point(216, 11 + counter - panel1.VerticalScroll.Value);
                    b0.Size = new System.Drawing.Size(20, 22);
                    b0.Click += new EventHandler(buttonclicked);

                    panel1.Controls.Add(t0);
                    panel1.Controls.Add(b0);

                    counter = counter + 25;
                }
            }
        }
    }

    private void buttonclicked(object sender, EventArgs e)
    {
        //Remove the textbox next to it.
    }
</code>```

Any help is appreciated

答:
I suggest you use a TableLayoutPanel. Set the GrowStyle on the TableLayoutPanel to AddRows or AddColumns and then you can add/remove controls to it and it will resize automatically. Set the height of each row to a number a little bigger than the height of the textbox. Set the column widths to a value so the textbox and the button can fit in them. You need 2 columns in it.

You do not need to set the location of the controls to a static location. They will be handled by the TableLayoutPanel for you.

Here is how you can add new controls to it.

```<code>yourTableLayoutPanel.Controls.Add(yourTextbox1, 0 /* Column Index */, 0 /* Row index */);
</code>```

Body:
I have really been struggling with this question for a long time.

I add a textbox and a button on tab press . I put text inside the textboxes:

Now, my question, how do I remove the textbox next to the button I click and move all the textboxes down, so I won't get any open space. If I press on the button next to the 7th textbox, I want it to look like this:

here's my code:

private void Form1_Load(object sender, EventArgs e)
    {
        //creates a textbox(t0) and a button(b0) on load
        TextBox t0 = new TextBox();
        t0.Name = "t0";
        t0.Location = new Point(16, 12);
        t0.Width = 200;
        t0.PreviewKeyDown += new PreviewKeyDownEventHandler(PreviewKeyDown);

        Button b0 = new Button();
        b0.TabStop = false;
        b0.Text = "x";
        b0.Location = new Point(216, 11);
        b0.Size = new System.Drawing.Size(20, 22);
        b0.Click += new EventHandler(buttonclicked);

        panel1.Controls.Add(t0);
        panel1.Controls.Add(b0);
    }

    private new void PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        //if I press tab in the last textbox it creates a new textbox(t + amount of textboxes) and button(b + amount of textboxes)
        if (e.KeyData == Keys.Tab)
        {
            int counter2 = 0;
            foreach (TextBox box in panel1.Controls.OfType<TextBox>())
            {
                counter2++;
            }

            counter2 = counter2 - 1;
            string Name = "t" + Convert.ToString(counter2);
            counter2++;
            foreach (TextBox box in panel1.Controls.OfType<TextBox>())
            {
                if (Name == box.Name && box.Focused)
                {
                    TextBox t0 = new TextBox();
                    Button b0 = new Button();

                    t0.Location = new Point(16, 12 + counter - panel1.VerticalScroll.Value);
                    t0.Width = 200;
                    t0.Name = "t" + Convert.ToString(counter2);
                    t0.PreviewKeyDown += new PreviewKeyDownEventHandler(PreviewKeyDown);

                    b0.TabStop = false;
                    b0.Text = "x";
                    b0.Name = "b" + Convert.ToString(counter2);
                    b0.Location = new Point(216, 11 + counter - panel1.VerticalScroll.Value);
                    b0.Size = new System.Drawing.Size(20, 22);
                    b0.Click += new EventHandler(buttonclicked);

                    panel1.Controls.Add(t0);
                    panel1.Controls.Add(b0);

                    counter = counter + 25;
                }
            }
        }
    }

    private void buttonclicked(object sender, EventArgs e)
    {
        //Remove the textbox next to it.
    }

Any help is appreciated

Body:
I suggest you use a TableLayoutPanel. Set the GrowStyle on the TableLayoutPanel to AddRows or AddColumns and then you can add/remove controls to it and it will resize automatically. Set the height of each row to a number a little bigger than the height of the textbox. Set the column widths to a value so the textbox and the button can fit in them. You need 2 columns in it.

You do not need to set the location of the controls to a static location. They will be handled by the TableLayoutPanel for you.

Here is how you can add new controls to it.

yourTableLayoutPanel.Controls.Add(yourTextbox1, 0 /* Column Index */, 0 /* Row index */);


来源: stackexchange

问:
Prevent typing non-numeric in input type number
Using <input type=number> will cause this.value inside of an event listener to return an empty string if the input is not a valid number.  You can see an example of this at http://jsfiddle.net/fSy53/

However, the invalid characters are still displayed in the input.

Is there any way to get the value that is actually displayed, including the invalid characters, from within an event listener?

My ultimate goal is to prevent users from actually typing any non-numeric characters into the field.  I need to use type=number so that the numeric virtual keyboard is used by mobile devices.  My goal would be to do something like this.value = this.value.replace(/[^0-9.]/g, "") on keyup keypress, but this doesn't work because if an invalid character is typed, reading from this.value returns "".

答:
```<code>inputs[5].addEventListener('keydown', enterNumbers);

function enterNumbers(event) {
  if ((event.code == 'ArrowLeft') || (event.code == 'ArrowRight') ||
     (event.code == 'ArrowUp') || (event.code == 'ArrowDown') ||
     (event.code == 'Delete') || (event.code == 'Backspace')) {
     return;
  } else if (event.key.search(/\d/) == -1) {
    event.preventDefault();
  }
}
</code>```

in this case, the value of the input field stays intact when a non-number button is pressed, and still delete, backspace, arrowup-down-left-right work properly and can be used for modifying the digital input.

ContentLicense: CC BY-SA 3.0

Body:
inputs[5].addEventListener('keydown', enterNumbers);

function enterNumbers(event) {
  if ((event.code == 'ArrowLeft') || (event.code == 'ArrowRight') ||
     (event.code == 'ArrowUp') || (event.code == 'ArrowDown') ||
     (event.code == 'Delete') || (event.code == 'Backspace')) {
     return;
  } else if (event.key.search(/\d/) == -1) {
    event.preventDefault();
  }
}

in this case, the value of the input field stays intact when a non-number button is pressed, and still delete, backspace, arrowup-down-left-right work properly and can be used for modifying the digital input.


问:
How can I pass HTML form information to javascript?
Alright, so I am working on a button that when clicked will display information from my RESTAPI - all without refreshing/reloading the page.

How it will work:
HTML button calls javascript function onClick -> javascript makes call to my API and displays the given information from my API.

Now, my API requires a "bet" parameter; which is a integer. The user provides this in a HTML input form.

```<code>        <form>
            Bet<br>
            <input onchange="checkBet" value="0.00001" type="text" name="bet"><br>
            <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"><img src="Images/dice.png"> Roll dice!</button>
        </form>
</code>```

So, assuming the user typed in a number in <input onchange="checkBet" value="0.00001" type="text" name="bet">
, how can I pass that to my javascript function "prepareRoll()"?

答:
instead of passing the value in the function call try to get the value in the function like here.</p>

```<code>function prepareRoll(){
     var value=$("input type=['text']").val()
     //write the remaining code.

}
</code>```

Body:
Alright, so I am working on a button that when clicked will display information from my RESTAPI - all without refreshing/reloading the page.

How it will work:
HTML button calls javascript function onClick -> javascript makes call to my API and displays the given information from my API.

Now, my API requires a "bet" parameter; which is a integer. The user provides this in a HTML input form.

        <form>
            Bet

            <input onchange="checkBet" value="0.00001" type="text" name="bet">

            <button type="button" id="dicebutton" onclick="prepareRoll()" style="vertical-align:middle"> Roll dice!</button>
        </form>

So, assuming the user typed in a number in <input onchange="checkBet" value="0.00001" type="text" name="bet">
, how can I pass that to my javascript function "prepareRoll()"?

Body:
instead of passing the value in the function call try to get the value in the function like here.

function prepareRoll(){
     var value=$("input type=['text']").val()
     //write the remaining code.

}


问:
Return the difference between two DateTime objects using KnpTimeBundle
I'm trying to get the ago datetime using KnpTimeBundle .
As the documentaion says , i need to use the helper class to acess to diff() function :

Take a look to my controller.php :

```<code>use Knp\Bundle\TimeBundle\Templating\Helper as Helper;

/**
 * @Route("/test",name="test")
 * @Method({"GET","POST"})
 */
public function testAction(Request $request){
$date = new \DateTime("now");
$h=new Helper();// here i got a 404 error
$ago=$h->diff($date);
return $this->render('test.html.twig', array());
}
</code>```

But calling the Helper class by this way didnt work for me , can any one give me the right way to do the trick .

答:
I just Create my own service no need for the bundle :

```<code><?php
namespace AppBundle\Services;

class Helpers {
public function pluralize( $count, $text )
{
    return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
}

function ago( $datetime )
{
    $interval = date_create('now')->diff( $datetime );
    $suffix = ( $interval->invert ? ' ago' : '' );
    if ( $v = $interval->y >= 1 ) return $this->pluralize( $interval->y, 'year' ) . $suffix;
    if ( $v = $interval->m >= 1 ) return $this->pluralize( $interval->m, 'month' ) . $suffix;
    if ( $v = $interval->d >= 1 ) return $this->pluralize( $interval->d, 'day' ) . $suffix;
    if ( $v = $interval->h >= 1 ) return $this->pluralize( $interval->h, 'hour' ) . $suffix;
    if ( $v = $interval->i >= 1 ) return $this->pluralize( $interval->i, 'minute' ) . $suffix;
    return $this->pluralize( $interval->s, 'second' ) . $suffix;
}
</code>```

in my services.yml:
services:

```<code>app.helpers:
    class: AppBundle\Services\Helpers
    arguments: [ "@doctrine.orm.entity_manager" , "@service_container" ]
</code>```

then i just called :

```<code>$helpers = $this->get("app.helpers");
$helpers->ago($date);
</code>```

Body:
I'm trying to get the ago datetime using KnpTimeBundle .
As the documentaion says , i need to use the helper class to acess to diff() function :

Take a look to my controller.php :

use Knp\Bundle\TimeBundle\Templating\Helper as Helper;

/**
 * @Route("/test",name="test")
 * @Method({"GET","POST"})
 */
public function testAction(Request $request){
$date = new \DateTime("now");
$h=new Helper();// here i got a 404 error
$ago=$h->diff($date);
return $this->render('test.html.twig', array());
}

But calling the Helper class by this way didnt work for me , can any one give me the right way to do the trick .

Body:
I just Create my own service no need for the bundle :

<?php
namespace AppBundle\Services;

class Helpers {
public function pluralize( $count, $text )
{
    return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
}

function ago( $datetime )
{
    $interval = date_create('now')->diff( $datetime );
    $suffix = ( $interval->invert ? ' ago' : '' );
    if ( $v = $interval->y >= 1 ) return $this->pluralize( $interval->y, 'year' ) . $suffix;
    if ( $v = $interval->m >= 1 ) return $this->pluralize( $interval->m, 'month' ) . $suffix;
    if ( $v = $interval->d >= 1 ) return $this->pluralize( $interval->d, 'day' ) . $suffix;
    if ( $v = $interval->h >= 1 ) return $this->pluralize( $interval->h, 'hour' ) . $suffix;
    if ( $v = $interval->i >= 1 ) return $this->pluralize( $interval->i, 'minute' ) . $suffix;
    return $this->pluralize( $interval->s, 'second' ) . $suffix;
}

in my services.yml:
services:

app.helpers:
    class: AppBundle\Services\Helpers
    arguments: [ "@doctrine.orm.entity_manager" , "@service_container" ]

then i just called :

$helpers = $this->get("app.helpers");
$helpers->ago($date);


问:
Encryption between C# and ActionScript 2
I'm trying to send encrypted data from a flash ( Action Script 2.0) to decrypt it in C#

So far I've found this post (Link opens in Chrome, Opera and Safari. Doesn't work in IE nor Firefox)
There's also this question: Encrypt in ActionScript3 and Decrypt in asp.net c#

But both only work in ActionScript 3

Do you know an API to do this on Action Script 2 ?

答:
It turned out that the first link indeed works with ActionScript 2.0

There's also code on how to do exactly what I was trying to achieve.

ContentLicense: CC BY-SA 2.5


问:
how to execute command in expect condition statement
When I try to use variable in an expect condition statement, it turns out that it doesn't work.

result:

```<code>qianyu@ubuntu:~/bin$ ./expectinstall.sh iotop
spawn sudo apt-get install iotop
[sudo] password for qianyu:
</code>```

my script below:

```<code>#!/usr/bin/expect -f

set timeout -1
set password qianyu
set app [lindex $argv 0]
set username `whoami`

spawn sudo apt-get install $app
expect {
"*password for ${username}*" { send "${password}\r" }
}
expect eof
</code>```

--update--

I find the problem of my script is not getting the username, but setting the username by command in `...`. I changed it to [exec ...], and it works well.

corrected script:

```<code>#!/usr/bin/expect -f

set timeout -1
set password qianyu
set app [lindex $argv 0]
set username [exec whoami]

spawn sudo apt-get install -y $app
expect {
"*password for ${username}*" { send "${password}\r"; }
}
expect eof
</code>```

答:
Prefix it with $env(...)

As an example, to use $HOME, do this

$env(HOME)

Body:
When I try to use variable in an expect condition statement, it turns out that it doesn't work.

result:

qianyu@ubuntu:~/bin$ ./expectinstall.sh iotop
spawn sudo apt-get install iotop
[sudo] password for qianyu:

my script below:

#!/usr/bin/expect -f

set timeout -1
set password qianyu
set app [lindex $argv 0]
set username `whoami`

spawn sudo apt-get install $app
expect {
"*password for ${username}*" { send "${password}\r" }
}
expect eof

--update--

I find the problem of my script is not getting the username, but setting the username by command in `...`. I changed it to [exec ...], and it works well.

corrected script:

#!/usr/bin/expect -f

set timeout -1
set password qianyu
set app [lindex $argv 0]
set username [exec whoami]

spawn sudo apt-get install -y $app
expect {
"*password for ${username}*" { send "${password}\r"; }
}
expect eof


问:
jQuery help: trying to set placeholder values for input fields
So, here's my jQuery code:

```<code> if($('#quotation_request_payment_option_lease').is(':checked')){
    $('#quotation_request_down_payment').attr('placeholder', "1300");
  }

 else if($('#quotation_request_payment_option_finance').is(':checked'))
  {
    $('#quotation_request_down_payment').attr('placeholder', "1500");
  }
</code>```

If the quotation_request_payment_option_lease checkbox is checked, then I want to set the placeholder in the quotation_request_down_payment input field to 1300.

And if the quotation_request_payment_option_finance checkbox is checked, then I want to set the placeholder in the quotation_request_down_payment input field to 1500.

Right now, the default for the page is that the quotation_request_payment_option_lease checkbox is checked, so when I load the page, the placeholder for the quoation_request_down_payment input field is set to 1300 (which is what I want).

The problem I'm having is that when I check the quotation_request_payment_option_finance checkbox (note: it's set so that only one of the two checkboxes can be checked at once), the placeholder remains 1300, it doesn't change to 1500.

Can anyone think of a way to fix this?

答:
You must do these validations within an event, like change()

Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

*You can do this without a class(.ckbox), with the selector $("input[type='checkbox']")

$(".ckbox").change(function() {
  if ($('#quotation_request_payment_option_lease').is(':checked')) {
    $('#quotation_request_down_payment').attr('placeholder', "1300");
  } else if ($('#quotation_request_payment_option_finance').is(':checked')) {
    $('#quotation_request_down_payment').attr('placeholder', "1500");
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="quotation_request_payment_option_lease" class="ckbox"><br>
<input type="checkbox" id="quotation_request_payment_option_finance" class="ckbox">
<br>
<input type="text" id="quotation_request_down_payment" placeholder="default"></code>```

Body:
So, here's my jQuery code:

 if($('#quotation_request_payment_option_lease').is(':checked')){
    $('#quotation_request_down_payment').attr('placeholder', "1300");
  }

 else if($('#quotation_request_payment_option_finance').is(':checked'))
  {
    $('#quotation_request_down_payment').attr('placeholder', "1500");
  }

If the quotation_request_payment_option_lease checkbox is checked, then I want to set the placeholder in the quotation_request_down_payment input field to 1300.

And if the quotation_request_payment_option_finance checkbox is checked, then I want to set the placeholder in the quotation_request_down_payment input field to 1500.

Right now, the default for the page is that the quotation_request_payment_option_lease checkbox is checked, so when I load the page, the placeholder for the quoation_request_down_payment input field is set to 1300 (which is what I want).

The problem I'm having is that when I check the quotation_request_payment_option_finance checkbox (note: it's set so that only one of the two checkboxes can be checked at once), the placeholder remains 1300, it doesn't change to 1500.

Can anyone think of a way to fix this?

Body:
You must do these validations within an event, like change()

Bind an event handler to the "change" JavaScript event, or trigger that event on an element.

*You can do this without a class(.ckbox), with the selector $("input[type='checkbox']")

$(".ckbox").change(function() {
  if ($('#quotation_request_payment_option_lease').is(':checked')) {
    $('#quotation_request_down_payment').attr('placeholder', "1300");
  } else if ($('#quotation_request_payment_option_finance').is(':checked')) {
    $('#quotation_request_down_payment').attr('placeholder', "1500");
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="quotation_request_payment_option_lease" class="ckbox"><br>
<input type="checkbox" id="quotation_request_payment_option_finance" class="ckbox">
<br>
<input type="text" id="quotation_request_down_payment" placeholder="default">


问:
Problems displaying .json values
I'm having trouble displaying two values on the screen( high-top and category):

This is my code:

```<code>      $.getJSON('data.json', function(obj){

        $.each(obj["best-seller"], function(key, value){

            console.log(value.title);
            console.log(value.price);
            console.log(value.higth-top);
            console.log(value.category);

                $("#produto").append(" <b>"
                    +value.title+"<br/>"
                    +value.price+"<br/>",
                    +value.category+ "<br/>",
                    +value.higth-top+ "<br/>",

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

Note: Category is shown perfectly on the console, but in html it is returned NaN
And the higth-top is returned NaN in the console and also in the Html

Other values are normally displayed

I search the data in a .json, like this:

```<code>{
"best-sellers": [
  {
  "title": "Chuteira Nike HyperVenomX Proximo II Society",
  "price": 499.9,
  "installments": {
    "number": 10,
    "value": 49.9
  },
  "high-top": true,
  "category": "society",
  "image": "aaaa.jpg"
   }
 ]
 }
</code>```

答:
Just remove the commas inside the append.

Right now you've separated the variables by commas, giving append multiple arguments, and the plus signs acts as coercion to numbers instead of string concatenation, giving you NaN instead of the expected string

```<code>$("#produto").append(" <b>"  + value.title +
                     "<br/>" + value.price +
                     "<br/>" + value.category +
                     "<br/>" + value['higth-top'] +
                     "<br/></b>"
);
</code>```

Also note that hyphens aren't valid in dot-nation, as they also mean "subtract", you'd have to use bracket notation for the property higth-top

Title: Problems displaying .json values

Body:
I'm having trouble displaying two values on the screen( high-top and category):

This is my code:

      $.getJSON('data.json', function(obj){

        $.each(obj["best-seller"], function(key, value){

            console.log(value.title);
            console.log(value.price);
            console.log(value.higth-top);
            console.log(value.category);

                $("#produto").append(" "
                    +value.title+"
"
                    +value.price+"
",
                    +value.category+ "
",
                    +value.higth-top+ "
",

                    ""
                );
            });
    });

Note: Category is shown perfectly on the console, but in html it is returned NaN
And the higth-top is returned NaN in the console and also in the Html

Other values are normally displayed

I search the data in a .json, like this:

{
"best-sellers": [
  {
  "title": "Chuteira Nike HyperVenomX Proximo II Society",
  "price": 499.9,
  "installments": {
    "number": 10,
    "value": 49.9
  },
  "high-top": true,
  "category": "society",
  "image": "aaaa.jpg"
   }
 ]
 }

Body:
Just remove the commas inside the append.

Right now you've separated the variables by commas, giving append multiple arguments, and the plus signs acts as coercion to numbers instead of string concatenation, giving you NaN instead of the expected string

$("#produto").append(" <b>"  + value.title +
                     "<br/>" + value.price +
                     "<br/>" + value.category +
                     "<br/>" + value['higth-top'] +
                     "<br/></b>"
);

Also note that hyphens aren't valid in dot-nation, as they also mean "subtract", you'd have to use bracket notation for the property higth-top


问:
meteor collections db.find() not a function (mid-development)
Ok I'm at a loss.  Writing a Meteor React app...it creates a collection and does that part still.  I recently uploaded a currency formatter: react-currency-input from npm that did what I wanted and wrote to the mongo db, which I can access from the terminal without an issue.

But when running my app, it gives me two new reasons it crashes and I don't know why:

Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

This is weird because I am not defining proptypes anywhere in my react.

2.
Uncaught TypeError: Tickets.find is not a function

It is referencing this code in the error:

```<code>export default class TicketList extends React.Component {
  constructor (props) {
      super(props);
      this.state = {
        tickets: []
      };
    }
    componentDidMount() {
      console.log('componentDidMount TicketList');
      this.ticketTracker = Tracker.autorun(() => {
        Meteor.subscribe('tickets');
        let tickets = Tickets.find({}).fetch();
        this.setState({ tickets });
      });
    }
    componentWillUnmount() {
      console.log('componentWillUnmount TicketList');
      this.ticketTracker.stop();
    }
</code>```

Does anyone have any idea of where I can start looking to debug this or why I am getting these new bugs out of the blue?

答: Yes, as @John Smith pointed out - my ticket collection was no longer a default export so I had to add the {} wherever I imported it and that solved the main issue.  Thanks!</p>

Body:
Ok I'm at a loss.  Writing a Meteor React app...it creates a collection and does that part still.  I recently uploaded a currency formatter: react-currency-input from npm that did what I wanted and wrote to the mongo db, which I can access from the terminal without an issue.

But when running my app, it gives me two new reasons it crashes and I don't know why:

Warning: Accessing PropTypes via the main React package is deprecated. Use the prop-types package from npm instead.

This is weird because I am not defining proptypes anywhere in my react.

2.
Uncaught TypeError: Tickets.find is not a function

It is referencing this code in the error:

export default class TicketList extends React.Component {
  constructor (props) {
      super(props);
      this.state = {
        tickets: []
      };
    }
    componentDidMount() {
      console.log('componentDidMount TicketList');
      this.ticketTracker = Tracker.autorun(() => {
        Meteor.subscribe('tickets');
        let tickets = Tickets.find({}).fetch();
        this.setState({ tickets });
      });
    }
    componentWillUnmount() {
      console.log('componentWillUnmount TicketList');
      this.ticketTracker.stop();
    }

Does anyone have any idea of where I can start looking to debug this or why I am getting these new bugs out of the blue?


问:
Resetting Constraints to Screen Location Programmatically
Currently, I have a Pan Gesture that moves an UIImageView by continuously changing the center of an image using something like this:

```<code>if let view = recognizer.view {
    view.center = CGPoint(x:view.center.x + translation.x,
                          y:view.center.y + translation.y)
}
</code>```

I also want to alter text labels every second (timer) and this resets the moved UIImageView to default constraints because of auto layout format. I've seen that the proper way to move UIImageViews is to change the constraints of the UIImageView and not the center. Is there any way to change the constraints of an UIImageView to fit the current position of the image? I tried using

```<code>view.updateConstraints()
</code>```

but that did not fix it. Ideally, it would behave like the "reset to suggested constraints" option when setting up constraints manually on storyboard, but used in the ViewController Class instead. I'm trying to avoid setting up all the constraints as IBOutlets and editing them like that as I have a lot of images with multiple constraints and multiple Pan Gestures that would need modifying.

答:
I don't think there's a way to reset to suggested constraints automatically. You can do it manually by updating the constants in the constraints.

You can't set position constraints equal to a constant, so you'll need to start with constraints relative to another object and modify them. For example, set the center to match the center of the superview, then change the constant to shift it to match the current state.

To do that, you'll need references to the constraints. You can either make your NSLayoutConstraints in Interface Builder and link to them with IBOutlets, or just create them programmatically. For the latter, declare them as instance properties of your view controller and then create them in its viewDidLoad() like this:

```<code>horizontalConstraint = NSLayoutConstraint(item: x.view, attribute: .centerX, relatedBy: .equal, toItem: x.view.superview, attribute: .centerX, multiplier: 1, constant: 0)
verticalConstraint = NSLayoutConstraint(item: x.view, attribute: .centerY, relatedBy: .equal, toItem: x.view.superview, attribute: .centerY, multiplier: 1, constant: 0)
x.view.superview.addConstraints([horizontalConstraint, verticalConstraint])
</code>```

When you want to update them, just change the constant:

```<code>let superview = x.view.superview
let currentOffsetX = x.view.center.x - superview.center.x
let currentOffsetY = x.view.center.y - superview.center.y

horizontalConstraint.constant = currentOffsetX
verticalConstraint.constant = currentOffsetY
</code>```

Body:
Currently, I have a Pan Gesture that moves an UIImageView by continuously changing the center of an image using something like this:

if let view = recognizer.view {
    view.center = CGPoint(x:view.center.x + translation.x,
                          y:view.center.y + translation.y)
}

I also want to alter text labels every second (timer) and this resets the moved UIImageView to default constraints because of auto layout format. I've seen that the proper way to move UIImageViews is to change the constraints of the UIImageView and not the center. Is there any way to change the constraints of an UIImageView to fit the current position of the image? I tried using

view.updateConstraints()

but that did not fix it. Ideally, it would behave like the "reset to suggested constraints" option when setting up constraints manually on storyboard, but used in the ViewController Class instead. I'm trying to avoid setting up all the constraints as IBOutlets and editing them like that as I have a lot of images with multiple constraints and multiple Pan Gestures that would need modifying.

Body:
I don't think there's a way to reset to suggested constraints automatically. You can do it manually by updating the constants in the constraints.

You can't set position constraints equal to a constant, so you'll need to start with constraints relative to another object and modify them. For example, set the center to match the center of the superview, then change the constant to shift it to match the current state.

To do that, you'll need references to the constraints. You can either make your NSLayoutConstraints in Interface Builder and link to them with IBOutlets, or just create them programmatically. For the latter, declare them as instance properties of your view controller and then create them in its viewDidLoad() like this:

horizontalConstraint = NSLayoutConstraint(item: x.view, attribute: .centerX, relatedBy: .equal, toItem: x.view.superview, attribute: .centerX, multiplier: 1, constant: 0)
verticalConstraint = NSLayoutConstraint(item: x.view, attribute: .centerY, relatedBy: .equal, toItem: x.view.superview, attribute: .centerY, multiplier: 1, constant: 0)
x.view.superview.addConstraints([horizontalConstraint, verticalConstraint])

When you want to update them, just change the constant:

let superview = x.view.superview
let currentOffsetX = x.view.center.x - superview.center.x
let currentOffsetY = x.view.center.y - superview.center.y

horizontalConstraint.constant = currentOffsetX
verticalConstraint.constant = currentOffsetY


问:
Loading large number of items in recycler view
I have a recycler view within a fragment and basically I m trying to load song list in the recycler view .Each row of recycler view contains an imageview (for album art) and textview ( for song name). I am having trouble when the size of the dataset is huge, that is when there are too many songs, the recycler view lags and the app ends up giving an ANR.I am using Glide to load album arts in each row's imageview.
How is google music player able to show such large number of songs without any lag?

Edit:
This is my SongsFragment

```<code>public class SongsFragment extends Fragment {
static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
ProgressBar progressBar;    // progress bar to show after every 30 items
NestedScrollView nestedScrollView;  //for smooth scrolling of recyclerview as well as to detect the end of recyclerview
RecyclerView recyclerView;
ArrayList<Song> songMainList = new ArrayList<>();  //partial list in which items are added
ArrayList<Song> songAllList = new ArrayList<>(); //Complete List of songs
SongAdapter songsAdapter;
private LinearLayoutManager layoutManager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_songs, container, false);

    nestedScrollView = (NestedScrollView) rootView.findViewById(R.id.nestedScrollView);
    progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);

    String songJson = getActivity().getIntent().getStringExtra("songList");
    songAllList = new Gson().fromJson(songJson, new TypeToken<ArrayList<Song>>() {
    }.getType());
            //Getting list of all songs in songAllList

    if (songAllList.size() > 30) {
        songMainList = new ArrayList<>(songAllList.subList(0,30));
    } else {
        songMainList = songAllList;
    }

    //if size of fetched songAllList>30 then add only 30 rows to songMainList

    recyclerView = (RecyclerView) rootView.findViewById(R.id.songs);
    int spanCount = 1; // 2 columns
    int spacing = 4; // 50px
    recyclerView.addItemDecoration(new GridItemDecoration(spanCount, spacing, true));
    recyclerView.setHasFixedSize(true);
    recyclerView.setNestedScrollingEnabled(false);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    songsAdapter = new SongAdapter(getActivity(), songMainList, recyclerView);

    nestedScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            View view = (View) nestedScrollView.getChildAt(nestedScrollView.getChildCount() - 1);
            int diff = (view.getBottom() - (nestedScrollView.getHeight() + nestedScrollView
                    .getScrollY()));

            if (diff == 0) {    //NestedScrollView scrolled to bottom
                progressBar.setVisibility(View.VISIBLE);    //show progressbar
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (songMainList.size() < songAllList.size()) {
                            int x = 0, y = 0;
                            if ((songAllList.size() - songMainList.size()) >= 30) {
                                x = songMainList.size();
                                y = x + 30;
                            } else {
                                x = songMainList.size();
                                y = x + songAllList.size() - songMainList.size();
                            }
                            for (int i = x; i < y; i++) {
                                songMainList.add(songAllList.get(i));   //Adding new items from songAllList to songMainList one by one
                                songsAdapter.notifyDataSetChanged();
                            }
                        }
                        progressBar.setVisibility(View.GONE);
                    }
                }, 1500);

            }
        }
    });
    recyclerView.setAdapter(songsAdapter);

    return rootView;
    }
}
</code>```

And this is my RecyclerViewAdapter along with viewholder

```<code>public class SongAdapter extends RecyclerView.Adapter {

private List<Song> songsList;
private Context c;

private RecyclerView.ViewHolder holder;

public SongAdapter(Context context) {
    mainActivityContext = context;
}

public SongAdapter(Context context, List<Song> songs, RecyclerView recyclerView) {
    songsList = songs;
    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
    c = context;
}

public SongAdapter getInstance() {
    return SongAdapter.this;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.song_list_row, parent, false);
    return new SongViewHolder(view,c);
}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

    if (holder instanceof SongViewHolder) {
        Song song = songsList.get(position);
        this.holder = holder;

        String name = song.getName();
        String artist = song.getArtist();
        String imagepath = song.getImagepath();

        ((SongViewHolder) holder).name.setText(name);

        ((SongViewHolder) holder).artist.setText(artist);

        if (!imagepath.equalsIgnoreCase("no_image")) //if the album art has valid  imagepath for this song

            Glide.with(c).load(imagepath)
                    .centerCrop()
                    .into(((SongViewHolder) holder).iv);
        else
            ((SongViewHolder) holder).iv.setImageResource(R.drawable.empty);

        ((SongViewHolder) holder).song = song;
    }
}

@Override
public int getItemCount() {
    return songsList.size();
}

static class SongViewHolder extends RecyclerView.ViewHolder{

    ImageView iv;
    TextView name, artist;
    CardView songListCard;
    private Context ctx;

    private OnLongPressListener mListener;

    SongViewHolder(View v, Context context) {
        super(v);
        this.ctx = context;
        iv= (ImageView) v.findViewById(R.id.album_art);
        name= (TextView) v.findViewById(R.id.name);
        artist= (TextView) v.findViewById(R.id.artist_mini);
        songListCard = (CardView) v.findViewById(R.id.song_list_card);
    }
}
</code>```

The recyclerview works fine when there are only 150-200 items but when reaching to 600-700 items , the whole app slows down. Could this be because of the way I have used glide in onBindViewHolder?

答: Do you load the data all at once? RecycleView should not have problem, I think if you have too much data the processing itself can take too much time. You should load the data in chunks and check the scroll state of the user and load the next batch etc. kinda how Instagram or Facebook does it.</p>

Body:
I have a recycler view within a fragment and basically I m trying to load song list in the recycler view .Each row of recycler view contains an imageview (for album art) and textview ( for song name). I am having trouble when the size of the dataset is huge, that is when there are too many songs, the recycler view lags and the app ends up giving an ANR.I am using Glide to load album arts in each row's imageview.
How is google music player able to show such large number of songs without any lag?

Edit:
This is my SongsFragment

public class SongsFragment extends Fragment {
static {
    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
ProgressBar progressBar;    // progress bar to show after every 30 items
NestedScrollView nestedScrollView;  //for smooth scrolling of recyclerview as well as to detect the end of recyclerview
RecyclerView recyclerView;
ArrayList<Song> songMainList = new ArrayList<>();  //partial list in which items are added
ArrayList<Song> songAllList = new ArrayList<>(); //Complete List of songs
SongAdapter songsAdapter;
private LinearLayoutManager layoutManager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_songs, container, false);

    nestedScrollView = (NestedScrollView) rootView.findViewById(R.id.nestedScrollView);
    progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);

    String songJson = getActivity().getIntent().getStringExtra("songList");
    songAllList = new Gson().fromJson(songJson, new TypeToken<ArrayList<Song>>() {
    }.getType());
            //Getting list of all songs in songAllList

    if (songAllList.size() > 30) {
        songMainList = new ArrayList<>(songAllList.subList(0,30));
    } else {
        songMainList = songAllList;
    }

    //if size of fetched songAllList>30 then add only 30 rows to songMainList

    recyclerView = (RecyclerView) rootView.findViewById(R.id.songs);
    int spanCount = 1; // 2 columns
    int spacing = 4; // 50px
    recyclerView.addItemDecoration(new GridItemDecoration(spanCount, spacing, true));
    recyclerView.setHasFixedSize(true);
    recyclerView.setNestedScrollingEnabled(false);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    songsAdapter = new SongAdapter(getActivity(), songMainList, recyclerView);

    nestedScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            View view = (View) nestedScrollView.getChildAt(nestedScrollView.getChildCount() - 1);
            int diff = (view.getBottom() - (nestedScrollView.getHeight() + nestedScrollView
                    .getScrollY()));

            if (diff == 0) {    //NestedScrollView scrolled to bottom
                progressBar.setVisibility(View.VISIBLE);    //show progressbar
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (songMainList.size() < songAllList.size()) {
                            int x = 0, y = 0;
                            if ((songAllList.size() - songMainList.size()) >= 30) {
                                x = songMainList.size();
                                y = x + 30;
                            } else {
                                x = songMainList.size();
                                y = x + songAllList.size() - songMainList.size();
                            }
                            for (int i = x; i < y; i++) {
                                songMainList.add(songAllList.get(i));   //Adding new items from songAllList to songMainList one by one
                                songsAdapter.notifyDataSetChanged();
                            }
                        }
                        progressBar.setVisibility(View.GONE);
                    }
                }, 1500);

            }
        }
    });
    recyclerView.setAdapter(songsAdapter);

    return rootView;
    }
}

And this is my RecyclerViewAdapter along with viewholder

public class SongAdapter extends RecyclerView.Adapter {

private List<Song> songsList;
private Context c;

private RecyclerView.ViewHolder holder;

public SongAdapter(Context context) {
    mainActivityContext = context;
}

public SongAdapter(Context context, List<Song> songs, RecyclerView recyclerView) {
    songsList = songs;
    LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
    c = context;
}

public SongAdapter getInstance() {
    return SongAdapter.this;
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.song_list_row, parent, false);
    return new SongViewHolder(view,c);
}

@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

    if (holder instanceof SongViewHolder) {
        Song song = songsList.get(position);
        this.holder = holder;

        String name = song.getName();
        String artist = song.getArtist();
        String imagepath = song.getImagepath();

        ((SongViewHolder) holder).name.setText(name);

        ((SongViewHolder) holder).artist.setText(artist);

        if (!imagepath.equalsIgnoreCase("no_image")) //if the album art has valid  imagepath for this song

            Glide.with(c).load(imagepath)
                    .centerCrop()
                    .into(((SongViewHolder) holder).iv);
        else
            ((SongViewHolder) holder).iv.setImageResource(R.drawable.empty);

        ((SongViewHolder) holder).song = song;
    }
}

@Override
public int getItemCount() {
    return songsList.size();
}

static class SongViewHolder extends RecyclerView.ViewHolder{

    ImageView iv;
    TextView name, artist;
    CardView songListCard;
    private Context ctx;

    private OnLongPressListener mListener;

    SongViewHolder(View v, Context context) {
        super(v);
        this.ctx = context;
        iv= (ImageView) v.findViewById(R.id.album_art);
        name= (TextView) v.findViewById(R.id.name);
        artist= (TextView) v.findViewById(R.id.artist_mini);
        songListCard = (CardView) v.findViewById(R.id.song_list_card);
    }
}

The recyclerview works fine when there are only 150-200 items but when reaching to 600-700 items , the whole app slows down. Could this be because of the way I have used glide in onBindViewHolder?


问:
Loop from start date to end date in Mac OS X shell script
The date function on OS X (Snow Leopard) does not have the --date option like the GNU version and I am not able to figure out how to get the equivalent of the following on OS X:

```<code>startdate=2010-01-01
enddate=2010-01-31
foldate="$startdate"

until [ "$foldate" == "$enddate" ]
do
    # do something with the date here - like pass it as a parameter to a command
    foldate=`/bin/date --date "$foldate 1 day" +%Y-%m-%d`
done
</code>```

SOLVED with answers from SiegeX:

```<code>startdate=2010-01-01
enddate=2010-01-31

sDateTs=`date -j -f "%Y-%m-%d" $startdate "+%s"`
eDateTs=`date -j -f "%Y-%m-%d" $enddate "+%s"`
dateTs=$sDateTs
offset=86400

while [ "$dateTs" -le "$eDateTs" ]
do
  date=`date -j -f "%s" $dateTs "+%Y-%m-%d"`
  printf '%s\n' $date
  dateTs=$(($dateTs+$offset))
done
</code>```

答:
Read your date's manpage by running man date and look at the -v option. Here is an excerpt:

-v      Adjust (i.e., take the
  current date and display the result of
  the adjustment; not actually set
               the date) the second, minute, hour, month day, week day,
  month or year according to val.  If
               val is preceded with a plus or minus sign, the date is
  adjusted forwards or backwards
  according
               to the remaining string, otherwise the relevant part of the
  date is set.  The date can be
               adjusted as many times as required using these flags.  Flags are
  processed in the order given.

Body:
The date function on OS X (Snow Leopard) does not have the --date option like the GNU version and I am not able to figure out how to get the equivalent of the following on OS X:

startdate=2010-01-01
enddate=2010-01-31
foldate="$startdate"

until [ "$foldate" == "$enddate" ]
do
    # do something with the date here - like pass it as a parameter to a command
    foldate=`/bin/date --date "$foldate 1 day" +%Y-%m-%d`
done

SOLVED with answers from SiegeX:

startdate=2010-01-01
enddate=2010-01-31

sDateTs=`date -j -f "%Y-%m-%d" $startdate "+%s"`
eDateTs=`date -j -f "%Y-%m-%d" $enddate "+%s"`
dateTs=$sDateTs
offset=86400

while [ "$dateTs" -le "$eDateTs" ]
do
  date=`date -j -f "%s" $dateTs "+%Y-%m-%d"`
  printf '%s\n' $date
  dateTs=$(($dateTs+$offset))
done


问:
How do I iterate over a range of numbers defined by variables in Bash?
How do I iterate over a range of numbers in Bash when the range is given by a variable?

I know I can do this (called "sequence expression" in the Bash documentation):

```<code> for i in {1..5}; do echo $i; done
</code>```

Which gives:

1

  2

  3

  4

  5

Yet, how can I replace either of the range endpoints with a variable? This doesn't work:

```<code>END=5
for i in {1..$END}; do echo $i; done
</code>```

Which prints:

{1..5}

答:
If you need it prefix than you might like this

```<code> for ((i=7;i<=12;i++)); do echo `printf "%2.0d\n" $i |sed "s/ /0/"`;done
</code>```

that will yield

```<code>07
08
09
10
11
12
</code>```

OwnerDisplayName: eschercycle

Body:
How do I iterate over a range of numbers in Bash when the range is given by a variable?

I know I can do this (called "sequence expression" in the Bash documentation):

 for i in {1..5}; do echo $i; done

Which gives:

1

  2

  3

  4

  5

Yet, how can I replace either of the range endpoints with a variable? This doesn't work:

END=5
for i in {1..$END}; do echo $i; done

Which prints:

{1..5}

LastEditorDisplayName: Greg Hewgill

Body:
If you need it prefix than you might like this

 for ((i=7;i<=12;i++)); do echo `printf "%2.0d\n" $i |sed "s/ /0/"`;done

that will yield

07
08
09
10
11
12


问:
PHPUnit - Version 3.7.21 instead of Version 6 installed
I followed the instructions on the official PHPUnit page to install PHPUnit 6.

```<code>composer require --dev phpunit/phpunit ^6.0
</code>```

However, If I go to the project folder and execute phpunit --version then I get PHPUnit 3.7.21 by Sebastian Bergmann..

Why is PHPUnit 3.7.21 installed instead of PHPUnit 6?

答:
I suppose you have xampp installed? It comes with PHPUnit 3.x.x preinstalled with PEAR which strangely can not be uninstalled with pear uninstall. And since its config is in php root folder, that 3-ish version has priority when running phpunit command (even if you have phpunit installed globally) in CMD or PS. How to fix:

Go to xampp/php folder and delete two files phpunit (with no extension) and phpunit.bat.  Usually it's enough to prevent older PHPUnit version from being run but let's be on the safer side:

Go to xampp/php/PEAR dir and delete two folders PHPUnit and PHPUnit2.

Go to Control Panel, then navigate System and Security->System and click "Advanced system settings" link on the left. This will open Advanced tab in System Properties window. Click "Environment Variables" button, then under System Variables select "Path" variable and click "Edit..." button. In the new window, click "New" button and type your path to vendor/bin folder (if you already installed PHPUnit for your project there will be phpunit.bat file). By default for xamp it looks like this: C:\xampp\htdocs\yourprojectname\vendor\bin.

Restart your Command Prompt (or PowerShell) window, then type phpunit --version to see the that it's PHPUnit 6.x.x now.

P.S. (If you want latest PHPUnit do not use ^6.0 in require string, since it will install v6.0.0, write it in composer.lock file that will never update PHPunit to the latest e.g. 6.2.1 version atm). Just use

```<code>composer require --dev phpunit/phpunit
</code>```

to install the latest stable version for your project.

Body:
I followed the instructions on the official PHPUnit page to install PHPUnit 6.

composer require --dev phpunit/phpunit ^6.0

However, If I go to the project folder and execute phpunit --version then I get PHPUnit 3.7.21 by Sebastian Bergmann..

Why is PHPUnit 3.7.21 installed instead of PHPUnit 6?

Body:
I suppose you have xampp installed? It comes with PHPUnit 3.x.x preinstalled with PEAR which strangely can not be uninstalled with pear uninstall. And since its config is in php root folder, that 3-ish version has priority when running phpunit command (even if you have phpunit installed globally) in CMD or PS. How to fix:

Go to xampp/php folder and delete two files phpunit (with no extension) and phpunit.bat.  Usually it's enough to prevent older PHPUnit version from being run but let's be on the safer side:

Go to xampp/php/PEAR dir and delete two folders PHPUnit and PHPUnit2.

Go to Control Panel, then navigate System and Security->System and click "Advanced system settings" link on the left. This will open Advanced tab in System Properties window. Click "Environment Variables" button, then under System Variables select "Path" variable and click "Edit..." button. In the new window, click "New" button and type your path to vendor/bin folder (if you already installed PHPUnit for your project there will be phpunit.bat file). By default for xamp it looks like this: C:\xampp\htdocs\yourprojectname\vendor\bin.

Restart your Command Prompt (or PowerShell) window, then type phpunit --version to see the that it's PHPUnit 6.x.x now.

P.S. (If you want latest PHPUnit do not use ^6.0 in require string, since it will install v6.0.0, write it in composer.lock file that will never update PHPunit to the latest e.g. 6.2.1 version atm). Just use

composer require --dev phpunit/phpunit

to install the latest stable version for your project.


问:
iOS iTunes FileSharing doesn't work
I'm trying to save mp3 ringtone files using iTunes FileSharing but it doesn't work. All mp3 files are stored under supporting files.

```<code>NSString *fileName = @"demo.mp3";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *m4rPath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];

NSError *err = nil;
[fileManager copyItemAtPath:filePath toPath:[m4rPath stringByAppendingPathComponent:fileName] error:&err];
        NSLog(@"%@",[err localizedDescription]);
</code>```

Any help would be highly appreciated

答:
Finally!! I've solved it. I was doing silly mistake in copying file.</p>

```<code>[fileManager copyItemAtPath:filePath toPath: m4rPath error:&err];
</code>```

Title: iOS iTunes FileSharing doesn't work

Body:
I'm trying to save mp3 ringtone files using iTunes FileSharing but it doesn't work. All mp3 files are stored under supporting files.

NSString *fileName = @"demo.mp3";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *m4rPath = [documentsDirectory stringByAppendingPathComponent:fileName];
NSFileManager *fileManager = [NSFileManager defaultManager];

NSError *err = nil;
[fileManager copyItemAtPath:filePath toPath:[m4rPath stringByAppendingPathComponent:fileName] error:&err];
        NSLog(@"%@",[err localizedDescription]);

Any help would be highly appreciated

Body:
Finally!! I've solved it. I was doing silly mistake in copying file.

[fileManager copyItemAtPath:filePath toPath: m4rPath error:&err];


问:
Counting number of directories
I'm trying to count the number of directories I have in a directory. I'm not sure what is wrong with my code:

```<code>@echo off
setlocal disabledelayedexpansion

set "folder=%~1"
if not defined folder set "folder=%cd%"

SET /a counter=0

for /D %%a in ("%folder%\*") do (
    echo folder %counter%: %%~nxa
    SET /a counter=%counter%+1
)

endlocal
</code>```

It is printing just

```<code>folder 0: folder1
folder 0: folder2
...
</code>```

So I think the counter is getting reset to 0 each time it loops, but I'm not sure why.

答:
If PowerShell can be used:</p>

```<code>PS C:\Users\pwatson> Get-ChildItem -Directory | Measure-Object | Select-Object -Property Count

Count
-----
   44
</code>```

Title: Counting number of directories

Body:
I'm trying to count the number of directories I have in a directory. I'm not sure what is wrong with my code:

@echo off
setlocal disabledelayedexpansion

set "folder=%~1"
if not defined folder set "folder=%cd%"

SET /a counter=0

for /D %%a in ("%folder%\*") do (
    echo folder %counter%: %%~nxa
    SET /a counter=%counter%+1
)

endlocal

It is printing just

folder 0: folder1
folder 0: folder2
...

So I think the counter is getting reset to 0 each time it loops, but I'm not sure why.

Body:
If PowerShell can be used:

PS C:\Users\pwatson> Get-ChildItem -Directory | Measure-Object | Select-Object -Property Count

Count
-----
   44


问:
Display decimal point with NSString stringWithFormat in Objective C
I'm a complete novice to objective C/iPad development, but I am trying to build a simple four function calculator on the iPad.

My current biggest difficulty is simply displaying a . when the decimal button is pressed. Here is what happens when a button (like two) is pressed.

```<code>-(IBAction)inTwo:(id)sender {
    display = display*10+2;
    [resultfield setText:[NSString stringWithFormat:@"%f",display]];
}
</code>```

Trying to just do

```<code>display = display*10+.
</code>```

Is obviously not working. Any way to append a period to the end of display?

Thanks

答:
```<code>resultfield.text = [result.text stringByAppendingString:@"."];
</code>```

You can't add a dot to display though, since it's not a string.

Body:
I'm a complete novice to objective C/iPad development, but I am trying to build a simple four function calculator on the iPad.

My current biggest difficulty is simply displaying a . when the decimal button is pressed. Here is what happens when a button (like two) is pressed.

-(IBAction)inTwo:(id)sender {
    display = display*10+2;
    [resultfield setText:[NSString stringWithFormat:@"%f",display]];
}

Trying to just do

display = display*10+.

Is obviously not working. Any way to append a period to the end of display?

Thanks

Body:
resultfield.text = [result.text stringByAppendingString:@"."];

You can't add a dot to display though, since it's not a string.


问:
My site can be opened by Chrome, but not by IE
I have built this site. It works perfectly in Chrome, whereas I cannot open it in Internet Explorer 11. It shows a blank page.

When I open the Developer Tools by F12, there is no error shown in the console.

Does anyone know where is the problem?

Edit 1:

I changed several machines and finally could see the error in the console: console error. as @MrNew commented, it is Unable to get property 'postMessage' of undefined or null reference.

Does anyone know how to fix this? is it because of the compatibility of angularjs and IE 11?

答:
I found it.

if ($window.opener === null) is not enough in IE 11, we should check if (($window.opener === null) || ($window.opener === undefined)).

So there is nothing to do with angularjs.


问:
Can't read params from route URL
I was trying create a simple component with my angular-cli project, which load parameter from URL

```<code>@Component({
  templateUrl: './confirm-registration.component.html',
})
export class ConfirmRegistrationComponent implements OnInit {

  constructor(private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
    this.route.params.switchMap((params: Params) => {
      return console.log('token:', params['registrationToken']);
    });
  }

}
</code>```

but I got error:

Failed to compile.

.../confirm-registration.component.ts (15,33): Argument of type
  '(params: Params) => void' is not assignable to parameter of type
  '(value: Params, index: number) => ObservableInput<{}>'.   Type 'void'
  is not assignable to type 'ObservableInput<{}>'.

I use Angular in 4.0.3 version. where I did make mistake?

答:
As dzejdzej has pointed out in his comment, you have to return an observable. This seems to have changed in the last months (at least it compiled the last time I tried some months ago), and they have not changed the docs yet.

So in your case you could simply return the same observable:

```<code>ngOnInit() {
  this.route.params.switchMap((params: Params) => {
    console.log('token:', params['registrationToken']);
    return this.route.params;
  });
}
</code>```

Title: Can't read params from route URL

Body:
I was trying create a simple component with my angular-cli project, which load parameter from URL

@Component({
  templateUrl: './confirm-registration.component.html',
})
export class ConfirmRegistrationComponent implements OnInit {

  constructor(private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
    this.route.params.switchMap((params: Params) => {
      return console.log('token:', params['registrationToken']);
    });
  }

}

but I got error:

Failed to compile.

.../confirm-registration.component.ts (15,33): Argument of type
  '(params: Params) => void' is not assignable to parameter of type
  '(value: Params, index: number) => ObservableInput<{}>'.   Type 'void'
  is not assignable to type 'ObservableInput<{}>'.

I use Angular in 4.0.3 version. where I did make mistake?

Body:
As dzejdzej has pointed out in his comment, you have to return an observable. This seems to have changed in the last months (at least it compiled the last time I tried some months ago), and they have not changed the docs yet.

So in your case you could simply return the same observable:

ngOnInit() {
  this.route.params.switchMap((params: Params) => {
    console.log('token:', params['registrationToken']);
    return this.route.params;
  });
}


问:
Why wp_schedule function in wordpress not work?
I understand that the wp_schedule function will make a cron like ajax running on background when you open a browser tab and not close it. So, why my function could not get it work ?

I changed my coumputer time = my wordpress setting time = the GMT time in php.ini. But it still not work, below is my code. I putted it inside a wordpress plugin. So what i have to do ?

```<code>class CronTest {

function __construct() {
    add_action( 'init', array ( $this, 'g_order_sync' ) );
    add_action( 'ga_order_syn', array ( $this, 'sync_order' ) );
}

// init

public function g_order_sync() {
    try{
        if ( ! wp_next_scheduled( 'ga_order_syn' ) ) {
            wp_schedule_event(  time() + 10, null, 'ga_order_syn' );
        }
    }
    catch(Exception $ex)
    {
        echo "<p>The error: " . $e->getMessage() . "</p>"; //display error
    }
}

// cron job

public function sync_order() {
    $content = time() . ": some text here";
    $this->_write_content ($content);
}

// write content

private function _write_content( $content = '') {
    $path =  $_SERVER[ 'DOCUMENT_ROOT' ] . "/myText.txt";
    if( is_writable($path)) {
        $original = file_get_contents($path);
        $original .= PHP_EOL . $content;
        $fp = fopen( $path, "wb" );
        fwrite( $fp, $original );
        fclose( $fp );
    } else {
        // log error here
    }
}
}

// must initialize the cron class
$cron_test = new CronTest();
</code>```

答:
WordPress checks if it is have cron tasks only when somebody visits site. If you set you next event in 2 min to run and next access to your site will be in 10 hours, then your event will be fired in 10 hours (immediately with the access) but not in 2 minutes.

It is not like ajax and doesn't need your browser open. WP_Cron runs in the background.

If your site is accessed quite often, you can be assured that planned event will run at selected time.

UPDATE

What is wrong with your code.

wp_schedule_event is called improperly.

First argument is to define time of the first event execution. It is in milliseconds from the beginning of UNIX epoch (1-Jan-1970). What you are doing, you tell to make the first run of your event in 10 millisecinds from now. No problem by the way, WordPress will do it as soon as it can, but time()+10 has no sense at all. Just leave time() as 1st parameter.

Second argument cannot be null. It has to specify recurrence of your event. WordPress has 3 predefined intervals: hourly, twicedaily and daily. If none of them is appropriate, then you have to setup it in special hook:

```<code>add_filter( 'cron_schedules', 'example_add_cron_interval' );

function example_add_cron_interval( $schedules ) {
    $schedules['ten_seconds'] = array(
        'interval' => 10,
        'display'  => esc_html__( 'Every Ten Seconds' ),
    );

    return $schedules;
}
</code>```

This example sets interval ten_seconds which can be used in wp_schedule_event. Finally, your call should look like that:

```<code>wp_schedule_event(  time(), 'ten_seconds', 'ga_order_syn' );
</code>```

Body:
I understand that the wp_schedule function will make a cron like ajax running on background when you open a browser tab and not close it. So, why my function could not get it work ?

I changed my coumputer time = my wordpress setting time = the GMT time in php.ini. But it still not work, below is my code. I putted it inside a wordpress plugin. So what i have to do ?

class CronTest {

function __construct() {
    add_action( 'init', array ( $this, 'g_order_sync' ) );
    add_action( 'ga_order_syn', array ( $this, 'sync_order' ) );
}

// init

public function g_order_sync() {
    try{
        if ( ! wp_next_scheduled( 'ga_order_syn' ) ) {
            wp_schedule_event(  time() + 10, null, 'ga_order_syn' );
        }
    }
    catch(Exception $ex)
    {
        echo "
The error: " . $e->getMessage() . "
"; //display error
    }
}

// cron job

public function sync_order() {
    $content = time() . ": some text here";
    $this->_write_content ($content);
}

// write content

private function _write_content( $content = '') {
    $path =  $_SERVER[ 'DOCUMENT_ROOT' ] . "/myText.txt";
    if( is_writable($path)) {
        $original = file_get_contents($path);
        $original .= PHP_EOL . $content;
        $fp = fopen( $path, "wb" );
        fwrite( $fp, $original );
        fclose( $fp );
    } else {
        // log error here
    }
}
}

// must initialize the cron class
$cron_test = new CronTest();

Body:
WordPress checks if it is have cron tasks only when somebody visits site. If you set you next event in 2 min to run and next access to your site will be in 10 hours, then your event will be fired in 10 hours (immediately with the access) but not in 2 minutes.

It is not like ajax and doesn't need your browser open. WP_Cron runs in the background.

If your site is accessed quite often, you can be assured that planned event will run at selected time.

UPDATE

What is wrong with your code.

wp_schedule_event is called improperly.

First argument is to define time of the first event execution. It is in milliseconds from the beginning of UNIX epoch (1-Jan-1970). What you are doing, you tell to make the first run of your event in 10 millisecinds from now. No problem by the way, WordPress will do it as soon as it can, but time()+10 has no sense at all. Just leave time() as 1st parameter.

Second argument cannot be null. It has to specify recurrence of your event. WordPress has 3 predefined intervals: hourly, twicedaily and daily. If none of them is appropriate, then you have to setup it in special hook:

add_filter( 'cron_schedules', 'example_add_cron_interval' );

function example_add_cron_interval( $schedules ) {
    $schedules['ten_seconds'] = array(
        'interval' => 10,
        'display'  => esc_html__( 'Every Ten Seconds' ),
    );

    return $schedules;
}

This example sets interval ten_seconds which can be used in wp_schedule_event. Finally, your call should look like that:

wp_schedule_event(  time(), 'ten_seconds', 'ga_order_syn' );


问:
Python seaborn heatmap grid - Not taking expected columns
I have following pandas dataframe. Basically, 7 different action categories, 5 different targets, each category has 1 or many unique endpoints, then each endpoint got a certain score in each target.
There are total 250 endpoints.

```<code>action,target,endpoint,score
Category1,target1,endpoint1,813.0
Category1,target2,endpoint1,757.0
Category1,target3,endpoint1,155.0
Category1,target4,endpoint1,126.0
Category1,target5,endpoint1,75.5
Category2,target1,endpoint2,106.0
Category2,target1,endpoint3,101.0
Category2,target1,endpoint4,499.0
Category2,target1,endpoint5,207.0
Category2,target2,endpoint2,316.0
Category2,target2,endpoint3,208.0
Category2,target2,endpoint4,161.0
Category2,target2,endpoint5,198.0
<omit>
Category3,target1,endpoint8,193.0
Category3,target1,endpoint9,193.0
Category3,target1,endpoint10,193.0
Category3,target1,endpoint11,193.0
Category3,target2,endpoint8,193.0
Category3,target2,endpoint9,193.0
<List goes on...>
</code>```

Now, I wanted to map out this dataframe as heatmap per category.
So, I used seabron facet grid heatmap with the following code.

```<code>import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

data = pd.read_csv('rawData.csv')
data = data.drop('Unnamed: 0', 1)

def facet_heatmap(data, **kwargs):

    data2 = data.pivot(index="target", columns='endpoint', values='score')
    ax1 = sns.heatmap(data2, cmap="YlGnBu", linewidths=2)

    for item in ax1.get_yticklabels():
        item.set_rotation(0)

    for item in ax1.get_xticklabels():
        item.set_rotation(70)

with sns.plotting_context(font_scale=5.5):

    g = sns.FacetGrid(data, col="action", col_wrap=7, size=5, aspect=0.5)

cbar_ax = g.fig.add_axes([.92, .3, .02, .4])

g = g.map_dataframe(facet_heatmap, cbar=cbar_ax, min=0, vmax=2000)
# <-- Specify the colorbar axes and limits

g.set_titles(col_template="{col_name}", fontweight='bold', fontsize=18)
g.fig.subplots_adjust(right=3)  # <-- Add space so the colorbar doesn't overlap the plot

plt.savefig('seabornPandas.png', dpi=400)
plt.show()
</code>```

It actually generates heatmap grid. However, the problem is the each heatmap uses the same column for some reason. See attached screenshot below.

(Please ignore color bar and limits.)

This is quite odd. First, the Index is not in order. Second, each heatmap box only takes the last three endpoints (Endpoint 248, 249, and 250). This is incorrect. For category 1, it should take endpoint 1 only. I don't expect a gray box there..

For category2, it should take endpoint 2,3,4,5. Not endpoint 248, 249, 250.

How can I fix these two issues? Any suggestion or comments are welcome.

答:
as mwaskom suggested: use the sharex parameter to fix your issues:</p>

```<code>...

with sns.plotting_context(font_scale=5.5):

g = sns.FacetGrid(data, col="action", col_wrap=7, size=5, aspect=0.5,
                 sharex=False)

...
</code>```

Body:
I have following pandas dataframe. Basically, 7 different action categories, 5 different targets, each category has 1 or many unique endpoints, then each endpoint got a certain score in each target.
There are total 250 endpoints.

action,target,endpoint,score
Category1,target1,endpoint1,813.0
Category1,target2,endpoint1,757.0
Category1,target3,endpoint1,155.0
Category1,target4,endpoint1,126.0
Category1,target5,endpoint1,75.5
Category2,target1,endpoint2,106.0
Category2,target1,endpoint3,101.0
Category2,target1,endpoint4,499.0
Category2,target1,endpoint5,207.0
Category2,target2,endpoint2,316.0
Category2,target2,endpoint3,208.0
Category2,target2,endpoint4,161.0
Category2,target2,endpoint5,198.0
<omit>
Category3,target1,endpoint8,193.0
Category3,target1,endpoint9,193.0
Category3,target1,endpoint10,193.0
Category3,target1,endpoint11,193.0
Category3,target2,endpoint8,193.0
Category3,target2,endpoint9,193.0
<List goes on...>

Now, I wanted to map out this dataframe as heatmap per category.
So, I used seabron facet grid heatmap with the following code.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

data = pd.read_csv('rawData.csv')
data = data.drop('Unnamed: 0', 1)

def facet_heatmap(data, **kwargs):

    data2 = data.pivot(index="target", columns='endpoint', values='score')
    ax1 = sns.heatmap(data2, cmap="YlGnBu", linewidths=2)

    for item in ax1.get_yticklabels():
        item.set_rotation(0)

    for item in ax1.get_xticklabels():
        item.set_rotation(70)

with sns.plotting_context(font_scale=5.5):

    g = sns.FacetGrid(data, col="action", col_wrap=7, size=5, aspect=0.5)

cbar_ax = g.fig.add_axes([.92, .3, .02, .4])

g = g.map_dataframe(facet_heatmap, cbar=cbar_ax, min=0, vmax=2000)
# <-- Specify the colorbar axes and limits

g.set_titles(col_template="{col_name}", fontweight='bold', fontsize=18)
g.fig.subplots_adjust(right=3)  # <-- Add space so the colorbar doesn't overlap the plot

plt.savefig('seabornPandas.png', dpi=400)
plt.show()

It actually generates heatmap grid. However, the problem is the each heatmap uses the same column for some reason. See attached screenshot below.

(Please ignore color bar and limits.)

This is quite odd. First, the Index is not in order. Second, each heatmap box only takes the last three endpoints (Endpoint 248, 249, and 250). This is incorrect. For category 1, it should take endpoint 1 only. I don't expect a gray box there..

For category2, it should take endpoint 2,3,4,5. Not endpoint 248, 249, 250.

How can I fix these two issues? Any suggestion or comments are welcome.

Body:
as mwaskom suggested: use the sharex parameter to fix your issues:

...

with sns.plotting_context(font_scale=5.5):

g = sns.FacetGrid(data, col="action", col_wrap=7, size=5, aspect=0.5,
                 sharex=False)

...


问:
Yahoo Finance URL not working
I have been using the following URL to fetch historical data from yahoo finance for quite some time now but it stopped working as of yesterday.

https://ichart.finance.yahoo.com/table.csv?s=SPY

When browsing to this site it says:

Will be right back...

Thank you for your patience.

Our engineers are working quickly to resolve the issue.

However, since this issue is still existing since yesterday I am starting to think that they discontinued this service?

My SO search only pointed me to this topic, which was related to https though...

Is anyone else experiencing this issue?
How can I resolve this problem? Do they offer a different access to their historical data?

答:
Fully working PHP example, based on this post and related sources:

```<code>function readYahoo($symbol, $tsStart, $tsEnd) {
  preg_match('"CrumbStore\":{\"crumb\":\"(?<crumb>.+?)\"}"',
    file_get_contents('https://uk.finance.yahoo.com/quote/' . $symbol),
    $crumb);  // can contain \uXXXX chars
  if (!isset($crumb['crumb'])) return 'Crumb not found.';
  $crumb = json_decode('"' . $crumb['crumb'] . '"');  // \uXXXX to UTF-8
  foreach ($http_response_header as $header) {
    if (0 !== stripos($header, 'Set-Cookie: ')) continue;
    $cookie = substr($header, 14, strpos($header, ';') - 14);  // after 'B='
  }  // cookie looks like "fkjfom9cj65jo&b=3&s=sg"
  if (!isset($cookie)) return 'Cookie not found.';
  $fp = fopen('https://query1.finance.yahoo.com/v7/finance/download/' . $symbol
    . '?period1=' . $tsStart . '&period2=' . $tsEnd . '&interval=1d'
    . '&events=history&crumb=' . $crumb, 'rb', FALSE,
    stream_context_create(array('http' => array('method' => 'GET',
      'header' => 'Cookie: B=' . $cookie))));
  if (FALSE === $fp) return 'Can not open data.';
  $buffer = '';
  while (!feof($fp)) $buffer .= implode(',', fgetcsv($fp, 5000)) . PHP_EOL;
  fclose($fp);
  return $buffer;
}
</code>```

Usage:

```<code>$csv = readYahoo('AAPL', mktime(0, 0, 0, 6, 2, 2017), mktime(0, 0, 0, 6, 3, 2017));
</code>```

Title: Yahoo Finance URL not working

Body:
Fully working PHP example, based on this post and related sources:

function readYahoo($symbol, $tsStart, $tsEnd) {
  preg_match('"CrumbStore\":{\"crumb\":\"(?<crumb>.+?)\"}"',
    file_get_contents('https://uk.finance.yahoo.com/quote/' . $symbol),
    $crumb);  // can contain \uXXXX chars
  if (!isset($crumb['crumb'])) return 'Crumb not found.';
  $crumb = json_decode('"' . $crumb['crumb'] . '"');  // \uXXXX to UTF-8
  foreach ($http_response_header as $header) {
    if (0 !== stripos($header, 'Set-Cookie: ')) continue;
    $cookie = substr($header, 14, strpos($header, ';') - 14);  // after 'B='
  }  // cookie looks like "fkjfom9cj65jo&b=3&s=sg"
  if (!isset($cookie)) return 'Cookie not found.';
  $fp = fopen('https://query1.finance.yahoo.com/v7/finance/download/' . $symbol
    . '?period1=' . $tsStart . '&period2=' . $tsEnd . '&interval=1d'
    . '&events=history&crumb=' . $crumb, 'rb', FALSE,
    stream_context_create(array('http' => array('method' => 'GET',
      'header' => 'Cookie: B=' . $cookie))));
  if (FALSE === $fp) return 'Can not open data.';
  $buffer = '';
  while (!feof($fp)) $buffer .= implode(',', fgetcsv($fp, 5000)) . PHP_EOL;
  fclose($fp);
  return $buffer;
}

Usage:

$csv = readYahoo('AAPL', mktime(0, 0, 0, 6, 2, 2017), mktime(0, 0, 0, 6, 3, 2017));


答:
You cannot concatenate a string with commas so you have to remove them, moreover hyphens are not allowed in dot-notation

```<code> value.higth-top
</code>```

here javascript understands "subtract top to value.high"

Write it as follows

```<code>$("#produto").append(" <b>"  + value.title +
                 "<br/>" + value.price +
                 "<br/>" + value.category +
                 "<br/>" + value['high-top'] +
                 "<br/></b>"
);
</code>```

Title: Problems displaying .json values

Body:
I'm having trouble displaying two values on the screen( high-top and category):

This is my code:

      $.getJSON('data.json', function(obj){

        $.each(obj["best-seller"], function(key, value){

            console.log(value.title);
            console.log(value.price);
            console.log(value.higth-top);
            console.log(value.category);

                $("#produto").append(" "
                    +value.title+"
"
                    +value.price+"
",
                    +value.category+ "
",
                    +value.higth-top+ "
",

                    ""
                );
            });
    });

Note: Category is shown perfectly on the console, but in html it is returned NaN
And the higth-top is returned NaN in the console and also in the Html

Other values are normally displayed

I search the data in a .json, like this:

{
"best-sellers": [
  {
  "title": "Chuteira Nike HyperVenomX Proximo II Society",
  "price": 499.9,
  "installments": {
    "number": 10,
    "value": 49.9
  },
  "high-top": true,
  "category": "society",
  "image": "aaaa.jpg"
   }
 ]
 }

Body:
You cannot concatenate a string with commas so you have to remove them, moreover hyphens are not allowed in dot-notation

 value.higth-top

here javascript understands "subtract top to value.high"

Write it as follows

$("#produto").append(" <b>"  + value.title +
                 "<br/>" + value.price +
                 "<br/>" + value.category +
                 "<br/>" + value['high-top'] +
                 "<br/></b>"
);


问:
What alternative user input techniques should be adopted in programming?
Programming is particularly different to, for example word processing due to the wealth of special symbols etc that need to be entered.

Of the current crop of new user interface techniques, which are suited to programming and why?

Or is the idea of a language syntax the problem, should we be programming more symbolically, and if so, how would this affect user interface?

Edit: When I specified user interface techniques, i left it open to both using existing hardware (mouse/keyboard) and some other things, like multi-touch, gesture recognition, augmented reality (see HitLabNz for some great examples).  I'm interested in how we can apply these to programming.

答: Wait... You need more than a text editor and a compiler/linker?</p>

OwnerDisplayName: Jesse Pepper

LastEditorDisplayName: Jesse Pepper

OwnerDisplayName: Omar Kooheji


问:
Trim Time from cell then calculate it
I have a single cell with multiple time values separated by Enter(each time value in each line).

```<code>09:30
09:32
09:34
21:00
</code>```

I want to subtract the first time value from the last time value. Is there any way to achieve a result?

P.S. I have tried extracting the first and last line using

```<code>=RIGHT(A1,FIND(CHAR(10),A1))
</code>```

and

```<code>=LEFT(A1,FIND(CHAR(10),A1))
</code>```

Then tried subtracting one from another, but excel results #VALUE! after the subtraction.
I tried Evaluating the formula and noticed that the time value does not converts to decimal for the calculation (which it should) and thus results nothing.

Any help will be appreciated.

答:
Say in B1:

```<code>=RIGHT(A1,FIND(CHAR(10),A1)-1)
</code>```

and in C1:

```<code>=LEFT(A1,FIND(CHAR(10),A1)-1)
</code>```

then:

```<code>=TIMEVALUE(B1)-TIMEVALUE(C1)
</code>```

should work.

Without the -1s you would be preventing conversion because of the line break characters.

You might combine all formulae into one:

```<code>=TEXT(TIMEVALUE(RIGHT(A1,FIND(CHAR(10),A1)-1))-TIMEVALUE(LEFT(A1,FIND(CHAR(10),A1)-1)),"hh:mm")
</code>```

Title: Trim Time from cell then calculate it

Body:
I have a single cell with multiple time values separated by Enter(each time value in each line).

09:30
09:32
09:34
21:00

I want to subtract the first time value from the last time value. Is there any way to achieve a result?

P.S. I have tried extracting the first and last line using

=RIGHT(A1,FIND(CHAR(10),A1))

and

=LEFT(A1,FIND(CHAR(10),A1))

Then tried subtracting one from another, but excel results #VALUE! after the subtraction.
I tried Evaluating the formula and noticed that the time value does not converts to decimal for the calculation (which it should) and thus results nothing.

Any help will be appreciated.

Body:
Say in B1:

=RIGHT(A1,FIND(CHAR(10),A1)-1)

and in C1:

=LEFT(A1,FIND(CHAR(10),A1)-1)

then:

=TIMEVALUE(B1)-TIMEVALUE(C1)

should work.

Without the -1s you would be preventing conversion because of the line break characters.

You might combine all formulae into one:

=TEXT(TIMEVALUE(RIGHT(A1,FIND(CHAR(10),A1)-1))-TIMEVALUE(LEFT(A1,FIND(CHAR(10),A1)-1)),"hh:mm")


问:
Common Lisp IDE for C# Developer?
UPDATE

I've decided to go with Clojure for now.

LispDev isn't ready, and Eclipse/cusp wasn't stable enough for me to feel comfortable.

As for Clojure, after a long, very frustrating, very annoying process trying to get Eclipse/CCW, Netbeans/Enclojure and IntelliJ/La Clojure working, I finally got Eclipse/CCW working.  The rest are still in mostly-broken states.

(If I get around to it, I'll document what it took for me to get Eclipse/CCW working.)

So for now, I'm going to use that.  I may dip back into CL, and check out LispWorks and AllegroLisp's free versions, but Clojure feels like a more natural step for me from working within the Microsoft CLR environment.

Thanks everyone for the help.

Original Question

I'm a C# developer very familiar with Visual Studio (with Resharper).

I'm new to Lisps.  I've taken an interest in both Common Lisp and Clojure recently, and found plenty of good material on both of them.

I've tried Emacs + Slime, but it feels like a very backwards, dated solution.  I have no doubts about its power, but it's usability is nothing like what I'm used to.  I don't want to struggle with an IDE in addition to the language.

There are Eclipse plugins for both Clojure and CL.  There's also a couple more options I've seen for Clojure.  Since I'm not a Java dev, I know nothing about these IDEs.

Is Eclipse a good place to start?  Are there other good options?

EDIT:

Here's the features I'm used to:

Syntax highlighting and autoindentation (everyone has this, so it's a moot point)

Autocomplete of functions and variable names

Realtime displays of all function overloads and parameters and the ability to arrow up/down through the list while typing in parameters

Syntax suggestions for code improvement, with the ability to do them for you ("use a const", "convert to LINQ expression (FP)", "variable will never be assigned to", "variable will never be used", "variable could be null", "function will never be used", etc.)

Extract Method/Function refactoring: select a block of text, and it can be extracted into a new function

Create Variable Refactoring: select a block of text and create a variable (e.g., a let)

Rename Refactoring: rename a function or variable declaration and all other functions using it will be updated (automated search/replace)

Go to Definition of a method/function, variable

Find Usages/References to a particular method/function, variable

Integrated folder-based project management tools and build tools

"Move class to new file" which creates a new file based on the class name, and containing all of its methods

"Rename file based on class type" which renames the file if you change the class name

F9/Click to the left of the line to add/remove breakpoints

F10/F11 to step into or over code when debugging, along with an arrow and highlighting to show which code is currently executing (step into a func execution, or just execute it here)

Most everything is available in a right-click context menu, or as a hovering combobox or textbox as you're typing.

I'm not saying emacs/slime can't do that, but if it does, it doesn't use anything similar in terms of usability techniques.

答:
While this question is old, and the OP has turned to Clojure, I think this is still a valid question, especially for those looking to learn Common Lisp and are either reluctant to switch from Visual Studio or just want to learn something new with a tool they are familiar with, to at least reduce the barrier to entry into such a great language, the same reasons why this question was asked.

I wrote an article explaining exactly how to achieve this, using Visual Studio as a Lisp IDE, which would be an almost great substitution for EMACS + SLIME combination.

The steps to achieve this setup are:

Visual Studio 2015 (Obviously the main ingredient)

Lisp Integration Visual Studio Extension.

Have ConEmu already installed and grab the ConEmuIntegration Visual Studio Extension.

A Common Lisp implementation of your choice, set in your %PATH% (via Environment Settings)

With that setup above, you will have an embedded REPL, and hovering the mouse over the Lisp functions/macros will give you tooltips with the signatures and definitions. This should accomplish most of the features requested in the original question.

It may have been unfortunate that at the time this question was asked, these tools weren't mature enough/created to be fully integrated as it is now, OR no one was aware or interested enough at the time.

As a bonus, if you are already familiar with C++, my recommendation would be to check out Embeddable Common Lisp (ECL), as that allows you to embed Lisp into your C++ code or call C++ from Lisp, how great is that combined with Visual Studio?

Title: Common Lisp IDE for C# Developer?


问:
Append HTML to Jquery response object
I'm having trouble appending html to ajax jQuery get request for some reason.

Here is the portion of html that is being returned from ajax get request that I'm trying to add html to:

```<code><div id="EndDateRange">
    <input class="text-box single-line" data-val="true" data-val-
    date="The field Enter End Date:  must be a date." data-val-
    required="Please enter an End Date." id="EndDate" name="EndDate"
    type="datetime" value="6/3/2017 1:04:15 PM" />
    <span class="field-validation-valid" data-valmsg-for="EndDate" data-
    valmsg-replace="true"></span>
    <input id="EndDate" name="EndDate" type="hidden" value="6/3/2017
    1:04:15 PM" />
</div>
</code>```

and here is the jquery:

```<code>$(response).find('#EndDate[type=hidden]').append("<div><span>Add</span</div>");
</code>```

For some reason this is not working.

Still can't get this to work.  Here are more details:

Here is "GET" request:

```<code>function showDates() {
var DatesViewRequest = $.ajax({
    type: 'GET',
    url: searchDatesUrl,
    cache: false,
    async: isAsync,
    contentType: 'text/html',
    xhrFields: {
        withCredentials: true
    },
    error: (function (error, variable) {
        alert('There was an error with the request');
    })
});
$.when(DatesViewRequest).done(function (response) {
    var picklist = $('<select>', {
        name: 'ValueNamesWebIds',
        id: 'value_name',
        multiple: 'multiple'
    })
    .attr('size', '15')
    .addClass('form-control')
    .on('change', function () {
        SetHiddenValues('value_name', 'ValueNames', 'true');
        EnableDisableButtons();
    })

    //var element = $(response).find('#EndDate[type=hidden]');

    $(response).find('#EndDate[type=hidden]').after('<div>Add</div>');

    $("#DisplayDateInputFields").append(response);

    $("#VerificationAndValidation").hide();

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

}

Here is a portion of html returned from "GET" request:

```<code><form action="SearchDate" id="Form" method="post">    <div
class="form-group">
    <fieldset>
        <div class="row" id="DateRangeValues">
            <div class="col-sm-6 dateWidth">
                <div id="StartDateLabel">
                    <label class="bold control-label" for="StartDate">Enter Start Date: </label>
                </div>
                <div id="StartDateRange">
                    <input class="text-box single-line" data-val="true" data-val-date="The field Enter Start Date:  must be a date." id="StartDate" name="StartDate" type="datetime" value="" />
                    <span class="field-validation-valid" data-valmsg-for="StartDate" data-valmsg-replace="true"></span>
                    <input id="StartDate" name="StartDate" type="hidden" value="" />
                </div>
            </div>
            <div class="col-sm-6 dateWidth">
                <div id="EndDateLabel">
                    <label class="bold control-label" for="EndDate">Enter End Date: </label>
                </div>
                <div id="EndDateRange">
                    <input class="text-box single-line" data-val="true" data-val-date="The field Enter End Date:  must be a date." data-val-required="Please enter an End Date." id="EndDate" name="EndDate" type="datetime" value="6/3/2017 11:51:48 AM" />
                    <span class="field-validation-valid" data-valmsg-for="EndDate" data-valmsg-replace="true"></span>
                    <input id="EndDate" name="EndDate" type="hidden" value="6/3/2017 11:51:48 AM" />
                </div>
            </div>
        </div>
</code>```

etc.

答:
You should append it after that element, not inside it.

```<code>$(response).find('#EndDate').after("<div><span>Add</span</div>");
</code>```

and using [type=hidden] is optional, and you may have only single element with id of EndDate.

Title: Append HTML to Jquery response object

Body:
I'm having trouble appending html to ajax jQuery get request for some reason.

Here is the portion of html that is being returned from ajax get request that I'm trying to add html to:

    <input class="text-box single-line" data-val="true" data-val-
    date="The field Enter End Date:  must be a date." data-val-
    required="Please enter an End Date." id="EndDate" name="EndDate"
    type="datetime" value="6/3/2017 1:04:15 PM" />

    <input id="EndDate" name="EndDate" type="hidden" value="6/3/2017
    1:04:15 PM" />

and here is the jquery:

$(response).find('#EndDate[type=hidden]').append("
Add</span
");

For some reason this is not working.

Still can't get this to work.  Here are more details:

Here is "GET" request:

function showDates() {
var DatesViewRequest = $.ajax({
    type: 'GET',
    url: searchDatesUrl,
    cache: false,
    async: isAsync,
    contentType: 'text/html',
    xhrFields: {
        withCredentials: true
    },
    error: (function (error, variable) {
        alert('There was an error with the request');
    })
});
$.when(DatesViewRequest).done(function (response) {
    var picklist = $('<select>', {
        name: 'ValueNamesWebIds',
        id: 'value_name',
        multiple: 'multiple'
    })
    .attr('size', '15')
    .addClass('form-control')
    .on('change', function () {
        SetHiddenValues('value_name', 'ValueNames', 'true');
        EnableDisableButtons();
    })

    //var element = $(response).find('#EndDate[type=hidden]');

    $(response).find('#EndDate[type=hidden]').after('
Add
');

    $("#DisplayDateInputFields").append(response);

    $("#VerificationAndValidation").hide();

    InitializeDateFields();
});

}

Here is a portion of html returned from "GET" request:

<form action="SearchDate" id="Form" method="post">

    <fieldset>

                    Enter Start Date:

                    <input class="text-box single-line" data-val="true" data-val-date="The field Enter Start Date:  must be a date." id="StartDate" name="StartDate" type="datetime" value="" />

                    <input id="StartDate" name="StartDate" type="hidden" value="" />

                    Enter End Date:

                    <input class="text-box single-line" data-val="true" data-val-date="The field Enter End Date:  must be a date." data-val-required="Please enter an End Date." id="EndDate" name="EndDate" type="datetime" value="6/3/2017 11:51:48 AM" />

                    <input id="EndDate" name="EndDate" type="hidden" value="6/3/2017 11:51:48 AM" />

etc.

Body:
You should append it after that element, not inside it.

$(response).find('#EndDate').after("<div><span>Add</span</div>");

and using [type=hidden] is optional, and you may have only single element with id of EndDate.