问:
How to add data to a TrieMap[Long,List[Long]] in Scala
i have this:

```<code>val vertexIdListPartitions: TrieMap[Long, List[Long]] = TrieMap()
</code>```

i need to add List(3) at vertexIdListPartitions(3).

I try to do this with:

```<code>vertexIdListPartitions(3)++List(3)
</code>```

but it doesn't work.

Please help me.
Thanks

答:
Mutable collections have the update() method for this.

```<code>vertexIdListPartitions.update(3L, List(3))  //res0: Unit = ()
vertexIdListPartitions  //res1: TrieMap[Long,List[Long]] = TrieMap(3 -> List(3))
</code>```

Body:
i have this:

val vertexIdListPartitions: TrieMap[Long, List[Long]] = TrieMap()

i need to add List(3) at vertexIdListPartitions(3).

I try to do this with:

vertexIdListPartitions(3)++List(3)

but it doesn't work.

Please help me.
Thanks

Body:
Mutable collections have the update() method for this.

vertexIdListPartitions.update(3L, List(3))  //res0: Unit = ()
vertexIdListPartitions  //res1: TrieMap[Long,List[Long]] = TrieMap(3 -> List(3))


来源: stackexchange

问:
Comparing two integers without any comparison
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

```<code>if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";
</code>```

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

答:
Subtract them and check the sign using nasty bit twiddling hacks

http://graphics.stanford.edu/~seander/bithacks.html

Don't do this in production code if the other programmers know where you live.

OwnerDisplayName: kvphxga

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to find the greatest of two integers without any comparison? I found some  solutions:

if(!(a/b)) // if a is less than b then division result will be zero.
{
    cout << " b is greater than a";
}
else if (!(a-b)) // we know a is greater than or equal to b now.  check whether they are equal.
{
    cout << "a and b are equal";
}
else
    cout << "a is greater than b";

But if(c) or if(!c) is a comparison to zero. In addition it doesn't work for negative numbers. In fact I need a solution that avoids any if statement. Instead I should use switch statements and arithmetic operators. ThanX.

LastEditorDisplayName: kvphxga

OwnerDisplayName: mgb


问:
SQL Server geography result format
Using SQL Server Management Studio:

```<code>declare @g geography
set @g = geography::Point(-77.1851436,39.1065236,4326)
select @g
</code>```

returns

```<code>0xE6100000010C14C48A64D94B53C04820B990A28D4340
</code>```

What format is this result? I know that it is not STAsBinary() - that returns

```<code>0x01010000004820B990A28D434014C48A64D94B53C0
</code>```

Is there a way to create the 0xE61... value using C#?

答:
result is type of Microsoft.SqlServer.Types.SqlGeography.Point

see this link

ContentLicense: CC BY-SA 3.0

Title: SQL Server geography result format

Body:
Using SQL Server Management Studio:

declare @g geography
set @g = geography::Point(-77.1851436,39.1065236,4326)
select @g

returns

0xE6100000010C14C48A64D94B53C04820B990A28D4340

What format is this result? I know that it is not STAsBinary() - that returns

0x01010000004820B990A28D434014C48A64D94B53C0

Is there a way to create the 0xE61... value using C#?


问:
Javascript: alternative or less complex code to create hidden input forms
I ask for your help to improve the form I created, keeping in mind that I am not a great expert in javascript programming.

I need to create a hotel search engine, with the possibility to choose the total number of rooms. Depending on the number of rooms selected, as many hidden form fields will be displayed, containing additional selection fields.

To make the idea of what I have created better, I attach a screen.

To view the hidden fields in relation to the number of rooms chosen, I used this javascript code, repeated 5 times (maximum number of rooms).

```<code>function admSelectCheck(nameSelect)
{
console.log(nameSelect);
if(nameSelect){
    admOptionValue = document.getElementById("room1").value;
    if(admOptionValue == nameSelect.value){
        document.getElementById("pax_room_1").style.display = "block";
    }
    else{
        document.getElementById("pax_room_1").style.display = "none";
    }
}
else{
    document.getElementById("pax_room_1").style.display = "none";
}
</code>```

To realize the options for choosing each room, I used this javascript code repetition in proportion to the room number. That is: 1 room -> entered code 1 once; 2 rooms -> entered the code 2 times; etc.

```<code>function childSelect(nameSelect)
{
console.log(nameSelect);
if(nameSelect){
    admOptionValue = document.getElementById("child1").value;
    if(admOptionValue == nameSelect.value){
        document.getElementById("agechild1").style.display = "block";
    }
    else{
        document.getElementById("agechild1").style.display = "none";
    }
 }
 else{
    document.getElementById("agechild1").style.display = "none";
 }

 if(nameSelect){
    admOptionValue = document.getElementById("child2").value;
    if(admOptionValue == nameSelect.value){
        document.getElementById("agechild2").style.display = "block";
    }
    else{
        document.getElementById("agechild2").style.display = "none";
    }
}
else{
    document.getElementById("agechild2").style.display = "none";
}

if(nameSelect){
    admOptionValue = document.getElementById("child3").value;
    if(admOptionValue == nameSelect.value){
        document.getElementById("agechild3").style.display = "block";
    }
    else{
        document.getElementById("agechild3").style.display = "none";
    }
}
else{
    document.getElementById("agechild3").style.display = "none";
}
}

$(function(){
     $(':submit').click(function(){
          $('select').each(function(){
              if ( $(this).val() == '' )
              {
                  $(this).remove(); // or
$(this).attr('disabled','disabled');
              }
          });
     });
});
</code>```

While, I used this html code repeated the same way.

```<code><div class="container_hidden">

    <div id="pax_room_1" style="display:none;" class="row_hidden">

        <div class="nrRoom" style="width: 100px;background: #f5a445;font-size: 15px;text-align: center;height: 30px; padding-top: 5px; border-radius: 10px 10px 0px 0px;"><font color="#000"><img src="images/family-room.png" alt="Icon Family Room" style="width: 19px;" /> Room 1</font></div>

            <div class="column"><font color="#000">Adult (18+)</font>
                <select id="adulti" name="nrAdult">
                    <option value="">-</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    <option value="6">6</option>
                </select>
            </div>
            <div class="column"><font color="#000">Children (0-17)</font>
                <select id="nrchild" name="nrChild" onchange="childSelect(this);">
                    <option value="">-</option>
                    <option id="child1" value="1">1</option>
                    <option id="child2" value="2">2</option>
                    <option id="child3" value="3">3</option>
                </select>
            </div>

                        <!-- Select Bambino 1 -->
                        <div id="agechild1" style="display:none;" class="row_hidden">
                        <div class="column"><font color="#000"> Child Age 1 </font>
                        <select id="child1" name="ageChild1">
                        <option value="">-</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                        <option value="11">11</option>
                        <option value="12">12</option>
                        <option value="13">13</option>
                        <option value="14">14</option>
                        <option value="15">15</option>
                        <option value="16">16</option>
                        <option value="17">17</option>
                        </select>
                        </div>
                        </div>

                        <!-- Select Bambino 1-2 -->
                        <div id="agechild2" style="display:none;" class="row_hidden">
                        <div class="column"><font color="#000"> Child Age 1 </font>
                        <select id="child1" name="ageChild1">
                        <option value="">-</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                        <option value="11">11</option>
                        <option value="12">12</option>
                        <option value="13">13</option>
                        <option value="14">14</option>
                        <option value="15">15</option>
                        <option value="16">16</option>
                        <option value="17">17</option>
                        </select>
                        </div>
                        <div class="column"><font color="#000"> Child Age 2 </font>
                        <select id="child2" name="ageChild2">
                        <option value="">-</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                        <option value="11">11</option>
                        <option value="12">12</option>
                        <option value="13">13</option>
                        <option value="14">14</option>
                        <option value="15">15</option>
                        <option value="16">16</option>
                        <option value="17">17</option>
                        </select>
                        </div>
                        </div>

                        <!-- Select Bambino 1-2-3 -->
                        <div id="agechild3" style="display:none;" class="row_hidden">
                        <div class="column"><font color="#000"> Child Age 1 </font>
                        <select id="child1" name="ageChild1">
                        <option value="">-</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                        <option value="11">11</option>
                        <option value="12">12</option>
                        <option value="13">13</option>
                        <option value="14">14</option>
                        <option value="15">15</option>
                        <option value="16">16</option>
                        <option value="17">17</option>
                        </select>
                        </div>
                        <div class="column"><font color="#000"> Child Age 2 </font>
                        <select id="child2" name="ageChild2">
                        <option value="">-</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                        <option value="11">11</option>
                        <option value="12">12</option>
                        <option value="13">13</option>
                        <option value="14">14</option>
                        <option value="15">15</option>
                        <option value="16">16</option>
                        <option value="17">17</option>
                        </select>
                        </div>
                        <div class="column"><font color="#000"> Child Age 3 </font>
                        <select id="child3" name="ageChild3">
                        <option value="">-</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                        <option value="11">11</option>
                        <option value="12">12</option>
                        <option value="13">13</option>
                        <option value="14">14</option>
                        <option value="15">15</option>
                        <option value="16">16</option>
                        <option value="17">17</option>
                        </select>
                        </div>
                        </div>
    </div>
</code>```

I realize that it is too laborious, even if it works. This is why I ask you if there is a way to lighten the code.

答:
You can use the data-* attribute to dynamically choose the relations in the html.

e.g.

(function() {
  const hiders = document.getElementsByClassName('hider');
  // const is ES6 syntax, you can use var, although you might want to read up on that

  for (let i = 0; i < hiders.length; ++i) {
    const hider = hiders[i];

    hider.onchange = function() {
      const hideTarget = hider.dataset.hideTarget; // this reads the value of data-hide-target

      if (hideTarget == null)
        return; // no target set (else we would potentially get an TypeError, when data-hide-target wasn't set. Still happens with an invalid value though, but there you want an error

      if (hider.value !== '')
        document.getElementById(hideTarget).style.display = "block";
      else
        document.getElementById(hideTarget).style.display = "none";
      // you might also want to take a look at .setAttribute("aria-hidden", "true") and .style.visibility = "hidden"
    };
  }
})()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="adulti" name="nrAdult" class="hider" data-hide-target="hideme1">
    <option value="">-</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
</select>

<div id="hideme1" style="display: none;">
  Hide me 1
</div>

<select id="adulti2" name="nrAdult" class="hider" data-hide-target="hideme2">
    <option value="">-</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
</select>

<div id="hideme2" style="display: none;">
  Hide me 2
</div></code>```

I think this snippet is rather easy to understand, but if you want me to elaborate a bit further, feel free to ask.

FYI, this can also be used for convenience in this example:

(function(){
  function makeOption(val) {
    const option = document.createElement('option');
    option.value = val;
    option.innerText = val;
    return option;
  }

  const simpleSelects = document.getElementsByClassName('simpleSelect');
  for(let i = 0; i < simpleSelects.length; ++i){
    const simpleSelect = simpleSelects[i];
    const min = simpleSelect.dataset.from;
    const max = simpleSelect.dataset.to;

    if(min == null || max == null)
      return;

    simpleSelect.appendChild(makeOption('-'));

    for (let j = min; j <= max; ++j) {
      simpleSelect.appendChild(makeOption(j));
    }
  }
})()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="nrAdult" class="simpleSelect" data-from="0" data-to="5"></select>
<select name="nrChildren" class="simpleSelect" data-from="0" data-to="10"></select></code>```

And I also just realised that you were using the same id multiple times, which is not only not allowed, but also doesn't work.

(And yes I am aware that what this does is quite different from what you want, but it is the same principle and I didn't want to give you an out-of-the-box solution.)

Body:
I ask for your help to improve the form I created, keeping in mind that I am not a great expert in javascript programming.

I need to create a hotel search engine, with the possibility to choose the total number of rooms. Depending on the number of rooms selected, as many hidden form fields will be displayed, containing additional selection fields.

To make the idea of what I have created better, I attach a screen.

To view the hidden fields in relation to the number of rooms chosen, I used this javascript code, repeated 5 times (maximum number of rooms).

function admSelectCheck(nameSelect)
{
console.log(nameSelect);
if(nameSelect){
    admOptionValue = document.getElementById("room1").value;
    if(admOptionValue == nameSelect.value){
        document.getElementById("pax_room_1").style.display = "block";
    }
    else{
        document.getElementById("pax_room_1").style.display = "none";
    }
}
else{
    document.getElementById("pax_room_1").style.display = "none";
}

To realize the options for choosing each room, I used this javascript code repetition in proportion to the room number. That is: 1 room -> entered code 1 once; 2 rooms -> entered the code 2 times; etc.

function childSelect(nameSelect)
{
console.log(nameSelect);
if(nameSelect){
    admOptionValue = document.getElementById("child1").value;
    if(admOptionValue == nameSelect.value){
        document.getElementById("agechild1").style.display = "block";
    }
    else{
        document.getElementById("agechild1").style.display = "none";
    }
 }
 else{
    document.getElementById("agechild1").style.display = "none";
 }

 if(nameSelect){
    admOptionValue = document.getElementById("child2").value;
    if(admOptionValue == nameSelect.value){
        document.getElementById("agechild2").style.display = "block";
    }
    else{
        document.getElementById("agechild2").style.display = "none";
    }
}
else{
    document.getElementById("agechild2").style.display = "none";
}

if(nameSelect){
    admOptionValue = document.getElementById("child3").value;
    if(admOptionValue == nameSelect.value){
        document.getElementById("agechild3").style.display = "block";
    }
    else{
        document.getElementById("agechild3").style.display = "none";
    }
}
else{
    document.getElementById("agechild3").style.display = "none";
}
}

$(function(){
     $(':submit').click(function(){
          $('select').each(function(){
              if ( $(this).val() == '' )
              {
                  $(this).remove(); // or
$(this).attr('disabled','disabled');
              }
          });
     });
});

While, I used this html code repeated the same way.

 Room 1

Adult (18+)
                <select id="adulti" name="nrAdult">
                    <option value="">-</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                    <option value="5">5</option>
                    <option value="6">6</option>
                </select>

Children (0-17)
                <select id="nrchild" name="nrChild" onchange="childSelect(this);">
                    <option value="">-</option>
                    <option id="child1" value="1">1</option>
                    <option id="child2" value="2">2</option>
                    <option id="child3" value="3">3</option>
                </select>

 Child Age 1
                        <select id="child1" name="ageChild1">
                        <option value="">-</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                        <option value="11">11</option>
                        <option value="12">12</option>
                        <option value="13">13</option>
                        <option value="14">14</option>
                        <option value="15">15</option>
                        <option value="16">16</option>
                        <option value="17">17</option>
                        </select>

 Child Age 1
                        <select id="child1" name="ageChild1">
                        <option value="">-</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                        <option value="11">11</option>
                        <option value="12">12</option>
                        <option value="13">13</option>
                        <option value="14">14</option>
                        <option value="15">15</option>
                        <option value="16">16</option>
                        <option value="17">17</option>
                        </select>

 Child Age 2
                        <select id="child2" name="ageChild2">
                        <option value="">-</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                        <option value="11">11</option>
                        <option value="12">12</option>
                        <option value="13">13</option>
                        <option value="14">14</option>
                        <option value="15">15</option>
                        <option value="16">16</option>
                        <option value="17">17</option>
                        </select>

 Child Age 1
                        <select id="child1" name="ageChild1">
                        <option value="">-</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                        <option value="11">11</option>
                        <option value="12">12</option>
                        <option value="13">13</option>
                        <option value="14">14</option>
                        <option value="15">15</option>
                        <option value="16">16</option>
                        <option value="17">17</option>
                        </select>

 Child Age 2
                        <select id="child2" name="ageChild2">
                        <option value="">-</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                        <option value="11">11</option>
                        <option value="12">12</option>
                        <option value="13">13</option>
                        <option value="14">14</option>
                        <option value="15">15</option>
                        <option value="16">16</option>
                        <option value="17">17</option>
                        </select>

 Child Age 3
                        <select id="child3" name="ageChild3">
                        <option value="">-</option>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                        <option value="4">4</option>
                        <option value="5">5</option>
                        <option value="6">6</option>
                        <option value="7">7</option>
                        <option value="8">8</option>
                        <option value="9">9</option>
                        <option value="10">10</option>
                        <option value="11">11</option>
                        <option value="12">12</option>
                        <option value="13">13</option>
                        <option value="14">14</option>
                        <option value="15">15</option>
                        <option value="16">16</option>
                        <option value="17">17</option>
                        </select>

I realize that it is too laborious, even if it works. This is why I ask you if there is a way to lighten the code.

Body:
You can use the data-* attribute to dynamically choose the relations in the html.

e.g.

(function() {
  const hiders = document.getElementsByClassName('hider');
  // const is ES6 syntax, you can use var, although you might want to read up on that

  for (let i = 0; i < hiders.length; ++i) {
    const hider = hiders[i];

    hider.onchange = function() {
      const hideTarget = hider.dataset.hideTarget; // this reads the value of data-hide-target

      if (hideTarget == null)
        return; // no target set (else we would potentially get an TypeError, when data-hide-target wasn't set. Still happens with an invalid value though, but there you want an error

      if (hider.value !== '')
        document.getElementById(hideTarget).style.display = "block";
      else
        document.getElementById(hideTarget).style.display = "none";
      // you might also want to take a look at .setAttribute("aria-hidden", "true") and .style.visibility = "hidden"
    };
  }
})()

<select id="adulti" name="nrAdult" class="hider" data-hide-target="hideme1">
    <option value="">-</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
</select>

<div id="hideme1" style="display: none;">
  Hide me 1
</div>

<select id="adulti2" name="nrAdult" class="hider" data-hide-target="hideme2">
    <option value="">-</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
</select>

<div id="hideme2" style="display: none;">
  Hide me 2
</div>

I think this snippet is rather easy to understand, but if you want me to elaborate a bit further, feel free to ask.

FYI, this can also be used for convenience in this example:

(function(){
  function makeOption(val) {
    const option = document.createElement('option');
    option.value = val;
    option.innerText = val;
    return option;
  }

  const simpleSelects = document.getElementsByClassName('simpleSelect');
  for(let i = 0; i < simpleSelects.length; ++i){
    const simpleSelect = simpleSelects[i];
    const min = simpleSelect.dataset.from;
    const max = simpleSelect.dataset.to;

    if(min == null || max == null)
      return;

    simpleSelect.appendChild(makeOption('-'));

    for (let j = min; j <= max; ++j) {
      simpleSelect.appendChild(makeOption(j));
    }
  }
})()

<select name="nrAdult" class="simpleSelect" data-from="0" data-to="5"></select>
<select name="nrChildren" class="simpleSelect" data-from="0" data-to="10"></select>

And I also just realised that you were using the same id multiple times, which is not only not allowed, but also doesn't work.

(And yes I am aware that what this does is quite different from what you want, but it is the same principle and I didn't want to give you an out-of-the-box solution.)


答:
Well one bad way you can simplify this is this

```<code>def calculate_level(xp):
    if xp < 368599:
        return 62
    for i in reversed(range(63, 99)):
        if xp > 368599 * 1.101141**(i - 62):
            return i
</code>```

But the other better thing to do is to work out a more mathematical definition of this problem and just figure out the direct function.

I think it would be something along the lines of

```<code>level = floor(log_1.101141(xp / 368599) +62)
</code>```

Title: How can I determine level based on experience?

Body:
How can I simply calculate the level based on an input experience?
I'm making a "pet chance generator" for a game called runescape. The program asks for your current experience and approximates the level based on the experience value input by the user. Below is the only method I could think of to do this but as you can see there is a wall of text basically copy pasted 40 times. Please help!

I currently have:

def calculate_level(xp):
if xp < 368599:
    level = 62
elif xp < 368599 * 1.101141**2:
    level = 63
elif xp < 368599 * 1.101141**3:
    level = 64
elif xp < 368599 * 1.101141**4:
    level = 65
elif xp < 368599 * 1.101141**5:
    level = 66
elif xp < 368599 * 1.101141**6:
    level = 67
elif xp < 368599 * 1.101141**7:
    level = 68
elif xp < 368599 * 1.101141**8:
    level = 69
elif xp < 368599 * 1.101141**9:
    level = 70
elif xp < 368599 * 1.101141**10:
    level = 71
elif xp < 368599 * 1.101141**11:
    level = 72
elif xp < 368599 * 1.101141**12:
    level = 73
elif xp < 368599 * 1.101141**13:
    level = 74
elif xp < 368599 * 1.101141**14:
    level = 75
elif xp < 368599 * 1.101141**15:
    level = 76
elif xp < 368599 * 1.101141**16:
    level = 77
elif xp < 368599 * 1.101141**17:
    level = 78
elif xp < 368599 * 1.101141**18:
    level = 79
elif xp < 368599 * 1.101141**19:
    level = 80
elif xp < 368599 * 1.101141**20:
    level = 81
elif xp < 368599 * 1.101141**21:
    level = 82
elif xp < 368599 * 1.101141**22:
    level = 83
elif xp < 368599 * 1.101141**23:
    level = 84
elif xp < 368599 * 1.101141**24:
    level = 85
elif xp < 368599 * 1.101141**25:
    level = 86
elif xp < 368599 * 1.101141**26:
    level = 87
elif xp < 368599 * 1.101141**27:
    level = 88
elif xp < 368599 * 1.101141**28:
    level = 89
elif xp < 368599 * 1.101141**29:
    level = 90
elif xp < 368599 * 1.101141**30:
    level = 91
elif xp < 368599 * 1.101141**31:
    level = 92
elif xp < 368599 * 1.101141**32:
    level = 93
elif xp < 368599 * 1.101141**33:
    level = 94
elif xp < 368599 * 1.101141**34:
    level = 95
elif xp < 368599 * 1.101141**35:
    level = 96
elif xp < 368599 * 1.101141**36:
    level = 97
elif xp < 368599 * 1.101141**37:
    level = 98
else:
    level = 99
return level

Body:
Well one bad way you can simplify this is this

def calculate_level(xp):
    if xp < 368599:
        return 62
    for i in reversed(range(63, 99)):
        if xp > 368599 * 1.101141**(i - 62):
            return i

But the other better thing to do is to work out a more mathematical definition of this problem and just figure out the direct function.

I think it would be something along the lines of

level = floor(log_1.101141(xp / 368599) +62)


问:
Why does DATEDIFF treat 23:59.59.999 as the next day?
When I run the following:

```<code>DECLARE @date1 datetime = '2017-12-01 23:59:59.998'
DECLARE @date2 datetime = '2017-12-11 00:00:00.000'
SELECT DATEDIFF(day, @date1, @date2)
</code>```

I get 10 as expected since it only compares the day part

However, if I add one millisecond:

```<code>DECLARE @date1 datetime = '2017-12-01 23:59:59.999'
DECLARE @date2 datetime = '2017-12-11 00:00:00.000'
SELECT DATEDIFF(day, @date1, @date2)
</code>```

I get 9. It seems like SQL Server is rounding 23:59.59.999 to 24:00.00.000 and thus the next day but won't round up anything else. Is there any way to prevent this?

答:
MS SQL Uses
4 bytes to store the days past Jan 1, 1900.
4 bytes to store the clock ticks past midnight. ( a tick is 3.3miliseconds)

What you are seeing is overflow. Since the number can not be represented by the 4 bytes, it will use the 5th byte thus incrementing the day by 1.

SQL Server stores the second integer for the time as the number of
  clock ticks after midnight. A second contains 300 ticks, so a tick
  equals 3.3 milliseconds (ms). You can see the values for days and
  clock ticks by converting a datetime value to a binary(8) value and
  using the substring function to extract each set of 4 bytes. The code
  in Figure 3 then converts each set of 4 bytes into an integer.

Source: http://www.itprotoday.com/microsoft-sql-server/solving-datetime-mystery

Body:
When I run the following:

DECLARE @date1 datetime = '2017-12-01 23:59:59.998'
DECLARE @date2 datetime = '2017-12-11 00:00:00.000'
SELECT DATEDIFF(day, @date1, @date2)

I get 10 as expected since it only compares the day part

However, if I add one millisecond:

DECLARE @date1 datetime = '2017-12-01 23:59:59.999'
DECLARE @date2 datetime = '2017-12-11 00:00:00.000'
SELECT DATEDIFF(day, @date1, @date2)

I get 9. It seems like SQL Server is rounding 23:59.59.999 to 24:00.00.000 and thus the next day but won't round up anything else. Is there any way to prevent this?


问:
C++ - class issue
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

There is the following program (I made some small modifications):

```<code>#include <iostream>

class Employee
{
public:
    char m_strName[25];
    int m_id;
    double m_wage;

    //set the employee information
    void setInfo(char *strName,int id,double wage)
    {
        strncpy(m_strName,strName,25);
        m_id=id;
        m_wage=wage;
    }

    //print employee information to the screen
    void print()
    {
        std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
    }
};

int main()
{
    //declare employee
    Employee abder;
    abder.setInfo("Abder-Rahman",123,400);
    abder.print();
    return 0;
}
</code>```

When I try to compile it, I get the following:

And, why is a pointer used here? void setInfo(char *strName,int id,double wage)

Thanks.

答: Regarding the last warning/error message - the first parameter of the setInfo() member function should be declared as const char*. Plain char* represents pointer to a mutable character array, which string literal "Abder-Rahman" isn't.

Title: C++ - class issue

Body:
At: http://www.learncpp.com/cpp-tutorial/82-classes-and-class-members/

There is the following program (I made some small modifications):

#include <iostream>

class Employee
{
public:
    char m_strName[25];
    int m_id;
    double m_wage;

    //set the employee information
    void setInfo(char *strName,int id,double wage)
    {
        strncpy(m_strName,strName,25);
        m_id=id;
        m_wage=wage;
    }

    //print employee information to the screen
    void print()
    {
        std::cout<<"Name: "<<m_strName<<"id: "<<m_id<<"wage: $"<<wage<<std::endl;
    }
};

int main()
{
    //declare employee
    Employee abder;
    abder.setInfo("Abder-Rahman",123,400);
    abder.print();
    return 0;
}

When I try to compile it, I get the following:

And, why is a pointer used here? void setInfo(char *strName,int id,double wage)

Thanks.


问:
self.kill() not removing sprite after Collision between Shot out Bullet and PowerUP
I'm trying to shoot out bullets right now and have them collide with a powerup successfully. Right now, I expect to do this because my bullet class has a checkCollision function. I also have called bullet.update in my update class in the GameScreen, so I'm not sure what's happening.

Here is my Bullet class:

```<code>class Bullet(Image):

    def __init__(self, screen_size, width, height, filename, color = (255, 0, 0)):

        super().__init__(screen_size, width, height, filename, color = (255, 0, 0))

    def checkCollision(self, powerup):

        return pygame.sprite.collide_mask(self, powerup)

    def removeBullet(self, powerup):
        if self.checkCollision(powerup):
            self.kill()

    def update(self, powerup):
        self.rect.centerx += 3
        self.removeBullet(powerup)
</code>```

Here is my PowerUp Class

```<code>class PowerUp(Image):

    kill_time = 0
    def __init__(self, screen_size, width, height, filename,  color = (255, 0, 0)):

        super().__init__(screen_size, width, height, filename, color = (255, 0 , 0))

        _centerx = random.randint(20, 1100)
        self.radius = 10
        self.rect = pygame.Rect(_centerx-self.radius,
                                _centery-self.radius,
                                self.radius*2, self.radius*2)

    def update(self):

        pass
</code>```

And here is where I run everything:

```<code>class GameScreen(SceneBase):

    randomNumber = random.randint(0, 2)
    def __init__(self):
        SceneBase.__init__(self)
        self.bg = pygame.image.load("images/asianbackground.jpg")
        self.my_font = pygame.font.SysFont("Arial", 50)

        self.bullets_group = pygame.sprite.Group()
        self.powerup_group = pygame.sprite.Group()
        self.player_paddle = classes.PlayerPaddle(screen_size, 40, 100, SceneBase.player1_character, self.bullets_group)

        self.ai_paddle = classes.AIPaddle(screen_size, 40, 100, SceneBase.characterlist[GameScreen.randomNumber])
        self.pong = classes.Pong(screen_size, 20, 20, "images/pokeball.png")

        self.now1 = pygame.time.get_ticks()

    def ProcessInput(self, events, pressed_keys):
        for event in events:
            self.player_paddle.handle_event(event)

    def Update(self):
        self.player_paddle.update()
        self.ai_paddle.update(self.pong, self.player_paddle)
        self.pong.update(self.player_paddle, self.ai_paddle)

        # if someone reaches a score of 2, then exit the game
        if self.player_paddle.score == 2 or self.ai_paddle.score == 2:
            SceneBase.is_game_over = True
            self.SwitchToScene(GameOverScreen())

        time_difference1 = pygame.time.get_ticks() - self.now1

        current_time = pygame.time.get_ticks()

        if time_difference1 >= 2000:
            powerup = classes.PowerUp(screen_size, 40, 40, "images/ramen.png")
            powerup.kill_time = current_time + 5000
            self.powerup_group.add(powerup)
            self.now1 = pygame.time.get_ticks()

        current_time = pygame.time.get_ticks()

        for powerup in self.powerup_group:
            for bullet in self.bullets_group:
                bullet.update(powerup)
            if powerup.kill_time <= current_time:
                self.powerup_group.remove(powerup)

    def Render(self, screen):
        screen.blit(self.bg, (0, 0))
        self.bullets_group.draw(screen)
        self.powerup_group.draw(screen)
        self.player_paddle.draw(screen)
        self.ai_paddle.draw(screen)
        self.pong.draw(screen)

        #Make the text for the user

        player_text = "Player 1" + ":" + str(self.player_paddle.score)
        player_text_image = self.my_font.render(player_text, True, GREEN)
        screen.blit(player_text_image, (screen_size[0] //4, screen_size[1] * 0.8))

        #Make the text for the AI
        ai_text = "Player 2" + ":" + str(self.ai_paddle.score)
        ai_text_image = self.my_font.render(ai_text, True, GREY)
        screen.blit(ai_text_image, (3* screen_size[0] // 4, screen_size[1] * 0.8))

    def SwitchToScene(self, next_scene):
        self.next = next_scene
</code>```

答:
Sprite has list with groups to which he belongs. You have to add bullet_group to this list in bullet and then kill() will remove bullet from group bullet_group

```<code>elif event.key == pygame.K_u:
  bullet = Bullet(screen_size, 25, 25, "images/naruto.png", color = (255, 0 , 0))
  bullet.rect.centerx = self.rect.centerx
  bullet.rect.centery = self.rect.centery

  bullet.add(self.bullet_group) # <-- add group to bullet

  self.bullet_group.add(bullet)
</code>```

Here bullet which should live only 3 seconds (3000ms).

See self.lifetime in __init__ and removeBullet

```<code>class Bullet(Image):

    def __init__(self, screen_size, width, height, filename, color = (255, 0, 0)):

        super().__init__(screen_size, width, height, filename, color = (255, 0, 0))

        self.lifetime = pygame.time.get_ticks() + 3000

    def checkCollision(self, powerup):

        return pygame.sprite.collide_mask(self, powerup)

    def removeBullet(self, powerup):
        if pygame.time.get_ticks() >= self.lifetime:
            self.kill()
        elif self.checkCollision(powerup):
            self.kill()

    def update(self, powerup):
        self.rect.centerx += 3
        self.removeBullet(powerup)
</code>```

Body:
I'm trying to shoot out bullets right now and have them collide with a powerup successfully. Right now, I expect to do this because my bullet class has a checkCollision function. I also have called bullet.update in my update class in the GameScreen, so I'm not sure what's happening.

Here is my Bullet class:

class Bullet(Image):

    def __init__(self, screen_size, width, height, filename, color = (255, 0, 0)):

        super().__init__(screen_size, width, height, filename, color = (255, 0, 0))

    def checkCollision(self, powerup):

        return pygame.sprite.collide_mask(self, powerup)

    def removeBullet(self, powerup):
        if self.checkCollision(powerup):
            self.kill()

    def update(self, powerup):
        self.rect.centerx += 3
        self.removeBullet(powerup)

Here is my PowerUp Class

class PowerUp(Image):

    kill_time = 0
    def __init__(self, screen_size, width, height, filename,  color = (255, 0, 0)):

        super().__init__(screen_size, width, height, filename, color = (255, 0 , 0))

        _centerx = random.randint(20, 1100)
        self.radius = 10
        self.rect = pygame.Rect(_centerx-self.radius,
                                _centery-self.radius,
                                self.radius*2, self.radius*2)

    def update(self):

        pass

And here is where I run everything:

class GameScreen(SceneBase):

    randomNumber = random.randint(0, 2)
    def __init__(self):
        SceneBase.__init__(self)
        self.bg = pygame.image.load("images/asianbackground.jpg")
        self.my_font = pygame.font.SysFont("Arial", 50)

        self.bullets_group = pygame.sprite.Group()
        self.powerup_group = pygame.sprite.Group()
        self.player_paddle = classes.PlayerPaddle(screen_size, 40, 100, SceneBase.player1_character, self.bullets_group)

        self.ai_paddle = classes.AIPaddle(screen_size, 40, 100, SceneBase.characterlist[GameScreen.randomNumber])
        self.pong = classes.Pong(screen_size, 20, 20, "images/pokeball.png")

        self.now1 = pygame.time.get_ticks()

    def ProcessInput(self, events, pressed_keys):
        for event in events:
            self.player_paddle.handle_event(event)

    def Update(self):
        self.player_paddle.update()
        self.ai_paddle.update(self.pong, self.player_paddle)
        self.pong.update(self.player_paddle, self.ai_paddle)

        # if someone reaches a score of 2, then exit the game
        if self.player_paddle.score == 2 or self.ai_paddle.score == 2:
            SceneBase.is_game_over = True
            self.SwitchToScene(GameOverScreen())

        time_difference1 = pygame.time.get_ticks() - self.now1

        current_time = pygame.time.get_ticks()

        if time_difference1 >= 2000:
            powerup = classes.PowerUp(screen_size, 40, 40, "images/ramen.png")
            powerup.kill_time = current_time + 5000
            self.powerup_group.add(powerup)
            self.now1 = pygame.time.get_ticks()

        current_time = pygame.time.get_ticks()

        for powerup in self.powerup_group:
            for bullet in self.bullets_group:
                bullet.update(powerup)
            if powerup.kill_time <= current_time:
                self.powerup_group.remove(powerup)

    def Render(self, screen):
        screen.blit(self.bg, (0, 0))
        self.bullets_group.draw(screen)
        self.powerup_group.draw(screen)
        self.player_paddle.draw(screen)
        self.ai_paddle.draw(screen)
        self.pong.draw(screen)

        #Make the text for the user

        player_text = "Player 1" + ":" + str(self.player_paddle.score)
        player_text_image = self.my_font.render(player_text, True, GREEN)
        screen.blit(player_text_image, (screen_size[0] //4, screen_size[1] * 0.8))

        #Make the text for the AI
        ai_text = "Player 2" + ":" + str(self.ai_paddle.score)
        ai_text_image = self.my_font.render(ai_text, True, GREY)
        screen.blit(ai_text_image, (3* screen_size[0] // 4, screen_size[1] * 0.8))

    def SwitchToScene(self, next_scene):
        self.next = next_scene

Body:
Sprite has list with groups to which he belongs. You have to add bullet_group to this list in bullet and then kill() will remove bullet from group bullet_group

elif event.key == pygame.K_u:
  bullet = Bullet(screen_size, 25, 25, "images/naruto.png", color = (255, 0 , 0))
  bullet.rect.centerx = self.rect.centerx
  bullet.rect.centery = self.rect.centery

  bullet.add(self.bullet_group) # <-- add group to bullet

  self.bullet_group.add(bullet)

Here bullet which should live only 3 seconds (3000ms).

See self.lifetime in __init__ and removeBullet

class Bullet(Image):

    def __init__(self, screen_size, width, height, filename, color = (255, 0, 0)):

        super().__init__(screen_size, width, height, filename, color = (255, 0, 0))

        self.lifetime = pygame.time.get_ticks() + 3000

    def checkCollision(self, powerup):

        return pygame.sprite.collide_mask(self, powerup)

    def removeBullet(self, powerup):
        if pygame.time.get_ticks() >= self.lifetime:
            self.kill()
        elif self.checkCollision(powerup):
            self.kill()

    def update(self, powerup):
        self.rect.centerx += 3
        self.removeBullet(powerup)


问:
Saving and restoring state of recyclerview with GridLayoutManager
The following is what I have in my code, but this isn't saving and restoring the state of my scroll position. I am trying to save the scroll position and restore it when user rotates the phone. </p>

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

    mRecyclerView = (RecyclerView) findViewById(R.id.rv_main_activity);
    mRecyclerView.setHasFixedSize(true);
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        mRecyclerView.setLayoutManager(mGridLayoutManager = new GridLayoutManager(this, 3));
    } else {
        mRecyclerView.setLayoutManager(mGridLayoutManager = new GridLayoutManager(this, 5));
    }

    mMoviesAdapter = new MoviesAdapter(this, this);
    mRecyclerView.setAdapter(mMoviesAdapter);

    if (Build.VERSION.SDK_INT > 10) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    getSupportLoaderManager().initLoader(ID_MOVIE_LOADER, null, this);
    MoviesSyncTask.syncMovies(this, "popular");

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelable(SCROLL_POSITION, mRecyclerView.getLayoutManager().onSaveInstanceState());
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if (savedInstanceState != null) {
        mListState = savedInstanceState.getParcelable(SCROLL_POSITION);
        mRecyclerView.getLayoutManager().onRestoreInstanceState(mListState);
    }
}
</code>```

答: In the activity using the recyclerview add a onOrientationChanged and set the recyclerview position to that saved instance state</p>

Body:
The following is what I have in my code, but this isn't saving and restoring the state of my scroll position. I am trying to save the scroll position and restore it when user rotates the phone.

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

    mRecyclerView = (RecyclerView) findViewById(R.id.rv_main_activity);
    mRecyclerView.setHasFixedSize(true);
    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        mRecyclerView.setLayoutManager(mGridLayoutManager = new GridLayoutManager(this, 3));
    } else {
        mRecyclerView.setLayoutManager(mGridLayoutManager = new GridLayoutManager(this, 5));
    }

    mMoviesAdapter = new MoviesAdapter(this, this);
    mRecyclerView.setAdapter(mMoviesAdapter);

    if (Build.VERSION.SDK_INT > 10) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    getSupportLoaderManager().initLoader(ID_MOVIE_LOADER, null, this);
    MoviesSyncTask.syncMovies(this, "popular");

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelable(SCROLL_POSITION, mRecyclerView.getLayoutManager().onSaveInstanceState());
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    if (savedInstanceState != null) {
        mListState = savedInstanceState.getParcelable(SCROLL_POSITION);
        mRecyclerView.getLayoutManager().onRestoreInstanceState(mListState);
    }
}


问:
writing every new char element to a single file if it's overwritten
I need to write some char element to a .txt before it gets overwritten by me in runtime.

I've tried doing like this:

```<code>public void keyTyped(KeyEvent keyEvent) {
    char c = keyEvent.getKeyChar();//this gets overwritten in runtime
    try {
        PrintWriter out = new PrintWriter("test.txt");
        out.print(c);
    } catch (FileNotFoundException x) {
        x.printStackTrace();
    }
}
</code>```

But as you may guess, if i type "java", only 'a'(last char) will be inside of test.txt. Also, when typed "rrr", same letters need to be saved too.
Sorry for bad English.
Any help is appreciated.

答:
From OP's edits in the question:

SOLUTION!

```<code>String s = "";//initializing a variable
s = s.concat(String.valueOf(c));//two-liner elegant solution!
</code>```

i had stuck on this for two days, so if you were thinking about this more than me  and/or have found more ellegant or effactive way, let me know.

Full code example:

```<code>String s = "";
public void keyTyped(KeyEvent keyEvent) {
    char c = keyEvent.getKeyChar();
    String s = s.concat(String.valueOf(c));
    try {
        PrintWriter out = new PrintWriter("test.txt");
        out.print(s);
        out.close();
    } catch (FileNotFoundException x) {
        x.printStackTrace();
    }
}
</code>```

Body:
I need to write some char element to a .txt before it gets overwritten by me in runtime.

I've tried doing like this:

public void keyTyped(KeyEvent keyEvent) {
    char c = keyEvent.getKeyChar();//this gets overwritten in runtime
    try {
        PrintWriter out = new PrintWriter("test.txt");
        out.print(c);
    } catch (FileNotFoundException x) {
        x.printStackTrace();
    }
}

But as you may guess, if i type "java", only 'a'(last char) will be inside of test.txt. Also, when typed "rrr", same letters need to be saved too.
Sorry for bad English.
Any help is appreciated.

Body:
From OP's edits in the question:

SOLUTION!

String s = "";//initializing a variable
s = s.concat(String.valueOf(c));//two-liner elegant solution!

i had stuck on this for two days, so if you were thinking about this more than me  and/or have found more ellegant or effactive way, let me know.

Full code example:

String s = "";
public void keyTyped(KeyEvent keyEvent) {
    char c = keyEvent.getKeyChar();
    String s = s.concat(String.valueOf(c));
    try {
        PrintWriter out = new PrintWriter("test.txt");
        out.print(s);
        out.close();
    } catch (FileNotFoundException x) {
        x.printStackTrace();
    }
}


问:
Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against
If dataitem is Null I want to show 0

```<code><asp:Label ID="Label18" Text='<%# Eval("item") %>' runat="server"></asp:Label>
</code>```

How can I accomplish this?

答:
Used a modified version of Jason's answer:</p>

```<code>public string ProcessMyDataItem(object myValue)
{
  if (myValue.ToString().Length < 1)
  {
     return "0 value";
  }

  return myValue.ToString();
}
</code>```

Body:
If dataitem is Null I want to show 0

<asp:Label ID="Label18" Text='<%# Eval("item") %>' runat="server"></asp:Label>

How can I accomplish this?

Body:
Used a modified version of Jason's answer:

public string ProcessMyDataItem(object myValue)
{
  if (myValue.ToString().Length < 1)
  {
     return "0 value";
  }

  return myValue.ToString();
}


问:
PHP foreach Loop data type complications and value retrieval
I am trying to pull data out of a foreach loop but I'm running into a strange phenomenon that I haven't encountered yet.

The first row of the CSV looks like this:

```<code>Part Number,Description,List Price
</code>```

Then Data so on and so forth.

What I have:

```<code>ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
   foreach (fgetcsv($openItems) as $key => $value) {
        $value = preg_replace('/\h+/', '', strtolower($value));
        echo $value;
        echo ' = ' . $key . " ";
        switch ($value) {
            case "partnumber":
                $pn = $key;
                break;
            case "description":
                $des = $key;
                break;
            case "listprice":
                $lp = $key;
                break;
        }
    }
    print_r("\npn: " . $pn . " des: " . $des . " lp: " . $lp);
}
</code>```

Print:

```<code>partnumber = 0 description = 1 listprice = 2
pn:  des: 1 lp: 2
</code>```

As you can see the first column is falsey so it is not assigned the proper value.

Alternative Print:

```<code>test = 0 partnumber = 1 description = 2 listprice = 3
pn: 1 des: 2 lp: 3
</code>```

I also tried an exercise after $key was echoed that checked:

```<code>if($value == 0) {
    echo " I'm 0 ";
}
</code>```

Print:

```<code>partnumber = 0  I'm 0. description = 1  I'm 0. listprice = 2  I'm 0.
pn:  des: 1 lp: 2
</code>```

But if you check for numeracy it comes back false:

```<code>if(is_numeric($value)) {
    echo " I'm a number. ";
}
</code>```

Print is unchanged:

```<code>partnumber = 0 description = 1 listprice = 2
pn:  des: 1 lp: 2
</code>```

That means it is 0 in a NULL or falsey sense right?

```<code>if(!$value) {
    echo " I'm False or Null. ";
}
</code>```

But Print is unchanged:

```<code>partnumber = 0 description = 1 listprice = 2
pn:  des: 1 lp: 2
</code>```

Type check:

```<code>echo "I'm of Type ". gettype($value) . ". ";
</code>```

returns:

```<code>partnumber = 0 I'm of Type string. description = 1 I'm of Type string. listprice = 2 I'm of Type string.
</code>```

Side Note:

```<code>case "partnumber":
    $pn = $key;
    break;
</code>```

is never accessed

```<code>case "partnumber":
    $pn = $key;
    echo "I Worked!";
    break;
</code>```

This returns with out any result.

Any, Suggestions?

This Scinario is thanks to @azjezz

```<code>$csv = [];
ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
    foreach (fgetcsv($openItems) as $key => $value) {
        $value = preg_replace('/\h+/', '', strtolower($value));
        $csv[$value] = (Int) $key;
        echo $value;
        echo ' = ' . $key . " ";
        switch ($csv[$value]) {
            case "partnumber":
                $pn = $key;
                break;
            case "description":
                $des = $key;
                break;
            case "listprice":
                $lp = $key;
                break;
        }
    }
    print_r("\npn: " . $pn . " des: " . $des . " lp: " . $lp);
}
</code>```

Results in:

```<code>partnumber = 0 description = 1 listprice = 2
pn: 0 des:  lp:
</code>```

Another weird scinario:

```<code>    switch ((int) $value) {
        case "partnumber":
            $pn = $key;
            break;
        case "description":
            $des = $key;
            break;
        case "listprice":
            $lp = $key;
            break;
    }
</code>```

Returns:

```<code>partnumber = 0 description = 1 listprice = 2
pn: 2 des:  lp:
</code>```

答:
Convert all values to integer then use $csv array.

```<code>$csv = [];
foreach (fgetcsv($openItems) as $key => $value) {
  $csv[$value] = (Int) $key;
}

var_dump($csv);
</code>```

Note that == and === are not the same!

```<code><?php

$a = 0;
$b = "0";

// == is the Equal Comparison Operator
//if $a is equal to $b after type juggling.
if($a == $b) {
  echo "YES ITS TRUE";
}

// === is the Identical Comparison Operator
//  if $a is equal to $b, and they are of the same type.
if($a === $b) {
  echo "Is it ?";
} else {
  echo "well its not";
}
</code>```

you can read more about comparison operators here : http://php.net/manual/en/language.operators.comparison.php

Body:
I am trying to pull data out of a foreach loop but I'm running into a strange phenomenon that I haven't encountered yet.

The first row of the CSV looks like this:

Part Number,Description,List Price

Then Data so on and so forth.

What I have:

ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
   foreach (fgetcsv($openItems) as $key => $value) {
        $value = preg_replace('/\h+/', '', strtolower($value));
        echo $value;
        echo ' = ' . $key . " ";
        switch ($value) {
            case "partnumber":
                $pn = $key;
                break;
            case "description":
                $des = $key;
                break;
            case "listprice":
                $lp = $key;
                break;
        }
    }
    print_r("\npn: " . $pn . " des: " . $des . " lp: " . $lp);
}

Print:

partnumber = 0 description = 1 listprice = 2
pn:  des: 1 lp: 2

As you can see the first column is falsey so it is not assigned the proper value.

Alternative Print:

test = 0 partnumber = 1 description = 2 listprice = 3
pn: 1 des: 2 lp: 3

I also tried an exercise after $key was echoed that checked:

if($value == 0) {
    echo " I'm 0 ";
}

Print:

partnumber = 0  I'm 0. description = 1  I'm 0. listprice = 2  I'm 0.
pn:  des: 1 lp: 2

But if you check for numeracy it comes back false:

if(is_numeric($value)) {
    echo " I'm a number. ";
}

Print is unchanged:

partnumber = 0 description = 1 listprice = 2
pn:  des: 1 lp: 2

That means it is 0 in a NULL or falsey sense right?

if(!$value) {
    echo " I'm False or Null. ";
}

But Print is unchanged:

partnumber = 0 description = 1 listprice = 2
pn:  des: 1 lp: 2

Type check:

echo "I'm of Type ". gettype($value) . ". ";

returns:

partnumber = 0 I'm of Type string. description = 1 I'm of Type string. listprice = 2 I'm of Type string.

Side Note:

case "partnumber":
    $pn = $key;
    break;

is never accessed

case "partnumber":
    $pn = $key;
    echo "I Worked!";
    break;

This returns with out any result.

Any, Suggestions?

This Scinario is thanks to @azjezz

$csv = [];
ini_set('auto_detect_line_endings', TRUE);
if (($openItems = fopen($uploadFile, 'r')) !== FALSE) {
    foreach (fgetcsv($openItems) as $key => $value) {
        $value = preg_replace('/\h+/', '', strtolower($value));
        $csv[$value] = (Int) $key;
        echo $value;
        echo ' = ' . $key . " ";
        switch ($csv[$value]) {
            case "partnumber":
                $pn = $key;
                break;
            case "description":
                $des = $key;
                break;
            case "listprice":
                $lp = $key;
                break;
        }
    }
    print_r("\npn: " . $pn . " des: " . $des . " lp: " . $lp);
}

Results in:

partnumber = 0 description = 1 listprice = 2
pn: 0 des:  lp:

Another weird scinario:

    switch ((int) $value) {
        case "partnumber":
            $pn = $key;
            break;
        case "description":
            $des = $key;
            break;
        case "listprice":
            $lp = $key;
            break;
    }

Returns:

partnumber = 0 description = 1 listprice = 2
pn: 2 des:  lp:

Body:
Convert all values to integer then use $csv array.

$csv = [];
foreach (fgetcsv($openItems) as $key => $value) {
  $csv[$value] = (Int) $key;
}

var_dump($csv);

Note that == and === are not the same!

<?php

$a = 0;
$b = "0";

// == is the Equal Comparison Operator
//if $a is equal to $b after type juggling.
if($a == $b) {
  echo "YES ITS TRUE";
}

// === is the Identical Comparison Operator
//  if $a is equal to $b, and they are of the same type.
if($a === $b) {
  echo "Is it ?";
} else {
  echo "well its not";
}

you can read more about comparison operators here : http://php.net/manual/en/language.operators.comparison.php


问:
copytree with loop in softlinks
Is there any way to detect softlink loops and omit copying them?

I have a directory that contain the softlink to himself. and I want to copy the folder recursively (including the meta data for all softlinks) except the one who create loop. it there any way to do so?

This is the structure of the director

```<code>makedir testdir
echo "hello world" > removeme.txt
cd testdir
ln TOPDIR ../testdir -s
ln -s ../removeme.txt slnk
</code>```

so the directory would be:

```<code>ls test_dir/ -l
total 64
lrwxrwxrwx 1 root root 15 Dec  7 09:31 slnk -> ../removeme.txt
lrwxrwxrwx 1 root root 11 Dec  6 12:46 TOPDIR -> ../test_dir
</code>```

this is the python:

```<code>from os.path import realpath
import shutil
shutil.copytree(realpath('testdir'),'removeme_softlink')
</code>```

It copies the folder into itself recursively until it raises exception. The error would like:

```<code>Traceback (most recent call last):
  File "./m.py", line 10, in <module>
   shutil.copytree(realpath(fileName),'removeme_softlink');
  File "/usr/lib64/python2.6/shutil.py", line 173, in copytree
   raise Error, errors
  shutil.Erro:
  /test_dir/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR', 'removeme_softlink/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR', "
  [Errno 40] Too many levels of symbolic links: ....
</code>```

答:
By using realpath() from docs:

Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path

EDIT:

I've done some more research and it seems this could be not solvable. All in all files are only sequences of bytes on your disk and what makes these bytes meaningful is your operating system. In particular symlinks are files with very arbitrary sequences of character which do not even need to be paths to existing files! When using methods like read() open() under your language layer it's your operating system that handles input/output operations on files. If it can't handle it, probably nothing won't and you'll have to make some workarounds like checking whether your symbolic link points to itself. I recommend this discussion:

Creating a symlink that contains the name of the current file may have
  a use.  I do not know.  But there isn't any content scanning of the
  contents of the symlink file.  Almost certainly someone someplace is
  using such a value as a flag of some sort.  If you try to open such a
  symlink the kernel will redirect back to itself creating a loop that
  will exceed the configured loop count and be detected.

Title: copytree with loop in softlinks

Body:
Is there any way to detect softlink loops and omit copying them?

I have a directory that contain the softlink to himself. and I want to copy the folder recursively (including the meta data for all softlinks) except the one who create loop. it there any way to do so?

This is the structure of the director

makedir testdir
echo "hello world" > removeme.txt
cd testdir
ln TOPDIR ../testdir -s
ln -s ../removeme.txt slnk

so the directory would be:

ls test_dir/ -l
total 64
lrwxrwxrwx 1 root root 15 Dec  7 09:31 slnk -> ../removeme.txt
lrwxrwxrwx 1 root root 11 Dec  6 12:46 TOPDIR -> ../test_dir

this is the python:

from os.path import realpath
import shutil
shutil.copytree(realpath('testdir'),'removeme_softlink')

It copies the folder into itself recursively until it raises exception. The error would like:

Traceback (most recent call last):
  File "./m.py", line 10, in <module>
   shutil.copytree(realpath(fileName),'removeme_softlink');
  File "/usr/lib64/python2.6/shutil.py", line 173, in copytree
   raise Error, errors
  shutil.Erro:
  /test_dir/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR', 'removeme_softlink/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR/TOPDIR', "
  [Errno 40] Too many levels of symbolic links: ....


问:
How to calculate Date difference in Hive
I'm a novice. I have a employee table with a column specifying the joining date and I want to retrieve the list of employees who have joined in the last 3 months. I understand we can get the current date using from_unixtime(unix_timestamp()). How do I calculate the datediff? Is there a built in DATEDIFF() function like in MS SQL? please advice!</p>

答:
If you need the difference in seconds (i.e.: you're comparing dates with timestamps, and not whole days), you can simply convert two date or timestamp strings in the format 'YYYY-MM-DD HH:MM:SS' (or specify your string date format explicitly) using unix_timestamp(), and then subtract them from each other to get the difference in seconds. (And can then divide by 60.0 to get minutes, or by 3600.0 to get hours, etc.)

Example:

UNIX_TIMESTAMP('2017-12-05 10:01:30') - UNIX_TIMESTAMP('2017-12-05 10:00:00') AS time_diff -- This will return 90 (seconds). Unix_timestamp converts string dates into BIGINTs.
```

More on what you can do with unix_timestamp() here, including how to convert strings with different date formatting: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

Body:
If you need the difference in seconds (i.e.: you're comparing dates with timestamps, and not whole days), you can simply convert two date or timestamp strings in the format 'YYYY-MM-DD HH:MM:SS' (or specify your string date format explicitly) using unix_timestamp(), and then subtract them from each other to get the difference in seconds. (And can then divide by 60.0 to get minutes, or by 3600.0 to get hours, etc.)

Example:

UNIX_TIMESTAMP('2017-12-05 10:01:30') - UNIX_TIMESTAMP('2017-12-05 10:00:00') AS time_diff -- This will return 90 (seconds). Unix_timestamp converts string dates into BIGINTs.

More on what you can do with unix_timestamp() here, including how to convert strings with different date formatting: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions


问:
How do you use a background.html page (instead of background.js) with Manifest 2 in a Chrome Extension
I have a Chrome Extension that worked great with the background specified as a script (background.js). Chrome created a virtual background.html page...

I need to a script to background (to get Google Drive integration) and so (as I understand it) need to move to background.html.

My Manifest now specifies:

```<code>"background": {
   "page": "background.html"},
</code>```

I added "https://apis.google.com/js/api.js" to my original setup (below) to gain Google Drive access for my Chrome Extension...but my background page was throwing "gapi is not defined" errors...so I switched to background.html to try and get my background processes to be able to access the Drive scripts.

```<code>"background": {
    "scripts": ["/dscripts/jquery-3.1.1.min.js","/dscripts/firebase.js","/dscripts/bootstrap-multiselect.min.js","/dscripts/bootstrap.min.js", "https://apis.google.com/js/api.js", "/scripts/background.js"]},
</code>```

My new background.html page looks like:

```<code><!DOCTYPE html>
<html>
  <head>
    <!--Original javascript / CDN -->
    <script type="text/javascript" src="dscripts/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="dscripts/jquery-ui.min.js"></script>
    <script type="text/javascript" src="dscripts/bootstrap.min.js"></script>
    <script type="text/javascript" src="dscripts/bootstrap-toggle.min.js"></script>

    <!-- FIREBASE  - I think we only need JS, not app.js and auth.js -->
    <script src="dscripts/firebase.js"></script>

    <!-- <script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<script> -->

    <!-- Google APIS -->
    <script type="text/javascript" src="https://apis.google.com/js/api.js"></script>

    <!-- background.js -->
    <script type="text/javascript" src="scripts/background.js">

  </head>
</html>
</code>```

I haven't made any changes to background.js - which holds chrome.runtime.onStartup.addListener and lots of well-established logic.

When I run my Extension and view the background.html console, I get:
Navigated to chrome-extension://XXXXX/background.html

Usually there would be a ton of debug console content generated by my background.js file. It's as if the background.js doesn't run.

Which makes sense, I guess - there's no dom to load and trigger actions.

I feel like I'm missing something really obvious (apologies) - but all the examples I could find use background.js, not background.html.

How do I get my javascript to fire when specifying background.html?

答:
Was missing closing  tag on the background.js file. Once I added that then the js in background ran exactly as expected.

So there is no extra action (for those coming after) required to use your own background.html page vs. the auto-generated one.

Body:
I have a Chrome Extension that worked great with the background specified as a script (background.js). Chrome created a virtual background.html page...

I need to a script to background (to get Google Drive integration) and so (as I understand it) need to move to background.html.

My Manifest now specifies:

"background": {
   "page": "background.html"},

I added "https://apis.google.com/js/api.js" to my original setup (below) to gain Google Drive access for my Chrome Extension...but my background page was throwing "gapi is not defined" errors...so I switched to background.html to try and get my background processes to be able to access the Drive scripts.

"background": {
    "scripts": ["/dscripts/jquery-3.1.1.min.js","/dscripts/firebase.js","/dscripts/bootstrap-multiselect.min.js","/dscripts/bootstrap.min.js", "https://apis.google.com/js/api.js", "/scripts/background.js"]},

My new background.html page looks like:

<!DOCTYPE html>


问:
how to load assets,such as .css, .js file, in finatra?
I try return a html file by finatra, the file itself loaded success but all assets can't, contains css, ico and js. Browser response 404:can't load resources.

find the document at bottom of the page:

-com.twitter.finatra.config.assetPath='/public': path to assets

I put public folder under src/main/resources/public, failed also.  :-(

my code simple as:

```<code>class Login extends Controller {

  get("/signin") { request: Request =>
    val content = Source.fromURL(getClass.getResource("/forwardend/signin.html")).mkString
    response.created.html(content).toFuture
  }
}
</code>```

答:
The guides were a bit confusing for me. They are very useful when you want to change settings but I wanted to know how to work with default settings using an example.

let's say your file is stored in: '/src/main/resources/public/hello.jpg'

You can load this directly using fileIO with the following

getClass.getClassLoader.getResource("samplecards/bcbs_anonymous.jpg").getPath can be used to return the path of the resource. you can use this information or this code segment accordingly with regular fileIO in scala.

If you're looking to make a finatra response, you can use the following for the example case:

```<code>get(GetImage) {
  request: ImageRequest => {
    response.ok.file(s"/public/hello.jpg")
  }
}
</code>```

The file requires a string and seems to default that string relative to {project_folder}/target/scala-x.xx/classes/ in the project folder which is populated with your static assets from the resources folder in src.

Body:
I try return a html file by finatra, the file itself loaded success but all assets can't, contains css, ico and js. Browser response 404:can't load resources.

find the document at bottom of the page:

-com.twitter.finatra.config.assetPath='/public': path to assets

I put public folder under src/main/resources/public, failed also.  :-(

my code simple as:

class Login extends Controller {

  get("/signin") { request: Request =>
    val content = Source.fromURL(getClass.getResource("/forwardend/signin.html")).mkString
    response.created.html(content).toFuture
  }
}

Body:
The guides were a bit confusing for me. They are very useful when you want to change settings but I wanted to know how to work with default settings using an example.

let's say your file is stored in: '/src/main/resources/public/hello.jpg'

You can load this directly using fileIO with the following

getClass.getClassLoader.getResource("samplecards/bcbs_anonymous.jpg").getPath can be used to return the path of the resource. you can use this information or this code segment accordingly with regular fileIO in scala.

If you're looking to make a finatra response, you can use the following for the example case:

get(GetImage) {
  request: ImageRequest => {
    response.ok.file(s"/public/hello.jpg")
  }
}

The file requires a string and seems to default that string relative to {project_folder}/target/scala-x.xx/classes/ in the project folder which is populated with your static assets from the resources folder in src.


问:
Storing Credit Card Info vs Re typing Info
This is a general security question and will probably end up in a discussion. I started to put the question on the Information Security site, but that site is for security experts, and I'm not an expert.

When I pay bills, and shop online, sometimes I save my credit card info on the website in use, sometimes I don't. In general, is it safer to store a credit card on a website, or to re type the information every time?

The tradeoff I see is sending your data over the wire numerous times, where any point along the path might be compromised, versus leaving it sitting on a server for a hacker. I would think saving the info on a website is riskier, because the amount of time the information is available for a hacker is much longer. And if the information is sitting on multiple websites/servers, then the risk is even greater. Maybe I'm wrong.

I guess the card information has to go over the wire again when making purchases, even if it is saved on a server, albeit there would be less hops, so perhaps there are no security advantages to saving the info on a website.

答:
It is always safer to type it in each time. The issue here is that you can't always solidly know how someone else (ie, a website) is going to store your data. Sure, they may encrypt it, but it could be a bad encryption cipher, or it could be a great one. You don't know. And because you don't know it's safer to keep it to yourself, and type it in each time.

However, keep in mind that unless you have a secure connection (https://) to the website you are entering your credit card data on, that data would be sent in cleartext. Cleartext meaning unencrypted data. Be weary of public wifi too. Sometimes they can replace the certificates used to encrypt websites with their own, and despite it being "secure", they would be able to read the data.

Short Answer: Only input sensitive data on networks you trust, like your home. And invest in a VPN if you want security no matter where you are.


答:
This is one way to do it (not complete solution but an example)

```<code>from collections import OrderedDict
import io

# Put your levels in a csvfile

data = '''\
62,144815767.41229948
63,159462585.01260683
64,175590796.3918269
65,193350231.1981527
66,212905873.000225
67,234439391.96980074
68,258150832.58147836
69,284260472.00806165
70,313010866.47588897
71,344669104.59058684'''

file = io.StringIO(data)

# Read file to dictionary
L = OrderedDict((int(i.split(',')[0]),float(i.split(',')[1])) for i in file.read().split('\n'))

experience = 450000

# Now to the code
current_lvl = next(k for k,v in L.items() if v > experience)
</code>```

Returns 62. Now that you have a dictionary you can do things like:

Calculate the exp needed for next level like this:

```<code>L.get(current_lvl+1)-experience
</code>```

Returns 159012585.01260683

Body:
How can I simply calculate the level based on an input experience?
I'm making a "pet chance generator" for a game called runescape. The program asks for your current experience and approximates the level based on the experience value input by the user. Below is the only method I could think of to do this but as you can see there is a wall of text basically copy pasted 40 times. Please help!

I currently have:

def calculate_level(xp):
if xp < 368599:
    level = 62
elif xp < 368599 * 1.101141**2:
    level = 63
elif xp < 368599 * 1.101141**3:
    level = 64
elif xp < 368599 * 1.101141**4:
    level = 65
elif xp < 368599 * 1.101141**5:
    level = 66
elif xp < 368599 * 1.101141**6:
    level = 67
elif xp < 368599 * 1.101141**7:
    level = 68
elif xp < 368599 * 1.101141**8:
    level = 69
elif xp < 368599 * 1.101141**9:
    level = 70
elif xp < 368599 * 1.101141**10:
    level = 71
elif xp < 368599 * 1.101141**11:
    level = 72
elif xp < 368599 * 1.101141**12:
    level = 73
elif xp < 368599 * 1.101141**13:
    level = 74
elif xp < 368599 * 1.101141**14:
    level = 75
elif xp < 368599 * 1.101141**15:
    level = 76
elif xp < 368599 * 1.101141**16:
    level = 77
elif xp < 368599 * 1.101141**17:
    level = 78
elif xp < 368599 * 1.101141**18:
    level = 79
elif xp < 368599 * 1.101141**19:
    level = 80
elif xp < 368599 * 1.101141**20:
    level = 81
elif xp < 368599 * 1.101141**21:
    level = 82
elif xp < 368599 * 1.101141**22:
    level = 83
elif xp < 368599 * 1.101141**23:
    level = 84
elif xp < 368599 * 1.101141**24:
    level = 85
elif xp < 368599 * 1.101141**25:
    level = 86
elif xp < 368599 * 1.101141**26:
    level = 87
elif xp < 368599 * 1.101141**27:
    level = 88
elif xp < 368599 * 1.101141**28:
    level = 89
elif xp < 368599 * 1.101141**29:
    level = 90
elif xp < 368599 * 1.101141**30:
    level = 91
elif xp < 368599 * 1.101141**31:
    level = 92
elif xp < 368599 * 1.101141**32:
    level = 93
elif xp < 368599 * 1.101141**33:
    level = 94
elif xp < 368599 * 1.101141**34:
    level = 95
elif xp < 368599 * 1.101141**35:
    level = 96
elif xp < 368599 * 1.101141**36:
    level = 97
elif xp < 368599 * 1.101141**37:
    level = 98
else:
    level = 99
return level

Body:
This is one way to do it (not complete solution but an example)

from collections import OrderedDict
import io

# Put your levels in a csvfile

data = '''\
62,144815767.41229948
63,159462585.01260683
64,175590796.3918269
65,193350231.1981527
66,212905873.000225
67,234439391.96980074
68,258150832.58147836
69,284260472.00806165
70,313010866.47588897
71,344669104.59058684'''

file = io.StringIO(data)

# Read file to dictionary
L = OrderedDict((int(i.split(',')[0]),float(i.split(',')[1])) for i in file.read().split('\n'))

experience = 450000

# Now to the code
current_lvl = next(k for k,v in L.items() if v > experience)

Returns 62. Now that you have a dictionary you can do things like:

Calculate the exp needed for next level like this:

L.get(current_lvl+1)-experience

Returns 159012585.01260683


问:
Laravel 5.5 - login explained?
My problem, or rather question is regarding the actual Login function of the builtin Authenthication feature by Laravel (v5.5).

I simply do not understand where the magic happens regarding logging the user into the system.

Here the login method within the LoginController

```<code>public function login(Request $request)
    {
        $this->validateLogin($request);

        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }
</code>```

and here the attemptedLogin method butthis one still does not give me any closure.

```<code>protected function attemptLogin(Request $request)
{
    return $this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    );
}
</code>```

Can ANYONE explain to me where exactly in laravel a user gets logged in into the application? i cant read it out of the documentation either.
Either i'm too blind or stupid but i really do not see it.

Thanks in advance!

答:
Yes, your hunch is correct. The actual login (match credentials and if successful, log user in) happens in the attemptLogin method. It's simply the same as an Auth::attempt call as explained in the Laravel docs

To understand the code completely, just read the code with the comments. I've pulled in the code below from the AuthenticatesUsers and ThrottlesLogins traits. The comments are pretty self explanatory:

```<code>/**
 * Handle a login request to the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
 */
public function login(Request $request)
{
    $this->validateLogin($request);
    // If the class is using the ThrottlesLogins trait, we can automatically throttle
    // the login attempts for this application. We'll key this by the username and
    // the IP address of the client making these requests into this application.
    if ($this->hasTooManyLoginAttempts($request)) {
        $this->fireLockoutEvent($request);
        return $this->sendLockoutResponse($request);
    }
    if ($this->attemptLogin($request)) {
        return $this->sendLoginResponse($request);
    }
    // If the login attempt was unsuccessful we will increment the number of attempts
    // to login and redirect the user back to the login form. Of course, when this
    // user surpasses their maximum number of attempts they will get locked out.
    $this->incrementLoginAttempts($request);
    return $this->sendFailedLoginResponse($request);
}
/**
 * Validate the user login request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 */
protected function validateLogin(Request $request)
{
    $this->validate($request, [
        $this->username() => 'required|string',
        'password' => 'required|string',
    ]);
}
/**
 * Attempt to log the user into the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return bool
 */
protected function attemptLogin(Request $request)
{
    return $this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    );
}
/**
 * Send the response after the user was authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
protected function sendLoginResponse(Request $request)
{
    $request->session()->regenerate();
    $this->clearLoginAttempts($request);
    return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
}
/**
 * The user has been authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function authenticated(Request $request, $user)
{
    //
}
/**
 * Get the failed login response instance.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Symfony\Component\HttpFoundation\Response
 *
 * @throws ValidationException
 */
protected function sendFailedLoginResponse(Request $request)
{
    throw ValidationException::withMessages([
        $this->username() => [trans('auth.failed')],
    ]);
}
/**
 * Determine if the user has too many failed login attempts.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return bool
 */
protected function hasTooManyLoginAttempts(Request $request)
{
    return $this->limiter()->tooManyAttempts(
        $this->throttleKey($request), $this->maxAttempts(), $this->decayMinutes()
    );
}
/**
 * Increment the login attempts for the user.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 */
protected function incrementLoginAttempts(Request $request)
{
    $this->limiter()->hit(
        $this->throttleKey($request), $this->decayMinutes()
    );
}
/**
 * Redirect the user after determining they are locked out.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 * @throws \Illuminate\Validation\ValidationException
 */
protected function sendLockoutResponse(Request $request)
{
    $seconds = $this->limiter()->availableIn(
        $this->throttleKey($request)
    );
    throw ValidationException::withMessages([
        $this->username() => [Lang::get('auth.throttle', ['seconds' => $seconds])],
    ])->status(423);
}
/**
 * Clear the login locks for the given user credentials.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 */
protected function clearLoginAttempts(Request $request)
{
    $this->limiter()->clear($this->throttleKey($request));
}
/**
 * Fire an event when a lockout occurs.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 */
protected function fireLockoutEvent(Request $request)
{
    event(new Lockout($request));
}
/**
 * Get the throttle key for the given request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return string
 */
protected function throttleKey(Request $request)
{
    return Str::lower($request->input($this->username())).'|'.$request->ip();
}
/**
 * Get the rate limiter instance.
 *
 * @return \Illuminate\Cache\RateLimiter
 */
protected function limiter()
{
    return app(RateLimiter::class);
}
</code>```

Title: Laravel 5.5 - login explained?

Body:
My problem, or rather question is regarding the actual Login function of the builtin Authenthication feature by Laravel (v5.5).

I simply do not understand where the magic happens regarding logging the user into the system.

Here the login method within the LoginController

public function login(Request $request)
    {
        $this->validateLogin($request);

        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

and here the attemptedLogin method butthis one still does not give me any closure.

protected function attemptLogin(Request $request)
{
    return $this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    );
}

Can ANYONE explain to me where exactly in laravel a user gets logged in into the application? i cant read it out of the documentation either.
Either i'm too blind or stupid but i really do not see it.

Thanks in advance!

Body:
Yes, your hunch is correct. The actual login (match credentials and if successful, log user in) happens in the attemptLogin method. It's simply the same as an Auth::attempt call as explained in the Laravel docs

To understand the code completely, just read the code with the comments. I've pulled in the code below from the AuthenticatesUsers and ThrottlesLogins traits. The comments are pretty self explanatory:

/**
 * Handle a login request to the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
 */
public function login(Request $request)
{
    $this->validateLogin($request);
    // If the class is using the ThrottlesLogins trait, we can automatically throttle
    // the login attempts for this application. We'll key this by the username and
    // the IP address of the client making these requests into this application.
    if ($this->hasTooManyLoginAttempts($request)) {
        $this->fireLockoutEvent($request);
        return $this->sendLockoutResponse($request);
    }
    if ($this->attemptLogin($request)) {
        return $this->sendLoginResponse($request);
    }
    // If the login attempt was unsuccessful we will increment the number of attempts
    // to login and redirect the user back to the login form. Of course, when this
    // user surpasses their maximum number of attempts they will get locked out.
    $this->incrementLoginAttempts($request);
    return $this->sendFailedLoginResponse($request);
}
/**
 * Validate the user login request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 */
protected function validateLogin(Request $request)
{
    $this->validate($request, [
        $this->username() => 'required|string',
        'password' => 'required|string',
    ]);
}
/**
 * Attempt to log the user into the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return bool
 */
protected function attemptLogin(Request $request)
{
    return $this->guard()->attempt(
        $this->credentials($request), $request->filled('remember')
    );
}
/**
 * Send the response after the user was authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
protected function sendLoginResponse(Request $request)
{
    $request->session()->regenerate();
    $this->clearLoginAttempts($request);
    return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
}
/**
 * The user has been authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function authenticated(Request $request, $user)
{
    //
}
/**
 * Get the failed login response instance.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Symfony\Component\HttpFoundation\Response
 *
 * @throws ValidationException
 */
protected function sendFailedLoginResponse(Request $request)
{
    throw ValidationException::withMessages([
        $this->username() => [trans('auth.failed')],
    ]);
}
/**
 * Determine if the user has too many failed login attempts.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return bool
 */
protected function hasTooManyLoginAttempts(Request $request)
{
    return $this->limiter()->tooManyAttempts(
        $this->throttleKey($request), $this->maxAttempts(), $this->decayMinutes()
    );
}
/**
 * Increment the login attempts for the user.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 */
protected function incrementLoginAttempts(Request $request)
{
    $this->limiter()->hit(
        $this->throttleKey($request), $this->decayMinutes()
    );
}
/**
 * Redirect the user after determining they are locked out.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 * @throws \Illuminate\Validation\ValidationException
 */
protected function sendLockoutResponse(Request $request)
{
    $seconds = $this->limiter()->availableIn(
        $this->throttleKey($request)
    );
    throw ValidationException::withMessages([
        $this->username() => [Lang::get('auth.throttle', ['seconds' => $seconds])],
    ])->status(423);
}
/**
 * Clear the login locks for the given user credentials.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 */
protected function clearLoginAttempts(Request $request)
{
    $this->limiter()->clear($this->throttleKey($request));
}
/**
 * Fire an event when a lockout occurs.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 */
protected function fireLockoutEvent(Request $request)
{
    event(new Lockout($request));
}
/**
 * Get the throttle key for the given request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return string
 */
protected function throttleKey(Request $request)
{
    return Str::lower($request->input($this->username())).'|'.$request->ip();
}
/**
 * Get the rate limiter instance.
 *
 * @return \Illuminate\Cache\RateLimiter
 */
protected function limiter()
{
    return app(RateLimiter::class);
}