问:
Test page for jQuery plugin shows flash of unstyled code when viewed in Chrome - why?
I am trying to implement a basic slide down panel using jQuery, based on the following plugin:

http://samuelgarneau.com/lab/slidebox/

The problem I'm having is that there seems to be a flash of unstyled content (from the panel) in the top left corner when I look at it in Chrome. Here is the link:

http://www.asolidsite.com/clients/glennstar/custom/index.html

This doesn't happen in the plugin demo - so I must've mucked something up. But I've tried playing with all kinds of things, to no luck. Wondering if there might be someone with some jQuery insight.

I wonder if the jQuery bg resizer might be interfering with things (and causing it to lag so much on load...).

Thanks for any help!

答:
Have you tried changing the source code around to have the fullscreen background javascript together and the slider javascript together? Because right now you have one, then the other and then the jquery action for each in turn. It might be better to have the fullscreen background script, then the jquery action, then the slider script followed by the jquery action. I'd also add the cufon script at the bottom because even if it doesn't load immediately, it has the least impact on functionality.

Also, if that doesn't work for you, change the fullscreen background and the slider scripts around, so the slider loads before the fullscreen background. As it is quite a large file, this could be causing the jitter.

Example:

```<code><script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.fullscreenr.js"></script>
<script type="text/javascript">
          <!--
          var FullscreenrOptions = {  width: 1400, height: 895, bgID: '#bgimg' };
          jQuery.fn.fullscreenr(FullscreenrOptions);
          //-->
</script>
<script type="text/javascript" src="js/slidebox.js"></script>
<script type="text/javascript">
                $(document).ready(function(){
                    $("#slider").slideBox({width: "100%", height: "200px", position: "top"});
                });
</script>
<script type="text/javascript" src="js/cufon-yui.js"></script>
</code>```

By the way (and off-topic), I think the design is beautiful. If I'm right, I used to live real close to this area, Medicine Hat, AB.

Body:
Have you tried changing the source code around to have the fullscreen background javascript together and the slider javascript together? Because right now you have one, then the other and then the jquery action for each in turn. It might be better to have the fullscreen background script, then the jquery action, then the slider script followed by the jquery action. I'd also add the cufon script at the bottom because even if it doesn't load immediately, it has the least impact on functionality.

Also, if that doesn't work for you, change the fullscreen background and the slider scripts around, so the slider loads before the fullscreen background. As it is quite a large file, this could be causing the jitter.

Example:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.fullscreenr.js"></script>
<script type="text/javascript">
          <!--
          var FullscreenrOptions = {  width: 1400, height: 895, bgID: '#bgimg' };
          jQuery.fn.fullscreenr(FullscreenrOptions);
          //-->
</script>
<script type="text/javascript" src="js/slidebox.js"></script>
<script type="text/javascript">
                $(document).ready(function(){
                    $("#slider").slideBox({width: "100%", height: "200px", position: "top"});
                });
</script>
<script type="text/javascript" src="js/cufon-yui.js"></script>

By the way (and off-topic), I think the design is beautiful. If I'm right, I used to live real close to this area, Medicine Hat, AB.


来源: stackexchange

问:
Different results with local vs SymPy live - problems with division?
I have an equation I'm trying to solve. I get a proper result with SymPy live console, which is available on their website. Yet when I'm trying to reproduce the same result on my local computer, I'm getting a ConditionSet and I can't solve the equation.

The exact same equation cannot be solved locally. I'm not sure if there's maybe something wrong with the divison (but I'm importing __future__.division), the lack of LaTex libraries, or some other settings?

Here are the commands from SymPy live:

```<code>Python console for SymPy 1.0 (Python 2.7.12)

These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)

Warning: this shell runs with SymPy 1.0 and so examples pulled from other documentation may provide unexpected results.
Documentation can be found at http://docs.sympy.org/1.0.

>>> a = Eq(309.07*(1+x)**(-1/12) + 309.07*(1+x)**(-2/12)+309.07*(1+x)**(-3/12) + 309.07*(1+x)**(-4/12) + 309.07*(1+x)**(-5/12) + 309.07*(1+x)**(-6/12) + 309.07*(1+x)**(-7/12), 1500)
>>> solveset(a, x, domain=S.Reals)
</code>```

Result printed in LaTex:

```<code>          {2.17102109654962}
</code>```

And here the local python script:

```<code>from __future__ import division
from sympy import *

init_printing()

x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)

a = Eq(309.07*(1+x)**(-1/12) + 309.07*(1+x)**(-2/12)+309.07*(1+x)**(-3/12) + 309.07*(1+x)**(-4/12) + 309.07*(1+x)**(-5/12) + 309.07*(1+x)**(-6/12) + 309.07*(1+x)**(-7/12), 1500)
b = solveset(a, x, S.Reals)

print b
</code>```

Result printed in ASCII text:

```<code>ConditionSet(x, Eq(309.07*(x + 1)**(-0.583333333333333) + 309.07*(x + 1)**(-0.5) + 309.07*(x + 1)**(-0.416666666666667) + 309.07*(x + 1)**(-0.333333333333333) + 309.07*(x + 1)**(-0.25) + 309.07*(x + 1)**(-0.166666666666667) + 309.07*(x + 1)**(-0.0833333333333333) - 1500, 0), (-oo, oo))
</code>```

I'm using Python 2.7 and SymPy 1.0
I would appreciate any help on this...

答:
I am not sure what causes the different behavior, but if you tell sympy to treat your exponents as sympy integers, then you will get the same result as with SymPy Live:

```<code>from __future__ import division
from sympy import *

init_printing()

x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)

a = Eq(309.07*(1+x)**(-1/Integer(12)) + 309.07*(1+x)**   (-2/Integer(12))+309.07*(1+x)**(-3/Integer(12)) + 309.07*(1+x)**(-4/Integer(12)) + 309.07*(1+x)**(-5/Integer(12)) + 309.07*(1+x)**(-6/Integer(12)) + 309.07*(1+x)**(-7/Integer(12)), 1500)
b = solveset(a, x, S.Reals)

print b
</code>```

As to why python integers are not treated like sympy Integers in the local install I don't know. To me it seems as if SymPy Live overrides the / operator. To clarify this behavior try

```<code>print(type(1/12))
</code>```

in your local install and in SymPy Live. The local result will be <class 'float'>, the SymPy Live result will be <class 'sympy.core.numbers.Rational'>.

ContentLicense: CC BY-SA 3.0

Body:
I have an equation I'm trying to solve. I get a proper result with SymPy live console, which is available on their website. Yet when I'm trying to reproduce the same result on my local computer, I'm getting a ConditionSet and I can't solve the equation.

The exact same equation cannot be solved locally. I'm not sure if there's maybe something wrong with the divison (but I'm importing __future__.division), the lack of LaTex libraries, or some other settings?

Here are the commands from SymPy live:

Python console for SymPy 1.0 (Python 2.7.12)

These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)

Warning: this shell runs with SymPy 1.0 and so examples pulled from other documentation may provide unexpected results.
Documentation can be found at http://docs.sympy.org/1.0.

>>> a = Eq(309.07*(1+x)**(-1/12) + 309.07*(1+x)**(-2/12)+309.07*(1+x)**(-3/12) + 309.07*(1+x)**(-4/12) + 309.07*(1+x)**(-5/12) + 309.07*(1+x)**(-6/12) + 309.07*(1+x)**(-7/12), 1500)
>>> solveset(a, x, domain=S.Reals)

Result printed in LaTex:

          {2.17102109654962}

And here the local python script:

from __future__ import division
from sympy import *

init_printing()

x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)

a = Eq(309.07*(1+x)**(-1/12) + 309.07*(1+x)**(-2/12)+309.07*(1+x)**(-3/12) + 309.07*(1+x)**(-4/12) + 309.07*(1+x)**(-5/12) + 309.07*(1+x)**(-6/12) + 309.07*(1+x)**(-7/12), 1500)
b = solveset(a, x, S.Reals)

print b

Result printed in ASCII text:

ConditionSet(x, Eq(309.07*(x + 1)**(-0.583333333333333) + 309.07*(x + 1)**(-0.5) + 309.07*(x + 1)**(-0.416666666666667) + 309.07*(x + 1)**(-0.333333333333333) + 309.07*(x + 1)**(-0.25) + 309.07*(x + 1)**(-0.166666666666667) + 309.07*(x + 1)**(-0.0833333333333333) - 1500, 0), (-oo, oo))

I'm using Python 2.7 and SymPy 1.0
I would appreciate any help on this...

Body:
I am not sure what causes the different behavior, but if you tell sympy to treat your exponents as sympy integers, then you will get the same result as with SymPy Live:

from __future__ import division
from sympy import *

init_printing()

x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)

a = Eq(309.07*(1+x)**(-1/Integer(12)) + 309.07*(1+x)**   (-2/Integer(12))+309.07*(1+x)**(-3/Integer(12)) + 309.07*(1+x)**(-4/Integer(12)) + 309.07*(1+x)**(-5/Integer(12)) + 309.07*(1+x)**(-6/Integer(12)) + 309.07*(1+x)**(-7/Integer(12)), 1500)
b = solveset(a, x, S.Reals)

print b

As to why python integers are not treated like sympy Integers in the local install I don't know. To me it seems as if SymPy Live overrides the / operator. To clarify this behavior try

print(type(1/12))

in your local install and in SymPy Live. The local result will be <class 'float'>, the SymPy Live result will be <class 'sympy.core.numbers.Rational'>.


问:
Bootstrap Navbar not rendering on Heroku (Meteor)
I am running a Meteor app on Heroku with a bootstrap Navbar. My local version runs fine however when I deploy to Heroku the Navbar doesn't render. Some people experiencing similar issues in Rails had to precompile the assets in order to solve this problem.

Has anyone come across a similar issue using Heroku/Meteor and how did you resolve it?

答: It was a Meteor issue, some helper functions were buggy. It was not a heroku / bootstrap issue.</p>


问:
Trying to form a half triangle using a for loop, nothing is printing out
This is a practice exam question I was given to study for my java exam approaching...I was given the main method and cannot change the input, only alter the two other methods and their code. I need to print out

```<code>     &
    &&
   &&&
  &&&&
 &&&&&
&&&&&&
</code>```

I think I have written my for loop wrong to create the blank spaces, I cannot seem to get this write with the main method I have been give, any ideas?

```<code>public static void main(String[] args) {
    int size = 6;
    char c = '&';
    for (int i = 1; i < size + 1; i++) {
        drawBlanks(size, size - i);
        drawChars(size, size - i, c);
        System.out.println();
    }
    System.out.println();

}

public static void drawChars(int size, int i, char c) {

    for (int j = size; j < 1; j--) {
        System.out.print(c);
    }

}

public static void drawBlanks(int size, int i) {

    for (int k = 0; k <= i; k++) {
        System.out.print(" ");
    }
}
</code>```

答:
You need to change j < 1; to j > 1;, After that your output will be,

Output:

```<code>      &&&&&
     &&&&&
    &&&&&
   &&&&&
  &&&&&
 &&&&&
</code>```

To get your expected output change j > 1 to j > i.

```<code> public static void main(String[] args) {
            int size = 6;
            char c = '&';
            for (int i = 1; i < size + 1; i++) {
                drawBlanks(size, size - i);
                drawChars(size, size - i, c);
                System.out.println();
        }
    System.out.println();

}

public static void drawChars(int size, int i, char c) {

    for (int j = size; j > i; j--) {
        System.out.print(c);
    }

}

public static void drawBlanks(int size, int i) {

    for (int k = 0; k <= i; k++) {
        System.out.print(" ");
    }
}
</code>```

Output:

```<code>      &
     &&
    &&&
   &&&&
  &&&&&
 &&&&&&
</code>```

Body:
This is a practice exam question I was given to study for my java exam approaching...I was given the main method and cannot change the input, only alter the two other methods and their code. I need to print out

     &
    &&
   &&&
  &&&&
 &&&&&
&&&&&&

I think I have written my for loop wrong to create the blank spaces, I cannot seem to get this write with the main method I have been give, any ideas?

public static void main(String[] args) {
    int size = 6;
    char c = '&';
    for (int i = 1; i < size + 1; i++) {
        drawBlanks(size, size - i);
        drawChars(size, size - i, c);
        System.out.println();
    }
    System.out.println();

}

public static void drawChars(int size, int i, char c) {

    for (int j = size; j < 1; j--) {
        System.out.print(c);
    }

}

public static void drawBlanks(int size, int i) {

    for (int k = 0; k <= i; k++) {
        System.out.print(" ");
    }
}

Body:
You need to change j < 1; to j > 1;, After that your output will be,

Output:

      &&&&&
     &&&&&
    &&&&&
   &&&&&
  &&&&&
 &&&&&

To get your expected output change j > 1 to j > i.

 public static void main(String[] args) {
            int size = 6;
            char c = '&';
            for (int i = 1; i < size + 1; i++) {
                drawBlanks(size, size - i);
                drawChars(size, size - i, c);
                System.out.println();
        }
    System.out.println();

}

public static void drawChars(int size, int i, char c) {

    for (int j = size; j > i; j--) {
        System.out.print(c);
    }

}

public static void drawBlanks(int size, int i) {

    for (int k = 0; k <= i; k++) {
        System.out.print(" ");
    }
}

Output:

      &
     &&
    &&&
   &&&&
  &&&&&
 &&&&&&


问:
How "perfect" does a database have to be?
I'm designing a website to track weight lifting and calories. I've never designed my own database before and I figured I should get is as spot on as possible before I start coding. Every time I think I'm done, I get antsy that it's not perfect. I've mostly fleshed it out in MySQL Workbench but I still have a few questions.

How important is it to make the
database "perfect" before hand? How
hard is it to re-factor a database
later?

What does the engine option do? Right
now all tables are defaulting to
InnoDB engine? Any issues with this?

Are dataypes changeable after data
entry? Maybe not going from VARCHAR
to INT, but what about VARCHAR(45) to
VARCHAR(255)?

What are basic database rules that HAVE to
be followed for a successful design?

I've also attached my ERM diagram. If anyone could point out any obvious irregularities it would be greatly appreciated.

答:
No practical, operating database is perfect.  They all have their warts.

One of the big advantages of using a database is that it can be built to withstand future change.  For example, use stored procedures for data updates and adding data.  If a table is eventually split, the stored procedure can be modified accordingly with no visible impact required for any external software.

If you wait until the design is perfect, you'll never get around to implementing anything useful.

ContentLicense: CC BY-SA 2.5


问:
prevent double click on animation but allow again
I have an fixed menu i hide and when i click the #menu-trigger , it pulls the menu out from the side of page. If i click #menu-trigger or #menu-overlay then i hide the menu again. When i single or double click the #menu-trigger , it hides the menu and runs animation one time , but when i double click the #menu-overlay it animates it twice sliding everything off the page too much.

I tried using .one click function but when i reopen the menu, i can not shut it using the overlay.

```<code>jQuery('#menu-trigger').click(function() {
    if ($(this).css('margin-right') == '250px') {
        $('#menu').animate({
            "margin-right": '-=250'
        });
        $('#menu-trigger').animate({
            'margin-right': '-=250'
        });
        $("#skinSelectorContainer").hide();
    } else {
        $('#menu').animate({
            'margin-right': '+=250'
        });
        $('#menu-trigger').animate({
            'margin-right': '+=250'
        });
    }
    $('#menu-overlay').fadeToggle();
});

jQuery('#menu-overlay').click(function() {
    $('#menu').animate({
        "margin-right": '-=250'
    });
    $('#menu-trigger').animate({
        'margin-right': '-=250'
    });
    $('#menu-overlay').fadeToggle();
});
</code>```

答:
You can use:

.stop() the currently-running animation before starting a new one

or you can test if the element is in the progress of an animation with

:animated selector

jQuery('#menu-trigger').on('click', function(e) {
  //
  // if menu is animated do nothing and return
  //
  if ($('#menu').is(':animated')) {
      console.log('animation prevented');
      return;
  }
  if ($('#menu').offset().left != 0) {
      $('#menu').animate({
          "left": 0
      }, 'slow');
  } else {
      $('#menu').animate({
          "left": ($('body').width()-$('#menu').width())
      }, 'slow');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#menu {
    width: 50px;
    height: 50px;
    position: absolute;
    right: 0;
    background: yellow;
}</code>```

<button type="button" id="menu-trigger">menu trigger</button>

```

Body:
I have an fixed menu i hide and when i click the #menu-trigger , it pulls the menu out from the side of page. If i click #menu-trigger or #menu-overlay then i hide the menu again. When i single or double click the #menu-trigger , it hides the menu and runs animation one time , but when i double click the #menu-overlay it animates it twice sliding everything off the page too much.

I tried using .one click function but when i reopen the menu, i can not shut it using the overlay.

jQuery('#menu-trigger').click(function() {
    if ($(this).css('margin-right') == '250px') {
        $('#menu').animate({
            "margin-right": '-=250'
        });
        $('#menu-trigger').animate({
            'margin-right': '-=250'
        });
        $("#skinSelectorContainer").hide();
    } else {
        $('#menu').animate({
            'margin-right': '+=250'
        });
        $('#menu-trigger').animate({
            'margin-right': '+=250'
        });
    }
    $('#menu-overlay').fadeToggle();
});

jQuery('#menu-overlay').click(function() {
    $('#menu').animate({
        "margin-right": '-=250'
    });
    $('#menu-trigger').animate({
        'margin-right': '-=250'
    });
    $('#menu-overlay').fadeToggle();
});

Body:
You can use:

.stop() the currently-running animation before starting a new one

or you can test if the element is in the progress of an animation with

:animated selector

jQuery('#menu-trigger').on('click', function(e) {
  //
  // if menu is animated do nothing and return
  //
  if ($('#menu').is(':animated')) {
      console.log('animation prevented');
      return;
  }
  if ($('#menu').offset().left != 0) {
      $('#menu').animate({
          "left": 0
      }, 'slow');
  } else {
      $('#menu').animate({
          "left": ($('body').width()-$('#menu').width())
      }, 'slow');
  }
});

#menu {
    width: 50px;
    height: 50px;
    position: absolute;
    right: 0;
    background: yellow;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button type="button" id="menu-trigger">menu trigger</button>
<div id="menu">

</div>


问:
Loop through table and extract specifics cells
I am having difficulty using jQuery to loop though a table, then extract specifics cells.

I know this can be done with .each, I don't have a code to share as example but I am trying as we speak, I am just looking for some suggestions. I will share any code I can come up with.

What would be the best way to achieve this?

Code Snippet:

      A
      Site1
      Site2
      D
      E
      F
      G
      H
      I
      J
      K
      L
      M

      Name1

      Arrival
      06/06/2017 09:30
      06/06/2017 16:00
      A
      B
      D
      E

      F
      G
      H
      I
      J

      Departure
      06/06/2017 10:00
      -
      -

      Name2

      Arrival
      06/06/2017 10:30
      06/06/2017 17:00
      A
      B
      D
      E

      F
      G
      H
      I
      J

      Departure
      06/06/2017 11:00
      -
       -

```

The result I want in array or variable:

Name1

1.Site 1 Arrival

2.Site 1 Departure

3.Site 2 Arrival

===============

Name2

1.Site 1 Arrival

2.Site 1 Departure

3.Site 2 Arrival

I know it sounds simple enough, but I am new to JavaScript so any examples/demos would be appreciated.

Note: There are no fixed values, Names keep changing and more rows are added.

答:
You can select each row with class parent and then get the following two rows using jQuery's next() function. From the docs:

Given a jQuery object that represents a set of DOM elements, the .next() method allows us to search through the immediately following sibling of these elements in the DOM tree and construct a new jQuery object from the matching elements.

Also each HTML element should have a unique id. In your code you used the id row0 for 3 different elements which is just bad practice. If such cases are needed you should uses classes instead of ids.

The below snippet creates an array containing objects that hold the requested information. The extraction of these information depends on the order of the columns (specifically, I used the :nth-child() selector to get the desired cell). If the order of the columns will change over time, please consider adding descriptive classes to each cell and select based on these classes.

var entries = [];

$("#tablemain tr.parent").each(function(){
  var child1 = $(this).next();
  var child2 = child1.next();
  var cells = {
    name: $(this).find("td:nth-child(1)").text(),
    arrival1: child1.find("td:nth-child(2)").text(),
    departure: child2.find("td:nth-child(2)").text(),
    arrival2: child1.find("td:nth-child(3)").text()
  };

  entries.push(cells);

});

console.log(entries);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tablemain" class="tableclass">
  <thead>
    <tr>
      <th>A</th>
      <th>Site1</th>
      <th>Site2</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
      <th>H</th>
      <th>I</th>
      <th>J</th>
      <th>K</th>
      <th style="width: 10%;">L</th>
      <th>M</th>
    </tr>
  </thead>
  <tbody>
    <tr id="row0" class="parent">
      <td class="radioTableDetails awarded-td-background-color">Name1</td>
      <td colspan="11"> </td>
      <td class="version-Link-Table even-td-TableDetails"> </td>
    </tr>
    <tr id="row01" class="child">
      <td class="child-row-Table-Details"><strong>Arrival</strong></td>
      <td class="even-td-TableDetails">06/06/2017 09:30</td>
      <td class="odd-td-TableDetails">06/06/2017 16:00</td>
      <td class="even-td-TableDetails">A</td>
      <td class="odd-td-TableDetails">B</td>
      <td class="even-td-TableDetails">D</td>
      <td class="odd-td-TableDetails">E</td>
      <td class="even-td-TableDetails"> </td>
      <td class="odd-td-TableDetails">F</td>
      <td class="even-td-TableDetails">G</td>
      <td class="odd-td-TableDetails">H</td>
      <td class="even-td-TableDetails diff-td-text-color">I</td>
      <td class="modify-Link-Table-Disabled odd-td-TableDetails">J</td>
    </tr>
    <tr id="row02" class="child">
      <td class="child-row-Table-Details"><strong>Departure</strong></td>
      <td class="even-td-TableDetails">06/06/2017 10:00</td>
      <td class="odd-td-TableDetails">-</td>
      <td class="even-td-TableDetails" colspan="9">-</td>
      <td> </td>
    </tr>
    <tr id="row1" class="parent">
      <td class="radioTableDetails">Name2</td>
      <td colspan="11"> </td>
      <td class="version-Link-Table even-td-TableDetails"> </td>
    </tr>
    <tr id="row11" class="child">
      <td class="child-row-Table-Details"><strong>Arrival</strong></td>
      <td class="even-td-TableDetails">06/06/2017 10:30</td>
      <td class="odd-td-TableDetails">06/06/2017 17:00</td>
      <td class="even-td-TableDetails">A</td>
      <td class="odd-td-TableDetails">B</td>
      <td class="even-td-TableDetails">D</td>
      <td class="odd-td-TableDetails">E</td>
      <td class="even-td-TableDetails"> </td>
      <td class="odd-td-TableDetails">F</td>
      <td class="even-td-TableDetails">G</td>
      <td class="odd-td-TableDetails">H</td>
      <td class="even-td-TableDetails diff-td-text-color">I</td>
      <td class="modify-Link-Table-Disabled odd-td-TableDetails">J</td>
    </tr>
    <tr id="row12" class="child">
      <td class="child-row-Table-Details"><strong>Departure</strong></td>
      <td class="even-td-TableDetails">06/06/2017 11:00</td>
      <td class="odd-td-TableDetails">-</td>
      <td class="even-td-TableDetails" colspan="9"> -</td>
      <td> </td>
    </tr>
  </tbody>
</table>
<p> </p></code>```

Body:
I am having difficulty using jQuery to loop though a table, then extract specifics cells.

I know this can be done with .each, I don't have a code to share as example but I am trying as we speak, I am just looking for some suggestions. I will share any code I can come up with.

What would be the best way to achieve this?

Code Snippet:

      A
      Site1
      Site2
      D
      E
      F
      G
      H
      I
      J
      K
      L
      M

      Name1

      Arrival
      06/06/2017 09:30
      06/06/2017 16:00
      A
      B
      D
      E

      F
      G
      H
      I
      J

      Departure
      06/06/2017 10:00
      -
      -

      Name2

      Arrival
      06/06/2017 10:30
      06/06/2017 17:00
      A
      B
      D
      E

      F
      G
      H
      I
      J

      Departure
      06/06/2017 11:00
      -
       -

The result I want in array or variable:

Name1

1.Site 1 Arrival

2.Site 1 Departure

3.Site 2 Arrival

===============

Name2

1.Site 1 Arrival

2.Site 1 Departure

3.Site 2 Arrival

I know it sounds simple enough, but I am new to JavaScript so any examples/demos would be appreciated.

Note: There are no fixed values, Names keep changing and more rows are added.

Body:
You can select each row with class parent and then get the following two rows using jQuery's next() function. From the docs:

Given a jQuery object that represents a set of DOM elements, the .next() method allows us to search through the immediately following sibling of these elements in the DOM tree and construct a new jQuery object from the matching elements.

Also each HTML element should have a unique id. In your code you used the id row0 for 3 different elements which is just bad practice. If such cases are needed you should uses classes instead of ids.

The below snippet creates an array containing objects that hold the requested information. The extraction of these information depends on the order of the columns (specifically, I used the :nth-child() selector to get the desired cell). If the order of the columns will change over time, please consider adding descriptive classes to each cell and select based on these classes.

var entries = [];

$("#tablemain tr.parent").each(function(){
  var child1 = $(this).next();
  var child2 = child1.next();
  var cells = {
    name: $(this).find("td:nth-child(1)").text(),
    arrival1: child1.find("td:nth-child(2)").text(),
    departure: child2.find("td:nth-child(2)").text(),
    arrival2: child1.find("td:nth-child(3)").text()
  };

  entries.push(cells);

});

console.log(entries);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tablemain" class="tableclass">
  <thead>
    <tr>
      <th>A</th>
      <th>Site1</th>
      <th>Site2</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
      <th>H</th>
      <th>I</th>
      <th>J</th>
      <th>K</th>
      <th style="width: 10%;">L</th>
      <th>M</th>
    </tr>
  </thead>
  <tbody>
    <tr id="row0" class="parent">
      <td class="radioTableDetails awarded-td-background-color">Name1</td>
      <td colspan="11">&nbsp;</td>
      <td class="version-Link-Table even-td-TableDetails">&nbsp;</td>
    </tr>
    <tr id="row01" class="child">
      <td class="child-row-Table-Details"><strong>Arrival</strong></td>
      <td class="even-td-TableDetails">06/06/2017 09:30</td>
      <td class="odd-td-TableDetails">06/06/2017 16:00</td>
      <td class="even-td-TableDetails">A</td>
      <td class="odd-td-TableDetails">B</td>
      <td class="even-td-TableDetails">D</td>
      <td class="odd-td-TableDetails">E</td>
      <td class="even-td-TableDetails">&nbsp;</td>
      <td class="odd-td-TableDetails">F</td>
      <td class="even-td-TableDetails">G</td>
      <td class="odd-td-TableDetails">H</td>
      <td class="even-td-TableDetails diff-td-text-color">I</td>
      <td class="modify-Link-Table-Disabled odd-td-TableDetails">J</td>
    </tr>
    <tr id="row02" class="child">
      <td class="child-row-Table-Details"><strong>Departure</strong></td>
      <td class="even-td-TableDetails">06/06/2017 10:00</td>
      <td class="odd-td-TableDetails">-</td>
      <td class="even-td-TableDetails" colspan="9">-</td>
      <td>&nbsp;</td>
    </tr>
    <tr id="row1" class="parent">
      <td class="radioTableDetails">Name2</td>
      <td colspan="11">&nbsp;</td>
      <td class="version-Link-Table even-td-TableDetails">&nbsp;</td>
    </tr>
    <tr id="row11" class="child">
      <td class="child-row-Table-Details"><strong>Arrival</strong></td>
      <td class="even-td-TableDetails">06/06/2017 10:30</td>
      <td class="odd-td-TableDetails">06/06/2017 17:00</td>
      <td class="even-td-TableDetails">A</td>
      <td class="odd-td-TableDetails">B</td>
      <td class="even-td-TableDetails">D</td>
      <td class="odd-td-TableDetails">E</td>
      <td class="even-td-TableDetails">&nbsp;</td>
      <td class="odd-td-TableDetails">F</td>
      <td class="even-td-TableDetails">G</td>
      <td class="odd-td-TableDetails">H</td>
      <td class="even-td-TableDetails diff-td-text-color">I</td>
      <td class="modify-Link-Table-Disabled odd-td-TableDetails">J</td>
    </tr>
    <tr id="row12" class="child">
      <td class="child-row-Table-Details"><strong>Departure</strong></td>
      <td class="even-td-TableDetails">06/06/2017 11:00</td>
      <td class="odd-td-TableDetails">-</td>
      <td class="even-td-TableDetails" colspan="9">&nbsp;-</td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table>
<p>&nbsp;</p>


问:
Why is x^0 = x?
I have a very simple question.

Why is a number when XOR'ed with 0 gives the number itself.

Can someone please give the proof using an example.

Lets say I have the number 5

5^0==>

I think the answer should be just the last bit of 5 XOR'ed with 0, but the answer is still 5.

答:
Bit-wise operations operates on set of bits in number - not just on last bit.
So if you perform some bit-wise operation on 32-bit integer, then all 32 bits are affected. So integer 5 is 0.....0000101 (32 bits). If you need just the resulting last bit after xor operation apply binary AND with 1:

```

Title: Why is x^0 = x?

Body:
Bit-wise operations operates on set of bits in number - not just on last bit.
So if you perform some bit-wise operation on 32-bit integer, then all 32 bits are affected. So integer 5 is 0.....0000101 (32 bits). If you need just the resulting last bit after xor operation apply binary AND with 1:

<script>
console.log("%i\n",(5^0)&1);
console.log("%i\n",(6^0)&1);
</script>


问:
Classify users by colors?
I have a list of users. In this list, each user represented as an object that has some properties. One of this property is color. So, each user has some color. For example, the color of one user is #f5abb5 and the color of the second user is #f5abbb. Both of them are the pink colors.

I need to classify my users by colors that they choose. These colors stored as hex codes. So, I think maybe Python has some tools that help to understand colors and say that #f5abb5 and #f5abbb are pink colors? I found colour library but there is no way to understand colors like I need.

Another one way (not so good) that in a RGB color space, hex #f5abb5 is composed of 96.1% red, 67.1% green and 71% blue. That means that red is main here and I can divide users like that. But the first way to understand that both colors are pink (or other colors are sky blue, and so on) is much better.

答:
Take a look at webcolors.

There's a function hex_to_name which meets your need perfectly.

```<code>>>> hex_to_name(u'#ffffff')
u'white'
>>> hex_to_name(u'#fff')
u'white'
>>> hex_to_name(u'#000080')
u'navy'
>>> hex_to_name(u'#daa520')
u'goldenrod'
</code>```

Edit:

Take care of the unmatched colors.

```<code>import webcolors as wc
import numpy as np

def get_approx_color(hex_color):
    orig = wc.hex_to_rgb(hex_color)
    similarity = {}
    for hex_code, color_name in wc.css3_hex_to_names.items():
        approx = wc.hex_to_rgb(hex_code)
        similarity[color_name] = sum(np.subtract(orig, approx) ** 2)
    return min(similarity, key=similarity.get)

def get_color_name(hex_color):
    try:
        return wc.hex_to_name(hex_color)
    except ValueError:
        return get_approx_color(hex_color)

print(get_color_name(u"#F5ABB5"))
# lightpink
</code>```

Title: Classify users by colors?

Body:
Take a look at webcolors.

There's a function hex_to_name which meets your need perfectly.

>>> hex_to_name(u'#ffffff')
u'white'
>>> hex_to_name(u'#fff')
u'white'
>>> hex_to_name(u'#000080')
u'navy'
>>> hex_to_name(u'#daa520')
u'goldenrod'

Edit:

Take care of the unmatched colors.

import webcolors as wc
import numpy as np

def get_approx_color(hex_color):
    orig = wc.hex_to_rgb(hex_color)
    similarity = {}
    for hex_code, color_name in wc.css3_hex_to_names.items():
        approx = wc.hex_to_rgb(hex_code)
        similarity[color_name] = sum(np.subtract(orig, approx) ** 2)
    return min(similarity, key=similarity.get)

def get_color_name(hex_color):
    try:
        return wc.hex_to_name(hex_color)
    except ValueError:
        return get_approx_color(hex_color)

print(get_color_name(u"#F5ABB5"))
# lightpink


问:
Wordpress responsive horizontal menu with more link
How to convert this awesome menu to wordpress.

Menu demo link.

答:
Wordpress has its own default feature to display a menu with using wp_nav_menu function.

You can create a menu from WordPress backend and call it using this function so your menu will be dynamically and you can set the last menu with label ... and select as a custom link with # then you can add another sub child under this menu as well.

You can apply same CSS to this menu also to look same as you want.

I hope this will be helpful for you.

Thanks.


问:
How to pass function property to child / grandchild through map function? (and delete item from state)
I've made a simple react tasklist, which allows me to add new tasks. I now want to be able to remove tasks, but cant see how to pass a function property down to a child / grandchild component.

I'm wanting to pass the deleteTaskFromState function property down to the <Task /> component. I've successfully done this with the addTaskToState function, but cant see how to do it with the deleteTaskFromState function prop.

Codepen here

On line 108 I've pass deleteTaskFromState to the <TaskList /> component, but when I put deleteTask={this.props.deleteTaskFromState} on the <Task /> component (line 57) it errors with Cannot read property 'props' of undefined.

If anyone can help I'd be hugely grateful!

After this property is passed I need to then complete the function prop deleteTaskFromState to remove the selected task from state, if anyone know how to do that too, that would be great!

```<code>// function to generate unique id for react keys - use npm uuid usually
function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4()
    // + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

class TaskInput extends React.Component {
    createTask(event){
        event.preventDefault();
        let task = {
            key: guid(),
            task : this.refs.task.value,
            priority : this.refs.priority.value,
        }
        this.props.addTaskToState(task);
        this.refs.addTaskForm.reset();
    }

    render() {
        return (
            <form onSubmit={this.createTask.bind(this)} ref="addTaskForm">
                <input placeholder="enter a task" ref="task" />
                <input placeholder="priority" ref="priority" />
                <button type="submit">Submit</button>
            </form>
        );
    }
}

class Task extends React.Component {
    render() {
        return (
            <div>
                <li className="task"><button>x</button>
                <strong> {this.props.taskdata.priority} </strong>
                {this.props.taskdata.task}</li>
            </div>
        );
    }
}

class TaskList extends React.Component {
    render() {
        if(this.props.deleteTaskFromState) {
            console.log('deleteTaskFromState found')
        }

         let TaskItems;
         if(this.props.taskstate){
            TaskItems = this.props.taskstate.map(function (taskdata)  {
                return (
                    <Task taskdata={taskdata} key={taskdata.key}/>
                );
            });
         }

        return (
            <ul className="task-list">
                {TaskItems}
            </ul>
        );
    }
}

class TaskListApp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tasks : [
            {
                key: "task1",
                task: "dance",
                priority: "superhigh",
              },
            {
                key: "task2",
                task: "tax return",
                priority: "superlow",
            }
            ]
        };
    }

    deleteTaskFromState(keyToDelete) {
        let tasks = this.state.tasks;
        // find object in state array with keyToDelete
        // remove object
    }

    addTaskToState(task) {
        let tasks = this.state.tasks;
        tasks.push(task);
        this.setState({tasks:tasks});
    }

    render() {
        return (
            <div>
                <h1>Task List</h1>
                <TaskInput addTaskToState={this.addTaskToState.bind(this)} />
                <TaskList
                    taskstate={this.state.tasks}
                    deleteTaskFromState={this.deleteTaskFromState.bind(this)}
                    />
            </div>
        );
    }
}

ReactDOM.render(<TaskListApp />, document.getElementById("app"));
</code>```

答:
All you have to do just pass deleteTaskFromState

to child/grandchild like you did with addTaskToState

CodePen

```<code>class Task extends React.Component {
    deleteTask() {
     this.props.deleteTaskFromState(this.props.taskdata.key)
   }

    render() {
        return (
            <div>
                <li className="task"><button onClick={this.deleteTask.bind(this)}>x</button>
                <strong> {this.props.taskdata.priority} </strong>
                {this.props.taskdata.task}</li>
            </div>
        );
    }
}

class TaskList extends React.Component {
    render() {
        if(this.props.deleteTaskFromState) {
            console.log('deleteTaskFromState found')
        }

         let TaskItems;
         if(this.props.taskstate){
       let deleteTaskFromState = this.props.deleteTaskFromState;
            TaskItems = this.props.taskstate.map(function (taskdata)  {
                return (
                    <Task
   taskdata={taskdata}
   key={taskdata.key}
   deleteTaskFromState={deleteTaskFromState} />
                );
            });
         }

        return (
            <ul className="task-list">
                {TaskItems}
            </ul>
        );
    }
}
</code>```

Body:
I've made a simple react tasklist, which allows me to add new tasks. I now want to be able to remove tasks, but cant see how to pass a function property down to a child / grandchild component.

I'm wanting to pass the deleteTaskFromState function property down to the <Task /> component. I've successfully done this with the addTaskToState function, but cant see how to do it with the deleteTaskFromState function prop.

Codepen here

On line 108 I've pass deleteTaskFromState to the <TaskList /> component, but when I put deleteTask={this.props.deleteTaskFromState} on the <Task /> component (line 57) it errors with Cannot read property 'props' of undefined.

If anyone can help I'd be hugely grateful!

After this property is passed I need to then complete the function prop deleteTaskFromState to remove the selected task from state, if anyone know how to do that too, that would be great!

// function to generate unique id for react keys - use npm uuid usually
function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4()
    // + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
}

class TaskInput extends React.Component {
    createTask(event){
        event.preventDefault();
        let task = {
            key: guid(),
            task : this.refs.task.value,
            priority : this.refs.priority.value,
        }
        this.props.addTaskToState(task);
        this.refs.addTaskForm.reset();
    }

    render() {
        return (
            <form onSubmit={this.createTask.bind(this)} ref="addTaskForm">
                <input placeholder="enter a task" ref="task" />
                <input placeholder="priority" ref="priority" />
                <button type="submit">Submit</button>
            </form>
        );
    }
}

class Task extends React.Component {
    render() {
        return (

<button>x</button>
                 {this.props.taskdata.priority}
                {this.props.taskdata.task}

        );
    }
}

class TaskList extends React.Component {
    render() {
        if(this.props.deleteTaskFromState) {
            console.log('deleteTaskFromState found')
        }

         let TaskItems;
         if(this.props.taskstate){
            TaskItems = this.props.taskstate.map(function (taskdata)  {
                return (
                    <Task taskdata={taskdata} key={taskdata.key}/>
                );
            });
         }

        return (

                {TaskItems}

        );
    }
}

class TaskListApp extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tasks : [
            {
                key: "task1",
                task: "dance",
                priority: "superhigh",
              },
            {
                key: "task2",
                task: "tax return",
                priority: "superlow",
            }
            ]
        };
    }

    deleteTaskFromState(keyToDelete) {
        let tasks = this.state.tasks;
        // find object in state array with keyToDelete
        // remove object
    }

    addTaskToState(task) {
        let tasks = this.state.tasks;
        tasks.push(task);
        this.setState({tasks:tasks});
    }

    render() {
        return (

Task List

                <TaskInput addTaskToState={this.addTaskToState.bind(this)} />
                <TaskList
                    taskstate={this.state.tasks}
                    deleteTaskFromState={this.deleteTaskFromState.bind(this)}
                    />

        );
    }
}

ReactDOM.render(<TaskListApp />, document.getElementById("app"));

Body:
All you have to do just pass deleteTaskFromState

to child/grandchild like you did with addTaskToState

CodePen

class Task extends React.Component {
    deleteTask() {
     this.props.deleteTaskFromState(this.props.taskdata.key)
   }

    render() {
        return (
            <div>
                <li className="task"><button onClick={this.deleteTask.bind(this)}>x</button>
                <strong> {this.props.taskdata.priority} </strong>
                {this.props.taskdata.task}</li>
            </div>
        );
    }
}

class TaskList extends React.Component {
    render() {
        if(this.props.deleteTaskFromState) {
            console.log('deleteTaskFromState found')
        }

         let TaskItems;
         if(this.props.taskstate){
       let deleteTaskFromState = this.props.deleteTaskFromState;
            TaskItems = this.props.taskstate.map(function (taskdata)  {
                return (
                    <Task
   taskdata={taskdata}
   key={taskdata.key}
   deleteTaskFromState={deleteTaskFromState} />
                );
            });
         }

        return (
            <ul className="task-list">
                {TaskItems}
            </ul>
        );
    }
}


答:
In general, try to get your entities worked out, but adding fields, indexes, etc. after the fact is no big deal.  Refactoring entities to support different cardinalities is somewhat more involved.

At a glance, a couple things pop out...
1. All those numbered fields in your exercise table.  HUGE red flag.  I would refactor this right away.
2. badges->userbadges.  Even if you're enforcing a unique constraint on name, I would still make a new PK for that table (an id).
3. I would also take some time to normalize the naming of your id fields (i.e. in User, you use 'userid' but in food, you use 'id' instead of 'foodid').  Which way you go is a matter of choice but do try to be consistent.

Title: How "perfect" does a database have to be?

Body:
I'm designing a website to track weight lifting and calories. I've never designed my own database before and I figured I should get is as spot on as possible before I start coding. Every time I think I'm done, I get antsy that it's not perfect. I've mostly fleshed it out in MySQL Workbench but I still have a few questions.

How important is it to make the
database "perfect" before hand? How
hard is it to re-factor a database
later?

What does the engine option do? Right
now all tables are defaulting to
InnoDB engine? Any issues with this?

Are dataypes changeable after data
entry? Maybe not going from VARCHAR
to INT, but what about VARCHAR(45) to
VARCHAR(255)?

What are basic database rules that HAVE to
be followed for a successful design?

I've also attached my ERM diagram. If anyone could point out any obvious irregularities it would be greatly appreciated.


问:
JSON string fails to convert to correct Lua table
I'm performing a request to a foreign API using luasec, lua-socket and converting the data, a JSON string, to a lua table with cjson. I've read the docs of said modules and unfortunately none of it helped me with my problem. Can't link more than 2 websites with current account, sorry.

Summary: I get the response and the appropiate string using the posted request function, when turning said string into a lua table via cjson.decode the output table isn't the desired one, it's a copy of my response header, which is not intentional.

The following code is how I do my request:

```<code>local function request (req_t)
  local res_t = {}

  resp = https.request {
    url = const.API_URL .. req_t.url,
    method = req_t.method,
    headers = req_t.headers,
    sink = ltn12.sink.table(res_t)
  }

  return table.concat(res_t), resp.headers, resp.code
end
</code>```

Using the following call

```<code>local res, headers = request({ ... })
</code>```

I receive the proper response as a string but my goal is to do data manipulation with it, so turning said response(string) to a lua table with

```<code>local resJson = cjson.decode(res)
</code>```

Does not produce the correct output. It does produce a table which is exactly the same as my response header. Here is the following output from my terminal alongside the code

```<code>When out of function type is: string

Desired response in string:
{"total_photos":221926,"photo_downloads":"186029632.0"}

When out of function type is: string

Desired response in string:
{"total_photos":221926,"photo_downloads":"186029632.0"}

After decode, type is: table

server  Cowboy
strict-transport-security   max-age=31536000
access-control-allow-headers    *
x-ratelimit-limit   50
x-ratelimit-remaining   46
x-cache-hits    0, 0
accept-ranges   bytes
access-control-request-method   *
x-request-id    ee5a74fd-2b10-4f46-9c25-5cfc53aeac6c
access-control-expose-headers   Link,X-Total,X-Per-Page,X-RateLimit-Limit,X-RateLimit-Remaining
content-type    application/json
connection  close
content-length  55
fastly-debug-digest f62d52c08b1ef74db89a66a0069f0a35c49e52230567905240dacf08c9ea1813
vary    Origin
cache-control   no-cache, no-store, must-revalidate
x-timer S1496524765.369880,VS0,VE111
x-cache MISS, MISS
x-served-by cache-iad2123-IAD, cache-mad9429-MAD
via 1.1 vegur, 1.1 varnish, 1.1 varnish
date    Sat, 03 Jun 2017 21:19:25 GMT
age 0
access-control-allow-origin *
x-runtime   0.011667

Printing header

server  Cowboy
strict-transport-security   max-age=31536000
access-control-allow-headers    *
x-ratelimit-limit   50
x-ratelimit-remaining   46
x-cache-hits    0, 0
accept-ranges   bytes
access-control-request-method   *
x-request-id    ee5a74fd-2b10-4f46-9c25-5cfc53aeac6c
access-control-expose-headers   Link,X-Total,X-Per-Page,X-RateLimit-Limit,X-RateLimit-Remaining
content-type    application/json
connection  close
content-length  55
fastly-debug-digest f62d52c08b1ef74db89a66a0069f0a35c49e52230567905240dacf08c9ea1813
vary    Origin
cache-control   no-cache, no-store, must-revalidate
x-timer S1496524765.369880,VS0,VE111
x-cache MISS, MISS
x-served-by cache-iad2123-IAD, cache-mad9429-MAD
via 1.1 vegur, 1.1 varnish, 1.1 varnish
date    Sat, 03 Jun 2017 21:19:25 GMT
age 0
access-control-allow-origin *
x-runtime   0.011667
</code>```

Function that produces said log

```<code>local res, headers = request({ ... })

print('When out of function type is: ' ..type(res) .. '\n')
print('Desired response in string:')
print(res .. '\n')
resJson = cjson.decode(res)
print('\nAfter decode, type is: ' .. type(resJson) .. '\n')
pTable(resJson)
print('\nPrinting header\n')
pTable(headers)
</code>```

pTable is just a function to output a table to stdout.

Thanks in advance

答: Posted function and routines are correct. The problem was located in my print table function, which I somehow had hardcoded my headers.</p>

Body:
I'm performing a request to a foreign API using luasec, lua-socket and converting the data, a JSON string, to a lua table with cjson. I've read the docs of said modules and unfortunately none of it helped me with my problem. Can't link more than 2 websites with current account, sorry.

Summary: I get the response and the appropiate string using the posted request function, when turning said string into a lua table via cjson.decode the output table isn't the desired one, it's a copy of my response header, which is not intentional.

The following code is how I do my request:

local function request (req_t)
  local res_t = {}

  resp = https.request {
    url = const.API_URL .. req_t.url,
    method = req_t.method,
    headers = req_t.headers,
    sink = ltn12.sink.table(res_t)
  }

  return table.concat(res_t), resp.headers, resp.code
end

Using the following call

local res, headers = request({ ... })

I receive the proper response as a string but my goal is to do data manipulation with it, so turning said response(string) to a lua table with

local resJson = cjson.decode(res)

Does not produce the correct output. It does produce a table which is exactly the same as my response header. Here is the following output from my terminal alongside the code

When out of function type is: string

Desired response in string:
{"total_photos":221926,"photo_downloads":"186029632.0"}

When out of function type is: string

Desired response in string:
{"total_photos":221926,"photo_downloads":"186029632.0"}

After decode, type is: table

server  Cowboy
strict-transport-security   max-age=31536000
access-control-allow-headers    *
x-ratelimit-limit   50
x-ratelimit-remaining   46
x-cache-hits    0, 0
accept-ranges   bytes
access-control-request-method   *
x-request-id    ee5a74fd-2b10-4f46-9c25-5cfc53aeac6c
access-control-expose-headers   Link,X-Total,X-Per-Page,X-RateLimit-Limit,X-RateLimit-Remaining
content-type    application/json
connection  close
content-length  55
fastly-debug-digest f62d52c08b1ef74db89a66a0069f0a35c49e52230567905240dacf08c9ea1813
vary    Origin
cache-control   no-cache, no-store, must-revalidate
x-timer S1496524765.369880,VS0,VE111
x-cache MISS, MISS
x-served-by cache-iad2123-IAD, cache-mad9429-MAD
via 1.1 vegur, 1.1 varnish, 1.1 varnish
date    Sat, 03 Jun 2017 21:19:25 GMT
age 0
access-control-allow-origin *
x-runtime   0.011667

Printing header

server  Cowboy
strict-transport-security   max-age=31536000
access-control-allow-headers    *
x-ratelimit-limit   50
x-ratelimit-remaining   46
x-cache-hits    0, 0
accept-ranges   bytes
access-control-request-method   *
x-request-id    ee5a74fd-2b10-4f46-9c25-5cfc53aeac6c
access-control-expose-headers   Link,X-Total,X-Per-Page,X-RateLimit-Limit,X-RateLimit-Remaining
content-type    application/json
connection  close
content-length  55
fastly-debug-digest f62d52c08b1ef74db89a66a0069f0a35c49e52230567905240dacf08c9ea1813
vary    Origin
cache-control   no-cache, no-store, must-revalidate
x-timer S1496524765.369880,VS0,VE111
x-cache MISS, MISS
x-served-by cache-iad2123-IAD, cache-mad9429-MAD
via 1.1 vegur, 1.1 varnish, 1.1 varnish
date    Sat, 03 Jun 2017 21:19:25 GMT
age 0
access-control-allow-origin *
x-runtime   0.011667

Function that produces said log

local res, headers = request({ ... })

print('When out of function type is: ' ..type(res) .. '\n')
print('Desired response in string:')
print(res .. '\n')
resJson = cjson.decode(res)
print('\nAfter decode, type is: ' .. type(resJson) .. '\n')
pTable(resJson)
print('\nPrinting header\n')
pTable(headers)

pTable is just a function to output a table to stdout.

Thanks in advance


问:
Create a program that calculates the square root of a number without using Math.sqrt
This is the formula that can be used to calculate the square root of a number.

```<code>result=(guess+(number/guess))/2;
</code>```

For example, I need to get the square root of 9. First, I need to make a guess. For this one, it's 6. Although, I know that the square root of 9 is 3, I chose 6 to show how the program should work.

that makes...

```<code>result=(6+(9/6))/2 which is equal to 3.75.
</code>```

To get the actual square root of 9, I need to make the result the new guess.The program should continue as...

```<code>result=(3.75+(9/3.75))/2 which is equal to 3.075.
</code>```

This process should continue till difference between result and the result after it is equal to 0. For example

```<code>result=(3+(9/3))/2 is always equal to 3.
</code>```

When the value of result is passed to guess, the next result will also be 3. That means 3 is the square root of nine.

Here's my code:

```<code>package javaPackage;

public class SquareRoot {

    public static void main(String[] args) {
        calcRoot();
    }

    public static void calcRoot(){
        double num=9;
        double guess=6;
        double result=0;

        while(Math.abs(guess-ans)!=0){
            result=(guess+(num/guess))/2;
            guess=result;
        }
    System.out.print(result);
    }
}
</code>```

Output

```<code>3.75
</code>```

My problem is I can't compare the value of result and the previous result. Since guess is equal to result, the program immediately since guess and result are already equal. How can I fix it?

答:
Just create another variable to store the value of the previous guess.
This is the code:</p>

```<code>package javaPackage;

public class SquareRoot {

    public static void main(String[] args) {
        calcRoot();
    }

    public static void calcRoot(){
        double num=9;
        double guess=6;
        double prevGuess=0;
        double result=0;

        while(Math.abs(guess-prevGuess)!=0){
            result=(guess+(num/guess))/2;
            prevGuess = guess;
            guess=result;
        }
        System.out.print(result);
    }
}
</code>```

Body:
This is the formula that can be used to calculate the square root of a number.

result=(guess+(number/guess))/2;

For example, I need to get the square root of 9. First, I need to make a guess. For this one, it's 6. Although, I know that the square root of 9 is 3, I chose 6 to show how the program should work.

that makes...

result=(6+(9/6))/2 which is equal to 3.75.

To get the actual square root of 9, I need to make the result the new guess.The program should continue as...

result=(3.75+(9/3.75))/2 which is equal to 3.075.

This process should continue till difference between result and the result after it is equal to 0. For example

result=(3+(9/3))/2 is always equal to 3.

When the value of result is passed to guess, the next result will also be 3. That means 3 is the square root of nine.

Here's my code:

package javaPackage;

public class SquareRoot {

    public static void main(String[] args) {
        calcRoot();
    }

    public static void calcRoot(){
        double num=9;
        double guess=6;
        double result=0;

        while(Math.abs(guess-ans)!=0){
            result=(guess+(num/guess))/2;
            guess=result;
        }
    System.out.print(result);
    }
}

Output

3.75

My problem is I can't compare the value of result and the previous result. Since guess is equal to result, the program immediately since guess and result are already equal. How can I fix it?

Body:
Just create another variable to store the value of the previous guess.
This is the code:

package javaPackage;

public class SquareRoot {

    public static void main(String[] args) {
        calcRoot();
    }

    public static void calcRoot(){
        double num=9;
        double guess=6;
        double prevGuess=0;
        double result=0;

        while(Math.abs(guess-prevGuess)!=0){
            result=(guess+(num/guess))/2;
            prevGuess = guess;
            guess=result;
        }
        System.out.print(result);
    }
}


问:
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column 'column_name'
I am using Java JDBC with MySQL and I get this error:

```<code>com.mysql.jdbc.MysqlDataTruncation: Data truncation:
Data too long for column 'column_name'
</code>```

How do I remedy this error?

答:
I faced the same issue in my Spring Boot Data JPA application when I was going to insert an image file in the database as bytes - it gave me the same error.

After many R&D I found a solution like below.

I added the following line in my application.properties file and it resolved the issue:

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/conweb?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false
</code>```

Hope it will be helpful to someone.

Body:
I am using Java JDBC with MySQL and I get this error:

com.mysql.jdbc.MysqlDataTruncation: Data truncation:
Data too long for column 'column_name'

How do I remedy this error?

Body:
I faced the same issue in my Spring Boot Data JPA application when I was going to insert an image file in the database as bytes - it gave me the same error.

After many R&D I found a solution like below.

I added the following line in my application.properties file and it resolved the issue:

spring.datasource.url=jdbc:mysql://localhost:3306/conweb?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false

Hope it will be helpful to someone.

ContentLicense: CC BY-SA 4.0


问:
Adding delay on loading each row in HTML table
I am loading data of HTML table dynamically from Jquery.

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

    for (var i = 0; i < StudentsList.length; i++) {
        LoadRow(StudentsList[i]);
    }

});
function LoadRow(student) {
        setTimeout(function (student) {
         $("#tbl tbody").append("<tr class='trStyleSummary'><td>" + student.Name + "</td></tr>");
         }, 1000);
}
</code>```

I want the table to load rows one by one with delay.

How do I do that? I tried SetTimeout with 1sec, But for some reason, its not working. The table is loading entirely after 1 second.

答:
Should try this way</p>

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

function LoadRow(list) {
    if(list != undefined || list.length < 1) {
        // done
        // do something else
        return;
    }

    // Get first item
    const student = list.shift();

    $("#tbl tbody").append(`<tr class='trStyleSummary'>td>${student.Name}</td></tr>`);
    setTimeout(function (student) {
        // Recall the function after 0.15 second
        LoadRow(list);
     }, 150);
}
</code>```

Body:
I am loading data of HTML table dynamically from Jquery.

$(document).ready(function () {

    for (var i = 0; i < StudentsList.length; i++) {
        LoadRow(StudentsList[i]);
    }

});
function LoadRow(student) {
        setTimeout(function (student) {
         $("#tbl tbody").append("
" + student.Name + "
");
         }, 1000);
}

I want the table to load rows one by one with delay.

How do I do that? I tried SetTimeout with 1sec, But for some reason, its not working. The table is loading entirely after 1 second.

Body:
Should try this way

$(document).ready(function () {
    LoadRow(StudentsList);
});

function LoadRow(list) {
    if(list != undefined || list.length < 1) {
        // done
        // do something else
        return;
    }

    // Get first item
    const student = list.shift();

    $("#tbl tbody").append(`<tr class='trStyleSummary'>td>${student.Name}</td></tr>`);
    setTimeout(function (student) {
        // Recall the function after 0.15 second
        LoadRow(list);
     }, 150);
}


问:
EC2 Can't resize volume after increasing size
I have followed the steps for resizing an EC2 volume

Stopped the instance

Took a snapshot of the current volume

Created a new volume out of the previous snapshot with a bigger size in the same region

Deattached the old volume from the instance

Attached the new volume to the instance at the same mount point

Old volume was 5GB and the one I created is 100GB
Now, when i restart the instance and run df -h I still see this

```<code>Filesystem            Size  Used Avail Use% Mounted on
/dev/xvde1            4.7G  3.5G 1021M  78% /
tmpfs                 296M     0  296M   0% /dev/shm
</code>```

This is what I get when running

```<code>sudo resize2fs /dev/xvde1

The filesystem is already 1247037 blocks long.  Nothing to do!
</code>```

If I run cat /proc/partitions I see

```<code> 202       64  104857600 xvde
 202       65    4988151 xvde1
 202       66     249007 xvde2
</code>```

From what I understand if I have followed the right steps xvde should have the same data as xvde1 but I don't know how to use it

How can I use the new volume or umount xvde1 and mount xvde instead?

I cannot understand what I am doing wrong

I also tried sudo ifs_growfs /dev/xvde1

```<code>xfs_growfs: /dev/xvde1 is not a mounted XFS filesystem
</code>```

By the way, this a linux box with centos 6.2 x86_64

答:
Prefect comment by jperelli above.

I faced same issue today. AWS documentation does not clearly mention growpart. I figured out the hard way and indeed the two commands worked perfectly on M4.large & M4.xlarge with Ubuntu

```<code>sudo growpart /dev/xvda 1
sudo resize2fs /dev/xvda1
</code>```

Body:
I have followed the steps for resizing an EC2 volume

Stopped the instance

Took a snapshot of the current volume

Created a new volume out of the previous snapshot with a bigger size in the same region

Deattached the old volume from the instance

Attached the new volume to the instance at the same mount point

Old volume was 5GB and the one I created is 100GB
Now, when i restart the instance and run df -h I still see this

Filesystem            Size  Used Avail Use% Mounted on
/dev/xvde1            4.7G  3.5G 1021M  78% /
tmpfs                 296M     0  296M   0% /dev/shm

This is what I get when running

sudo resize2fs /dev/xvde1

The filesystem is already 1247037 blocks long.  Nothing to do!

If I run cat /proc/partitions I see

 202       64  104857600 xvde
 202       65    4988151 xvde1
 202       66     249007 xvde2

From what I understand if I have followed the right steps xvde should have the same data as xvde1 but I don't know how to use it

How can I use the new volume or umount xvde1 and mount xvde instead?

I cannot understand what I am doing wrong

I also tried sudo ifs_growfs /dev/xvde1

xfs_growfs: /dev/xvde1 is not a mounted XFS filesystem

By the way, this a linux box with centos 6.2 x86_64

Body:
Prefect comment by jperelli above.

I faced same issue today. AWS documentation does not clearly mention growpart. I figured out the hard way and indeed the two commands worked perfectly on M4.large & M4.xlarge with Ubuntu

sudo growpart /dev/xvda 1
sudo resize2fs /dev/xvda1


问:
What could cause a VB.NET application to crash before running any code?
My VB.NET application compiles, installs and works fine on the development PC.

However, when I take the install package elsewhere, it installs ok but crashes before any code is executed.

The error is " has encountered a problem and needs to close..."

I have removed all references to external files e.g. icon files etc.

I have only one local dll and the reference seems ok.

What other issues could cause this problem?

Thanks!
Jon

Update: On 1 PC, re-installing MDAC has solved the issue. However most client's are XP, and so this is not going to help.

I am still receiving the same error on some Windows XP laptops.

答:
Could you be targeting a higher version of the .NET platform than is installed on other machines?
 You can check the target framework of your project (VS.2008) in "My Project" in the complile tab. Click Advanced Compile Options...

At the bottom of the Advanced Compiler Setting dialog there will be a drop down list with each framework.

On the client machine you can check .NET version in the "programs and features" control panel (Vista) or "Add & Remove programs" in XP

OwnerDisplayName: Tom Willwerth


问:
Set up cookie for the component in react.js
I have read this article How can I do to set cookie in the react code? about setting up cookie in reactjs code, however, I cannot use any library, what I can use is just the javascrip.
Now, what I want to achieve is to show up a welcome box for the first time visit.
What I have done and tested are: 1.the welcome box, it is a component coding in jsx; 2. the cookie coding in js. Both sub-part are tested working, however, when I tried to combine these two part into a single component, it is not working.

var Child = React.createClass({
  render: function() {
    return (

Welcome to our website

         <button onClick={this.props.onClick}>Click me to close</button>

    );
  }
});

var ShowHide = React.createClass({
createCookie(name,value,days) {
 if (days) {
  var date = new Date();
  date.setTime(date.getTime()+(days*24*60*60*1000));
  var expires = "; expires="+date.toGMTString();
 }
 else var expires = "";
 document.cookie = name+"="+value+expires+"; path=/";
},

readCookie(name) {
 var nameEQ = name + "=";
 var ca = document.cookie.split(';');
 for(var i=0;i < ca.length;i++) {
  var c = ca[i];
  while (c.charAt(0)==' ') c = c.substring(1,c.length);
  if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
 }
 return "";
},

eraseCookie(name) {
 createCookie(name,"",-1);
},

firstVisit() {
  var isFirstVisit;
 var result = readCookie('firstVisit');
    if (result == "") {
        createCookie('firstVisit', 'true', 365);
        isFirstVisit = true;
  return isFirstVisit;
    }
    else {
  isFirstVisit = false;
  return isFirstVisit;
 }
},

getInitialState: function () {
    if(firstVisit()) {
      return { childVisible: true };
    }
    else
    {
      return { childVisible: true };
    }
},

onClick: function() {
  this.setState({childVisible: !this.state.childVisible});
},

  render: function() {
    return(

        {
          this.state.childVisible
            ? <Child onClick={this.onClick} />
            : null
        }

    )
  },
});

React.render(<ShowHide />, document.getElementById('container'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script></code>```

答:
Alternatively to cookies you could use localStorage. Here's a basic example of that. It sets an item in the storage once the main component is mounted and reacts to that item in the render() method.

```<code>componentDidMount() {
  // Get item from localStorage and save it to a constant.
  const hasVisitedBefore = localStorage.getItem('hasVisitedBefore');

  // Check if the user has visited the site (component) before.
  if (!hasVisitedBefore) {
    // If not, set the component state (or dispatch an action if you need)
    // Also set the localStorage so it's globally accessible.
    this.setState({ hasVisitedBefore: false });
    localStorage.setItem('hasVisitedBefore', true);
  }
}

// Based on the state set in `componentDidMount()`, show or hide the welcome modal.
render() {
  return (
    <div>
      {this.state.hasVisitedBefore
        ? 'Welcome back!'
        : 'Welcome for the first time!'}
    </div>
  );
}
</code>```

Working demo on JSFiddle.

In other components you could then just check for localStorage.getItem('hasVisitedBefore') and render things based on that.

Body:
Alternatively to cookies you could use localStorage. Here's a basic example of that. It sets an item in the storage once the main component is mounted and reacts to that item in the render() method.

componentDidMount() {
  // Get item from localStorage and save it to a constant.
  const hasVisitedBefore = localStorage.getItem('hasVisitedBefore');

  // Check if the user has visited the site (component) before.
  if (!hasVisitedBefore) {
    // If not, set the component state (or dispatch an action if you need)
    // Also set the localStorage so it's globally accessible.
    this.setState({ hasVisitedBefore: false });
    localStorage.setItem('hasVisitedBefore', true);
  }
}

// Based on the state set in `componentDidMount()`, show or hide the welcome modal.
render() {
  return (
    <div>
      {this.state.hasVisitedBefore
        ? 'Welcome back!'
        : 'Welcome for the first time!'}
    </div>
  );
}

Working demo on JSFiddle.

In other components you could then just check for localStorage.getItem('hasVisitedBefore') and render things based on that.


问:
STM32 float over USB from PC, endianess struggling
I'm currently trying to send floats over USB.
The PC has a Qt application running the following code

```<code>float x = 2.0;
memcpy(buffer.data() + 14, &x,  sizeof x);
</code>```

with the debuglog function i can clearly see the series of bytes passing through with the following order

```<code>.. 00 00 00 40 ..
</code>```

which according to this site

http://www.scadacore.com/field-tools/programming-calculators/online-hex-converter/

is converted to 1073741824 in case of little endianess.

on my STM32 i can use the following code to then turn on LED4

```<code>uint32_t a = buffer[14] | (buffer[15] << 8) | (buffer[16] << 16) | (buffer[17] << 24);
if (a == 1073741824){
    HAL_GPIO_WritePin(LED4_PORT, LED4_PIN, GPIO_PIN_RESET);
}
</code>```

The problem arises when i want to convert to the real float value 2.0

in fact if i do

```<code>float b = buffer[14] | (buffer[15] << 8) | (buffer[16] << 16) | (buffer[17] << 24);
if (b == 2.0f){
    HAL_GPIO_WritePin(LED5_PORT, LED5_PIN, GPIO_PIN_RESET);
}
</code>```

the LED5 is not turning on.

Is it an endianess problem?
How can i obtain the float value 2.0?

Regards,

答:
For IEEE 754 floats, the endianess is usually not a problem, but check just to be sure.

Your main problem is reading the value. You are ORing value in integer arithmetic and get an integer value, which is correct, but then you convert it to float. This will always give garbage, except for 0.

You need to reinterpret it as float. You can use :

A pointer cast : float a = *(float*)&myInt;

A memcpy : memcpy(&myFloat, &myInt, 4);

A union : union { uint32_t i; float f; };, u.i = myInt; float f = u.f;

You also need to be careful when comparing floating point. It is generally a bad idea to write if( f == 2.0f ), because 2.0f is an approximation. It is better to avoid ==, and use > >= < <= instead. If you want to check a particular value and not a range, check a small enough range around your value, with your range matching your precision needs.

Body:
I'm currently trying to send floats over USB.
The PC has a Qt application running the following code

float x = 2.0;
memcpy(buffer.data() + 14, &x,  sizeof x);

with the debuglog function i can clearly see the series of bytes passing through with the following order

.. 00 00 00 40 ..

which according to this site

http://www.scadacore.com/field-tools/programming-calculators/online-hex-converter/

is converted to 1073741824 in case of little endianess.

on my STM32 i can use the following code to then turn on LED4

uint32_t a = buffer[14] | (buffer[15] << 8) | (buffer[16] << 16) | (buffer[17] << 24);
if (a == 1073741824){
    HAL_GPIO_WritePin(LED4_PORT, LED4_PIN, GPIO_PIN_RESET);
}

The problem arises when i want to convert to the real float value 2.0

in fact if i do

float b = buffer[14] | (buffer[15] << 8) | (buffer[16] << 16) | (buffer[17] << 24);
if (b == 2.0f){
    HAL_GPIO_WritePin(LED5_PORT, LED5_PIN, GPIO_PIN_RESET);
}

the LED5 is not turning on.

Is it an endianess problem?
How can i obtain the float value 2.0?

Regards,


问:
Unresolved reference async in Kotlin
I am trying to perform network operation async in Kotlin. I read it you can do async using async function. I am getting below error, can anyone guess what could be the issue ?

Unresolved reference: async

```<code>override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    async() {
        val forecastWeather = ForecastRequest("302015").execute()
        Log.d("Test", forecastWeather.toString())
    }
}
</code>```

ForecastRequest.kt

```<code>class ForecastRequest(val zipcode: String) {
    companion object {
        private val APP_ID = "XYZ"
        private val URL = "http://api.openweathermap.org/data/2.5/" +
                    "forecast/daily?mode=json&units=metric&cnt=7"
        private val COMPLETE_URL = "$URL&APPID=$APP_ID&q="
    }

    fun execute(): ForecastResponse {
        val forecastJsonStr = java.net.URL(COMPLETE_URL + zipcode).readText()
        return Gson().fromJson(forecastJsonStr, ForecastResponse::class.java)
    }
}
</code>```

Top level build.gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Module level build.gradle

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.williams.thirddemo"
        minSdkVersion 23
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.code.gson:gson:2.8.1'
}
</code>```

答:
I see async function is available in anko library not Kotlin library itself. https://github.com/Kotlin/anko

I resolved by adding this dependency in build.gradle compile "org.jetbrains.anko:anko-commons:0.10.1" as this is not available in Kotlin itself.

I see that async is deprecated now, library suggests to use doAsync instead.

```<code>doAsync {
    val forecastWeather = ForecastRequest("302015").execute()
    uiThread {
        Log.d("Test", forecastWeather.toString())
    }
}
</code>```

Title: Unresolved reference async in Kotlin

Body:
I am trying to perform network operation async in Kotlin. I read it you can do async using async function. I am getting below error, can anyone guess what could be the issue ?

Unresolved reference: async

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    async() {
        val forecastWeather = ForecastRequest("302015").execute()
        Log.d("Test", forecastWeather.toString())
    }
}

ForecastRequest.kt

class ForecastRequest(val zipcode: String) {
    companion object {
        private val APP_ID = "XYZ"
        private val URL = "http://api.openweathermap.org/data/2.5/" +
                    "forecast/daily?mode=json&units=metric&cnt=7"
        private val COMPLETE_URL = "$URL&APPID=$APP_ID&q="
    }

    fun execute(): ForecastResponse {
        val forecastJsonStr = java.net.URL(COMPLETE_URL + zipcode).readText()
        return Gson().fromJson(forecastJsonStr, ForecastResponse::class.java)
    }
}

Top level build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext.kotlin_version = '1.1.2-4'
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        maven { url 'https://maven.google.com' }
        jcenter()
        mavenCentral()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Module level build.gradle

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.williams.thirddemo"
        minSdkVersion 23
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    compile 'com.android.support:appcompat-v7:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.code.gson:gson:2.8.1'
}

Body:
I see async function is available in anko library not Kotlin library itself. https://github.com/Kotlin/anko

I resolved by adding this dependency in build.gradle compile "org.jetbrains.anko:anko-commons:0.10.1" as this is not available in Kotlin itself.

I see that async is deprecated now, library suggests to use doAsync instead.

doAsync {
    val forecastWeather = ForecastRequest("302015").execute()
    uiThread {
        Log.d("Test", forecastWeather.toString())
    }
}


问:
Amount to always show 2 decimal places
Hi I have an ajax that gives result of my Balance when a particular is selected. My question is I want it to show with 2 decimal places even the amount is not in decimal form.

For example:

9000 = 9000.00

9000.1 = 9000.10

9000.11 = 9000.11

9000.159 = 9000.16

The form looks like this to give you a view of the result.

I have already tried the toFixed that is mostly answered but I cannot seem to make it work here, I have tried 2 codes.

1st code:

```<code>function specificBalance(row = null)
{

$('#subpaymentamount'+row).val('');
calculateTotalAmount();

var particulars =  $('#subparticulars'+row).val();

$.ajax({
        url: baseUrl+'/admin/summary/fetchSpecificBalance/'+schoolyearId+'/'+studentId+'/'+particulars,
        type: 'post',
        dataType: 'json',
        success:function(response) {

        $('#subpaymentbalance'+row).val(response.feestudent_amount).toFixed(2);

    } // /successs
}); // /ajax

}
</code>```

2nd Code:

```<code>function specificBalance(row = null)
{

$('#subpaymentamount'+row).val('');
calculateTotalAmount();

var particulars =  $('#subparticulars'+row).val();

$.ajax({
        url: baseUrl+'/admin/summary/fetchSpecificBalance/'+schoolyearId+'/'+studentId+'/'+particulars,
        type: 'post',
        dataType: 'json',
        success:function(response) {

        parseFloat($('#subpaymentbalance'+row).val(response.feestudent_amount)).toFixed(2);

    } // /successs
}); // /ajax

}
</code>```

Still same results.

答:
var amount = +"100";
$('#subpaymentbalance').val(amount.toFixed(2));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="subpaymentbalance" /></code>```

You need to do this if response.feestudent_amount is string. toFixed needs to be called on Number and then it needs to be set.

```<code>var amount = +response.feestudent_amount;
$('#subpaymentbalance' + row).val(amount.toFixed(2));
</code>```

See the sample code:

Title: Amount to always show 2 decimal places

Body:
Hi I have an ajax that gives result of my Balance when a particular is selected. My question is I want it to show with 2 decimal places even the amount is not in decimal form.

For example:

9000 = 9000.00

9000.1 = 9000.10

9000.11 = 9000.11

9000.159 = 9000.16

The form looks like this to give you a view of the result.

I have already tried the toFixed that is mostly answered but I cannot seem to make it work here, I have tried 2 codes.

1st code:

function specificBalance(row = null)
{

$('#subpaymentamount'+row).val('');
calculateTotalAmount();

var particulars =  $('#subparticulars'+row).val();

$.ajax({
        url: baseUrl+'/admin/summary/fetchSpecificBalance/'+schoolyearId+'/'+studentId+'/'+particulars,
        type: 'post',
        dataType: 'json',
        success:function(response) {

        $('#subpaymentbalance'+row).val(response.feestudent_amount).toFixed(2);

    } // /successs
}); // /ajax

}

2nd Code:

function specificBalance(row = null)
{

$('#subpaymentamount'+row).val('');
calculateTotalAmount();

var particulars =  $('#subparticulars'+row).val();

$.ajax({
        url: baseUrl+'/admin/summary/fetchSpecificBalance/'+schoolyearId+'/'+studentId+'/'+particulars,
        type: 'post',
        dataType: 'json',
        success:function(response) {

        parseFloat($('#subpaymentbalance'+row).val(response.feestudent_amount)).toFixed(2);

    } // /successs
}); // /ajax

}

Still same results.

Body:
var amount = +"100";
$('#subpaymentbalance').val(amount.toFixed(2));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="subpaymentbalance" />

You need to do this if response.feestudent_amount is string. toFixed needs to be called on Number and then it needs to be set.

var amount = +response.feestudent_amount;
$('#subpaymentbalance' + row).val(amount.toFixed(2));

See the sample code:


问:
How to send SIGINT (Ctrl-C) to current remote process over SSH (without -t option)
I need to send a SIGINT to the remote process running in foreground in an SSH session.

The SSH session is already established, so I cannot use option of starting it with (as described in How to send SIGINT to a remote process over SSH?)

```<code>ssh -t user@host
</code>```

I know I could open a second ssh session and kill the process or close the current ssh session, but I want to avoid that and do it directly throw the current session (if this is possible).

答:
Short answer:

```<code>ssh -t fs "stty isig intr ^N -echoctl ; trap '/bin/true' SIGINT; sleep 1000; echo f" > foo
</code>```

and stop the program by CTRL+N.

Long explanation:

1.You must use stty option intr to change your server or local interrupt character to not collide with each other.In the command above I've changed the server interrupt character to CTRL+N. You can change your local interrupt character and leave the server's one without any changes.

2.If you don't want the interrupt character to be in your output (and any other control character) use stty -echoctl.

3.You must assure that control characters are switched on on the server bash invoked by sshd . If you don't you can end up with processes still hanging around after you logout.
stty isig

4.You actually catch SIGINT signal by trap '/bin/true' SIGINT with empty statement. Without the trap you will not have any stdout after SIGINT signal on your end.

But without -t option that cannot be quit with a signal to the process that runs over the terminal.

Body:
I need to send a SIGINT to the remote process running in foreground in an SSH session.

The SSH session is already established, so I cannot use option of starting it with (as described in How to send SIGINT to a remote process over SSH?)

ssh -t user@host

I know I could open a second ssh session and kill the process or close the current ssh session, but I want to avoid that and do it directly throw the current session (if this is possible).

Body:
Short answer:

ssh -t fs "stty isig intr ^N -echoctl ; trap '/bin/true' SIGINT; sleep 1000; echo f" > foo

and stop the program by CTRL+N.

Long explanation:

1.You must use stty option intr to change your server or local interrupt character to not collide with each other.In the command above I've changed the server interrupt character to CTRL+N. You can change your local interrupt character and leave the server's one without any changes.

2.If you don't want the interrupt character to be in your output (and any other control character) use stty -echoctl.

3.You must assure that control characters are switched on on the server bash invoked by sshd . If you don't you can end up with processes still hanging around after you logout.
stty isig

4.You actually catch SIGINT signal by trap '/bin/true' SIGINT with empty statement. Without the trap you will not have any stdout after SIGINT signal on your end.

But without -t option that cannot be quit with a signal to the process that runs over the terminal.


问:
How do I access innerText of a specific XMLnode
Hi
I have the following XML fragment:

```<code>  <Customer AccountNumber="4">
    <CustomerInfo>
      <firstName>Andrew</firstName>
      <lastName>Walker</lastName>
    </CustomerInfo>
    <Transactions>
      <AccountBalance>595848584.4</AccountBalance>
    </Transactions>
  </Customer>
</code>```

from a bigger XML file. I want to access the <firsName> in C#.
Currently I am doing the following:

```<code>    foreach (XmlNode customer in root)
    {
        i++;
        if(_AccNumber== Convert.ToInt32(customer.Attributes[0].Value))
        {
            searchNode = CustNodes[(i - 1)];
            string _firstName = searchNode.FirstChild.FirstChild.InnerText;

        }
    }
</code>```

When I view searchNode in the debugger I can see in the results view element [0] which has a localName CustomerInfo as you expect. So in the debugger first name has the following path:

```<code>searchNode -> [0].[0].[0].value
</code>```

if that makes sense?

Is there any better way of doing this? (without LINQ)?
Apologies, if something isn't clear....its 2:30AM! Let me know and I'll explain myself better.
Thanks!!

答:
Try XPath.. something like this should work:</p>

```<code>string firstName = String.Empty;

var xmlNode = doc.SelectSingleNode(String.Format("//Customer[@AccountNumber='{0}']/CustomerInfo/firstName", _AccNumber));
if (xmlNode != null)
    firstName = xmlNode.InnerText;
</code>```

Body:
Hi
I have the following XML fragment:

  <Customer AccountNumber="4">
    <CustomerInfo>
      <firstName>Andrew</firstName>
      <lastName>Walker</lastName>
    </CustomerInfo>
    <Transactions>
      <AccountBalance>595848584.4</AccountBalance>
    </Transactions>
  </Customer>

from a bigger XML file. I want to access the <firsName> in C#.
Currently I am doing the following:

    foreach (XmlNode customer in root)
    {
        i++;
        if(_AccNumber== Convert.ToInt32(customer.Attributes[0].Value))
        {
            searchNode = CustNodes[(i - 1)];
            string _firstName = searchNode.FirstChild.FirstChild.InnerText;

        }
    }

When I view searchNode in the debugger I can see in the results view element [0] which has a localName CustomerInfo as you expect. So in the debugger first name has the following path:

searchNode -> [0].[0].[0].value

if that makes sense?

Is there any better way of doing this? (without LINQ)?
Apologies, if something isn't clear....its 2:30AM! Let me know and I'll explain myself better.
Thanks!!

Body:
Try XPath.. something like this should work:

string firstName = String.Empty;

var xmlNode = doc.SelectSingleNode(String.Format("//Customer[@AccountNumber='{0}']/CustomerInfo/firstName", _AccNumber));
if (xmlNode != null)
    firstName = xmlNode.InnerText;


问:
What is the difference between ptr = my_array and ptr = &my_array[0][0] in C language?
I am a newbie to C. For the following code:

```<code>int *ptr;
int my_array[5][5] = {{1,2},{3,4,5},{6},{7}};
</code>```

I noticed my compiler produced a warning for:

```<code>ptr = my_array;
</code>```

But worked fine for:

```<code>ptr = &my_array[0][0];
</code>```

Why is that?

答:
An array used in expressions with rare exceptions is converted to the pointer to its first element.

If you have an array like this

```<code>int my_array[5][5];
</code>```

then it is an array of arrays that is the elements of the array have types int[5]. For example the expression my_array[0] has the type int[5]. So the array used in expressions is converted to a pointer of type int ( * )[5] that points to its first element (to its first "row").

Types int * and int ( * )[5] are different types and there is no an implicit conversion from one type to another.

The expression &my_array[0][0] has the type int *.

So if you want to reinterpret the array as a one-dimensional array you need to use the implicit cast

```<code>ptr = ( int * )my_array;
</code>```

Investigate this demonstrative program

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

int main( void )
{
    int my_array[5][5] =
    {
        { 1, 2 },
        { 3, 4, 5 },
        { 6 },
        { 7 }
    };

    for (int(*p)[5] = my_array; p != my_array + 5; ++p)
    {
        for (int *q = *p; q != *p + 5; ++q)
        {
            printf("%d ", *q);
        }
        putchar('\n');
    }
}
</code>```

Its output is

```<code>1 2 0 0 0
3 4 5 0 0
6 0 0 0 0
7 0 0 0 0
0 0 0 0 0
</code>```

Body:
I am a newbie to C. For the following code:

int *ptr;
int my_array[5][5] = {{1,2},{3,4,5},{6},{7}};

I noticed my compiler produced a warning for:

ptr = my_array;

But worked fine for:

ptr = &my_array[0][0];

Why is that?

Body:
An array used in expressions with rare exceptions is converted to the pointer to its first element.

If you have an array like this

int my_array[5][5];

then it is an array of arrays that is the elements of the array have types int[5]. For example the expression my_array[0] has the type int[5]. So the array used in expressions is converted to a pointer of type int ( * )[5] that points to its first element (to its first "row").

Types int * and int ( * )[5] are different types and there is no an implicit conversion from one type to another.

The expression &my_array[0][0] has the type int *.

So if you want to reinterpret the array as a one-dimensional array you need to use the implicit cast

ptr = ( int * )my_array;

Investigate this demonstrative program

#include <stdio.h>

int main( void )
{
    int my_array[5][5] =
    {
        { 1, 2 },
        { 3, 4, 5 },
        { 6 },
        { 7 }
    };

    for (int(*p)[5] = my_array; p != my_array + 5; ++p)
    {
        for (int *q = *p; q != *p + 5; ++q)
        {
            printf("%d ", *q);
        }
        putchar('\n');
    }
}

Its output is

1 2 0 0 0
3 4 5 0 0
6 0 0 0 0
7 0 0 0 0
0 0 0 0 0


问:
Cache SQL Update for daily reuse
I have a big table with 40 million rows in a Table. I am having to update the entire table because I don't want anything to missed. The Update Command Is being used to get the value from a different table and using this to join on.

```<code>Update D
Set D.Key = S.Key
from Activity D with (NOLOCK)
inner Join Account S
on D.ID = S.ID
OPTION (HASH JOIN)
</code>```

With Activity D being the Big Table 40 million and Account Table S being a 1.2 Million, that's why I have take the HASH Option Join.

Anyways I am having to do this update everyday in an Execute SQL task in my ETL Process,Just wondering since not much gets changed and no index exist to speed in the process up in the table. Is there a way to speed this process up at all, whether there is a way to cache this so everynight its not having to do the whole thing from scratch or would wrapping this in a Stored Proc speed things up rather than just using a SQL Script as I am doing at the moment?

Thank you

答:
One simple approach to avoid that UPDATE could be to use a trigger on dbo.Activity table thus:

```<code>CREATE TRIGGER trgIU_Activity_UpdateKey
ON dbo.Activity
AFTER INSERT, UPDATE
AS
BEGIN

IF UPDATE(ID)
BEGIN
    UPDATE d
    SET D.Key = S.Key
    FROM dbo.Activity d INNER JOIN dbo.Account s ON d.ID = s.ID
    WHERE d.ID IN (SELECT i.ID FROM inserted i)
END

END
</code>```

After every INSERT / UPDATE on Activity table, if there are any changes within dbo.Activity.ID column then it will update the Key column.

Title: Cache SQL Update for daily reuse

Body:
I have a big table with 40 million rows in a Table. I am having to update the entire table because I don't want anything to missed. The Update Command Is being used to get the value from a different table and using this to join on.

Update D
Set D.Key = S.Key
from Activity D with (NOLOCK)
inner Join Account S
on D.ID = S.ID
OPTION (HASH JOIN)

With Activity D being the Big Table 40 million and Account Table S being a 1.2 Million, that's why I have take the HASH Option Join.

Anyways I am having to do this update everyday in an Execute SQL task in my ETL Process,Just wondering since not much gets changed and no index exist to speed in the process up in the table. Is there a way to speed this process up at all, whether there is a way to cache this so everynight its not having to do the whole thing from scratch or would wrapping this in a Stored Proc speed things up rather than just using a SQL Script as I am doing at the moment?

Thank you

Body:
One simple approach to avoid that UPDATE could be to use a trigger on dbo.Activity table thus:

CREATE TRIGGER trgIU_Activity_UpdateKey
ON dbo.Activity
AFTER INSERT, UPDATE
AS
BEGIN

IF UPDATE(ID)
BEGIN
    UPDATE d
    SET D.Key = S.Key
    FROM dbo.Activity d INNER JOIN dbo.Account s ON d.ID = s.ID
    WHERE d.ID IN (SELECT i.ID FROM inserted i)
END

END

After every INSERT / UPDATE on Activity table, if there are any changes within dbo.Activity.ID column then it will update the Key column.