问:
Flex 4 wont recognise flash.events.UncaughtErrorEvent
test.mxml:

```<code><?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()" x="0" y="0" width="703" height="609"  xmlns:ns1="*" >
<mx:Script>
<![CDATA[
import flash.events.*;
// stuff
private function onUncaughtError(e:UncaughtErrorEvent):void {
//Do Stuff
}
</code>```

This gives:
apitester.mxml  1046: Type was not found or was not a compile-time constant: UncaughtErrorEvent.    /apitester/src  line 35 Flex Problem

According to Adobe it is available in flex and Air.

The Flex 4/Eclipse build path shows:

Flex 4.0

playerglobal.swc

textLayout.swc

osmf.swc

framework.swc

spark.swc

sparkskins.swc

rpc.swc

datavisualisation.swc

flash-integration.swc

flex.swc

utilities.swc

Any ideas?

答:
You need the Flex 4.1 SDK.

See: http://flassari.is/2010/06/global-error-handling-with-flash-player-10-1/

Also you need to specify to the flex compiler that you are require flash player 10.1 (not the minimum version required by the SDK which is 10.0) because earlier versions of the flash player do not support this.

ContentLicense: CC BY-SA 2.5

Body:
test.mxml:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()" x="0" y="0" width="703" height="609"  xmlns:ns1="*" >
<mx:Script>
<![CDATA[
import flash.events.*;
// stuff
private function onUncaughtError(e:UncaughtErrorEvent):void {
//Do Stuff
}

This gives:
apitester.mxml  1046: Type was not found or was not a compile-time constant: UncaughtErrorEvent.    /apitester/src  line 35 Flex Problem

According to Adobe it is available in flex and Air.

The Flex 4/Eclipse build path shows:

Flex 4.0

playerglobal.swc

textLayout.swc

osmf.swc

framework.swc

spark.swc

sparkskins.swc

rpc.swc

datavisualisation.swc

flash-integration.swc

flex.swc

utilities.swc

Any ideas?


来源: stackexchange

问:
Visual Studio 2012 combobox and textbox
friends, I have a combo box and text box. I want when I choose the combobox, then automatically the textbox will be filled automatically with autogenerate number in the textbox, "an example: I chose combobox letter" M ", then I want in the textbox to appear" M.0001 ", please its support master, , ?? I am using visual studio 2012</p>

答:
Very simple, you can include the following code in the comboBox's click event:</p>

```<code>TextBox1.Text = ComboBox1.SelectedItem & Textbox1.Text.
</code>```

ContentLicense: CC BY-SA 3.0

Title: Visual Studio 2012 combobox and textbox

Body:
Very simple, you can include the following code in the comboBox's click event:

TextBox1.Text = ComboBox1.SelectedItem & Textbox1.Text.


问:
Python pandas groupby aggregate on multiple columns, then pivot
In Python, I have a pandas DataFrame similar to the following:

```<code>Item | shop1 | shop2 | shop3 | Category
------------------------------------
Shoes| 45    | 50    | 53    | Clothes
TV   | 200   | 300   | 250   | Technology
Book | 20    | 17    | 21    | Books
phone| 300   | 350   | 400   | Technology
</code>```

Where shop1, shop2 and shop3 are the costs of every item in different shops.
Now, I need to  return a DataFrame, after some data cleaning, like this one:

```<code>Category (index)| size| sum| mean | std
----------------------------------------
</code>```

where size is the number of items in each Category and sum, mean and std are related to the same functions applied to the 3 shops. How can I do these operations with the split-apply-combine pattern (groupby, aggregate, apply,...) ?

Can someone help me out? I'm going crazy with this one...thank you!

答:
Edited for Pandas 0.22+ considering the deprecation of the use of dictionaries in a group by aggregation.

We set up a very similar dictionary where we use the keys of the dictionary to specify our functions and the dictionary itself to rename the columns.

```<code>rnm_cols = dict(size='Size', sum='Sum', mean='Mean', std='Std')
df.set_index(['Category', 'Item']).stack().groupby('Category') \
  .agg(rnm_cols.keys()).rename(columns=rnm_cols)

            Size   Sum        Mean        Std
Category
Books          3    58   19.333333   2.081666
Clothes        3   148   49.333333   4.041452
Technology     6  1800  300.000000  70.710678
</code>```

option 1

use agg ← link to docs

```<code>agg_funcs = dict(Size='size', Sum='sum', Mean='mean', Std='std')
df.set_index(['Category', 'Item']).stack().groupby(level=0).agg(agg_funcs)

                  Std   Sum        Mean  Size
Category
Books        2.081666    58   19.333333     3
Clothes      4.041452   148   49.333333     3
Technology  70.710678  1800  300.000000     6
</code>```

option 2

more for less

use describe ← link to docs

```<code>df.set_index(['Category', 'Item']).stack().groupby(level=0).describe().unstack()

            count        mean        std    min    25%    50%    75%    max
Category
Books         3.0   19.333333   2.081666   17.0   18.5   20.0   20.5   21.0
Clothes       3.0   49.333333   4.041452   45.0   47.5   50.0   51.5   53.0
Technology    6.0  300.000000  70.710678  200.0  262.5  300.0  337.5  400.0
</code>```

Body:
In Python, I have a pandas DataFrame similar to the following:

Item | shop1 | shop2 | shop3 | Category
------------------------------------
Shoes| 45    | 50    | 53    | Clothes
TV   | 200   | 300   | 250   | Technology
Book | 20    | 17    | 21    | Books
phone| 300   | 350   | 400   | Technology

Where shop1, shop2 and shop3 are the costs of every item in different shops.
Now, I need to  return a DataFrame, after some data cleaning, like this one:

Category (index)| size| sum| mean | std
----------------------------------------

where size is the number of items in each Category and sum, mean and std are related to the same functions applied to the 3 shops. How can I do these operations with the split-apply-combine pattern (groupby, aggregate, apply,...) ?

Can someone help me out? I'm going crazy with this one...thank you!

Body:
Edited for Pandas 0.22+ considering the deprecation of the use of dictionaries in a group by aggregation.

We set up a very similar dictionary where we use the keys of the dictionary to specify our functions and the dictionary itself to rename the columns.

rnm_cols = dict(size='Size', sum='Sum', mean='Mean', std='Std')
df.set_index(['Category', 'Item']).stack().groupby('Category') \
  .agg(rnm_cols.keys()).rename(columns=rnm_cols)

            Size   Sum        Mean        Std
Category
Books          3    58   19.333333   2.081666
Clothes        3   148   49.333333   4.041452
Technology     6  1800  300.000000  70.710678

option 1

use agg ← link to docs

agg_funcs = dict(Size='size', Sum='sum', Mean='mean', Std='std')
df.set_index(['Category', 'Item']).stack().groupby(level=0).agg(agg_funcs)

                  Std   Sum        Mean  Size
Category
Books        2.081666    58   19.333333     3
Clothes      4.041452   148   49.333333     3
Technology  70.710678  1800  300.000000     6

option 2

more for less

use describe ← link to docs

df.set_index(['Category', 'Item']).stack().groupby(level=0).describe().unstack()

            count        mean        std    min    25%    50%    75%    max
Category
Books         3.0   19.333333   2.081666   17.0   18.5   20.0   20.5   21.0
Clothes       3.0   49.333333   4.041452   45.0   47.5   50.0   51.5   53.0
Technology    6.0  300.000000  70.710678  200.0  262.5  300.0  337.5  400.0

ContentLicense: CC BY-SA 4.0


问:
What is are these commands in square brackets doing in Vim?
Doing a Vimgolf exercise that requires you to start with the following:

```<code>- One number per line -
-----------------------
2,3,5,7,
11,13,17,
19,23,29,
</code>```

And then transform it to:

```<code>2
3
5
7
11
13
17
19
23
29
</code>```

One solution given is:

```<code>dj3gJV"=[<C-R><C-A>]<CR>pZZ
</code>```

I'm following everything up to "=[", etc.  Doing ":help [" in Vim only reveals some movements with square brackets in normal mode.  I think the quotation mark indicates to use a special register, but I'm unclear on the rest of what follows after the equals sign.

1) What's a good way to query Vim's help system to get what's going on with "=[ ..." in visual mode?
2) And, can you explain what is going on with "=[ ..."? (where ... is an abbreviation for the rest of the commands that follow)

答:
You call 'expression register', put List of vim script language and evaluate it.

"= will call 'expression register'. If you put to this register vim-script language expression, it's will be computed.

:help "= for more information about expression register.

:help <C-R> for information about special registers.

:help c_<C-R>_<C-A> insert WORD under cursor. You in Visual mode, so all selection will be inserted.

[2,3,5,7,11,13,17,19,23,29,] this is a List of vim script language. :help List

As you can read in :help "=

If the result is a List each element is turned into a String and used as a line.

Body:
Doing a Vimgolf exercise that requires you to start with the following:

- One number per line -
-----------------------
2,3,5,7,
11,13,17,
19,23,29,

And then transform it to:

2
3
5
7
11
13
17
19
23
29

One solution given is:

dj3gJV"=[<C-R><C-A>]<CR>pZZ

I'm following everything up to "=[", etc.  Doing ":help [" in Vim only reveals some movements with square brackets in normal mode.  I think the quotation mark indicates to use a special register, but I'm unclear on the rest of what follows after the equals sign.

1) What's a good way to query Vim's help system to get what's going on with "=[ ..." in visual mode?
2) And, can you explain what is going on with "=[ ..."? (where ... is an abbreviation for the rest of the commands that follow)


问:
Canvas: Strange behavior when pressing key down
By default the rectangle of my canvas should move from left to right. When pressing the key down, it should start moving down.

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    x = 0,
    y = 0;

function draw(x_move, y_move) {
  requestAnimationFrame(function() {
    draw(x_move, y_move);
  });
  ctx.beginPath();
  ctx.rect(x, y, 20, 20);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#ffffff";
  ctx.fill();
  ctx.closePath();
  x = x + x_move;
  y = y + y_move;
}

draw(1, 0);

document.addEventListener('keydown', function(event) {
  //console.log(event.keyCode);
  if (event.keyCode == 40) {
    draw(0, 1);
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas { background-color: red; }</code>```

<canvas id="canvas" width="600" height="400"></canvas>```

Using the code above, you may at least notice two issues:

When pressing key down, the rectangle moves down but also keeps moving to the right.

When you keep pressing the down key multiple times, the speed gets increased.

How can I fix those issues?

答:
See where you call

```<code>requestAnimationFrame(function() {
    draw(x_move, y_move);
  });
</code>```

You're now recursively calling draw().

Now every time you call draw(), it gets called over and over and over again. And when you call it from the keydown event, you call it 2x as often, then 3x as often on the second time you press it, etc.

I'm not entirely clear on what your objective is here, but if you wanted to just adjust the trajectory of the square by pressing down, you could do something like this:

```<code>document.addEventListener('keydown', function(event) {
  //console.log(event.keyCode);
  if (event.keyCode == 40) {
    adjustDownwardTrajectory();
  }
});
</code>```

and have that adjustDownwardTrajectory() change some downwardTrajectory variable such that:

```<code>function draw(x_move, y_move) {
  requestAnimationFrame(function() {
    draw(x_move, y_move);
  });
  ctx.beginPath();
  ctx.rect(x, y, 20, 20);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#ffffff";
  ctx.fill();
  ctx.closePath();
  x = x + x_move;
  y = y + y_move + downwardTrajectory;
}
</code>```

Body:
By default the rectangle of my canvas should move from left to right. When pressing the key down, it should start moving down.

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d'),
    x = 0,
    y = 0;

function draw(x_move, y_move) {
  requestAnimationFrame(function() {
    draw(x_move, y_move);
  });
  ctx.beginPath();
  ctx.rect(x, y, 20, 20);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#ffffff";
  ctx.fill();
  ctx.closePath();
  x = x + x_move;
  y = y + y_move;
}

draw(1, 0);

document.addEventListener('keydown', function(event) {
  //console.log(event.keyCode);
  if (event.keyCode == 40) {
    draw(0, 1);
  }
});

canvas { background-color: red; }

<canvas id="canvas" width="600" height="400"></canvas>

Using the code above, you may at least notice two issues:

When pressing key down, the rectangle moves down but also keeps moving to the right.

When you keep pressing the down key multiple times, the speed gets increased.

How can I fix those issues?

Body:
See where you call

requestAnimationFrame(function() {
    draw(x_move, y_move);
  });

You're now recursively calling draw().

Now every time you call draw(), it gets called over and over and over again. And when you call it from the keydown event, you call it 2x as often, then 3x as often on the second time you press it, etc.

I'm not entirely clear on what your objective is here, but if you wanted to just adjust the trajectory of the square by pressing down, you could do something like this:

document.addEventListener('keydown', function(event) {
  //console.log(event.keyCode);
  if (event.keyCode == 40) {
    adjustDownwardTrajectory();
  }
});

and have that adjustDownwardTrajectory() change some downwardTrajectory variable such that:

function draw(x_move, y_move) {
  requestAnimationFrame(function() {
    draw(x_move, y_move);
  });
  ctx.beginPath();
  ctx.rect(x, y, 20, 20);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "#ffffff";
  ctx.fill();
  ctx.closePath();
  x = x + x_move;
  y = y + y_move + downwardTrajectory;
}


问:
Why can't $(document).ready() be inside API call?
FYI Trial 1 does not work, but Trial 2 works.

I understand that getJSON is executes asynchronously, but I don't actually understand how it applies to the code I've written.

What can I learn about asynchronous execution from this?

Why do I have to separate the getJSON call into a function separate from ready()?

FOR TRIAL 2:
How can I write this code so I don't have to initialize functions inside of getJSON? If there isn't a way, how can I write this code to be more robust?

```<code>/*
//TRIAL 1
$(document).ready(function(){
  console.log("loaded");
  $.getJSON(url, function(json){
    var fahrenheit = true;
    getLocation(json);
    getTemperature(fahrenheit, json);
    $("#unit").on("click", function(){
      fahrenheit = !fahrenheit;
      getTemperature(fahrenheit, json);
    });
    getWeather(json);
  });
});

//Gets current weather conditions from current_observation
function getWeather(json){
  var currWeather = "";
  var iconURL = "";
  currWeather=json.current_observation.weather;
  iconURL=json.current_observation.icon_url;
  $("#icon").attr("src", iconURL);
  $("#weather").html(currWeather);
};

//Gets current temperature from current_observation
function getTemperature(fahrenheit, json){
  var currTemp = 0;
  if(fahrenheit){
    currTemp+=json.current_observation.temp_f;
    currTemp+="&#8457";
  } else{
    currTemp+=json.current_observation.temp_c;
    currTemp+="&#8451";
  }
  $("#temperature").html(currTemp);
};

//Gets city, state, country, zip, latitude, and longitude from location
function getLocation(json){
  var currLocation=["city", "state", "country", "zip", "lat", "lon"];
  var locationHTML = "";
  currLocation[0] = json.location.city;
  currLocation[1] = json.location.state;
  currLocation[2] = json.location.country_name;
  currLocation[3] = json.location.zip;
  currLocation[4] = json.location.lat;
  currLocation[5] = json.location.lon;
  locationHTML += currLocation[0]+", "+currLocation[1]+", "+currLocation[2]+" " +currLocation[3]+"<br>";
  locationHTML += "Latitude: "+currLocation[4]+"<br>Longitude: "+currLocation[5];
  $("#location").html(locationHTML);
};
*/

//TRIAL 2

$(document).ready(function(){
  console.log("loaded");
  dispWeather();
});

function dispWeather(){
  console.log("inside dispWeather");
  //Retrieve json from weather underground
  var url = "https://api.wunderground.com/api/19c5c96f0b140c0f/geolookup/conditions/q/autoip.json";
  $.getJSON(url, function(json){
    console.log("Got JSON");
    console.log(json);
    var fahrenheit = true;
    getLocation(json);
    getTemperature(fahrenheit, json);
    $("#unit").on("click", function(){
      fahrenheit = !fahrenheit;
      getTemperature(fahrenheit, json);
    });
    getWeather(json);

    //Gets current weather conditions from current_observation
    function getWeather(json){
      var currWeather = "";
      var iconURL = "";
      currWeather=json.current_observation.weather;
      iconURL=json.current_observation.icon_url;
      $("#icon").attr("src", iconURL);
      $("#weather").html(currWeather);
    };

    //Gets current temperature from current_observation
    function getTemperature(fahrenheit, json){
      var currTemp = 0;
      if(fahrenheit){
        currTemp+=json.current_observation.temp_f;
        currTemp+="&#8457";
      } else{
        currTemp+=json.current_observation.temp_c;
        currTemp+="&#8451";
      }
      $("#temperature").html(currTemp);
    };

    //Gets city, state, country, zip, latitude, and longitude from location
    function getLocation(json){
      var currLocation=["city", "state", "country", "zip", "lat", "lon"];
      var locationHTML = "";
      currLocation[0] = json.location.city;
      currLocation[1] = json.location.state;
      currLocation[2] = json.location.country_name;
      currLocation[3] = json.location.zip;
      currLocation[4] = json.location.lat;
      currLocation[5] = json.location.lon;
      locationHTML += currLocation[0]+", "+currLocation[1]+", "+currLocation[2]+" " +currLocation[3]+"<br>";
      locationHTML += "Latitude: "+currLocation[4]+"<br>Longitude: "+currLocation[5];
      $("#location").html(locationHTML);
    };
  })
};
</code>```

答:
.ready() jQuery Documentation

Specify a function to execute when the DOM is fully loaded.

What can I learn about asynchronous execution from this?

Your learning that you don't know when the document is going to be ready() so we wait until the event completes before beginning execution on our application. You also learned that you have to wait for $.getJSON to fetch json then you process the data.

Why do I have to separate the getJSON call into a function separate from ready()?

As specified above .ready() is waiting for the DOM to be fully loaded, then we start the application. So when we are "ready" lets fetch the weather data. The document is only ready one time when the DOM is fully loaded.

How can I write this code so I don't have to initialize functions inside of getJSON?

Without you being specific, I'm assuming your problem here was with toggling the degrees between celsius and fahrenheit. After we load the weather you can store the data in a variable outside of the scope of the function, this way when you click to change the degrees you can pass in the same data without having to call the api again (although at this point the weather could have changed)

how can I write this code to be more robust?

I've included a JS Bin that alters your code. The biggest problem was bad naming conventions and not keeping things simple. Example getWeather() was not "getting weather" it was setting html from data we got from $.getJSON which was invoked in your ready() instead of breaking it out into another function we could call later on.

For the most part this is how the code reads now, clear function names help quickly see what this code is supposed to do.

```<code>$(document).ready(function() {
  renderWeather();
});

var state = {
    fahrenheit: true,
    data: {}
};

function renderWeather() {
  getWeatherJSON()
    .then(data => {
      state.data = data;
      setWeatherHTML(data);
      setTemperatureHTML(data, state.fahrenheit);
      setLocationHTML(data);
    })
    .catch(err => console.log(err));
}
</code>```

http://jsbin.com/cekite/edit?js,output

If we wanted to take this a step further we could create a WeatherAPI prototype concealing our html render functions and extend it with a WeatherUndergroudAPI prototype, this way if we ever change our weather service we should only have to implement a format function to marshall the data the way the WeatherAPI expects it to be in.

```<code>class WeatherAPI {
  constructor(opt) {
    ...
  }

  init() {
    ...
  }

  get() {
    ... feteches json from endpoint provided
  }

  renderWeather() {
    this.get()
      .then(this.formatter.bind(this))
      .then(this.setWeatherData.bind(this))
      .then(this.renderWeatherHTML.bind(this))
      .then(this.renderTemperatureHTML.bind(this))
      .then(this.renderLocationHTML.bind(this))
      .catch(err => console.log(err));
  }

  formatter(data) {
    ...
  }

  setWeatherData(data) {
    ...
  }

  renderWeatherHTML() {
    ...
  }

  renderTemperatureHTML() {
    ...
  }

  renderLocationHTML() {
    ...
  }
}
</code>```

Extending the WeatherAPI is then a matter of passing in a new endpoint to get data from. Or in this case overriding the WeatherAPI get method and returning static data.

```<code>class FakeWeatherAPI extends WeatherAPI {
  constructor(opt = {}) {
    super(opt);
  }

  get() {
    return new Promise((resolve) => {
      const data = {
        someReallyWeirdKeyForACity: 'San Francisco',
        state: 'CA',
        country: 'US',
        lat: '37.77999878',
        lon: '122.41999817',
        f: '1000',
        c: '25',
        icon: 'http://www.nyan.cat/cats/zombie.gif',
        weather: 'Acid Rain'
      };

      resolve(data);
    });
  }

  formatter(data) {
    const formattedData = {
      city: data.someReallyWeirdKeyForACity,
      state: data.state,
      country: data.country,
      lat: data.lat,
      lon: data.lon,
      temperature: {
        fahrenheit: data.f,
        celsius: data.c
      },
      icon: data.icon,
      weather: data.weather
    };

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

Our application init code then becomes.

```<code>$(document).ready(init);

function init(){
  const weatherAwesomeService = new FakeWeatherAPI();
  weatherAwesomeService.init();
};
</code>```

Here is a working jsbin for they above

http://jsbin.com/sicofe/edit?js,output

Body:
FYI Trial 1 does not work, but Trial 2 works.

I understand that getJSON is executes asynchronously, but I don't actually understand how it applies to the code I've written.

What can I learn about asynchronous execution from this?

Why do I have to separate the getJSON call into a function separate from ready()?

FOR TRIAL 2:
How can I write this code so I don't have to initialize functions inside of getJSON? If there isn't a way, how can I write this code to be more robust?

/*
//TRIAL 1
$(document).ready(function(){
  console.log("loaded");
  $.getJSON(url, function(json){
    var fahrenheit = true;
    getLocation(json);
    getTemperature(fahrenheit, json);
    $("#unit").on("click", function(){
      fahrenheit = !fahrenheit;
      getTemperature(fahrenheit, json);
    });
    getWeather(json);
  });
});

//Gets current weather conditions from current_observation
function getWeather(json){
  var currWeather = "";
  var iconURL = "";
  currWeather=json.current_observation.weather;
  iconURL=json.current_observation.icon_url;
  $("#icon").attr("src", iconURL);
  $("#weather").html(currWeather);
};

//Gets current temperature from current_observation
function getTemperature(fahrenheit, json){
  var currTemp = 0;
  if(fahrenheit){
    currTemp+=json.current_observation.temp_f;
    currTemp+="&#8457";
  } else{
    currTemp+=json.current_observation.temp_c;
    currTemp+="&#8451";
  }
  $("#temperature").html(currTemp);
};

//Gets city, state, country, zip, latitude, and longitude from location
function getLocation(json){
  var currLocation=["city", "state", "country", "zip", "lat", "lon"];
  var locationHTML = "";
  currLocation[0] = json.location.city;
  currLocation[1] = json.location.state;
  currLocation[2] = json.location.country_name;
  currLocation[3] = json.location.zip;
  currLocation[4] = json.location.lat;
  currLocation[5] = json.location.lon;
  locationHTML += currLocation[0]+", "+currLocation[1]+", "+currLocation[2]+" " +currLocation[3]+"
";
  locationHTML += "Latitude: "+currLocation[4]+"
Longitude: "+currLocation[5];
  $("#location").html(locationHTML);
};
*/

//TRIAL 2

$(document).ready(function(){
  console.log("loaded");
  dispWeather();
});

function dispWeather(){
  console.log("inside dispWeather");
  //Retrieve json from weather underground
  var url = "https://api.wunderground.com/api/19c5c96f0b140c0f/geolookup/conditions/q/autoip.json";
  $.getJSON(url, function(json){
    console.log("Got JSON");
    console.log(json);
    var fahrenheit = true;
    getLocation(json);
    getTemperature(fahrenheit, json);
    $("#unit").on("click", function(){
      fahrenheit = !fahrenheit;
      getTemperature(fahrenheit, json);
    });
    getWeather(json);

    //Gets current weather conditions from current_observation
    function getWeather(json){
      var currWeather = "";
      var iconURL = "";
      currWeather=json.current_observation.weather;
      iconURL=json.current_observation.icon_url;
      $("#icon").attr("src", iconURL);
      $("#weather").html(currWeather);
    };

    //Gets current temperature from current_observation
    function getTemperature(fahrenheit, json){
      var currTemp = 0;
      if(fahrenheit){
        currTemp+=json.current_observation.temp_f;
        currTemp+="&#8457";
      } else{
        currTemp+=json.current_observation.temp_c;
        currTemp+="&#8451";
      }
      $("#temperature").html(currTemp);
    };

    //Gets city, state, country, zip, latitude, and longitude from location
    function getLocation(json){
      var currLocation=["city", "state", "country", "zip", "lat", "lon"];
      var locationHTML = "";
      currLocation[0] = json.location.city;
      currLocation[1] = json.location.state;
      currLocation[2] = json.location.country_name;
      currLocation[3] = json.location.zip;
      currLocation[4] = json.location.lat;
      currLocation[5] = json.location.lon;
      locationHTML += currLocation[0]+", "+currLocation[1]+", "+currLocation[2]+" " +currLocation[3]+"
";
      locationHTML += "Latitude: "+currLocation[4]+"
Longitude: "+currLocation[5];
      $("#location").html(locationHTML);
    };
  })
};

Body:
.ready() jQuery Documentation

Specify a function to execute when the DOM is fully loaded.

What can I learn about asynchronous execution from this?

Your learning that you don't know when the document is going to be ready() so we wait until the event completes before beginning execution on our application. You also learned that you have to wait for $.getJSON to fetch json then you process the data.

Why do I have to separate the getJSON call into a function separate from ready()?

As specified above .ready() is waiting for the DOM to be fully loaded, then we start the application. So when we are "ready" lets fetch the weather data. The document is only ready one time when the DOM is fully loaded.

How can I write this code so I don't have to initialize functions inside of getJSON?

Without you being specific, I'm assuming your problem here was with toggling the degrees between celsius and fahrenheit. After we load the weather you can store the data in a variable outside of the scope of the function, this way when you click to change the degrees you can pass in the same data without having to call the api again (although at this point the weather could have changed)

how can I write this code to be more robust?

I've included a JS Bin that alters your code. The biggest problem was bad naming conventions and not keeping things simple. Example getWeather() was not "getting weather" it was setting html from data we got from $.getJSON which was invoked in your ready() instead of breaking it out into another function we could call later on.

For the most part this is how the code reads now, clear function names help quickly see what this code is supposed to do.

$(document).ready(function() {
  renderWeather();
});

var state = {
    fahrenheit: true,
    data: {}
};

function renderWeather() {
  getWeatherJSON()
    .then(data => {
      state.data = data;
      setWeatherHTML(data);
      setTemperatureHTML(data, state.fahrenheit);
      setLocationHTML(data);
    })
    .catch(err => console.log(err));
}

http://jsbin.com/cekite/edit?js,output

If we wanted to take this a step further we could create a WeatherAPI prototype concealing our html render functions and extend it with a WeatherUndergroudAPI prototype, this way if we ever change our weather service we should only have to implement a format function to marshall the data the way the WeatherAPI expects it to be in.

class WeatherAPI {
  constructor(opt) {
    ...
  }

  init() {
    ...
  }

  get() {
    ... feteches json from endpoint provided
  }

  renderWeather() {
    this.get()
      .then(this.formatter.bind(this))
      .then(this.setWeatherData.bind(this))
      .then(this.renderWeatherHTML.bind(this))
      .then(this.renderTemperatureHTML.bind(this))
      .then(this.renderLocationHTML.bind(this))
      .catch(err => console.log(err));
  }

  formatter(data) {
    ...
  }

  setWeatherData(data) {
    ...
  }

  renderWeatherHTML() {
    ...
  }

  renderTemperatureHTML() {
    ...
  }

  renderLocationHTML() {
    ...
  }
}

Extending the WeatherAPI is then a matter of passing in a new endpoint to get data from. Or in this case overriding the WeatherAPI get method and returning static data.

class FakeWeatherAPI extends WeatherAPI {
  constructor(opt = {}) {
    super(opt);
  }

  get() {
    return new Promise((resolve) => {
      const data = {
        someReallyWeirdKeyForACity: 'San Francisco',
        state: 'CA',
        country: 'US',
        lat: '37.77999878',
        lon: '122.41999817',
        f: '1000',
        c: '25',
        icon: 'http://www.nyan.cat/cats/zombie.gif',
        weather: 'Acid Rain'
      };

      resolve(data);
    });
  }

  formatter(data) {
    const formattedData = {
      city: data.someReallyWeirdKeyForACity,
      state: data.state,
      country: data.country,
      lat: data.lat,
      lon: data.lon,
      temperature: {
        fahrenheit: data.f,
        celsius: data.c
      },
      icon: data.icon,
      weather: data.weather
    };

    return formattedData;
  }
}

Our application init code then becomes.

$(document).ready(init);

function init(){
  const weatherAwesomeService = new FakeWeatherAPI();
  weatherAwesomeService.init();
};

Here is a working jsbin for they above

http://jsbin.com/sicofe/edit?js,output


问:
Convert C# to VB,NET: Event with a delegate type that has a return type
This is the original source-code written in C#

```<code>public delegate Unit UnitResolveEventHandler(object sender, ResolveEventArgs args);

public event UnitResolveEventHandler UnitResolve;

public static Unit GetUnitByName(string name) {
    Instance.unitsByName.TryGetValue(name, out result);
    if (Instance.UnitResolve != null) {
        foreach (UnitResolveEventHandler handler in Instance.UnitResolve.GetInvocationList()) {
            result = handler(Instance, new ResolveEventArgs(name));
        }
    }
}
</code>```

Using an online translator, I get this VB.NET code:

Public Delegate Function UnitResolveEventHandler(sender As Object, args As ResolveEventArgs) As Unit

Public Event UnitResolve As UnitResolveEventHandler

Public Shared Function GetUnitByName(name As String) As Unit
    Instance.unitsByName.TryGetValue(name, result)
    If Instance.UnitResolve IsNot Nothing Then
        For Each handler As UnitResolveEventHandler In Instance.UnitResolve.GetInvocationList()
            result = handler(Instance, New ResolveEventArgs(name))
        Next
    End If
End Function
```

The compiler marks the event declaration with this error message:

Events cannot be declared with a delegate type that has a return type.

And the Instance.UnitResolve calls inside the GetUnitByName() method with this error message:

Public Event UnitResolve As UnitResolveEventHandler' is an event, and
  cannot be called directly.

How can I properly translate the code from C# to VB.NET without losing functionality?

答:
The original C# source code is bad; event handlers shouldn’t return values. You’ll have to make it not-an-event:

Public UnitResolve As UnitResolveEventHandler
```

<p>and use <code>Delegate.Combine</code> manually to add event handler:</p>

<pre class="lang-vb prettyprint-override"><code>Instance.UnitResolve = Delegate.Combine(Instance.UnitResolve, newHandler)
</code>```

Body:
This is the original source-code written in C#

public delegate Unit UnitResolveEventHandler(object sender, ResolveEventArgs args);

public event UnitResolveEventHandler UnitResolve;

public static Unit GetUnitByName(string name) {
    Instance.unitsByName.TryGetValue(name, out result);
    if (Instance.UnitResolve != null) {
        foreach (UnitResolveEventHandler handler in Instance.UnitResolve.GetInvocationList()) {
            result = handler(Instance, new ResolveEventArgs(name));
        }
    }
}

Using an online translator, I get this VB.NET code:

Public Delegate Function UnitResolveEventHandler(sender As Object, args As ResolveEventArgs) As Unit

Public Event UnitResolve As UnitResolveEventHandler

Public Shared Function GetUnitByName(name As String) As Unit
    Instance.unitsByName.TryGetValue(name, result)
    If Instance.UnitResolve IsNot Nothing Then
        For Each handler As UnitResolveEventHandler In Instance.UnitResolve.GetInvocationList()
            result = handler(Instance, New ResolveEventArgs(name))
        Next
    End If
End Function

The compiler marks the event declaration with this error message:

Events cannot be declared with a delegate type that has a return type.

And the Instance.UnitResolve calls inside the GetUnitByName() method with this error message:

Public Event UnitResolve As UnitResolveEventHandler' is an event, and
  cannot be called directly.

How can I properly translate the code from C# to VB.NET without losing functionality?

Body:
The original C# source code is bad; event handlers shouldn’t return values. You’ll have to make it not-an-event:

Public UnitResolve As UnitResolveEventHandler

and use Delegate.Combine manually to add event handler:

Instance.UnitResolve = Delegate.Combine(Instance.UnitResolve, newHandler)


问:
What is the difference in floor function and truncate function?
What is the difference between Math.Floor() and Math.Truncate() in .NET?

For example, Math.Floor(4.4) = 4 Math.Truncate(4.4) = 4.

答: Math.Floor rounds down Math.Ceiling rounds up and Math.Truncate rounds towards zero. Thus, Math.Truncate is like Math.Floor for positive numbers, and like Math.Ceiling for negative numbers.</p>


问:
List style none not applying + li border
I am testing out vertical navigation and want to remove the bullets from my ul.
I have even tried applying !important in case there was an override. The bottom border on my li will also not apply. I have researched online but cannot find a solution.

Nothing within the "nav" id will apply except

```<code>#nav a {
    text-decoration: none;
}
</code>```

Link to codepen: https://codepen.io/Saharalara/pen/WpPgpJ

Here is the html:

```<code><!Doctype html>
<html>
<head>
    <title>About Us</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="nav">
   <ul>
        <li><a href="#">Mission</a></li>
        <li><a href="#">History</a></li>
        <li><a href="#">Executive Team</a>
            <ul>
        <li><a href='#'>» CEO</a>
        <li><a href='#'>» CFO</a>
        <li><a href='#'>» COO</a>
        <li><a href='#'>» Other Minions</a>
        </ul>
    </li>
    <li><a href='#'>Contact Us</a></li>
  </ul>
    </div>

    <div id="content">
    <h1>About Us</h1>
    <ul>
    <p><li><a href="#">Mission</a> Lorem ipsum dolor sit amet, ultricies adipiscing lectus, pharetra mauris amet luctus, ac vitae pulvinar, aenean urna porttitor eu etiam eu non. Accumsan tortor sit ac integer. Ipsum occaecat ad ipsum vestibulum, pellentesque posuere, sit enim curabitur odio.</li>

       <li><a href="#">History</a> Ut at montesdui ullam orci, justo leo sem vitae sit quam, quis massa cras volutpat eget ac a.</li>

       <li><a href="#">Executive team</a> Vitaeconvallis duis, dui adipiscing felis quam, laoreet nec non, lectus massa morbi et, amet nec in lacus urna.</li>

       <li><a href="#">Contact us</a> Proin enim venenatis diam nascetur odio, nullam dui nam mauris quisque dignissim, eleifend sed platea ut, risus temporibus ante eu, dui eros libero ultrices eget non. Iaculis mauris nulla phasellus vel, pede nunc et libero mauris ac, erat volutpat non netus sed risus sed, dignissim aenean sit curabitur.</li>
       </p>
       </ul>
    </div>
</body>
</html>
</code>```

The Css:

```<code>body {
    font: 12pt Verdana, Arial, Georgia, sans-serif;
}

#nav {
    width:150px;
    float:left;
    margin-top:12px;
    margin-right:18px;
}

#nav a {
    text-decoration: none;
}

//making sure there are no extra padding or margins lying around to line up with ABOUT US content

#nav ul {
    list-style-type: none;
    margin: 12px 0px 0px 0px;
    padding: 0px;
}

//border for visual seperation

#nav li {
    border-bottom: 1px solid #ffffff;
}

#nav li a:link, #nav li a:visited {
    font-size: 10pt;
    font-weight: bold;
    display: block;
    padding: 3px 0px 3px 3px;
    background-color: #628794;
    color: #ffffff;
}

//higlight when hover

#nav li a:hover, #nav li a:active {
    font-size: 10pt;
    font-weight: bold;
    display: block;
    padding: 3px 0px 3px 3px;
    background-color: #6cac46;
    color: #000000;
}

#content {
    width:550px;
    float: left;
}

#content a {
    text-decoration: none;
    font-weight: bold;
}
</code>```

答:
The problem with your code isn't the selectors, it's the comment.

If you're using raw CSS, you'll need to use block comments because inline comments will cause an error and then the rest of your CSS won't process. The reason that text-decoration works is because it occurs before your first inline comment.

Change

```<code>//making sure there are no extra padding or margins lying around to line up with ABOUT US content
</code>```

to

```<code>/* making sure there are no extra padding or margins lying around to line up with ABOUT US content */
</code>```

Body:
I am testing out vertical navigation and want to remove the bullets from my ul.
I have even tried applying !important in case there was an override. The bottom border on my li will also not apply. I have researched online but cannot find a solution.

Nothing within the "nav" id will apply except

#nav a {
    text-decoration: none;
}

Link to codepen: https://codepen.io/Saharalara/pen/WpPgpJ

Here is the html:

<!Doctype html>

    <title>About Us</title>
    <link rel="stylesheet" href="style.css">

Mission

History

Executive Team

» CEO

» CFO

» COO

» Other Minions

Contact Us

About Us

Mission Lorem ipsum dolor sit amet, ultricies adipiscing lectus, pharetra mauris amet luctus, ac vitae pulvinar, aenean urna porttitor eu etiam eu non. Accumsan tortor sit ac integer. Ipsum occaecat ad ipsum vestibulum, pellentesque posuere, sit enim curabitur odio.

History Ut at montesdui ullam orci, justo leo sem vitae sit quam, quis massa cras volutpat eget ac a.

Executive team Vitaeconvallis duis, dui adipiscing felis quam, laoreet nec non, lectus massa morbi et, amet nec in lacus urna.

Contact us Proin enim venenatis diam nascetur odio, nullam dui nam mauris quisque dignissim, eleifend sed platea ut, risus temporibus ante eu, dui eros libero ultrices eget non. Iaculis mauris nulla phasellus vel, pede nunc et libero mauris ac, erat volutpat non netus sed risus sed, dignissim aenean sit curabitur.

The Css:

body {
    font: 12pt Verdana, Arial, Georgia, sans-serif;
}

#nav {
    width:150px;
    float:left;
    margin-top:12px;
    margin-right:18px;
}

#nav a {
    text-decoration: none;
}

//making sure there are no extra padding or margins lying around to line up with ABOUT US content

#nav ul {
    list-style-type: none;
    margin: 12px 0px 0px 0px;
    padding: 0px;
}

//border for visual seperation

#nav li {
    border-bottom: 1px solid #ffffff;
}

#nav li a:link, #nav li a:visited {
    font-size: 10pt;
    font-weight: bold;
    display: block;
    padding: 3px 0px 3px 3px;
    background-color: #628794;
    color: #ffffff;
}

//higlight when hover

#nav li a:hover, #nav li a:active {
    font-size: 10pt;
    font-weight: bold;
    display: block;
    padding: 3px 0px 3px 3px;
    background-color: #6cac46;
    color: #000000;
}

#content {
    width:550px;
    float: left;
}

#content a {
    text-decoration: none;
    font-weight: bold;
}

Body:
The problem with your code isn't the selectors, it's the comment.

If you're using raw CSS, you'll need to use block comments because inline comments will cause an error and then the rest of your CSS won't process. The reason that text-decoration works is because it occurs before your first inline comment.

Change

//making sure there are no extra padding or margins lying around to line up with ABOUT US content

to

/* making sure there are no extra padding or margins lying around to line up with ABOUT US content */


问:
Check if a point is in a rotated rectangle (C#)
I have a program in C# (Windows Forms) which draws some rectangles on a picturebox. They can be drawn at an angle too (rotated).

I know each of the rectangles' start point (upper-left corner), their size(width+height) and their angle. Because of the rotation, the start point is not necessarely the upper-left corner, but that does not matter here.
Then when I click the picturebox, I need to check in which rectangle (if any) I have clicked.

So I need some way of checking if a point is in a rectangle, but I also need to take into account the rotation of each rectangle.
Does anybody know of a way to do this in C#?

答:
Edit: After looking back, I'm using MonoGame and the OP is using Windows Forms. The following is for MonoGame.

I've been messing this for a while now and have found a couple answers, just none of them actually worked. Here is a C# function that does exactly as OP describes, if not for OP then other people Googling like I was.

It was a headache to figure this out. A lot of the typical guesswork.

```<code>    bool PointIsInRotatedRectangle(Vector2 P, Rectangle rect, float rotation)
    {
        Matrix rotMat = Matrix.CreateRotationZ(-rotation);
        Vector2 Localpoint = P - (rect.Location).ToVector2();
        Localpoint = Vector2.Transform(Localpoint, rotMat);
        Localpoint += (rect.Location).ToVector2();

        if (rect.Contains(Localpoint)) { return true; }
        return false;
    }
</code>```

And here it is in a single line of code. Probably faster to use.

```<code>    bool PointIsInRotatedRectangle(Vector2 P, Rectangle rect, float rotation)
    {
        return rect.Contains(Vector2.Transform(P - (rect.Location).ToVector2(), Matrix.CreateRotationZ(-rotation)) + (rect.Location).ToVector2());
    }
</code>```

Body:
Edit: After looking back, I'm using MonoGame and the OP is using Windows Forms. The following is for MonoGame.

I've been messing this for a while now and have found a couple answers, just none of them actually worked. Here is a C# function that does exactly as OP describes, if not for OP then other people Googling like I was.

It was a headache to figure this out. A lot of the typical guesswork.

    bool PointIsInRotatedRectangle(Vector2 P, Rectangle rect, float rotation)
    {
        Matrix rotMat = Matrix.CreateRotationZ(-rotation);
        Vector2 Localpoint = P - (rect.Location).ToVector2();
        Localpoint = Vector2.Transform(Localpoint, rotMat);
        Localpoint += (rect.Location).ToVector2();

        if (rect.Contains(Localpoint)) { return true; }
        return false;
    }

And here it is in a single line of code. Probably faster to use.

    bool PointIsInRotatedRectangle(Vector2 P, Rectangle rect, float rotation)
    {
        return rect.Contains(Vector2.Transform(P - (rect.Location).ToVector2(), Matrix.CreateRotationZ(-rotation)) + (rect.Location).ToVector2());
    }


问:
Insert filename into text file with sed
I've been learning about sed and finding it very useful, but cannot find an answer to this in any of the many guides and examples ... I'd like to insert the filename of a text file, minus its path and extension, into a specific line within the text itself. Possible?</p>

答:
In such cases, the correct starting point should be man pages. Manual of sed does not provide a feature for sed to understand "filename", but sed does support inserting a text before/after a line.

As a result you need to isolate the filename separatelly , store the text to a variable and inject this text after/before the line you wish.

Example:

```<code>$ a="/home/gv/Desktop/PythonTests/cpu.sh"
$ a="${a##*/}";echo "$a"
cpu.sh
$ a="${a%.*}"; echo "$a"
cpu

$ cat file1
LOCATION 0 X 0
VALUE 1a 2 3
VALUE 1b 2 3
VALUE 1c 2 3

$ sed "2a $a" file1   # Inject the contents of variable $a after line2
LOCATION 0 X 0
VALUE 1a 2 3
cpu
VALUE 1b 2 3
VALUE 1c 2 3

$ sed "2i $a" file1   # Inject the contetns of variable $a before line2
LOCATION 0 X 0
cpu
VALUE 1a 2 3
VALUE 1b 2 3
VALUE 1c 2 3

$ sed "2a George" file1  #Inject a fixed string "George" after line 2
LOCATION 0 X 0
VALUE 1a 2 3
George
VALUE 1b 2 3
VALUE 1c 2 3
</code>```

Explanation:

a="${a##*/}"  : Removes all chars from the beginning of string up to last found slash /  (longer match)

a="${a%.*}"    : Remove all chars starting from the end of the string up to the first found dot . (short match) . You can also use %% for the longest found dot.

sed "2a $a"     : Insert after line 2 the contents of variable $a

sed "2i $q"     : Insert before line 2 the contents of $a

Optionally you can use sed -i to make changes in-place / in file under process

Title: Insert filename into text file with sed

Body:
In such cases, the correct starting point should be man pages. Manual of sed does not provide a feature for sed to understand "filename", but sed does support inserting a text before/after a line.

As a result you need to isolate the filename separatelly , store the text to a variable and inject this text after/before the line you wish.

Example:

$ a="/home/gv/Desktop/PythonTests/cpu.sh"
$ a="${a##*/}";echo "$a"
cpu.sh
$ a="${a%.*}"; echo "$a"
cpu

$ cat file1
LOCATION 0 X 0
VALUE 1a 2 3
VALUE 1b 2 3
VALUE 1c 2 3

$ sed "2a $a" file1   # Inject the contents of variable $a after line2
LOCATION 0 X 0
VALUE 1a 2 3
cpu
VALUE 1b 2 3
VALUE 1c 2 3

$ sed "2i $a" file1   # Inject the contetns of variable $a before line2
LOCATION 0 X 0
cpu
VALUE 1a 2 3
VALUE 1b 2 3
VALUE 1c 2 3

$ sed "2a George" file1  #Inject a fixed string "George" after line 2
LOCATION 0 X 0
VALUE 1a 2 3
George
VALUE 1b 2 3
VALUE 1c 2 3

Explanation:

a="${a##*/}"  : Removes all chars from the beginning of string up to last found slash /  (longer match)

a="${a%.*}"    : Remove all chars starting from the end of the string up to the first found dot . (short match) . You can also use %% for the longest found dot.

sed "2a $a"     : Insert after line 2 the contents of variable $a

sed "2i $q"     : Insert before line 2 the contents of $a

Optionally you can use sed -i to make changes in-place / in file under process


问:
Dice roll console app returns errors in C#
I'm trying to write a console app, that does dicerolls with multiple types of dice, and after having done that, asks the user to confirm a new roll, or quit.

Here is minimal part that shows the problem:

```<code>string rolltype = "bob";
if (rolltype = "d4") // <-- error on this line
{
    Console.WriteLine("d4 roll is {0}", d4);
}
</code>```

Code produces following error at compile time:

cannot implicitly convert type string to bool

Complete source:

```<code>namespace diceroll
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rand = new Random();
            int d4 = rand.Next(1, 5);
            int d6 = rand.Next(1, 7);
            int d8 = rand.Next(1, 9);
            int d10 = rand.Next(1, 11);
            int d12 = rand.Next(1, 13);
            int d20 = rand.Next(1, 21);
            string rolltype;
            Console.WriteLine("what do you want to roll?");
            rolltype = (Console.ReadLine());
            Console.WriteLine("your choice is {0}", rolltype);
            if (rolltype = "d4")
            {
                Console.WriteLine("d4 roll is {0}", d4);
            }
            else { }
            Console.ReadKey();
        }
    }
}
</code>```

What I wish to achieve here, is the console asking for the type of roll, and upon being given that, it returns you a random number. The (rolltype = "d4" ) returns an error "cannot implicitly convert type string to bool".

答:
```<code> if (rolltype == "d4")
</code>```

You need to use the equality operator not the assignment one.

Body:
I'm trying to write a console app, that does dicerolls with multiple types of dice, and after having done that, asks the user to confirm a new roll, or quit.

Here is minimal part that shows the problem:

string rolltype = "bob";
if (rolltype = "d4") // <-- error on this line
{
    Console.WriteLine("d4 roll is {0}", d4);
}

Code produces following error at compile time:

cannot implicitly convert type string to bool

Complete source:

namespace diceroll
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rand = new Random();
            int d4 = rand.Next(1, 5);
            int d6 = rand.Next(1, 7);
            int d8 = rand.Next(1, 9);
            int d10 = rand.Next(1, 11);
            int d12 = rand.Next(1, 13);
            int d20 = rand.Next(1, 21);
            string rolltype;
            Console.WriteLine("what do you want to roll?");
            rolltype = (Console.ReadLine());
            Console.WriteLine("your choice is {0}", rolltype);
            if (rolltype = "d4")
            {
                Console.WriteLine("d4 roll is {0}", d4);
            }
            else { }
            Console.ReadKey();
        }
    }
}

What I wish to achieve here, is the console asking for the type of roll, and upon being given that, it returns you a random number. The (rolltype = "d4" ) returns an error "cannot implicitly convert type string to bool".

Body:
 if (rolltype == "d4")

You need to use the equality operator not the assignment one.


问:
If the difference between 2 numbers is between 1 and 100 it should run an if statement
I'm not sure why the if statement saying the "numbers are close" is not running?

I've tested it with numbers to create a difference between 1-100.

Any ideas?

```<code>#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;

int main()
{
    double num1, num2, difference;

    while(num1 != 100 || num2 != 200)
    {
        cout << "Enter a number:" << endl ;
        cin >> num1 ;
        cout << "Enter a 2nd number: " << endl ;
        cin >> num2 ;
        if (num1 == num2)
            { cout << "the numbers are equal" << endl ;
            }
        else if (num1 > num2)
        {   cout << "The larger number is num1:" << num1 << endl ;
            cout << "The smaller number is num2:" <<num2 << endl;
            difference = num1- num2;
           if (difference <100 && difference > 1)
            {
            cout << "Numbers are almost equal\n" ;
            }
            else
            {}
        }
    else if (num2 - num1)
        {   cout << "The larger number is num2:" << num2 << endl ;
            cout << "The smaller number is num1:" <<num1 << endl;
        }

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

Kind regards,

答:
you should use abs to get the absolute value of the difference of the 2 numbers.

also your while look had some issues, mainly calling variables that hadn't been given a value yet try the code below, it should do what you're wanting to accomplish.

```<code>#include <iostream>
#include <cmath>
#include <string>

using namespace std;

int main() {

  bool again = true;

  while(again){
    double num1, num2, diffrence;
    cout << "Enter a Number: " << endl;
    cin >>num1;
    cout << "Enter a 2nd Number: " << endl;
    cin >> num2;

    diffrence = abs(num1-num2);

    if(diffrence==0){
        cout << "the numbers are equal";
    }else{
      if(num1>num2){
        cout << "the larger number is num1: " << num1 << endl;
        cout << "the smaller number is num2: " << num2 << endl;
      }else{
        cout << "the larger number is num2: " << num2 << endl;
        cout << "the smaller number is num1: " << num1 << endl;
      }
      if(diffrence<100){
        cout << "Numbers are almost equal\n";
      }else{
        cout << "Numbers are not even close";
      }
    }
    cout << "Try again (y/n)?" << endl;
    char response;
    cin >> response;
    if(tolower(response)=='n'){
      again = false;
    }
  }
  return 0;
}

auto x = main();
</code>```

Body:
I'm not sure why the if statement saying the "numbers are close" is not running?

I've tested it with numbers to create a difference between 1-100.

Any ideas?

#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;

int main()
{
    double num1, num2, difference;

    while(num1 != 100 || num2 != 200)
    {
        cout << "Enter a number:" << endl ;
        cin >> num1 ;
        cout << "Enter a 2nd number: " << endl ;
        cin >> num2 ;
        if (num1 == num2)
            { cout << "the numbers are equal" << endl ;
            }
        else if (num1 > num2)
        {   cout << "The larger number is num1:" << num1 << endl ;
            cout << "The smaller number is num2:" <<num2 << endl;
            difference = num1- num2;
           if (difference <100 && difference > 1)
            {
            cout << "Numbers are almost equal\n" ;
            }
            else
            {}
        }
    else if (num2 - num1)
        {   cout << "The larger number is num2:" << num2 << endl ;
            cout << "The smaller number is num1:" <<num1 << endl;
        }

    }
    return 0;
}

Kind regards,

Body:
you should use abs to get the absolute value of the difference of the 2 numbers.

also your while look had some issues, mainly calling variables that hadn't been given a value yet try the code below, it should do what you're wanting to accomplish.

#include <iostream>
#include <cmath>
#include <string>

using namespace std;

int main() {

  bool again = true;

  while(again){
    double num1, num2, diffrence;
    cout << "Enter a Number: " << endl;
    cin >>num1;
    cout << "Enter a 2nd Number: " << endl;
    cin >> num2;

    diffrence = abs(num1-num2);

    if(diffrence==0){
        cout << "the numbers are equal";
    }else{
      if(num1>num2){
        cout << "the larger number is num1: " << num1 << endl;
        cout << "the smaller number is num2: " << num2 << endl;
      }else{
        cout << "the larger number is num2: " << num2 << endl;
        cout << "the smaller number is num1: " << num1 << endl;
      }
      if(diffrence<100){
        cout << "Numbers are almost equal\n";
      }else{
        cout << "Numbers are not even close";
      }
    }
    cout << "Try again (y/n)?" << endl;
    char response;
    cin >> response;
    if(tolower(response)=='n'){
      again = false;
    }
  }
  return 0;
}

auto x = main();


问:
Query timestamp and value at same time in Firebase
I want to sort my entries by their star count as "Top of Week", "Top of Month", "Top of All Time". Multiple orderBy is not allowed so I can't query star and timestamp childs at same time. How sould I structure, index and query my data?

I am using REST API in my sotfware. But answers using SDK also can help me. Any idea?

答:
I assume you have a numeric star count as a property.

Use indexed properties that have the year and month+year combined with the star count in a way that sorts the way you want like:

```<code>"stars": 123,
"stars-by-year": "2017-000000000123",
"stars-by-month": "2017-04-000000000123"
</code>```

Then you can use startAt() to query for each. It's not clear if the date is for stars given this month or items created this month but this should work for both.

Body:
I assume you have a numeric star count as a property.

Use indexed properties that have the year and month+year combined with the star count in a way that sorts the way you want like:

"stars": 123,
"stars-by-year": "2017-000000000123",
"stars-by-month": "2017-04-000000000123"

Then you can use startAt() to query for each. It's not clear if the date is for stars given this month or items created this month but this should work for both.


问:
How to migrate multiple users' Access db's to one single SQLServer db
UPDATED 2010-11-25

A legacy stand-alone application (A1) is being re-created as a web application (A2).

A1 is written in Delphi 7 and uses a MS Access database to store the data. A1 has been distributed to ~1000 active users that we have no control over during the build of A2.

The database has ~50 tables, some which contain user data, some which contain template data (which does not need to be copied); 3-4 of these user tables are larger (<5000 records), the rest is  small (<100).

Once A2 is 'live', users of A1 should be able to migrate to A2. I'm looking for a comparison of scenario's to do so.

One option is to develop a stand-alone 'update' tool for these users, and have this update tool talk to the A2 database through webservices.

Another option is to allow users to upload their Access db (~15 MB) database to our server, run some kind of SSIS package (overnight, perhaps) to get this into A2 for that user, and delete the Access db afterward.

Am I missing options? Which option is 'best' (I understand this may be somewhat subjective, but hopefully the pro's and cons for the scenario's can at least be made clear).

I'll gladly make this a community wiki if so demanded.

UPDATE 2010-11-23: it has been suggested that a variant of scenario 1 would be to have the update tool/application talk directly to the production database. Is this feasible?

UPDATE 2011-11: By now, this has been taken into production. Users upload the .zip file the .mdb is in, which is unpacked and placed in a secure location. A nightly SSIS scheduled job comes along and moves the data to staging tables, which are then moved into production through SP's.

答:
If you have no control of the 1000+ users of A1, how are you going to get them all to convert to A2?

Have you considered giving them an SQL Server Express DB to upgrade to, and letting them host the Web App on their own servers?


问:
How do I continue the input to fprintf on the next line?
Given the following code:

```<code>fprintf('test test',...
        'test');
</code>```

I get the following output on my terminal:

test test

How can I continue on to the next line for fprintf?

答:
The issue has nothing to do with the line continuation characters.

Only the format specifier string (the first or second input) is processed unless a format operator is provided in that format specifier string.

```<code>fprintf('test test %s', ...
        'test');
</code>```

If you instead want to concatenate strings, you should use [] to create a string across multiple lines that you then pass to fprintf as the format specifier.

```<code>fprintf(['test test ', ...
        'test'])
</code>```

If you want the last 'test' to appear on a new line, then you should use the newline control sequence to specify that you'd like it on a new line

```<code>fprintf('test test\ntest')
</code>```

Body:
Given the following code:

fprintf('test test',...
        'test');

I get the following output on my terminal:

test test

How can I continue on to the next line for fprintf?

Body:
The issue has nothing to do with the line continuation characters.

Only the format specifier string (the first or second input) is processed unless a format operator is provided in that format specifier string.

fprintf('test test %s', ...
        'test');

If you instead want to concatenate strings, you should use [] to create a string across multiple lines that you then pass to fprintf as the format specifier.

fprintf(['test test ', ...
        'test'])

If you want the last 'test' to appear on a new line, then you should use the newline control sequence to specify that you'd like it on a new line

fprintf('test test\ntest')


问:
Payload error in Cloud Functions for Firebase Messaging
I wrote a cloud function using Cloud Functions for Firebase that sends notifications to certain topics of Firebase Messaging. The final parts of the function define the payload to be sent, then sends it:

```<code>// javascript code in cloud functions
const payload = {
      'notification': {
        'title': `${toTitleCase(name)} just logged an event`,
        'body': `${events[eventType]} for ${toTitleCase(petName)}`,
        'data': {
            'personSent': userSent
        }
      }
    };
console.log(payload);
admin.messaging().sendToTopic(pet_Id, payload);
</code>```

However, I'm getting the error log in my Firebase console:

Error: Messaging payload contains an invalid value for the "notification.data" property. Values must be strings.

When I logout the payload I confirmed it is all strings:

```<code>{ notification:
   { title: 'Turtle Dude just logged an event',
     body: 'Walk for Beer',
     data: { personSent: 'mfsP8U0qDdQL4rrrbXp6K0YsF423' } } }
</code>```

However, when I send the same payload from my iPhone app (which I'm trying to avoid since that means I have to store the messaging private key on the client side) I am able to attach the extra data I want to send just fine:

// Swift code in iPhone app
let body: [String: Any] = ["to": "/topics/\(currentPet)",
                            "priority" : "high",
                            "notification" : [
                                "body" : "\(events[eventType]) for \(petsName.localizedCapitalized)",
                                "title" : "\(myName.localizedCapitalized) just logged an event",
                                "data" : ["personSent": myId]
                              ]
                           ]
```

How can I accomplish adding additional data in my cloud function like I do in my Swift code?

答:
As others explained in the comments, the data object should go inside payload,

 NOT inside notification.

Try the following code:

```<code>// javascript code in cloud functions
const payload = {
      'notification': {
        'title': `${toTitleCase(name)} just logged an event`,
        'body': `${events[eventType]} for ${toTitleCase(petName)}`,
      },
      // NOTE: The 'data' object is inside payload, not inside notification
      'data': {
            'personSent': userSent
      }
    };
console.log(payload);
admin.messaging().sendToTopic(pet_Id, payload);
</code>```

Body:
I wrote a cloud function using Cloud Functions for Firebase that sends notifications to certain topics of Firebase Messaging. The final parts of the function define the payload to be sent, then sends it:

// javascript code in cloud functions
const payload = {
      'notification': {
        'title': `${toTitleCase(name)} just logged an event`,
        'body': `${events[eventType]} for ${toTitleCase(petName)}`,
        'data': {
            'personSent': userSent
        }
      }
    };
console.log(payload);
admin.messaging().sendToTopic(pet_Id, payload);

However, I'm getting the error log in my Firebase console:

Error: Messaging payload contains an invalid value for the "notification.data" property. Values must be strings.

When I logout the payload I confirmed it is all strings:

{ notification:
   { title: 'Turtle Dude just logged an event',
     body: 'Walk for Beer',
     data: { personSent: 'mfsP8U0qDdQL4rrrbXp6K0YsF423' } } }

However, when I send the same payload from my iPhone app (which I'm trying to avoid since that means I have to store the messaging private key on the client side) I am able to attach the extra data I want to send just fine:

// Swift code in iPhone app
let body: [String: Any] = ["to": "/topics/\(currentPet)",
                            "priority" : "high",
                            "notification" : [
                                "body" : "\(events[eventType]) for \(petsName.localizedCapitalized)",
                                "title" : "\(myName.localizedCapitalized) just logged an event",
                                "data" : ["personSent": myId]
                              ]
                           ]

How can I accomplish adding additional data in my cloud function like I do in my Swift code?

Body:
As others explained in the comments, the data object should go inside payload,

 NOT inside notification.

Try the following code:

// javascript code in cloud functions
const payload = {
      'notification': {
        'title': `${toTitleCase(name)} just logged an event`,
        'body': `${events[eventType]} for ${toTitleCase(petName)}`,
      },
      // NOTE: The 'data' object is inside payload, not inside notification
      'data': {
            'personSent': userSent
      }
    };
console.log(payload);
admin.messaging().sendToTopic(pet_Id, payload);


问:
Bron-Kerbosch algorithm in R
I want to implement Bron-Kerbosch algorithm in igraph manually. I want to replicate the example with the graph from Wikipedia page. This is the solution I came up with so far.

```<code>library(igraph)
g <- graph.formula(1-2,1-5,5-2,2-3,3-4,4-5,4-6)
P <- as.vector(V(g))
bron_kerbosch <- function(R,P,X) {

    if (length(P) == 0 && length(X) == 0) {
        print (R)
    } else {
        for (v in P) {
            neis <- as.vector(neighbors(g,v))
            bron_kerbosch(union(R,v),intersect(P,neis),intersect(X,neis))
            P <- c(P[-which(P==v)])
            X <- c(X,v)
        }
    }
}
> bron_kerbosch(c(),P,c())
[1] 1 2 3
[1] 2 4
[1] 3 5
[1] 4 5
[1] 5 6
</code>```

And the answer should be:
 [[1, 2, 5], [2, 3], [3, 4], [4, 5], [4, 6]]
I am indexing from 1, not from 0.
Any idea what I'm doing wrong?

答:
And I've just found the solution. I used the indices of g graph, instead of names :/.
So I changed two lines:

```<code> P <- V(g)$name
 neis <- neighbors(g,v)$name
</code>```

This will work now with characters instead of numbers. And the result:

```<code> [1] "1" "2" "5"
 [1] "2" "3"
 [1] "5" "4"
 [1] "3" "4"
 [1] "4" "6"
</code>```

So the vertices are not ordered (5,4) should be (4,5) but I think it doesn't matter much. However it should be good to write this to integer numbers, instead of chars.

Title: Bron-Kerbosch algorithm in R

Body:
I want to implement Bron-Kerbosch algorithm in igraph manually. I want to replicate the example with the graph from Wikipedia page. This is the solution I came up with so far.

library(igraph)
g <- graph.formula(1-2,1-5,5-2,2-3,3-4,4-5,4-6)
P <- as.vector(V(g))
bron_kerbosch <- function(R,P,X) {

    if (length(P) == 0 && length(X) == 0) {
        print (R)
    } else {
        for (v in P) {
            neis <- as.vector(neighbors(g,v))
            bron_kerbosch(union(R,v),intersect(P,neis),intersect(X,neis))
            P <- c(P[-which(P==v)])
            X <- c(X,v)
        }
    }
}
> bron_kerbosch(c(),P,c())
[1] 1 2 3
[1] 2 4
[1] 3 5
[1] 4 5
[1] 5 6

And the answer should be:
 [[1, 2, 5], [2, 3], [3, 4], [4, 5], [4, 6]]
I am indexing from 1, not from 0.
Any idea what I'm doing wrong?

Body:
And I've just found the solution. I used the indices of g graph, instead of names :/.
So I changed two lines:

 P <- V(g)$name
 neis <- neighbors(g,v)$name

This will work now with characters instead of numbers. And the result:

 [1] "1" "2" "5"
 [1] "2" "3"
 [1] "5" "4"
 [1] "3" "4"
 [1] "4" "6"

So the vertices are not ordered (5,4) should be (4,5) but I think it doesn't matter much. However it should be good to write this to integer numbers, instead of chars.


答:
These function behave differently for negative numbers.

Math.Truncate(-4.5) = -4

Math.Floor(-4.5) = -5

Title: What is the difference in floor function and truncate function?

Body:
What is the difference between Math.Floor() and Math.Truncate() in .NET?

For example, Math.Floor(4.4) = 4 Math.Truncate(4.4) = 4.


问:
client and server don't have same version (client : 1.21, server: 1.18)
my:Docker version 1.6.2, build 7c8fca2
my:docker-compose version 1.11.2, build dfed245
erreur: ERROR: client and server don't have same version (client : 1.21, server: 1.18)

How i can solve this problem Thank you

答:
If your server version (1.6.2) is correct, that's from back in May 2015 and extremely old. It predates docker network and docker volume, build ARGs, privileged containers, DNS discovery, and many other features you may expect. You should really upgrade this to a current release.

With docker-compose, you can use the COMPOSE_API_VERSION variable to tell compose which server API version to use, but as mentioned in the documentation, this is not supported and some errors are expected, particularly when you have a significant version mismatch like you do.


问:
Retrieving all GridViewRow objects from a GridView control with paging enabled
I currently have a GridView control on my aspx page with paging enabled and I need to loop through the entire row collection/count to process the selected records.  With my current code, it will only loop through the current page of GridView row.

What is the best way to accomplish this task?

Here is my current code:

ASPX page:

```<code><asp:GridView ID="MyGridView" runat="server" AllowPaging="true" PageSize="20">
   <Columns>
      <!-- My Column list -->
   </Columns>
</asp:GridView>
<asp:Button id="MyButton" runat="server" Text="Add" OnClick="MyButton_Click" />
</code>```

code behind:

```<code>protected void MyButton_Click(object sender, EventArgs e)
{
    for (int Count = 0; Count < MyGridView.Rows.Count; Count++)
    {
        //The row count is 20 and only contains the GridViewRow object in the current page view
        //I want to retrieve the all GridViews rows so I can add them to a ReorderList control
    }
}
</code>```

答:
@CRice's answer should have been the official answer.

Here is my solution. You need to presave the gridview's data, via its DataSource, into ViewState or Session.

GridView.Rows only refers to the "visible" rows, or the page currently shown on the screen.

```<code>    protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView gv = (GridView)sender;

        DataSourceSelectArguments dss = new DataSourceSelectArguments();

    //get the datasource related to the gridview
    string wsDataSourceID = (gv.DataSourceID == string.Empty) ? ViewState["DataSourceID"].ToString() : gv.DataSourceID;
    SqlDataSource sds = (SqlDataSource)pnlMAIN.FindControl(wsDataSourceID);
    if (sds != null)
    {
        //load the data again but this time into a dataview object
        DataView dv = (DataView)sds.Select(DataSourceSelectArguments.Empty);
        if (dv != null)
        {
            //convert the dataview to a datatable so we can see the row(s)
            DataTable dt = (DataTable)dv.ToTable();
            if (dt != null)
            {
                //Save your data before changing pages
                ViewState["AllTheData"] = dt;

                gv.DataSource = dt;
                gv.DataSourceID = null;
            }
        }
    }

    //now change pages!
        gv.PageIndex = e.NewPageIndex;
        gv.DataBind();
    }
</code>```

Next, when changing pages, here we save the data

```<code>protected void GridView_PageIndexChanged(object sender, EventArgs e)
{
    GridView gv = (GridView)sender;

    DataSourceSelectArguments dss = new DataSourceSelectArguments();

    //reload the datatable back to the gridview
    gv.DataSource = ViewState["AllTheData"];
    gv.DataSourceID = null;
    gv.DataBind();
</code>```

I hope the code speaks for itself.

Thanks

Body:
I currently have a GridView control on my aspx page with paging enabled and I need to loop through the entire row collection/count to process the selected records.  With my current code, it will only loop through the current page of GridView row.

What is the best way to accomplish this task?

Here is my current code:

ASPX page:

<asp:GridView ID="MyGridView" runat="server" AllowPaging="true" PageSize="20">
   <Columns>

   </Columns>
</asp:GridView>
<asp:Button id="MyButton" runat="server" Text="Add" OnClick="MyButton_Click" />

code behind:

protected void MyButton_Click(object sender, EventArgs e)
{
    for (int Count = 0; Count < MyGridView.Rows.Count; Count++)
    {
        //The row count is 20 and only contains the GridViewRow object in the current page view
        //I want to retrieve the all GridViews rows so I can add them to a ReorderList control
    }
}

Body:
@CRice's answer should have been the official answer.

Here is my solution. You need to presave the gridview's data, via its DataSource, into ViewState or Session.

GridView.Rows only refers to the "visible" rows, or the page currently shown on the screen.

    protected void GridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView gv = (GridView)sender;

        DataSourceSelectArguments dss = new DataSourceSelectArguments();

    //get the datasource related to the gridview
    string wsDataSourceID = (gv.DataSourceID == string.Empty) ? ViewState["DataSourceID"].ToString() : gv.DataSourceID;
    SqlDataSource sds = (SqlDataSource)pnlMAIN.FindControl(wsDataSourceID);
    if (sds != null)
    {
        //load the data again but this time into a dataview object
        DataView dv = (DataView)sds.Select(DataSourceSelectArguments.Empty);
        if (dv != null)
        {
            //convert the dataview to a datatable so we can see the row(s)
            DataTable dt = (DataTable)dv.ToTable();
            if (dt != null)
            {
                //Save your data before changing pages
                ViewState["AllTheData"] = dt;

                gv.DataSource = dt;
                gv.DataSourceID = null;
            }
        }
    }

    //now change pages!
        gv.PageIndex = e.NewPageIndex;
        gv.DataBind();
    }

Next, when changing pages, here we save the data

protected void GridView_PageIndexChanged(object sender, EventArgs e)
{
    GridView gv = (GridView)sender;

    DataSourceSelectArguments dss = new DataSourceSelectArguments();

    //reload the datatable back to the gridview
    gv.DataSource = ViewState["AllTheData"];
    gv.DataSourceID = null;
    gv.DataBind();

I hope the code speaks for itself.

Thanks


问:
Password security in Java - Converting char[] to String
I am trying to build an unofficial api for a website. It will require the user to log in, and the password will be read from the console using the standard Console.readPassword() method. Now, this gives me a char array, but I have to send the password through a POST request using the HttpPost class in Apache's HttpClient library. For this, a String is required, but conversion of the password to String will create a security risk.
What can I do?

Edit : I know how to convert a char array to string. The problem is that Strings are immutable and since you cannot delete objects explicitly in Java, the password will be left in the memory.

答: What I would suggest would be to hash the input user's password on the client-side and send the hash to the server, as storing plain-text passwords on the server-side is a security risk in the first place. This answer lays out the entire method of hashing passwords in java and then authenticating the password with the hash stored on the server when a user logs in. </p>


问:
How do I find a value in an array in the specific situation?
I am creating an array that stores a name and a bowling score from the same line and then using Split() to split the name and score into two separate arrays.  Then I need to find the highest score along with the name with the highest score and write it to the console using a method somehow.

Here is what i have so far.  Thanks.

```<code>    const int SIZE = 10;

    string[] arrayNames = new string[SIZE];
    int[] arrayScores = new int[SIZE];

    for (int i = 0; i < SIZE; i++){
        Write("Enter the name and score of a player on one line seperated by a space or press Enter to stop ");

        string input = ReadLine();

        if (input == ""){
            break;
        }
        string[] scoreInfo = input.Split();
        arrayNames[i] = scoreInfo[0];

        bool valid = false;
        do{
            if (input == ""){
                break;
            }
            valid = int.TryParse(scoreInfo[1], out arrayScores[i]);
            valid = valid && (arrayScores[i] <= 300);

        } while (!valid);

    }

    int max = bowling.CalcHighest(arrayScores);
    int min = bowling.CalcLowest(arrayScores);
    int average = bowling.CalcAverage(arrayScores);
</code>```

答:
Your problem is that you aren't maintaining a reference between the name and the score.

When you read in a line you are separating the values into arrayNames[i] and arrayScores[i].

Consider using a Dictionary maybe instead of two separate arrays.

```<code>Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add(name, score);
</code>```

Then do your calculations using the dictionary as a parameter rather than the array. If you're using System.Linq you can do all the calculations on the dictionary real easy:

```<code>var orderedDict = dict.OrderByDescending(d => d.Value); //This orders the dictionary by the scor
var first = orderedDict.First(); //This gets the highest score
var last = orderedDict.Last(); //This gets the lowest score
var average = dict.Sum(s => s.Value)/dict.Count(); //This is the average

var firstName = first.Key; //Name of winner
var lastName = last.Key; //Name of loser
</code>```

Body:
I am creating an array that stores a name and a bowling score from the same line and then using Split() to split the name and score into two separate arrays.  Then I need to find the highest score along with the name with the highest score and write it to the console using a method somehow.

Here is what i have so far.  Thanks.

    const int SIZE = 10;

    string[] arrayNames = new string[SIZE];
    int[] arrayScores = new int[SIZE];

    for (int i = 0; i < SIZE; i++){
        Write("Enter the name and score of a player on one line seperated by a space or press Enter to stop ");

        string input = ReadLine();

        if (input == ""){
            break;
        }
        string[] scoreInfo = input.Split();
        arrayNames[i] = scoreInfo[0];

        bool valid = false;
        do{
            if (input == ""){
                break;
            }
            valid = int.TryParse(scoreInfo[1], out arrayScores[i]);
            valid = valid && (arrayScores[i] <= 300);

        } while (!valid);

    }

    int max = bowling.CalcHighest(arrayScores);
    int min = bowling.CalcLowest(arrayScores);
    int average = bowling.CalcAverage(arrayScores);

Body:
Your problem is that you aren't maintaining a reference between the name and the score.

When you read in a line you are separating the values into arrayNames[i] and arrayScores[i].

Consider using a Dictionary maybe instead of two separate arrays.

Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add(name, score);

Then do your calculations using the dictionary as a parameter rather than the array. If you're using System.Linq you can do all the calculations on the dictionary real easy:

var orderedDict = dict.OrderByDescending(d => d.Value); //This orders the dictionary by the scor
var first = orderedDict.First(); //This gets the highest score
var last = orderedDict.Last(); //This gets the lowest score
var average = dict.Sum(s => s.Value)/dict.Count(); //This is the average

var firstName = first.Key; //Name of winner
var lastName = last.Key; //Name of loser


问:
What is this called in C#?
```<code>Book x = new Book(){
              Author = "Rowling",
              Title = "Harry Potter",
              Genre = Genres.Fantasy
              };
</code>```

I've tried googling for Inline declaration, but I guess thats not what it's officially called.

Thoughts?

答: Object Initializers</p>

OwnerDisplayName: delete

LastEditorDisplayName: delete

Title: What is this called in C#?

Body:
Book x = new Book(){
              Author = "Rowling",
              Title = "Harry Potter",
              Genre = Genres.Fantasy
              };

I've tried googling for Inline declaration, but I guess thats not what it's officially called.

Thoughts?

Body: Object Initializers


问:
MySQL "backtrack" to get the first record in most recent "sequence"
I have 2 tables: customers and customers_history.

Columns in each table:

customers.id, customers.email,

customers_history.date, customers_history.user_id, customers_history.renewal_error

I have an array of customer ID's who are currently in a renewal_error state: $failing_customers_ids = array(10, 20);

Example of records in customers_history for a customer:

Date      user_id   renewal_error
28-03-17  10        Insufficient Funds
29-03-17  10        Insufficient Funds
30-03-17  10        NULL
31-03-17  10        Insufficient Funds
01-04-17  10        Insufficient Funds
31-03-17  20        Insufficient Funds
01-04-17  20        Insufficient Funds

I need to query the customer's details such as email, and the date of first renewal error in the current failing sequence, so in this case, the query would result in:

email: someEmailUserID10@example.com, date: 31-03-17

email: someEmaiUserID20l@example.com, date: 31-03-17

I've tried joining the tables and then do the processing via PHP to "backtrack" and get what I want, but I am looking forward to see if I can achieve this all via MySQL.

答:
the query could be:</p>

```<code>$sql = "SELECT DISTINCT * from customers
 join customers_history
 on customers.id = customers_history.user_id
 where customers.id IN (:ids)
 and customers_history.renewal_error = :error
 ORDER BY customers_history.date ASC"
</code>```

Body:
the query could be:

$sql = "SELECT DISTINCT * from customers
 join customers_history
 on customers.id = customers_history.user_id
 where customers.id IN (:ids)
 and customers_history.renewal_error = :error
 ORDER BY customers_history.date ASC"


问:
Change a property with the element itself in a list of dictionaries with list comprehension
Okay, so you can change an element in a list with simple number values this way:

```<code>>>> a=[1,2,3,4,5,1,2,3,4,5,1]
>>> for n,i in enumerate(a):
...   if i==1:
...      a[n]=10
...
>>> a
[10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]
</code>```

and with list comprehension:

```<code>>>> a=[1,2,3,1,3,2,1,1]
>>> a = [4 if x==1 else x for x in a]
>>> a
[4, 2, 3, 4, 3, 2, 4, 4]
</code>```

But if I have a list of dictionaries, can I change not only an element but one of its property as well, using list comprehension? Is there some expression for that?

答:
Is this what you were looking for:</p>

```<code>a = [{1: [1,2,3], 2: [3,4,5]}]

a = [{k: [1,1,1]} if k == 2 else {k: v} for x in a for k, v in x.items()]
</code>```

Body:
Okay, so you can change an element in a list with simple number values this way:

>>> a=[1,2,3,4,5,1,2,3,4,5,1]
>>> for n,i in enumerate(a):
...   if i==1:
...      a[n]=10
...
>>> a
[10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]

and with list comprehension:

>>> a=[1,2,3,1,3,2,1,1]
>>> a = [4 if x==1 else x for x in a]
>>> a
[4, 2, 3, 4, 3, 2, 4, 4]

But if I have a list of dictionaries, can I change not only an element but one of its property as well, using list comprehension? Is there some expression for that?

Body:
Is this what you were looking for:

a = [{1: [1,2,3], 2: [3,4,5]}]

a = [{k: [1,1,1]} if k == 2 else {k: v} for x in a for k, v in x.items()]


答:
"cannot implicitly convert type string to bool", and i have no idea
  how to fix it

this is because the code below doesn't result to a boolean value, below you're trying to assign rolltype to the string "d4" hence the error.

```<code>if (rolltype = "d4")
</code>```

what you want is this:

```<code>if (rolltype == "d4")
</code>```

Also is there a more elegant way of going at this than writing 6
  separate if statements for the rolltypes?

Sure, we can use an array to store the possible options and then just loop over it.

Step 1 - create the array:

```<code>string[] myArray = {"d4","d6","d8","d10","d12","d20"};
</code>```

now your code becomes like this:

```<code>Random rand = new Random();
int d4 = rand.Next(1, 5);
int d6 = rand.Next(1, 7);
int d8 = rand.Next(1, 9);
int d10 = rand.Next(1, 11);
int d12 = rand.Next(1, 13);
int d20 = rand.Next(1, 21);
string[] myArray = {"d4","d6","d8","d10","d12","d20"};
</code>```

Step 2 - loop over it to find if the entered value is equal to any of those within the array.

```<code>foreach(string str in myArray){
   if (rolltype == str){
      // do something
      break; // if we get here then we don't need to loop any further
   }
}
</code>```

now your code becomes like this:

```<code>Random rand = new Random();
int d4 = rand.Next(1, 5);
int d6 = rand.Next(1, 7);
int d8 = rand.Next(1, 9);
int d10 = rand.Next(1, 11);
int d12 = rand.Next(1, 13);
int d20 = rand.Next(1, 21);
string[] myArray = {"d4","d6","d8","d10","d12","d20"};
string rolltype;
Console.WriteLine("what do you want to roll?");
rolltype = (Console.ReadLine());
Console.WriteLine("your choice is {0}", rolltype);

foreach(string str in myArray){
    if (rolltype == str){
          // do something
        break; // if we get here then we don't need to loop any further
    }
}
</code>```

Another good solution suggested by Chris within the comments is to  simply take the number out of the string. This will obviously reduce the amount of rand.Next() you currently have.

Example:

```<code>int dieType = int.Parse(rollType.Substring(1));
int result = rand.Next(1,dieType+1);
</code>```

Title: Dice roll console app returns errors in C#

Body:
I'm trying to write a console app, that does dicerolls with multiple types of dice, and after having done that, asks the user to confirm a new roll, or quit.

Here is minimal part that shows the problem:

string rolltype = "bob";
if (rolltype = "d4") // <-- error on this line
{
    Console.WriteLine("d4 roll is {0}", d4);
}

Code produces following error at compile time:

cannot implicitly convert type string to bool

Complete source:

namespace diceroll
{
    class Program
    {
        static void Main(string[] args)
        {
            Random rand = new Random();
            int d4 = rand.Next(1, 5);
            int d6 = rand.Next(1, 7);
            int d8 = rand.Next(1, 9);
            int d10 = rand.Next(1, 11);
            int d12 = rand.Next(1, 13);
            int d20 = rand.Next(1, 21);
            string rolltype;
            Console.WriteLine("what do you want to roll?");
            rolltype = (Console.ReadLine());
            Console.WriteLine("your choice is {0}", rolltype);
            if (rolltype = "d4")
            {
                Console.WriteLine("d4 roll is {0}", d4);
            }
            else { }
            Console.ReadKey();
        }
    }
}

What I wish to achieve here, is the console asking for the type of roll, and upon being given that, it returns you a random number. The (rolltype = "d4" ) returns an error "cannot implicitly convert type string to bool".

Body:
"cannot implicitly convert type string to bool", and i have no idea
  how to fix it

this is because the code below doesn't result to a boolean value, below you're trying to assign rolltype to the string "d4" hence the error.

if (rolltype = "d4")

what you want is this:

if (rolltype == "d4")

Also is there a more elegant way of going at this than writing 6
  separate if statements for the rolltypes?

Sure, we can use an array to store the possible options and then just loop over it.

Step 1 - create the array:

string[] myArray = {"d4","d6","d8","d10","d12","d20"};

now your code becomes like this:

Random rand = new Random();
int d4 = rand.Next(1, 5);
int d6 = rand.Next(1, 7);
int d8 = rand.Next(1, 9);
int d10 = rand.Next(1, 11);
int d12 = rand.Next(1, 13);
int d20 = rand.Next(1, 21);
string[] myArray = {"d4","d6","d8","d10","d12","d20"};

Step 2 - loop over it to find if the entered value is equal to any of those within the array.

foreach(string str in myArray){
   if (rolltype == str){
      // do something
      break; // if we get here then we don't need to loop any further
   }
}

now your code becomes like this:

Random rand = new Random();
int d4 = rand.Next(1, 5);
int d6 = rand.Next(1, 7);
int d8 = rand.Next(1, 9);
int d10 = rand.Next(1, 11);
int d12 = rand.Next(1, 13);
int d20 = rand.Next(1, 21);
string[] myArray = {"d4","d6","d8","d10","d12","d20"};
string rolltype;
Console.WriteLine("what do you want to roll?");
rolltype = (Console.ReadLine());
Console.WriteLine("your choice is {0}", rolltype);

foreach(string str in myArray){
    if (rolltype == str){
          // do something
        break; // if we get here then we don't need to loop any further
    }
}

Another good solution suggested by Chris within the comments is to  simply take the number out of the string. This will obviously reduce the amount of rand.Next() you currently have.

Example:

int dieType = int.Parse(rollType.Substring(1));
int result = rand.Next(1,dieType+1);


问:
How do I change the orientation of the anchor on UMG (Unreal Engine)?
The anchor in UMG anchors the top left hook of a widget, and I think this is pretty unintuitive. Shouldn't the anchor be in the middle of a widget? Anyways, how do I make it so that the widget is anchored through the middle?</p>

答:
Change the item's pivot. It's a 2D value 0..1, where 0 is the top/left and 1 is the bottom/right. So to put the pivot in the item center, set Pivot to (0.5, 0.5).

Also pivot location seems unintuitive to you but it's perfectly intuitive to me. So don't focus on the issues you have with an implementation, work within the constraints given. If you write your own engine, you can decide how it is used. Until then...


问:
Why FCM does not work in the region different than its registered region?
I am trying to integrate FCM in my android app. Notifications are sent perfectly if I register my app with country as India (where notification are being tested). But notifications are not sent if the app is registered in US and I am testing it from a phone in India. Is there any kind of restriction in FCM regarding region?</p>

答:
FCM makes no difference based on the region where you registered your app.

It's possible that there was some other problem with your first configuration, or maybe FCM was having some issues when you tried it.


问:
Clusters are not showing
I am using the below code to generate a graph with two clusters with four nodes each
For some reasons when I print the graph the clusters do not show up.
What am I doing wrong?

```<code>import pygraphviz as pgv

A=pgv.AGraph(bgcolor="#cccccc",layout='neato')
A.add_edge('R1','R2')
A.add_edge('R2','R3')
A.add_edge('R3','R4')
A.add_edge('R4','R5')
A.add_edge('R5','R6')
A.add_subgraph(['R1','R2','R3','R4'], 'pbd01')
A.add_subgraph(['R5','R6','R7','R8'], 'pbd02')

A.write('cluster.dot')
A.draw('Topology.png', prog='neato')
</code>```

答:
I believe there are two problems:

The 'neato' rendering engine does not support clustering

By convention, rendering engines that do support clustering require that the subgraph name starts with 'cluster'

The following code / image was produced with the 'dot' engine and correctly clusters the nodes:

```<code>import pygraphviz as pgv

A=pgv.AGraph(bgcolor="#cccccc",layout='dot')
A.add_edge('R1','R2')
A.add_edge('R2','R3')
A.add_edge('R3','R4')
A.add_edge('R4','R5')
A.add_edge('R5','R6')
A.add_subgraph(['R1','R2','R3','R4'], name='cluster_pbd01')
A.add_subgraph(['R5','R6','R7','R8'], name='cluster_pbd02')

A.write('cluster.dot')
A.draw('Topology.png', prog='dot')
</code>```

Topology.png

Title: Clusters are not showing

Body:
I am using the below code to generate a graph with two clusters with four nodes each
For some reasons when I print the graph the clusters do not show up.
What am I doing wrong?

import pygraphviz as pgv

A=pgv.AGraph(bgcolor="#cccccc",layout='neato')
A.add_edge('R1','R2')
A.add_edge('R2','R3')
A.add_edge('R3','R4')
A.add_edge('R4','R5')
A.add_edge('R5','R6')
A.add_subgraph(['R1','R2','R3','R4'], 'pbd01')
A.add_subgraph(['R5','R6','R7','R8'], 'pbd02')

A.write('cluster.dot')
A.draw('Topology.png', prog='neato')

Body:
I believe there are two problems:

The 'neato' rendering engine does not support clustering

By convention, rendering engines that do support clustering require that the subgraph name starts with 'cluster'

The following code / image was produced with the 'dot' engine and correctly clusters the nodes:

import pygraphviz as pgv

A=pgv.AGraph(bgcolor="#cccccc",layout='dot')
A.add_edge('R1','R2')
A.add_edge('R2','R3')
A.add_edge('R3','R4')
A.add_edge('R4','R5')
A.add_edge('R5','R6')
A.add_subgraph(['R1','R2','R3','R4'], name='cluster_pbd01')
A.add_subgraph(['R5','R6','R7','R8'], name='cluster_pbd02')

A.write('cluster.dot')
A.draw('Topology.png', prog='dot')

Topology.png


问:
In Java, can I change a variable name in a for loop?
Is it possible to change a variable name every time a for loop loops itself?
`

```<code>for(int j=1;j<non-1;j++){
    int []newT=new int[non-j];
    for(int i=0;i<non-j;i++){
        newT[i]=pattern[i+1]-pattern[i];
        System.out.print(newT[i]+" ");
        System.out.println("");
        }}
</code>```

`
Can I make the newT change every time the loop repeats, like after the for loop repeats, newT becomes new1, then new2, new3 and so on?

答:
Probably you can not name it new1 but you can use 2d arrays and name it newT[ ][ ] and use it like newT[1][ ].
For example:

```<code>  for(int i = 0;i < n; i++){
      for(int j = 0; j < n; j++){
         newT [i][j] = i*j;
         System.out.println(new [i][j]);
      }
  }
</code>```

You can reach it now, as newT[1][ ], newT[2][ ] ...

Body:
Is it possible to change a variable name every time a for loop loops itself?
`

for(int j=1;j<non-1;j++){
    int []newT=new int[non-j];
    for(int i=0;i<non-j;i++){
        newT[i]=pattern[i+1]-pattern[i];
        System.out.print(newT[i]+" ");
        System.out.println("");
        }}

`
Can I make the newT change every time the loop repeats, like after the for loop repeats, newT becomes new1, then new2, new3 and so on?

Body:
Probably you can not name it new1 but you can use 2d arrays and name it newT[ ][ ] and use it like newT[1][ ].
For example:

  for(int i = 0;i < n; i++){
      for(int j = 0; j < n; j++){
         newT [i][j] = i*j;
         System.out.println(new [i][j]);
      }
  }

You can reach it now, as newT[1][ ], newT[2][ ] ...


问:
SSRS - Excel data source error when report deployed to localhost report server
I need help with an SSRS report deployed to localhost which uses ODBC data source to retrieve data from excel file.
When the same report is previewed through BIDS 2008, it displays the results as expected. But after deploying the report to the Report Server on the same machine (localhost) where BIDS is running it gives the below error.

ERROR: Throwing Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: , Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: Cannot create a connection to data source 'dsInvoice'. ---> System.Data.Odbc.OdbcException: ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

I have tried shared data source as well as custom data source but both didn't work. When I looked up for this error it mentioned that I need to use 32-bit ODBC Administrator tool under %windir%\SysWOW64\odbcad32.exe and that's what I'm using but that also didn't work. I'm an Administrator on the local machine.

Below is some information about the machine:

Windows 7 64 bit

SQL Server 2008 R2

Office 2010 32 bit

Steps to reproduce the error:

Create a Microsoft Excel Driver User DSN - Test_Excel_Driver - under %windir%\SysWOW64\odbcad32.exe

Create an SSRS report using BIDS 2008 and select datasource as an ODBC Embedded Connection with following connection string - Dsn=Test_Excel_Driver;dbq=C:...\Test Excel.xlsx;defaultdir=C:...\;driverid=1046;fil=excel 12.0;maxbuffersize=2048;pagetimeout=5

Preview the report in BIDS - Works fine !

Deploy the report to localhost SSRS Report Server with full permissions. Click on the report in report manager and get the above error.

答: Have you created the DSN under User DSN tab? If so can you try creating it under File DSN or System DSN and try again?


问:
multi select folders and files
it is possible to select multiple files using OpenFileDialog. (setting multiselect as true)

the question is how to select multiple files and folders at the same time?

I know what is FolderBrowseDialog, I know I should Hold ctrl or shift! :D

assume a folder contain 5 folder and 2 files, the scenario is to select for example 1 of files and 2 folders.

I don't know why people down vote this question!!

----------------- Edit --------------------

assume an OpenFileDialog, you can select as many file as you want in a folder, ok?
I want something like this but with the ability to select folders too!
so as OpenFileDialog return selected file names in FileNames array that dialog return something Like SelectedPaths array that contains filenames and folderpaths.

答:
The Common Item Dialog (which replaces the Open File Name Common Dialog Box) has a few points of customization. I haven't tried, but by hooking IFileDialogEvents you should be able to change behavior as you need.
(You might need to add some trickery, it was possible with an OFNHookProc in XP style file dialog)

Even though this means reading a lot of frustrating Microsoft documentation, It's preferrable over developing a custom dialog:

When copying a platform feature, you have to copy all of it.

That means e.g. pasting files through Ctrl+V, Shift+Ins or the context menu, and if that shell extension I just wrote doesn't work, I'm pissed.

Title: multi select folders and files