text:
Q: Quaternion rotation ignoring yaw I'am working with Quaternion and one LSM6DSO32 captor gyro + accel. So I fused datas coming from my captor and after that I have a Quaternion, everything works well.
Now I'd like to detect if my Quaternion has rotated more than 90° about a initial quaternion, here is what I do, first I have q1 is my initial quaternion, q2 is the Quaternion coming from my fusion data, to detect if q2 has rotated more than 90° from q1 I do :
q_conj = conjugateQuaternion(q2);
q_mulitply = multiplyQuaternion(q1, q_conj);

float angle = (2 * acos(q_mulitply.element.w)) * RAD_TO_DEG;

if(angle > 90.0f)
   do something

this is works very well I can detect if q2 has rotated more than 90°. But my "problem" is I also detect 90° rotation in yaw, and I don't want integrate yaw in my test. Is it possible to nullify yaw (z component in my quaternion) without modify w, x and y component ?
My final objective is to detect a rotation more than 90° but without caring yaw, and I don't want to use Euler angle because I want avoid Gimbal lock
Edit : I want to calculate the magnitude between q1and q2 and don't care about yaw

A: The "yaw" of a quaternion generally means q_yaw in a quaternion formed by q_roll * q_pitch * q_yaw. So that quaternion without its yaw would be q_roll * q_pitch. If you have the pitch and roll values at hand, the easiest thing to do is just to reconstruct the quaternion while ignoring q_yaw.
However, if we are really dealing with a completely arbitrary quaternion, we'll have to get from q_roll * q_pitch * q_yaw to q_roll * q_pitch.
We can do it by appending the opposite transformation at the end of the equation: q_roll * q_pitch * q_yaw * conj(q_yaw). q_yaw * conj(q_yaw) is guaranteed to be the identity quaternion as long as we are only dealing with normalized quaternions. And since we are dealing with rotations, that's a safe-enough assumption.
In other words, removing the "Yaw" of a quaternion would involve:

*

*Find the yaw of the quaternion

*Multiply the quaternion by the conjugate of that.

So we need to find the yaw of the quaternion, which is how much the forward vector is rotated around the up axis by that quaternion.
The simplest way to do that is to just try it out, and measure the result:

*

*Transform a reference forward vector (on the ground plane) by the quaternion

*Take that and project it back on the ground plane.

*Get the angle between this projection and the reference vector.

*Form a "Yaw" quaternion with that angle around the Up axis.

Putting all this together, and assuming you are using a Y=up system of coordinates, it would look roughly like this:
quat remove_yaw(quat q) {
  vec3 forward{0, 0, -1};
  vec3 up{0, 1, 0};

  vec3 transformed = q.rotate(forward);

  vec3 projected = transformed.project_on_plane(up);
  if( length(projected) < epsilon ) {
    // TODO: unsolvable, what should happen here?
  }

  float theta = acos(dot(normalize(projected), forward));

  quat yaw_quat = quat.from_axis_angle(up, theta);

  return multiply(q, conjugate(yaw_quat));
}

This can be simplified a bit, obviously. For example, the conjugate of a axis-angle quaternion is the same thing as a quaternion of the negative angle around the same axis, and I'm sure there are other possible simplifications here. However, I wanted to illustrate the principle as clearly as possible.
There's also a singularity when the pitch is exactly ±90°. In these cases the yaw is gimbal-locked into being indistinguishable from roll, so you'll have to figure out what you want to do when length(projected) < epsilon.


text:
Q: Sorting lists by multiple variables in C# (Unity) I am new to programming and am in the process of converting a board game I play with my friends into a virtual version using Unity.  The game has a unique way of determining turn order after each round and I am really stuck on how to implement it. I keep each player's data in an instance of a  script named "Player" and have two functions to retrieve the relevant variables (GetUnits() and GetScore()).
I also keep a list of all the players in a List of Players "playerList".  There can be anywhere between 3-6 players.
The turn order for each round is the player with the least amount of units (ascending) and if two players are tied it is whoever has the higher score (descending).  If still tied, the players will have to roll a die for the third tiebreaker.  I need to capture the full turn order before starting the next round (I can't recalculate as each player takes their turn.)
In reality the third tiebreaker is almost never needed, and the second tiebreaker is rarely needed after round 2.  The exception to all of this is of course the very first turn of the game, where everyone is tied on score and units.  I could write just a separate die-roller function for Rd 1, but if I correctly code my setTurn function it should seamlessly handle Rd 1 and every other possible tie-scenario for any other turns.
Everytime I sit down to code this I wind up with tons of nested loops and if statements and I can't quite land at a solution.  Any advice on how to tackle this is greatly appreciated.

A: Implement IComparable for your Player class.  Then you can simply tell your List to Sort() itself and you're done.
Implementing the interface would look something like:
public class Player : IComparable<Player>
{

    private static Random R = new Random();

    public String Name;
    public int GetUnits() { return -1; } // obviously you have other code to support this
    public int GetScore() { return -1; } // obviously you have other code to support this

    public int CompareTo(Player other)
    {
        // sort by Units first
        int result = this.GetUnits().CompareTo(other.GetUnits());
        if (result == 0) // units were equal
        {
            // sort by score next
            result = this.GetScore().CompareTo(other.GetScore());
            if (result == 0) //scores were equal
            {
                // sort by dice roll: <=3 first player, otherwise second player
                result = (R.Next(1, 7) <= 3 ? -1 : 1);
            }
        }
        return result;
    }

}

Then you simply tell the list to Sort() itself!
playerList.Sort();

Original poster comment from another answer:

My only concern is what happens when there is a 3 (or more) way tie? I
  would want the 3 players to roll against each other simultaneously and
  not be 1 on 1 rolls. For example, before the first round (assuming 6
  players) I would want to do a 6 way die-roll.

This is actually more difficult than you think.  Consider we sort without the dice rolls first.  Then you have to iterate over the results and see which possible MULTIPLE sections of your sort have a tie.  Then you have to roll for each player with a tie.  Afterwards you have to sort only the SUBSETS of your already sorted list (leaving all other players in their current positions) to only re-arrange the subsections that were tied.  Remember, this could occur in multiple places of your list.  There is also the possibility that after rolling the dice there could be more ties requiring more passes.  There is an overload of Sort() that allows you to sort only a portion of a list.
So you'd have sort on (1) Units/Score, (2) Check for Ties, (3) Roll Dice, (4) Sort all SUBSETS that were tied, looping back to (2) as many times as necessary.

A: Here's a simple solution you could consider.
If I understood your rules correctly you want to sort players by lowest points goes first, then for tie-breaker 1 player with more points go first, then if still tied its just rng (Dice roll).
You could use c# IComparer to do that. Its simpler than it sounds:
 public class PlayerCompare : IComparer<Player>
{
    public int Compare(Player x, Player y)
    {
        int unitComparison = x.Units.CompareTo(y.Units);//Note im comparing X to Y here so its ascending order.

        if (unitComparison != 0)
        {
            //if they have not the same number of unit, return the higher one.
            return unitComparison;
        }
        else
        {
            //if they have the same number of units, compare the scores
            int scoreComparison = y.Score.CompareTo(x.Score);//Note im comparing Y to X here so its descending order.
            if (scoreComparison != 0)
            {
                //If they don't have the same number of units, return the lower one.
                return scoreComparison;
            }
            else
            {
                //They have the same number of units and score, roll a dice.
                if (UnityEngine.Random.value > 0.5f)//this is a straight up 50/50
                {
                    return 1;
                }
                else
                {
                    return -1;
                }
            }
        }
    }
}
public class Player
{
    public int Units;
    public int Score;

    public Player(int units, int score)
    {
        Units = units;
        Score = score;
    }
}
//This is an example list of players (6) with assorted scores/units
public List<Player> playerList = new List<Player>() {
    new Player(1,10), new Player(8, 2),
    new Player(2, 20), new Player(4, 0),
    new Player(1, 10), new Player(8, 20)
};
//This is the sorting
private void Sort()
{
    playerList.Sort(new PlayerCompare());
}

Now you just need to update the scores/units and at the end of the round call Sort(). I made a dummy player class for the example, obviously use yours.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I optimize my array_join (simulates a LEFT JOIN) function? I wrote the following code to take arrays in PHP and "join" them together the way that a LEFT JOIN would in MySQL. For my sake I wrote the function using foreach and passed the arrays in and returned a new array... I feel like it's pretty readable, but I also know that it's inefficient.
Ideally, I'd like this function to handle upwards of 10,000 rows per array, and I suspect that means: 1) passing $original by reference (to save memory), and 2) using one of PHP iterative array function rather than a foreach (to save processing time).
Usually I don't post these sort of "quiz" like questions, but I feel like the answer to this will benefit the community. (Like this guy: Join 2 multidimensional array)
May the 1) fastest, and 2) lowest memory consuming answer win! :P
<?php

// Join Arrays on Keys (**updated with knittl's suggestion**)
function array_join($original, $merge, $on) {
    if (!is_array($on)) $on = array($on);
    foreach ($merge as $remove => $right) {
        foreach ($original as $index => $left) {
            foreach ($on as $from_key => $to_key) {
                if (!isset($original[$index][$from_key])
                    || !isset($right[$to_key])
                    || $original[$index][$from_key] != $right[$to_key])
                    continue 2;
            }
            $original[$index] = array_merge($left, $right);
            unset($merge[$remove]);
        }
    }
    return array_merge($original, $merge);
}

// Test Arrays
$data1 = array(
    array(
        'productId' => '822335',
        'dateHour' => '2011-11-17 06:00:00',
        'qtySold' => '200',
        'qtyCanceled' => '10',
    ),
    array(
        'productId' => '822335',
        'dateHour' => '2011-11-17 07:00:00',
        'qtySold' => '100',
        'qtyCanceled' => '20',
    ),
    array(
        'productId' => '822336',
        'dateHour' => '2011-11-17 06:00:00',
        'qtySold' => '0',
        'qtyCanceled' => '30',
    ),
    array(
        'productId' => '822336',
        'dateHour' => '2011-11-17 07:00:00',
        'qtySold' => '50',
        'qtyCanceled' => '40',
    ),
);

$data2 = array(
    array(
        'entity_id' => '822335',
        'dateHour' => '2011-11-17 06:00:00',
        'productInventory' => '300',
    ),
    array(
        'entity_id' => '822335',
        'dateHour' => '2011-11-17 07:00:00',
        'productInventory' => '200',
    ),
    array(
        'entity_id' => '822336',
        'dateHour' => '2011-11-17 06:00:00',
        'productInventory' => '100',
    ),
    array(
        'entity_id' => '822336',
        'dateHour' => '2011-11-17 07:00:00',
        'productInventory' => '50',
    ),
);

// Usage
$result = array_join($data1, $data2, array(
    'productId' => 'entity_id',
    'dateHour' => 'dateHour'
));
print_r($result);

A: Better?
function array_join($original, $merge, $on) {
    if (!is_array($on)) $on = array($on);
    foreach ($merge as $remove => $right) {
        foreach ($original as $index => $left) {
            foreach ($on as $from_key => $to_key) {
                if (!isset($original[$index][$from_key])
                || !isset($right[$to_key])
                || $original[$index][$from_key] != $right[$to_key])
                    continue 2;
            }
            $original[$index] = array_merge($left, $right);
            unset($merge[$remove]);
        }
    }
    return array_merge($original, $merge);
}


text:
Q: Build reference EL tags to beans within a servlet? I have a servlet that reads an external HTML file as a String. I want to add a specific button inside this html which then makes reference to one of my EJB.
Therefore I inserted a:
String button=<h:commandButton value="Test" action="#{myBean.buttonMethod()}" />;

BUT this expression is not evaluated in the output of the servlet by:
out.println(thePage);

I do see just the code for the button, but it is not interpreted.
How can I insert such a reference to one of my method within a servlet dynamically?

A: That's not HTML code. That's JSF code. JSF code is supposed to be executed by declaring the tags in a Facelets or JSP file and having it processed by the FacesServlet by invoking its URL. It's definitely not the webbrowser who understands JSF as you seemed to think. It only understands HTML.
It's unclear what the concrete functional requirement and why you're attempting to mix JSF and Servlets this way (I can't for life imagine a sensible real world reason for this), but assuming that you've a plain HTML <form> which submits to a particular servlet, then one of the ways is to just write normal HTML code instead (which is also what JSF ultimately produces).
<input type="submit" name="buttonMethod" value="Test" />

In the servlet behind that particular <form action>, do something like
if (request.getParameter("buttonMethod") != null) {
    myBean.buttonMethod();
}


text:
Q: Is my "Games for Windows Marketplace" ID the same as my Windows Live ID? I am able to sign in on xbox live and hotmail using the same credentials I am entering in the "games for windows marketplace" application. However, I get an error code 80048882 with the details being Exception of type 'Microsoft.GamesForWindows.XLiveServices.LiveIdWrapper.IDCRLException' was thrown. I have added the application to my firewall. Any ideas what causes this?

A: I don't know what the problem was, but it went away after I switched to my home network. I was earlier behind a corporate firewall(which closes everything except port 80, i think) and a proxy. Not sure what was responsible, but it seems the error was due to connectivity problems.

A: For error:
Exception of type 'Microsoft.GamesForWindows.XLiveServices.LiveIdWrapper.IDCRLException' was thrown.
Type
netsh int ip reset c:\resetlog.txt

in the Command Prompt shell, and then press the Enter key and restart the PC.

Warning The netsh int ip reset command
  will reset all IP information, default
  gateway information, and DNS server
  information. Before you restart the
  computer after you run this command,
  you must configure your TCP/IP
  settings. Otherwise, you may not be
  able to connect to the computer
  remotely.

An addendum to the solution: Add the games exe to your Firewall exclusions list (Win XP/ Win Vista), and forward the following ports:
UDP 88
UDP 3074


text:
Q: Unpack array of objects into strings to display on a template in meteor I have a collection that has within it an object that holds an array of yet more objects that need to be unpacked to display in a template eventually.
The item in the sub-object is an order, and the order contains an array of line items.
I can get the order out fine, and see the array of line items no problem, but that's where I come unstuck.
I thought the following would work (using js to convert them into an array of strings to then display somehow)
Template.editEvent.helpers({
    lineItems: function(req) {
        var order = req.order;
        console.log(order);
        var lines;
        var count = 1;

        _.each(order, function(item) {
            var string;
            string +count++ + '. ';
            if(item.age) { // we have a cloathing string
                string += item.age + " " + item.sex + " " + item.Season + " " + "Number: " + item.Number;
                lines.push(string);
            }
            else if(item.pushers) {
                string += "Pushers needed: " + item.pushers;
                lines.push(string);
            }
            else if(item.cots) {
                string += "Cots needed: " + item.pushers;
                lines.push(string);
            }
            else if(items.extra) {
                string = "Extra info: " + item.extra;
                lines.push(string);
            }
            else {
                string = "Don't know this field";
                lines.push(string);
            }
            console.log(lines);
        });
        return lines;
    }
})

Where the tests are to see if the line item starts with the field shown (because the line items can be different).
However, the _.each is throwing up on the client, (it works fine in the startup code, so I guess from that its server only?)
Am I barking up the wrong tree here, should this embedded object be a new collection? If I am right, how do I go about displaying the returned string array (only just thought of this) in the template anway?

A: You are not initializing lines. Use:
var lines = [];

also, what is: string +count++ + '. '? did you mean string += count++ + '. '? If so then you also need to initialize string, e.g., var string = "";
From your comment, I get the sense that what you really want is to show the list reactively in the template. For that, you'd probably want to directly use a transform. Here is how that could work. Alternatively you could wrap your code into a Deps.autorun.
HTML (e.g., edit_event.html):
<template name="editEvent">
    {{lines}}
</template>

Javascript (e.g., edit_event.js):
Template.editEvent.lines = function() {
    var order = Orders.find(
        {id: Session.get('currentOrder')},
        {limit: 1,
         transform: function(order) {
             console.log(order);
             var lines;
             var count = 1;

             _.each(order, function(item) {
                 var string = count++ + '. ';
                 if(item.age) { // we have a cloathing string
                     string += item.age + " " + item.sex + " "
                         + item.Season + " " + "Number: " + item.Number;
                     lines.push(string);
                 }
                 else if(item.pushers) {
                     string += "Pushers needed: " + item.pushers;
                     lines.push(string);
                 }
                 else if(item.cots) {
                     string += "Cots needed: " + item.pushers;
                     lines.push(string);
                 }
                 else if(items.extra) {
                     string = "Extra info: " + item.extra;
                     lines.push(string);
                 }
                 else {
                     string = "Don't know this field";
                     lines.push(string);
                 }
                 console.log(lines);
             });
             return lines;
         }
        })
}


text:
Q: Windows Server 2008, "The requested operation requires elevation" Sorry for the newbe question, but I'm a developer who hasn't touch a Windows Server in years.  A recent project has required me to setup and configure a development VM running Windows Server 2008, IIS 7, and SQL Server 2008 Express.  I need to run commands in the command window and get the following message:
"The requested operation requires elevation"
Reminds me of SUDO in Ubuntu, what's the command to elevate?

A: This is a stab in the dark, but can you right click on the command icon, and select "Run as" and select an account with administrator privileges?

A: After you type cmd in the "run" box you can press Ctrl-Shift-Enter.

A: Alternatively, just run the command prompt itself as Administrator, and you won't need to worry about needing elevation.  You will, however, need to worry about having it.


text:
Q: Prevent Overlap When Using IE11 CSS Grid I'm making a date picker component that includes a calendar which I'm styling using CSS grid. It works great in all browsers except IE11 which shows all the elements in the same position in the top left corner. Am I missing an IE11 specific css property that will prevent this or is it not feasible for this to work in IE11?
How it looks in Chrome:

How it looks in IE11

Here's the code snippet:

.date-picker .dates .days {
    display: -ms-grid;
    display: grid;
    -ms-grid-columns: (1fr)[7];
    grid-template-columns: repeat(7, 1fr);
    justify-items: center;
}

.date-picker .dates .days-of-week {
    display: -ms-grid;
    display: grid;
    -ms-grid-columns: (1fr)[7];
    grid-template-columns: repeat(7, 1fr);
    justify-items: center;
}

.date-picker .dates .days .day {
    margin-top: .5em;
    margin-bottom: .5em;
    height: 36px;
    width: 36px;

}

.date-picker .dates .days-of-week .day {
    height: 36px;
    width: 36px;
}

S

M

T

W

T

F

S

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

A: After doing some more research it seems that I have to specify each cell's position in the grid in order for it to display correctly in IE11
So the css would look like this:

.date-picker .dates .days {
    display: -ms-grid;
    display: grid;
    -ms-grid-columns: (1fr)[7];
    grid-template-columns: repeat(7, 1fr);
    justify-items: center;
}

.date-picker .dates .days-of-week {
    display: -ms-grid;
    display: grid;
    -ms-grid-columns: (1fr)[7];
    grid-template-columns: repeat(7, 1fr);
    justify-items: center;
}

.date-picker .dates .days .day {
    margin-top: .5em;
    margin-bottom: .5em;
    height: 36px;
    width: 36px;

}

.date-picker .dates .days-of-week .day {
    height: 36px;
    width: 36px;
}

/* Because of IE11 we have to specify every cells place in the grid */

/* Days of the week cell placement */
.days-of-week div:nth-child(1){
    -ms-grid-column: 1;
    grid-column: 1;
    -ms-grid-row: 1;
    grid-row: 1;
}

.days-of-week div:nth-child(2){
    -ms-grid-column: 2;
    grid-column: 2;
    -ms-grid-row: 1;
    grid-row: 1;
}

.days-of-week div:nth-child(3){
    -ms-grid-column: 3;
    grid-column: 3;
    -ms-grid-row: 1;
    grid-row: 1;
}

.days-of-week div:nth-child(4){
    -ms-grid-column: 4;
    grid-column: 4;
    -ms-grid-row: 1;
    grid-row: 1;
}

.days-of-week div:nth-child(5){
    -ms-grid-column: 5;
    grid-column: 5;
    -ms-grid-row: 1;
    grid-row: 1;
}

.days-of-week div:nth-child(6){
    -ms-grid-column: 6;
    grid-column: 6;
    -ms-grid-row: 1;
    grid-row: 1;
}

.days-of-week div:nth-child(7){
    -ms-grid-column: 7;
    grid-column: 7;
    -ms-grid-row: 1;
    grid-row: 1;
}

/* Day cell placement */
/* Row one */
.days div:nth-child(1){
    -ms-grid-column: 1;
    grid-column: 1;
    -ms-grid-row: 1;
    grid-row: 1;
}

.days div:nth-child(2){
    -ms-grid-column: 2;
    grid-column: 2;
    -ms-grid-row: 1;
    grid-row: 1;
}

.days div:nth-child(3){
    -ms-grid-column: 3;
    grid-column: 3;
    -ms-grid-row: 1;
    grid-row: 1;
}

.days div:nth-child(4){
    -ms-grid-column: 4;
    grid-column: 4;
    -ms-grid-row: 1;
    grid-row: 1;
}

.days div:nth-child(5){
    -ms-grid-column: 5;
    grid-column: 5;
    -ms-grid-row: 1;
    grid-row: 1;
}

.days div:nth-child(6){
    -ms-grid-column: 6;
    grid-column: 6;
    -ms-grid-row: 1;
    grid-row: 1;
}

.days div:nth-child(7){
    -ms-grid-column: 7;
    grid-column: 7;
    -ms-grid-row: 1;
    grid-row: 1;
}

/* Row two */
.days div:nth-child(8){
    -ms-grid-column: 1;
    grid-column: 1;
    -ms-grid-row: 2;
    grid-row: 2;
}

.days div:nth-child(9){
    -ms-grid-column: 2;
    grid-column: 2;
    -ms-grid-row: 2;
    grid-row: 2;
}

.days div:nth-child(10){
    -ms-grid-column: 3;
    grid-column: 3;
    -ms-grid-row: 2;
    grid-row: 2;
}

.days div:nth-child(11){
    -ms-grid-column: 4;
    grid-column: 4;
    -ms-grid-row: 2;
    grid-row: 2;
}

.days div:nth-child(12){
    -ms-grid-column: 5;
    grid-column: 5;
    -ms-grid-row: 2;
    grid-row: 2;
}

.days div:nth-child(13){
    -ms-grid-column: 6;
    grid-column: 6;
    -ms-grid-row: 2;
    grid-row: 2;
}

.days div:nth-child(14){
    -ms-grid-column: 7;
    grid-column: 7;
    -ms-grid-row: 2;
    grid-row: 2;
}

/* Row three */
.days div:nth-child(15){
    -ms-grid-column: 1;
    grid-column: 1;
      -ms-grid-row: 3;
    grid-row: 3;
}

.days div:nth-child(16){
    -ms-grid-column: 2;
    grid-column: 2;
      -ms-grid-row: 3;
    grid-row: 3;
}

.days div:nth-child(17){
    -ms-grid-column: 3;
    grid-column: 3;
      -ms-grid-row: 3;
    grid-row: 3;
}

.days div:nth-child(18){
    -ms-grid-column: 4;
    grid-column: 4;
      -ms-grid-row: 3;
    grid-row: 3;
}

.days div:nth-child(19){
    -ms-grid-column: 5;
    grid-column: 5;
      -ms-grid-row: 3;
    grid-row: 3;
}

.days div:nth-child(20){
    -ms-grid-column: 6;
    grid-column: 6;
      -ms-grid-row: 3;
    grid-row: 3;
}

.days div:nth-child(21){
    -ms-grid-column: 7;
    grid-column: 7;
      -ms-grid-row: 3;
    grid-row: 3;
}

/* Row four */
.days div:nth-child(22){
    -ms-grid-column: 1;
    grid-column: 1;
        -ms-grid-row: 4;
    grid-row: 4;
}

.days div:nth-child(23){
    -ms-grid-column: 2;
    grid-column: 2;
        -ms-grid-row: 4;
    grid-row: 4;
}

.days div:nth-child(24){
    -ms-grid-column: 3;
    grid-column: 3;
        -ms-grid-row: 4;
    grid-row: 4;
}

.days div:nth-child(25){
    -ms-grid-column: 4;
    grid-column: 4;
        -ms-grid-row: 4;
    grid-row: 4;
}

.days div:nth-child(26){
    -ms-grid-column: 5;
    grid-column: 5;
        -ms-grid-row: 4;
    grid-row: 4;
}

.days div:nth-child(27){
    -ms-grid-column: 6;
    grid-column: 6;
        -ms-grid-row: 4;
    grid-row: 4;
}

.days div:nth-child(28){
    -ms-grid-column: 7;
    grid-column: 7;
        -ms-grid-row: 4;
    grid-row: 4;
}

/* Row five */
.days div:nth-child(29){
    -ms-grid-column: 1;
    grid-column: 1;
        -ms-grid-row: 5;
    grid-row: 5;
}

.days div:nth-child(30){
    -ms-grid-column: 2;
    grid-column: 2;
        -ms-grid-row: 5;
    grid-row: 5;
}

.days div:nth-child(31){
    -ms-grid-column: 3;
    grid-column: 3;
        -ms-grid-row: 5;
    grid-row: 5;
}

.days div:nth-child(32){
    -ms-grid-column: 4;
    grid-column: 4;
        -ms-grid-row: 5;
    grid-row: 5;
}

.days div:nth-child(33){
    -ms-grid-column: 5;
    grid-column: 5;
        -ms-grid-row: 5;
    grid-row: 5;
}

.days div:nth-child(34){
    -ms-grid-column: 6;
    grid-column: 6;
        -ms-grid-row: 5;
    grid-row: 5;
}

.days div:nth-child(35){
    -ms-grid-column: 7;
    grid-column: 7;
        -ms-grid-row: 5;
    grid-row: 5;
}

/* Row six */
.days div:nth-child(36){
    -ms-grid-column: 1;
    grid-column: 1;
        -ms-grid-row: 6;
    grid-row: 6;
}

.days div:nth-child(37){
    -ms-grid-column: 2;
    grid-column: 2;
        -ms-grid-row: 6;
    grid-row: 6;
}

.days div:nth-child(38){
    -ms-grid-column: 3;
    grid-column: 3;
        -ms-grid-row: 6;
    grid-row: 6;
}

.days div:nth-child(39){
    -ms-grid-column: 4;
    grid-column: 4;
        -ms-grid-row: 6;
    grid-row: 6;
}

.days div:nth-child(40){
    -ms-grid-column: 5;
    grid-column: 5;
        -ms-grid-row: 6;
    grid-row: 6;
}

.days div:nth-child(41){
    -ms-grid-column: 6;
    grid-column: 6;
        -ms-grid-row: 6;
    grid-row: 6;
}

.days div:nth-child(42){
    -ms-grid-column: 7;
    grid-column: 7;
        -ms-grid-row: 6;
    grid-row: 6;
}


text:
Q: jQuery - Key-Stroke Fires Reload and Shouldn't I have a form that, using jQuery, will create code that asks for Admin Approval in certain instances. The instance I'm specifically working on right now asks for Admin Approval if a lower level user tries to raise their own level (this can be allowed IF someone higher than them allows it).
For several other inputs on the page, I have the following code running to accept a stroke on the "Enter" key as a substitute for pushing the "Submit" button.
$('input[kind="pw1"]').keyup(function (key) {
  var enterKey = key.which;

  if (enterKey == 13) {
    $("#submit2").trigger("click");
    }
  });

This works for literally every single input I've done so far, except the one that I'm using for a user to input a higher level password. It's exactly the same as the code above, except it's input[kind="adPw"] to specify the Admin Approval input. Instead of triggering a click on the submit button, it tries to reload the page.

I've tried out a lot of different fixes thus far:

*

*Calling by ID

*Unbinding other clicks on all inputs

*Unbinding other clicks on all .button

*Unbinding other clicks on just this input

*Checked all code for anything linking this input to a reload

*Checked all code for anything linking any input to a reload

I did some research as well, but I'm not finding anything that's quite on target for the issue that I'm having. I'm also not receiving any errors or warnings in the console, and I'm 99% certain that all of my tags are properly closed.

I'm linking to a JSFiddle below so that you can also experience this crazy thing. I've re-coded it to speed up your time there. It will create two users for you: and admin, and a regular user, then it will reload the page. When it does, follow these steps:

*

*Log in as the regular user (U: "tester", P: "password")

*

*The "Enter key" code is at work here on both the Username input and the password input, and it definitely works here!

*Click on "Manage Users"

*Change tester's level to "Level 2"

*Click on "Save Changes"

This is the Admin Approval box. If you click the Submit button, it will give the alert "sub2", indicating a click on the button. If you hit "Enter" while in the input box, it should do the same thing, but instead it tries to reload the page.
JSFiddle: https://jsfiddle.net/claybarnard/r0cqs9dg/32/

A: Pressing Enter inside a single-input <form> will automatically submit the form. This is a quirk in most browsers.
The reason this specific area is the only one with the issue is because all of your other <form> areas have at least two inputs.
The easiest workaround is to just add another (hidden) input to the form:
<form>
  <input type="text">
  <input type="text" style="display: none;" />
</form>

Original: (demonstrating the single-input form quirk)

$("#adPw").keyup(function(key) {
  var enterKey = key.which;

  if (enterKey == 13) {
    $("#submit2").trigger("click");
  }
});

$("#submit2").on("click", function() {
  alert("sub2");
});

<form>Please enter a password from a Level 1 or Level 2 User.
<input type="password" id="adPw"></form>

Submit

Solution: (with extra input added)

$("#adPw").keyup(function(key) {
  var enterKey = key.which;

  if (enterKey == 13) {
    $("#submit2").trigger("click");
  }
});

$("#submit2").on("click", function() {
  alert("sub2");
});

<form>Please enter a password from a Level 1 or Level 2 User.
<input type="password" id="adPw"><input style="display: none"></form>

Submit

Here's your updated JSFiddle with this extra input added (OP's code does not work in JSFiddle for whatever reason): https://jsfiddle.net/18chywap/
See this question for more information:
Why does forms with single input field submit upon pressing enter key in input


text:
Q: When convert a void pointer to a specific type pointer, which casting symbol is better, static_cast or reinterpret_cast? In this program I have a void * as a parameter and want to cast it to a specific type. But I don't know which "casting symbol" to use.  Both static_cast or reinterpret_cast work.  Which one is better? Which one does the Standard C++ recommend?
typedef struct
{
    int a;
}A, *PA;

int foo(void* a)                // the real type of a is A*
{
    A* pA = static_cast<A*>(a); // or A* pA = reinterpret_cast<A*>(a);?
    return pA->a;
}

Here, is
A* pA = static_cast<A*>(a);

or
A* pA = reinterpret_cast<A*>(a);

more proper?


text:
Q: Pinning objects to memory I'm trying to think of a simple way to permanently pin a PHP object to memory and then have it available to other more transient objects to message with during their normal job of servicing  page requests. I'm still relatively new to Wordpress so maybe I'm making things too complicated ... let me demonstrate through an example what I would want to be able to do:

*

*Have a UOM (unit of measure) object load up at startup that polls the database for a list of units, the default units, categories of units (e.g., pounds is an imperial measurement), conversion rates, etc.

*Subsequent service requests that want to use UOM conversions or lookups would simply call the global UOM object ( $UOM->get_measures_for_category ('speed') ). This object would already be in memory and not need to go back to the database to service requests.

*An update() method on UOM would allow event or timing based triggers to ask for the UOM object to update itself.

This is just one example of where there is a some relatively static set of data that is used regularly by service requests and the repeated querying of the database would be wasteful. Hopefully people are familiar with this pattern and could maybe point me to some examples of how you would do this in a Wordpress/PHP environment.

A: For what you want this is not the best way of doing it. However what you're talking about requires knowledge of one of the fundamental tennets of PHP and programming in general aka scope, namely what the global scope is.
So, if you declare this in the global scope:
 $uom = new UOM_Class();

Then in any file afterwards you write:
global $uom;
$uom->something();

it will work.
This is all wasteful however, instead you would be better with static methods, and something more like a singleton pattern e.g.:
UOM::Something();

I leave it as a task for you to learn what a singleton is, and what scope is, these are fundamental tennets of PHP, and you should not claim to know PHP without knowing about scope. The best way of putting it is when in everyday conversation, it is called context, the global scope is tantamount to shouting in everyones ear at the same time. Everyone can access it, and its not something you want to pollute
I'm sorry if I seem a bit harsh, here's some articles that should help, they talk about scope, singletons and some other methods of doing it, like object factories
http://php.net/manual/en/language.variables.scope.php
http://www.homeandlearn.co.uk/php/php8p2.html
http://php.net/manual/en/language.oop5.patterns.php

A: I did not make my question clear when I initially posted but based on the conversation with Tom, I have agreed to repost this more clearly on Stack Overflow.


text:
Q: When should one include a variable in a regression despite it not being statistically significant? I am an economics student with some experience with econometrics and R. I would like to know if there is ever a situation where we should include a variable in a regression in spite of it not being statistically significant?

A: In econometrics this happens left and right. For instance, if you are using quarterly seasonality dummies Q2,Q3, and Q4, it happens often that as a group they're significant, but some of them are not significant individually. In this case you usually keep them all.
Another typical case is interactions. Consider a model $y\sim x*z$, where main effect $z$ is not significant but the interaction $x*z$ is. In this case it's customary to keep the main effect. There are many reasons why you should not drop it, and some of them were discussed in the forum.
UPDATE:
Another common example is forecasting. Econometrics is usually taught from inference perspective in economics departments. In inference perspective a lot of attention is on p-values and significance, because you're trying to understand what causes what and so on. In forecasting, there's not much emphasis on this stuff, because all you care is how well the model can forecast the variable of interest.
This is similar to machine learning applications, btw, which are making their way into economics recently. You can have a model with all significant variables that doesn't forecast well. In ML it's often associated with so called "over fitting". There's very little use of such model in forecasting, obviously.

A: You are asking two different questions:

*

*When does statistical significance not matter?

*When should we include a variable in a regression in spite of it not being statistically significant?

Edit: this was true about the original post, but might no longer be true after the edits.

Regarding Q1, I think it is on the border of being too broad. There are many possible answers, some already provided. One more example is when building models for forecasting (see the source cited below for an explanation).

Regarding Q2, statistical significance is not a sound criterion for model building. Rob J. Hyndman writes the following in his blog post "Statistical tests for variable selection":

Statistical significance is not usually a good basis for determining whether a variable should be included in a model, despite the fact that many people who should know better use them for exactly this purpose. <...> Statistical tests were designed to test hypotheses, not select variables.

Also note that you can often find some variables that are statistically significant purely by chance (the chance being controlled by your choice of the significance level). The observation that a variable is statistically significant is not enough to conclude that the variable belongs in the model.

A: The only thing that the result of "statistical insignificance" truly says is that, at the selected level of Type I error, we cannot even tell whether the effect of the regressor on the dependent variable is positive or negative (see this post).
So, if we keep this regressor, any discussion about its own effect on the dependent variable does not have statistical evidence to back it up.
But this estimation failure does not say that the regressor does not belong to the structural relation, it only says that with the specific data set we were unable to determine with some certainty the sign of its coefficient.
So in principle, if there are theoretical arguments that support its presence, the regressor should be kept.
Other answers here provided specific models/situations for which such regressors are kept in the specification, for example the answer mentioning the fixed-effects panel data model.

A: I'll add another "yes". I've always been taught -- and I've tried to pass it along -- that the primary consideration in covariate choice is domain knowledge, not statistics. In biostatistics, for instance, if I'm modelling some health outcome on individuals, then no matter what the regression says, you'll need some darn good arguments for me not to include age, race, and sex in the model.
It also depends on the purpose of your model. If the purpose is gaining better understanding of what factors are most associated with your outcome, then building a parsimonious model has some virtues. If you care about prediction, and not so much about understanding, then eliminating covariates may be a smaller concern.
(Finally, if you're planning to use statistics for variable selection, check out what Frank Harrell has to say on the subject -- http://www.stata.com/support/faqs/statistics/stepwise-regression-problems/, and his book Regression Modeling Strategies. Briefly, by the time you've used stepwise or similar statistically-based strategies for choosing the best predictors, then any tests of "are these good predictors?" are terribly biased -- of course they're good predictors, you've chosen them on that basis, and so the p values for those predictors are falsely low.)

A: Yes!
That a coefficient is statistically indistinguishable from zero does not imply that the coefficient actually is zero, that the coefficient is irrelevant. That an effect does not pass some arbitrary cutoff for statistical significance does not imply one should not attempt to control for it.
Generally speaking, the problem at hand and your research design should guide what to include as regressors.
Some Quick Examples:
And do not take this as an exhaustive list. It's not hard to come up with tons more...
1. Fixed effects
A situation where this often occurs is a regression with fixed effects.
Let's say you have panel data and want to estimate $b$ in the model:
$$ y_{it} = b x_{it} + u_i + \epsilon_{it}$$
Estimating this model with ordinary least squares where $u_i$ are treated as fixed effects is equivalent to running ordinary least squares with an indicator variable for each individual $i$.
Anyway, the point is that the $u_i$ variables (i.e. the coefficients on the indicator variables) are often poorly estimated. Any individual fixed effect $u_i$ is often statistically insignificant. But you still include all the indicator variables in the regression if you are taking account of fixed effects.
(Further note that most stats packages won't even give you the standard errors for individual fixed effects when you use the built-in methods. You don't really care about significance of individual fixed effects. You probably do care about their collective significance.)
2. Functions that go together...
(a) Polynomial curve fitting (hat tip @NickCox in the comments)
If you're fitting a $k$th degree polynomial to some curve, you almost always include lower order polynomial terms.
E.g. if you were fitting a 2nd order polynomial you would run:
$$ y_i = b_0 + b_1 x_i + b_2 x_i^2 + \epsilon_i$$
Usually it would be quite bizarre to force $b_1 = 0$ and instead run
$$ y_i = b_0 + b_2 x_i^2 + \epsilon_i$$
but students of Newtonian mechanics will be able to imagine exceptions.
(b) AR(p) models:
Let's say you were estimating an AR(p) model you would also include the lower order terms. For example for an AR(2) you would run:
$$ y_t = b_0 + b_1 y_{t-1} + b_2 y_{t-2} + \epsilon_t$$
And it would be bizarre to run:
$$ y_t = b_0 + b_2 y_{t-2} + \epsilon_t$$
(c) Trigonometric functions
As @NickCox mentions, $\cos$ and $\sin$ terms similarly tend to go together. For more on that, see e.g. this paper.
More broadly...
You want to include right-hand side variables when there are good theoretical reasons to do so.
And as other answers here and across StackExchange discuss, step-wise variable selection can create numerous statistical problems.
It's also important to distinguish between:

*

*a coefficient statistically indistinguishable from zero with a small standard error.

*a coefficient statistically indistinguishable from zero with a large standard error.

In the latter case, it's problematic to argue the coefficient doesn't matter. It may simply be poorly measured.

A: You may include a variable of particular interest if it is the focus of research, even if not statistically significant. Also, in biostatistics, clinical significance is often different than statistical significance.

A: Yes, there are. Any variable that could correlate with your response variable in a meaningful way, even at a statistically insignificant level, could confound your regression if it is not included. This is known as underspecification, and leads to parameter estimates that are not as accurate as they could otherwise be.
https://onlinecourses.science.psu.edu/stat501/node/328
From the above:

A regression model is underspecified (outcome 2) if the regression
  equation is missing one or more important predictor variables. This
  situation is perhaps the worst-case scenario, because an
  underspecified model yields biased regression coefficients and biased
  predictions of the response. That is, in using the model, we would
  consistently underestimate or overestimate the population slopes and
  the population means. To make already bad matters even worse, the mean
  square error MSE tends to overestimate σ², thereby yielding wider
  confidence intervals than it should.

A: Usually you do not include or exclude variables for linear regression because of their significance. You include them because you assume that the selected variables are (good) predictors of the regression criteria. In other words, the predictor selection is based on theory.
Statistical insignificance in linear regression can mean two things (of which I know):

*

*The insignificant predictors are not related to the criteria. Exclude them but keep in mind that the insignificance does not prove that they are unrelated. Check your theory.

*The predictors are insignificant because they can be expressed as a function of other predictors. The set of predictors is then called multicollinear. This does not make the predictors "bad" in any sense but redundant.

A valid reason to exclude insignificant predictors is that you are looking for the smallest subset of predictors that explain the criteria variance or most of it. If you have found it check your theory.


text:
Q: Variables de entorno Tomcat Estoy en un proyecto en el cual necesito tener varias variables de entorno en Angular, pero no puedo solicitar que sean en varias compilaciones (-ng build --prod, -ng build --des...), si no crear solo un -ng build de Angular, pero que pueda recoger del servidor de Tomcat las variables de entorno que tenga definidas en el mismo, para que a la hora de tener que modificarse, solo haya que habilitar dichas variables en Tomcat.
He estado buscando, pero lo único que encuentro es definir las variables de entorno en "environment.ts", pero me solicitan que no puede estar en el código fuente, si no que las recoja del servidor (como bien se puede hacer en Java).
¿Me podríais ayudar o pasar algún enlace donde explique esto, o es imposible comunicar las variables de entorno de un servidor Tomcat con Angular?
Gracias.


text:
Q: When trying to get an instance it returns null I have a Main class where I initialize the instance. I then with the help of a getter want to get that same instance from another class, however, it throws a null pointer exception.
Main class:
private static Main instance;

public static Main getInstance() {
    return instance;
}

private NPCLib npcLibrary;

@Override
public void onEnable() {
    Main.instance = this;

    npcLibrary = new NPCLib(this);

}

public NPCLib getNPCLib() {
    return npcLibrary;
}

Other class:
private NPCLib npcLibrary = Main.getInstance().getNPCLib(); //This is null

A: I have a Main class where I initialize the instance.
I dont see the instance initialization.For initializing the instance you need to call constructor for example:
private static Main instance=new Main();


text:
Q: Vim: Custom Shortcut for Select all and Copy I want to map a vim keyboard shortcut in .vimrc that copies all lines in a file to a shortcut key.  I've tried various forms of let and map, but they don't recognize the actual copy command.  I've also tried escaping the double-quotes, but that didn't work either.
What is the right way to do this?  Thanks
map <C-c> gg"+yG


text:
Q: Can't call the server using volley library? i am posting data to the server and while debugging i get the following error at this line. and unable to call the server.
network calls. i am using sql server version 2014, and the url to web services is localhost:8081/api/login/signup.
    StringRequest strReq = new StringRequest(Request.Method.POST, Constants.SIGN_UP,new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Snackbar.make(mainlayout, response.toString(), Snackbar.LENGTH_LONG).show();
                    Log.e("Responce from server", response);
                    avi.hide();
                    if(!response.contains("User")) {
                        spEdit.putString(getString(R.string.uaccount), response);
                        spEdit.commit();
                        Intent intent = new Intent(SignUp.this, Products.class);
                        intent.putExtra(getString(R.string.uemail), Email_Address);
                        intent.putExtra(getString(R.string.uphone), Phone_Number);
                        intent.putExtra(getString(R.string.upass), Password);
                        startActivity(intent);
                        finish();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            avi.hide();
            Log.e("Volley Error", error.toString());
            if(error.toString().contains("NoConnectionError")) {
                Snackbar.make(mainlayout, "Internet Not Available!", Snackbar.LENGTH_LONG).show();
            }else{
                Snackbar.make(mainlayout, "Webservice not responding!", Snackbar.LENGTH_LONG).show();
            }
        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> data = new HashMap<String, String>();
            String name[] = Name.split(" ");
        String first = "", last = "";
        boolean firstb = true;
        for (int i = 0; i < name.length; i++) {
            if (firstb) {
                first += name[i];
                firstb = false;
            } else {
                if (i == name.length - 1) {
                    last = name[i];
                } else {
                    first += " ";
                    first += name[i];
                }
            }
        }
        data.put("FirstName", first);
        data.put("LastName", last);
        data.put("LoginName", Login_Name);
        data.put("PrimaryEmail", Email_Address);
        data.put("PrimaryPasscode", Encrypted_Password);
        data.put("PhoneNumber", Phone_Number);
        data.put("MobileVerificationCode", smsCode);
        data.put("AccountType", UserType);

            return data;
        }
    };

    AppController.getInstance().addToRequestQueue(strReq, REQ_TAG);
}

Error:
E/AndroidRuntime: FATAL EXCEPTION: main
              Process: market.enxo.com.marketstore, PID: 3202
              java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
                  at com.android.volley.Request.<init>(Request.java:136)
                  at com.android.volley.toolbox.StringRequest.<init>(StringRequest.java:43)
                  at market.enxo.com.marketstore.SignUp$8.<init>(SignUp.java:361)
                  at market.enxo.com.marketstore.SignUp.signUpWS(SignUp.java:332)
                  at market.enxo.com.marketstore.SignUp$4.onClick(SignUp.java:297)
                  at android.view.View.performClick(View.java:5198)
                  at android.view.View$PerformClick.run(View.java:21147)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)


text:
Q: Android Map Center on location only within a certain radius I am developing a Farmers Market app.  I am having a little trouble getting the map set up just right.  I would like the map to

*

*zoom to a certain area if the user is not at the market

*When a user is at the market, zoom to their location

The way it seems to work now is, it always zooms to the same spot every time you open the app.  Even if I am at the market.
Any advice would be appreciated.
I have attached my locationmanager from the maps.java file in my project.  I can post the whole java file if that is helpful.

LocationManager locationManager = (LocationManager)getSystemService
                (Context.LOCATION_SERVICE);
        Location location = locationManager.getLastKnownLocation
                (LocationManager.PASSIVE_PROVIDER);
        Location centLocation = new Location("");
        centLocation.setLongitude(43.074691);
        centLocation.setLatitude(-89.384152);
        if(location != null) {
            if (location.distanceTo(centLocation) < 250)
                moveToLocation(new LatLng(location.getLatitude(), location.getLongitude()), 20, 1);
            else
                moveToLocation(new LatLng(43.0746443789058, -89.3860458564343), 20, 1);
        }
        else
        {
            moveToLocation(new LatLng(43.0746443789058, -89.3860458564343), 20, 1);
            AlertDialog.Builder builder1 = new AlertDialog.Builder(this);


text:
Q: How to make sign-up form stationary on a sliding sign-in/sign-up when the sign-up button is clicked? I'm doing a side project where I'm creating a website with a sigin-in/sign-up form. I'm using HTML, CSS, PHP and some JavaScript to create the website. I've followed this tutorial  to create the following sliding sign-in and sign-up form. The GIF to demo it is here
When a user clicks on the sign-up button, the form slides so that the Create Account form appears.
What I want to achieve is that when the user fills in the create account page and clicks on the sign up button, there's PHP running at the back to do some user authentication and then displays a message in the window where "Welcome Back!" is orrignally meant to appear like so
However, when the user clicks the sign-up button after filling out the form, the page seems to refreshes and is returned to the sign in form. It's only when I click on the sign up button on the sign in form that it goes back to the sign up form and displays the message on the back.
My question is how would I be able to make the sign up form stationary when the the sign up button is clicked so that the message can appear on the left.
Here is my code so far (loginRegister.html)....

        <form method="POST">

Create Account

            or use your email to join us
            <input type="text" placeholder="Username" name = "username"/>
            <input type="text" placeholder="Email" name = "email"/>
            <input type="password" placeholder="Password" name = "password"/>
            <input type="password" placeholder="Confirm Password" name = "pwdConfirm"/>
            <input type = "text" placeholder="First Name" name = "firstName">
            <input type = "text" placeholder="Last Name" name = "lastName">
            <button id="Sign-Up">Sign Up</button>
        </form>

        <form method="POST" action="authentication.php">

Sign In

            or use your account
            <input type="text" placeholder="Username" name = "username" required/>
            <input type="password" placeholder="Password" name = "password" required/>
            Forgot your Password
            <button type="submit" name="Sign-In">Sign In</button>
        </form>

                <?php
                require_once "db.php";
                if(isset($_POST['username']) && isset($_POST['password']) && isset($_POST['pwdConfirm']) && isset($_POST['firstName']) && isset($_POST['lastName']) && isset($_POST['email']))
                {
                    // Declaring and Initializing variables from the registration form
                    $uname = $_POST['username'];
                    $pwd = $_POST['password'];
                    $pc = $_POST['pwdConfirm'];
                    $fname = $_POST['firstName'];
                    $lname = $_POST['lastName'];
                    $email = $_POST['email'];

                    $usernameCheck = "SELECT * FROM user WHERE userName='$uname'";
                    $results = mysqli_query($db, $usernameCheck);
                    $table = mysqli_num_rows($results);

                    // Error checking the form to make sure it complies with the specifications given
                    if($uname == '' || $pwd == '' || $fname == '' || $pc == '' || $lname == '' || $email == '')
                    {
                        echo "
All fields must be filled in order to continue
";
                    }
                    else if($table > 0)
                    {
                        echo "
The user name that you have entered is already taken! Please enter a new username
";
                    }
                    else if($pwd != $pc)
                    {
                        echo "
The password that you have entered does not match! Please try again
";
                    }
                    else
                    {
                        $sql = "INSERT INTO user (userName, emailAddress, password, firstName, LastName) VALUES ('$uname', '$email', '$pwd', '$fname', '$lname')";
                        // Inserting the user's details into the database and displaying a confirmation message
                        // to the user with a link to return to the login page
                        mysqli_query($db, $sql);
                        echo '
Congratulations! Your account was created successfully. Click here to return to the home page
';
                    }
                }
                else
                {
                    echo "
Welcome Back!
 ";
                    echo "
To keep connected with us please log in with your account
 ";
                    echo '  <button class="over-btn" id="signin">Sign In</button> ';
                }
                ?>

Don't have an account?

Create an account by clicking the button bellow

                <button class="over-btn" id="signup">Sign Up</button>

....and for the Javascript (loginRegister.js)
const signUpbtn = document.getElementById('signup');
const signInbtn = document.getElementById('signin');
const container = document.getElementById('cont');

signUpbtn.addEventListener('click',()=>{
   container.classList.add('right-panel-active')
});

signInbtn.addEventListener('click',()=>{
    container.classList.remove('right-panel-active')
});

...and finally the CSS (logReg.css)
#contPadding{
    padding: 25px;
}
h1
{
    font-weight: bold;
    margin:0;
}

p{
    font-size: 14px;
    font-weight: 100;
    line-height: 20px;
    letter-spacing: 0.5px;
    margin: 20px 0 30px;
}
span{
    font-size: 12px;
}
a{
    color: #333;
    text-decoration: none;
}
.cont
{
    background: #fff;
    border-radius: 10px;
    box-shadow:  0 14px 28px rgba(0,0,0,0.25),0 10px 10px rgba(0,0,0,0.22);
    position: relative;
    overflow: hidden;
    width: 100%;
    min-height: 546px;
    min-width: 50%;

}

.form-container
{
    background: #fff;
    display: flex;
    flex-direction: column;
    padding: 0 50px;
    height: 100%;
    justify-content: center;
    align-items:center;
    text-align: center;
}
.social-container
{
    margin: 20px 0;
}
.social-container a{
    border: 1px solid #ddd;
    border-radius: 50%;
    display: inline-flex;
    justify-content:center;
    align-items: center;
    margin: 0 5px;
    height: 40px;
    width: 40px;
}
.form-container input{
    background:  #eee;
    border: none;
    padding: 12px 15px;
    margin: 8px 0;
    width: 100%;
}
.form-container button
{
    margin-top: 10px;
}

button
{
    border-radius: 20px;
    border: 1px solid #ffaa23;
    background: #ffaa23;
    color: #fff;
    font-size: 12px;
    font-weight: bold;
    padding:12px 45px;
    letter-spacing: 1px;
    text-transform: uppercase;
    transition: transform 80ms ease-in;

}
button:active{
    transform: scale(0.95);
}
button:focus
{
    outline: none;
}
button.over-btn
{
    background: transparent;
    border-color: #fff;
}
.social:hover
{
    color: #ffaa23;
    border-color: #ffaa23;
}
.form-container
{
    position: absolute;
    top: 0;
    height:  100%;
    transition:  0.6s ease-in-out;
}

.signin-container
{
    left:0;
    width: 50%;
    z-index:2;
}

.signup-container
{
    left:0;
    width: 50%;
    z-index:1;
    opacity: 0;
}
.signup-container button
{
    background: #ff782b;
    border-color: #ff782b;
}
.signup-container .social:hover
{
    color: #ff782b;
    border-color: #ff782b;
}
.signin-container button
{
    background: #ffa705;
    border-color: #ffa705;
}
.signin-container .forgot
{
  font-size: 12px;
  display: flex;
  flex-direction: column;
  margin-bottom: 0;
}

.overlay-container
{
    position: absolute;
    top=0;
    left: 50%;
    width: 50%;
    height: 100%;
    overflow: hidden;
    transition: transform 0.6s ease-in-out;
    z-index: 100;
}
.overlay
{
    background: #ffaa23;
    background: linear-gradient(to right, #ed2a31,#ffaa23) no-repeat 0 0 / cover;
    color: #fff;
    position: relative;
    left: -100%;
    height: 100%;
    width: 200%;
    transform: translateX(0);
    transition: transform 0.6s ease-in-out;
}
.overlay-panel
{
    position: absolute;
    top: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 0 40px;
    height: 100%;
    width: 50%;
    text-align: center;
    transform: translateX(0);
    transition:  transform 0.6s ease-in-out;
}
.overlay-right
{
    right: 0;
    transform: translateX(0);
}
.overlay-left
{
    transform: translateX(-20%);
}

.cont.right-panel-active .signin-container
{
    transform: translateX(100%);
}
.cont.right-panel-active .overlay-container
{
    transform: translateX(-100%);
}
.cont.right-panel-active .signup-container
{
    transform: translateX(100%);
    opacity: 1;
    z-index: 5;
}

.cont.right-panel-active .overlay
{
    transform: translateX(50%);
}
.cont.right-panel-active .overlay-left
{
    transform: translateX(0);
}
.cont.right-panel-active .overlay-right
{
    transform: translateX(20%);
}

I would very much appreciate it if someone could help me. I've been stuck on this for a while and would like to resolve it.
Cheers!


text:
Q: Lagrange method with inequality constraints Please can someone help me with the follwoing optimisation:
Minimize $-x+y$
subject to $0 \leq x \leq a$ and $0 \leq y \leq 1$ and $x^2 \leq y$.
I am not sure how to deal with inequality constraints. Do I still make the Lagrangian:
$$L(x,y,\lambda_1, \lambda_2, \lambda_3) = -x+y+ \lambda_1(x^2-y) + \lambda_2(x-a) + \lambda_3(y-1)$$ and then find the derivatives and make them equal 0? I am not sure what to do.

A: I'll try to solve it using an example to make it clearer. We'll solve the same problem, but I'll use some value for $a$. Let it be $a = \frac 12$. now we have the following conditions:
$$f(x,y) = y-x$$
$$g(x) = x - \frac 12 \le 0$$
$$h(y) = y - 1 \le 0$$
$$j(x,y) = x^2 - y \le 0$$
Now the Lagrangian looks like:
$$F(x,y,\lambda,\lambda_1, \lambda_2) = y-x + \lambda(\frac 12 - x) + \lambda_1(1-y) + \lambda_2(y-x^2)$$
Now we take partial derivatives:
$$F_x = -1 - \lambda - 2\lambda_2x = 0$$
$$F_y = 1 - \lambda_1 + \lambda_2 = 0$$
We know that the last three terms(constrains) must equal $0$ and gradients $\lambda, \lambda_1, \lambda_2$ must have non-negative value. Now we have 8 distinctive cases:
Case 1: $\lambda = \lambda_1 = \lambda_2 = 0$
This case is contradiction, beacuse substituting back into the partial derivatives we'll get $-1 = 0$ and $1=0$, which is impossible.
Case 2: $\lambda = \lambda_1 = y-x^2 = 0$
This would imply that $\lambda_2 = -1$. Now substituting into the first partial derivative we have;
$$-1 + 2x = 0$$
$$2x = 1$$
$$x = \frac 12$$
This implies that $y = \frac 14$
So now we have one potential solution $(x,y) = (\frac 12, \frac 14)$
Case 3: $\lambda = 1-y = \lambda_2 = 0$
Also this case is contradiction, because in the first partial derivative we'll end up with $-1 = 0$
Case 4: $\lambda = 1-y = y-x^2 = 0$
Now we have that $y=1 = x^2$, beacuse only positive values are allowed, we have $x=1$, but from the constrain $x \le \frac 12$ so this case doesn't provide a solution.
Case 5: $\frac 12 - x = \lambda_1 = \lambda_2 = 0$
This case leads to contradiction in the second partial derivative.
Case 6: $\frac 12 - x = \lambda_1 = x^2-y = 0$
This implies that $x = \frac 12$, implying that $y = \frac 14$. But we've already obtained this solution, so there aren't new solution in this case.
Case 7: $\frac 12 - x = y-1 = \lambda_2 = 0$
This implies that $x= \frac 12$ and $y=1$. This solution satisfy all conditions so we obtatin another solution: $(x,y) = (\frac 12, 1)$
Case 8: $\frac 12 - x = y-1 = x^2-y = 0$
This case doesn't provide a solution, because it's impossible all three conditions to be fulfilled at same time.
Plugging the two solution into the initial function we have:
$$f(\frac 12, \frac 14) =\frac14 - \frac12 = -\frac 14$$
$$f(\frac 12, 1) = 1 - \frac 12 = \frac 12$$
The first one is the global minima, while the second is a saddle point.
If you check the boundary, you'll get another few solution, but you'll just find a few saddle point and the maxima, that occurs at $f(0,1) = 1 - 0 = 1$

A: Ok, here's what you do, you use Lagrange Multipliers to solve it on the BOUNDARIES of the allowed region, and you search for critical points (minima or maxima) within the interior of the region, not near its boundary. You compare all the distinct solutions and you find the one that optimizes it the most. If the point you're looking for is in the interior, it will be a critical point, and if it's on the boundary, it will be found using Lagrange Multipliers, so you have to do both to cover all your bases. Just remember, you have several distinct regions you need to test over for the boundary, namely you need to test along the line x=0 and y between 0 and 1, you need to test the line x=a for y between 0 and 1, etcetera. A pain to be sure. And then, finally, you have to test the CORNERS of the region too, just to be absolutely certain that the minimum isn't on one of the corners. Actually, since the function you're trying to minimize is linear, I can all but guarantee you the minimum WILL be one of the corners, if not for that x^2

A: I think Stefan4024 made a mistake in his answer. I shall hence write my own solution and compare the result and argument for why I believe the provided answer is wrong.
Specifying The Problem
First, we have that we must minimize:
$f_1(x,y)=-x+y$
Let's convert it to a maximization problem by multiplying by -1:
$f_2(x,y)=x-y$
We now specify the constraints in the generic form:
${h_j(x,y)}\leq{0}$
Which gives:
$-a\le h_1(x,y)=x-a\leq{0}$
$-1\le h_2(x,y)=y-1\leq{0}$
$-y\le h_3(x,y)=x^2-y\leq{0}$
As for the lagrange equation:
$\nabla{f_2(x,y)}=\sum_i{\lambda_i\cdot\nabla{g_i(x,y)}}+\sum_j{\mu_j\cdot\nabla{h_j(x,y)}}$
Since we have no fixed constraints, we can omit g's sum entirely such that:
$\nabla{f_2(x,y)}=\sum_j{\mu_j\cdot\nabla{h_j(x,y)}} \Rightarrow (1,-1)=\mu_1(1,0)+\mu_2(0,1)+\mu_3(2x,-1)$
The second last step in formulating the problem is to state that:
$\forall{j},\mu_j\ge0$. Here is where I think the Stefan4024 answer fails, as I think his answer has no consistent usage of this specifier; and thus an invalid answer comes up. I question the validity of the assertion that it is a saddle point, as the Hessian matrix shows that it is indeterminate (0) at that point.   The invalidity can be observed in Case 2, where $\lambda_2 = -1$.
The last step will be to formulate the tightness of inequalities through:
$\forall j, \mu_j\cdot h_j(x,y) = 0$
Which implies that either of the factors are 0.

Here are all equation/inequalities for a quick reference.

*

*$1=\mu_11+\mu_3\cdot2x$

*$-1=\mu_2-\mu_3$

*$\forall j, \mu_j\cdot h_j(x,y) = 0$

*$\forall{j},\mu_j\ge0$

Solving The Problem
Case 1: $\mu_1 = \mu_2 = \mu_3 = 0$
Plugging the values into equation 2, we observe that -1 = 0; such that this case is a contradiction.
Case 2: $\mu_1=\mu_2=x^2-y=0$
From equation 2 we get $1=\mu_3$, such that substituting in equation 1 results in $\frac{1}{2}=x$.
Since $y=±\sqrt{x}$ according to $x^2-y=0$, we observe from eq. 3.2 that $0\le y$, such that y can only be $\frac{1}{4}$.
Point: $(2^{-1}, 4^{-1})$
Case 3: $\mu_1=y-1=\mu_3=0$
We observe that equation 1 grants: 1=0, which invalidates case 3.
Case 4: $\mu_1=y-1=x^2-y=0$
From equation 1 we get: $\mu_3=\frac{1}{2x}$, by substituting in eq. 2, we get: $\mu_2=\frac{1}{2x}-1$.
Since $y=1, x=±1$, we get from the above that $\mu_2=\frac{1}{2x}-1$, which only results in a negative result in either case, in which case $\mu_2 \lt 0$, which invalidates this case.
Case 5: $x-a=\mu_2=\mu_3=0$
From equation 2 we observe that -1 = 0, which contradicts this case.
Case 6: $x-a=\mu_2=x^2-y=0$
From equation 2 we get $\mu_3=1$, which we plug into the first, giving:
$1/2=x$. Since $y=1, x^2=y$, then x must be ±1, which contradicts that it must be 1/2.
Case 7: $x-a=y-1=\mu_3=0$
Pluggin into equation 2, we get $\mu_2=-1$ which is invalid.
Case 8: $x-a=y-1=x^2-y=0$
$x=a, y=1, y=x^2 \Rightarrow 1=a^2 \Rightarrow a=±1$. From our boundaries, we observe that a is always larger than 0, thus, a = 1.
Plugging the values into equation 1: $1=\mu_1+\mu_3\cdot2$, we observe that our system of equations is unsolvable, so this answer is invalidated.
Set Of Solutions
We have acquired only 1 point:
A = $(1/2, 1/4)$
$f_1($**A**$) = -1/4$
We can easily observe that this answer is only valid for $a \ge 1/2$.
As stated before, Stefan has a "saddle point" on this linear curve at (1,1), which appears invalid to me (as I think his answer used a negative/positive lambda quite liberally.)
When $a$ becomes smaller than 1/2, we need to solve for boundary points; which appear to me to be located at $(a, a^2)$ (Without evidence).

A: An approach using analytic geometry.
Problem: Minimize $ - x +y $ , $x \in [0,a]$, $a \gt 0$, $y \in [0,1] $, subject to $x^2 \leq y$ .
1) $a \geq 1$.
Consider the parabola $y = x^2 $in the first quadrant. Of interest are $y -$ values on or above the parabola, where $x \in [0,1 ]$  ( since $y(1) =1$ ).
Now look at the family of straight lines $y = x + C$. Each line $y$ has slope $m = 1$ and $y$ - intercept $C$.
A tangent to the parabola has a slope $y'(x) = 2x$.
Choose: $x = 1/2$, then $y = 1/4$, and $y'(1/2) = 1$.
At the above point a member of the family $y = x + C$ touches the parabola.
$C = y - x = 1/4 - 1/2 = - 1/4$.
Any member of the family $y = x + C$ with smaller $C$ will be parallel, pass below, and have no common points with our area of interest.
$Min (C) = min (y - x) =  - 1/4$ .
2) $a \geq 1/2$.
The above reasoning can be repeated to find
$Min (C) = - 1/4$.
3) $a \lt 1/2$.
We consider the area of interest, on or above the parabola  $y = x^2$ where $x \in [0,a]$ and $y \in [0,1]$.
Choose the boundary point $x = a$, then $y = a^2$.
We find C for a line that passes through this point.
$C = y - x = a^2 - a = (a - 1/2)^2 - 1/4$.
Reasoning for our choice:
This line $y = x + (a - 1/2)^2 - 1/4$ has one common point with the parabola, the boundary point. No other point is common to both curves. (Note also: $f'(x) \lt 1$ for $x \in [0,a]$)
Any smaller choice for $C$, I.e. moving south on the $y -$axis, will result in a line parallel to the above, below,  that does not intersect $y = x^2$ for $x \in [0,a]$.
$Finally :$
$Min (C) = min (y - x) = (a - 1/2)^2 - 1/4$.
Comments welcome.


text:
Q: How does Android return the values from a void function? I was glancing through this function getLocationOnScreen()
void getLocationOnScreen (int[] outLocation)
Computes the coordinates of this view on the screen. The argument must be an array of two integers. After the method returns, the array contains the x and y location in that order.
What I don't understand here is that if I am passing an array something like this,
int position[] = new int[2];

view.getLocationOnScreen(position);

The function being return type being void how does my array contains those values without the function returning it ?
Note: This question is not a duplicate of the below as it explains the working of the 2 methods.
getLocationOnScreen() vs getLocationInWindow()

A: The primitive type will pass variable by copy it value ,so the value will not change after the method finished.But as you see ,you created an array type using keyword new ( new int[2]),so the this variable is an object type, when you passed param to the method it would be reference of the array.
In Java the primitive type pass by value while object type by reference and you can not chose to pass address like C using operation &

A: It's about the reference an object from memory. You are sending your object adress which means the adress referencing your object. And the function using this adress of your object. With that way the function can change your object's value but can not change the adress.
Here, this idea coming from C language
And usage in java:

Java works exactly like C. You can assign a pointer, pass the pointer to a method, follow the pointer in the method and change the data that was pointed to. However, you cannot change where that pointer points


text:
Q: Calculating physico-chemical properties of amino acids in Biojava I need to calculate the number and percentages of polar/non-polar, aliphatic/aromatic/heterocyclic amino acids in this protein sequence that I got from UNIPROT, using BioJava.
I have found in the BioJava tutorial how to read the Fasta files and implemented this code. But I have no ideas how to solve this problem.
If you have some ideas please help me.
Maybe there are some sources where I can check it.
This is the code.
package biojava.biojava_project;

import java.net.URL;

import org.biojava.nbio.core.sequence.ProteinSequence;
import org.biojava.nbio.core.sequence.io.FastaReaderHelper;

public class BioSeq {
    // Inserting the sequence from UNIPROT
    public static ProteinSequence getSequenceForId(String uniProtId) throws Exception {
        URL uniprotFasta = new URL(String.format("https://rest.uniprot.org/uniprotkb/P31574.fasta", uniProtId));
        ProteinSequence seq = FastaReaderHelper.readFastaProteinSequence(uniprotFasta.openStream()).get(uniProtId);
        System.out.printf("id : P31574", uniProtId, seq, System.getProperty("line.separator"), seq.getOriginalHeader());
        System.out.println();
        return seq;
    }
    public static void main(String[] args) {
        try {
            System.out.println(getSequenceForId("P31574"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

A: I don't know if BioJava stores these properties anywhere. But it's easy to just list all the amino acids with their properties manually. Then iterate over the sequence and count those that satisfy the property. Here's an example for the polarity:
import java.io.InputStream;
import java.net.URL;
import java.util.Set;

import org.biojava.nbio.core.sequence.ProteinSequence;
import org.biojava.nbio.core.sequence.compound.AminoAcidCompound;
import org.biojava.nbio.core.sequence.io.FastaReaderHelper;

public class BioSeq {

    public static void main(String[] args) throws Exception {
        ProteinSequence seq = loadFromUniprot("P31574");

        int polarCount = numberOfOccurrences(seq, /*Polar AAs:*/ Set.of("Y", "S", "T", "N", "Q", "C"));
        System.out.println("% of polar AAs: " + ((double)polarCount)/seq.getLength());
    }

    public static ProteinSequence loadFromUniprot(String uniProtId) throws Exception {
        URL uniprotFasta = new URL(String.format("https://rest.uniprot.org/uniprotkb/%s.fasta", uniProtId));
        try (InputStream is = uniprotFasta.openStream()) {
            return FastaReaderHelper.readFastaProteinSequence(is).get(uniProtId);
        }
    }

    private static int numberOfOccurrences(ProteinSequence seq, Set<String> bases) {
        int count = 0;
        for (AminoAcidCompound aminoAcid : seq)
            if(bases.contains(aminoAcid.getBase()))
                count++;
        return count;
    }
}

PS: don't forget to close IO streams after you used them. In the example above I used try-with-resources syntax which automatically closes the InputStream.


text:
Q: How to customer login with prestashop 1.7 I am stuck over here for a long. I have to verify password on user login, but the password_verify returns always false.
Here is the code I have used
password_verify('123456789', '$2y$10$SB6R0jIknvmTNNL.h5rbd.FE1udyPiZHqr4g\/gMOYbgJtBWXLkkgm')

I am using Prestashop v1.7. Please help


text:
Q: HTML and Touch Devices I am developing a responsive web site and one of the requirements is to have elements that are only 'clickable' on mobile devices, especially iPhones and iPads (not on PC browsers).
Say for example, displaying phone numbers which can only be clicked on an touch device ... but on desktop browsers it should only display and not be clickable.
Is it possible to this?
If so, can anyone guide me on how to go about doing this please.
Thank you.

A: You can use PHP user agent detection,for example like this:
<?php
if(strstr($_SERVER['HTTP_USER_AGENT'],"iPad") || strstr($_SERVER['HTTP_USER_AGENT'],"iPhone")){
    echo 'bar'
}
else{
    echo 'bar'
}
?>

Or in JavaScript (replace bar with the link location and foo with a fitting id.):
function iPhoneLinks(){
    if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPad/i))) {
        document.getElementById('foo').href='bar';
    }
}

    This will only be a link on iOS

Untested but should work


text:
Q: Internet connection fails on 1 machine, the other is OK I have 2 Windows XP computers connected on a wireless network via a router. Both machines can see each other's shared folders and on machine 1 I can connect to the Internet without a problem. The connection on the other machine OTOH is so sssllooowww that Firefox (or IE8 for that matter) never manages to load a page ("The connection was reset" after 15 minutes or so).
PC 2 can ping the router and the other machine successfully, and also load the router's setup page.
The software (OS + apps) was reinstalled today, and Firefox did work properly after installation.
Any ideas?
TIA
Steven
edit:
Fixed! Installed an audio(!) driver and everything is peachy again (for the time being). Question can be closed AFAIC.

A: I would unplug all connections to the router and turn it off and unplug it.  Then, turn off both XP machines.  Plug the router in and then boot XP machine number 1.  Go to the setup network wizard and create a network that replaces the existing network.  Call the work-group something different than it was named before.
Then boot XP machine number 2, and go through the same network setup wizard.  Name the work-group the same.  Reboot both XP machines and see what happens.
What you might find is that some config was messed up and doing a fresh configuration may help this.
PS - At some point early one, perhaps before configuring the network for the two XP machines, plug one directly into the router and be sure it is configured correctly, i.e., IP range set (192.168.10.10 through 100, for example, DHCP enabled, etc).

A: I'm afraid this will be another "not an answer". I don't know how else to approach this other than by trying to narrow down the scope of the problem via trial and error.
The first thing I suggest you do is determine whether the problem is related to your wireless connection or not. Turn off wireless on the PC experiencing problems and connect it via wired ethernet. Then use it long enough to determine whether the problem is still there.
If the problem goes away then I think that would suggest a problem with your wireless connection. If the problem persists when using a wired connection to the router, then I would guess ... and it's only a WAG ... that you have some sort of malware installed on that system.
When you "reinstalled" the software, did you do an XP repair install or did you format the partition and do a "clean" XP install?

A: Fixed! Installed an audio(!) driver and everything is peachy again.
edit:
the driver was the SIGMATEL driver which you can download from the audio section in the XPS M1710 downloads on the Dell support page. Filename is R171789.exe. Note that I'm not quite sure that the lacking driver was the culprit, but the installation was the only change I made.


text:
Q: drawing balls from an urn Suppose there are 7 golf balls in an urn and you draw balls in 3 stages without replacement.  First you draw 2, then 3, and then the remaining 2.  How many ways are there to do this?
I believe the answer would be ${7\choose 2}{5\choose 3}$ but I am making this question up so  would like to verify the answer.

A: Your answer appears correct.
In particular, the number of ways will be the number of ways of choosing groups of 2,3 and 2 from a set of 7.
This is the multinomial coefficient ${7 \choose 2, 3, 2} = \frac{7!}{2!\, 3! 2!}$.
As you state in your question, its value is equal to ${7\choose 2}{5\choose 3}$, which you can arrive at via a number of different routes.


text:
Q: MVC Razor doesn't detect LINQ Methods I used [assembly: PreApplicationStartMethod(typeof(XXXXX), "Init")] in AssemblyInfo.cs.
After built the project, Razor view engine doesn't detect IEnumerable collection Methods like WHERE in editor.
When i commented this line and built project, problem solved.
How i can do, if i want these together?

A: Need to make sure you are referencing and using System.Linq; namespaces as LINQ is mostly extension methods.


text:
Q: R2 Score and RMS Loss in ML.NET - Is there something wrong with the way I trained the model or is it on the data that I have? I am fairly new in ML.NET. Right now, I just simply copy and then paste the code from here ML.NET Tutorial Taxi Fare. But, instead of using the given CSV files, I am using the BMW.DE historical stock prices from 1996 to date. I got it from here Finance Yahoo.
My goal is to predict the "Open" value on the next day.
A sample data in my BWM.DE.csv file:
    Date,Open
    12/19/1996,20.0
    12/20/1996,20.3
    12/23/1996,20.6
    12/27/1996,20.8
    12/30/1996,20.9
    1/2/1997,20.7
    1/3/1997,20.8
    1/6/1997,20.9
    1/7/1997,20.6

My BMW Class
    public class BmwOpenClass
    {
        [LoadColumn(0)]
        public string Date;

        [LoadColumn(1)]
        public float Open;
    }

    public class PredictedOpen
    {
        [ColumnName("Score")]
        public float Open;
    }

And this is how I trained it
public static ITransformer Train(MLContext mlContext, string dataPath)
        {
            IDataView dataView = mlContext.Data.LoadFromTextFile<BmwOpenClass>(dataPath, hasHeader: true, separatorChar: ',');

            var pipeline = mlContext.Transforms.CopyColumns(outputColumnName: "Label", inputColumnName: "Open")
                .Append(mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "DateEncoded", inputColumnName: "Date"))
                .Append(mlContext.Transforms.Concatenate("Features", "DateEncoded"))
                .Append(mlContext.Regression.Trainers.FastTree());

            var model = pipeline.Fit(dataView);

            SaveModelAsFile(mlContext, model);

            return model;
        }

Now, when I tried to evaluate the model(I have a separate CSV file for evaluation purposes) I'm getting a Model quality of:
R2 Score: -2.57
RMS Loss: 59.94
I'm pretty sure the -2.57 is not normal, because per the documentation, R2 should be closer to 1 to tell the model is fine.

A: I am not sure using OneHotEncoding is a good idea for your Date column, as is. The whole Date day/month/year is not a categorical value. It would be better if the day, month, year get split in separate columns, than you can encode them each. Also, just the Date is not a very good feature, that's why the model might not be a good one. Try to augment your dataset by adding a column for day of the week, something around whether it is a holiday or not and it should do slightly better. Ultimately for a better model you need more features...


text:
Q: Is it safe to use default value with not null when adding a new column? We have a Rails app powered by Postgresql v11.4 where I want to add a new column with a default value and a not null constraint like below:
ALTER TABLE "blogs" ADD "published" boolean DEFAULT FALSE NOT NULL

I know adding a new column with a default value is safe. However, is it still safe when combined with NOT NULL? Or will it lock the database? Thanks!

A: That statement is safe.
An ALTER TABLE will never lock "the database", it will only lock the table.
Postgres will not actually rewrite the table because you provided a constant value (false) for the default value. So adding the column is actually done in a few milliseconds because Postgres only stores the information that a new column is available. When that column is accessed (and no value is available) then it will use the default value from the column's definition. Only when a row is updated, the new row will contain an actual value for the column.
If the default value was an expression that could potentially be different for each row, Postgres would rewrite the table to physically put the default column into all rows. But still, that would only lock the table, not the database.
From Postgres documentation about ALTER TABLE: "When a column is added with ADD COLUMN and a non-volatile DEFAULT is specified, the default is evaluated at the time of the statement and the result stored in the table's metadata. That value will be used for the column for all existing rows. If no DEFAULT is specified, NULL is used. In neither case is a rewrite of the table required."
And tested in Postgres v.11: dbfiddle.uk


text:
Q: ¿como solucionar este problema en python? Un comercio dispone de los datos correspondientes a las N (dato) ventas:

*

*código del artículo (A o B) .

*precio unitario del artículo .

*cantidad de    artículos.

Se pide:

*

*la cantidad de total artículos vendida de cada código

*el importe total de los artículos de cada código( sabiendo que si la
cantidad de artículos por cada compra supera los 10, se le hace un descuento del 20%)

'''
art=" "
costoA=0
contA=0
impTA=0
costoB=0
contB=0
impTB=0
print("ingrese numero de ventas")
n=int(input())
for i in range(n):
    print("ingrese articulo A o B")
    art.islower()
    art=str(input())
    if art=="a":
        print("ingrese el precio unitario del articulo")
        precioA=float(input())
        print("ingrese la cantidad de articulos de A va a comprar")
        cantA=float(input())
        contA=contA+cantA
        if cantA>10:
            costoA=precioA*cantA - (precioA*cantA)*0,2
            impTA=impTA+costoA
        else:
            costoA=precioA*cantA
            impTA=impTA+costoA
    else:
        print("ingrese el precio unitario del articulo")
        precioB=float(input())
        print("ingrese la cantidad de articulos de A va a comprar")
        cantB=float(input())
        contB=contB+cantB
        if cantB>10:
                costoB=precioB*cantB - (precioB*cantB)*0,2
                impTB=impTB+costoB
        else:
            costoA=precioA*cantA
            impTB=impTB+costoB
print("Cantidad de A vendidos:", contA)
print("Cantidad de B vendidos:", contB)
print("importe total de venta de A",impTA)
print("importe total de venta de B",impTB)

'''


text:
Q: Reset bundler path? How can I reset the bundler install path to default?
I had initially set it with bundle install --path .gems but now I'd like to reset it to the default system location.

A: bundle install --system

Bundler docs
Edit - this command has now been updated!
See @Najmul's answer for the latest version

A: For anyone visiting this in 2021, the above mentioned system flag is now deprecated.
You have to set the bundle config by running: `
bundle config set --local system 'true'

and then you run:
 bundle install

as usual.


text:
Q: Python pandas: how to create a new row based on missing value from a column? Suppose I have a dataframe like this:

country
year
value

A
2008
1

A
2011
1

B
2008
1

B
2011
1

I want to add missing year per country, in this case 2009 and 2010, with desired output like this:

country
year
value

A
2008
1

A
2009

A
2010

A
2011
1

B
2008
1

B
2009

B
2010

B
2011
1

How can I do that?
Thanks in advance!

A: First let's create your dataset for the MCVE sake:
import pandas as pd

frame = pd.DataFrame([
    {"country": "A", "year": 2008, "value": 1},
    {"country": "A", "year": 2011, "value": 1},
    {"country": "B", "year": 2008, "value": 1},
    {"country": "B", "year": 2011, "value": 1},
])

Then we create the missing data by ruling from min(year) to max(year):
extension = frame.groupby("country")["year"].agg(["min", "max"]).reset_index()
extension["year"] = extension.apply(lambda x: list(range(x["min"], x["max"] + 1)), axis=1)

#   country   min   max                      year
# 0       A  2008  2011  [2008, 2009, 2010, 2011]
# 1       B  2008  2011  [2008, 2009, 2010, 2011]

Exploding the structure gives the correct format but without values:
extension = extension.explode("year")[["country", "year"]]
extension["year"] = extension["year"].astype(int)

#   country  year
# 0       A  2008
# 0       A  2009
# 0       A  2010
# 0       A  2011
# 1       B  2008
# 1       B  2009
# 1       B  2010
# 1       B  2011

Then we merge back with the original data to get the values:
results = frame.merge(extension, how="right", on=["country", "year"])

#   country  year  value
# 0       A  2008    1.0
# 1       A  2009    NaN
# 2       A  2010    NaN
# 3       A  2011    1.0
# 4       B  2008    1.0
# 5       B  2009    NaN
# 6       B  2010    NaN
# 7       B  2011    1.0

The advantage of this method - in addition of being purely pandas - is that it is robust against data variation:
frame = pd.DataFrame([
    {"country": "A", "year": 2008, "value": 1},
    {"country": "A", "year": 2011, "value": 2},
    {"country": "B", "year": 2005, "value": 1},
    {"country": "B", "year": 2009, "value": 2},
    {"country": "C", "year": 2008, "value": 1},
    {"country": "C", "year": 2010, "value": 2},
    {"country": "C", "year": 2012, "value": 3},
])

#    country  year  value
# 0        A  2008    1.0
# 1        A  2009    NaN
# 2        A  2010    NaN
# 3        A  2011    2.0
# 4        B  2005    1.0
# 5        B  2006    NaN
# 6        B  2007    NaN
# 7        B  2008    NaN
# 8        B  2009    2.0
# 9        C  2008    1.0
# 10       C  2009    NaN
# 11       C  2010    2.0
# 12       C  2011    NaN
# 13       C  2012    3.0

A: Let's create a dataframe first as follows :
import pandas as pd
data = {'country' : ['A', 'A', 'B', 'B'],
        'year' : ['2008', '2011', '2008', '2011'],
        'value':[1,1,1,1]}
df = pd.DataFrame(data=data)

Created dataset :
  country  year  value
0       A  2008      1
1       A  2011      1
2       B  2008      1
3       B  2011      1

Lets define the years we need to consider :
yr_list = ['2008', '2009', '2010', '2011']

Lets modify the dataset based on our requirement :
for country in df['country'].unique() :
  for yr in yr_list :
    if yr not in list(df.loc[df['country'] == country, 'year']):
      update_data = {'country' : country, 'year' : yr}
      df = df.append(update_data, ignore_index = True)

final_df = df.sort_values(by = ['country', 'year'],ignore_index=True)
print(final_df)

The final output :
  country  year  value
0       A  2008    1.0
1       A  2009    NaN
2       A  2010    NaN
3       A  2011    1.0
4       B  2008    1.0
5       B  2009    NaN
6       B  2010    NaN
7       B  2011    1.0

A: One option is with the complete function from pyjanitor:
# pip install pyjanitor
import pandas as pd
import janitor

Create a dictionary, with an anonymous function,  containing all possible years:
new_years = {'year': lambda year: range(year.min(), year.max() + 1)}

Use the dictionary within complete, with the by parameter, so it is applied per group:
df.complete(new_years, by = 'country')
  country  year  value
0       A  2008    1.0
1       A  2009    NaN
2       A  2010    NaN
3       A  2011    1.0
4       B  2008    1.0
5       B  2009    NaN
6       B  2010    NaN
7       B  2011    1.0

A: arr1 = [['A', 2008, 1],['A', 2011, 1],['B', 2008, 1],['B', 2011, 1]]

arr2 = [['A', 2008, 1],['A', 2009, None],['A', 2010, None],à['A', 2011, 1],['B', 2008, 1],['B', 2009, None],['B', 2010, None],['B', 2011, 1]]

for elm in arr2:
    if elm not in arr1:
        arr1.append(elm)


text:
Q: IE IE11 angularjs controller won't load - $controller:ctrlreg error I know this isn't the right way to document this, but I feel the "question" is important enough that an answer should be readily searchable.
I have an angularjs controller that loads perfectly in chrome and firefox, but not in IE(11). Long story short, chrome supports arrow function expressions ()=>{} and internet explorer does not.
A controller, or one of the dependencies of that controller that are written with arrow expressions will not even load in IE, arrow expressions are seen as syntax errors.
The fix is, where your code has arrow expressions () =>,
change them to function(), and you're golden.


text:
Q: Sublime text is running with an incorrect PATH environment variable If I run the following in the console, it outputs '/usr/bin:/bin:/usr/sbin:/sbin':
import os
os.environ['PATH']

But everywhere else the PATH is correct. In both ~/.MacOSX/environment.plist and if I run launchctl getenv PATH I get the correct path.
This is preventing me from running CoffeeCompile. Any ideas how I can fix this?

A: I encountered the same problem, and did not find a way to pass down the correct PATH. However, I have a workaround: It seems to work with the correct PATH as soon as you open Sublime Text from a shell. In other words:

*

*Follow this tip to create a shell shortcut to Sublime Text. This is optional, but comes in handy.

*Create a Workflow as described in the answer to this thread, with a shell script to open Sublime Text (using the above created subl command, or directly). That way you can open ST from your Dock.

I hope that helps.

A: Create an empty text file called "Sublime Text.sh" in the Sublime Text application bundle directory
/Applications/Sublime\ Text.app/Contents/MacOS

Open the Sublime Text.sh in a text editor and enter the following contents:
#!/bin/sh

. ~/.bash_profile

logger "`dirname \"$0\"`/Sublime Text"

exec "`dirname \"$0\"`/Sublime Text" $@

In the Terminal set the executable flag of the shell script eclipse.sh, i.e.:
chmod +x /Applications/Sublime\ Text.app/Contents/MacOS/Sublime\ Text.sh

Open the Sublime Text.app Info.plist and change the value for the key CFBundleExecutable from Sublime Text to Sublime Text.sh.
MacOS X does not automatically detect that the Sublime Text.app's Info.plist has changed. Therefore you need to force update the LaunchService database in the Terminal by using the lsregister command:
/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -v -f /Applications/eclipse/Sublime Text.app

The next time you launch Sublime Text.app from the Dock or from the Finder the environment variables should be set.
This will make it so that when you open Sublime Text.app it will run your shell script instead of the Sublime Text executable.
Your shell script then executes .bash_profile (setting the path) and starts the Sublime Text executable with that path.