text:
Q: Check if input value already exist in an array I am trying to get my code to check if the value submitted in "username" already exist in "usernames" list. If it does, would like to have the message displayed and if it does not, add that value to the "usernames" list and submit form.
Don't understand why my code doesn't work. Please see below:
HTML
<!DOCTYPE html>

    <title>Validating Form Data</title>
    <link rel="stylesheet" href="index.css" type="text/css">

Register your account:

    <form id="registration-form" method="POST" action="https://formdump.codeinstitute.net/">

            Username:
            <input id="username" name="username" type="text" required>

            Password:
            <input id="password" name="password" type="password" required>

        <input type="submit">

    </form>

CSS
label {
    display: block;
}
input {
    margin-bottom: 1rem;
}
p {
    color: red;
    font-weight: bold;
}

JS
let usernames = ["Harry", "Daisy", "Michael", "Sarah", "Sally"];

// Write your code here
let form = document.getElementById("registration-form");
form.addEventListener("submit", handleSubmit);

let errorMsg = document.getElementById("errors");
let uName = form.elements["username"].value;

let abc = usernames.includes(uName);

function handleSubmit(event) {
    event.preventDefault();
    if (abc) {
        errorMsg.innerHTML = `
Sorry, the username ${uName} is already in use. Please choose another username.

  `;
    } else {
        usernames.push(uName);
        form.submit();
        console.log(usernames);
    }
}

I tried replacing includes() with indexOf(), but still doesn't work.

A: As I said in the comment,you need to get the input value correctly each time it submit,so needs to put below code inside handleSubmit,otherwise uName will be null and abc will always be false(due to it execute before submiting)
let uName = form.elements["username"].value;
let abc = usernames.includes(uName);

let usernames = ["Harry", "Daisy", "Michael", "Sarah", "Sally"];

// Write your code here
let form = document.getElementById("registration-form");
form.addEventListener("submit", handleSubmit);

let errorMsg = document.getElementById("errors");

function handleSubmit(event) {
    event.preventDefault();
    let uName = form.elements["username"].value;
    let abc = usernames.includes(uName);
    if (abc) {
        errorMsg.innerHTML = `
Sorry, the username ${uName} is already in use. Please choose another username.

  `;
    } else {
        usernames.push(uName);
        form.submit();
        console.log(usernames);
    }
}
label {
    display: block;
}
input {
    margin-bottom: 1rem;
}
p {
    color: red;
    font-weight: bold;
}
<!DOCTYPE html>

    <title>Validating Form Data</title>
    <link rel="stylesheet" href="index.css" type="text/css">

Register your account:

    <form id="registration-form" method="POST" action="https://formdump.codeinstitute.net/">

            Username:
            <input id="username" name="username" type="text" required>

            Password:
            <input id="password" name="password" type="password" required>

        <input type="submit">

    </form>


text:
Q: Can we have $ \lim_{x \to f(x)}$? Can we have a limit where $x$ approaches a variable like this one:$\displaystyle \lim_{x \to f(x)}$ or $\displaystyle \lim_{x \to \cos(x)}$ ? And why? Thank you!

A: Usually, one defines
$$\lim_{x\to a}y$$
only if

*

*$x$ is a variable

*$a$ is an expression not depending on $x$

*$y$ is an expression possibly depending on $x$

and defines it as the unique number $c$ (if it exists) such that
$$\tag1 \forall \epsilon>0\exists \delta>0\forall x\in\mathbb R\colon (|x-a|<\delta\to|y-c|<\epsilon)$$
(where, to be formal again, $\delta,\epsilon$ are "new" variables not occuring in $x,a,y,c$).
However, by interpreting (1) very literally, one might interprete $\lim_{x\to f(x)}$ as taking the limit when e.g. $x$ tends to a fixpoint of a continuous function $f$. I have yet to see such a notion in the wild and doubt its usefulness (for example because $f$ might have several fixpoints and in fact $x\to f(x)$ might not even imply that $x$ converges in the first place)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mean residual life function limits In my paper about mean residual life functions and heavy tails I've come across the examples listed in the picture below.

*

*http://i.stack.imgur.com/OnklD.png

*source (page 124/125): http://www.mi.uni-koeln.de/~schmidli/vorl/Risk/vorl.pdf
I've managed to successfully calculate the limits when $M \rightarrow\infty$ for the Exponential and Pareto distribution myself using the  equation $$\frac{\int_M^\infty {(1-F(z))dz}}{1-F(M)}$$ however I fail to understand how to calculate the remaining three (marked in yellow). I am new to probability so please bear with me. Thank you for your aid.

A: First, let us write the formulas themselves.  As I come from an actuarial background, my notation is slightly different:  $$\overset\circ e_m = \operatorname{E}[T-m \mid T > m] = \frac{\int_{t=m}^\infty S(t) \, dt}{S(m)} = \int_{t=0}^\infty \vphantom._t p_m \, dt$$ where $T$ is the lifetime random variable, $S(t) = 1 - F(t)$ is the survival function of $T$, and $\vphantom._t p_m = S(m+t)/S(m)$ is the probability of survival of a life aged $m$ to age $m+t$.  The key observation is that as $m \to \infty$, both the numerator and denominator tend to $0$, so L'Hopital's rule applies.  Then by the fundamental theorem, and noting $S(\infty) = 0$:  $$\lim_{m \to \infty} \overset\circ e_m = \lim_{m \to \infty} \frac{-S(m)}{-f(m)} = \lim_{m \to \infty} \frac{-f(m)}{f'(m)},$$ where $f$ is the density of $T$.  Now all that remains is to choose a density:  for a gamma distribution with shape $\gamma$ and rate $\alpha$, we have $$f(m) \propto m^{\gamma-1} e^{-\alpha m},$$ consequently $$f'(m) \propto (\gamma - 1)m^{\gamma-2} e^{-\alpha m} - m^{\gamma - 1} \alpha e^{-\alpha m} = m^{\gamma - 2} e^{-\alpha m} (\gamma - 1 - \alpha m).$$  Hence $$\lim_{m \to \infty} \frac{-f(m)}{f'(m)} = \frac{m}{\alpha m + 1 - \gamma},$$ and as $m \to \infty$, this is clearly $1/\alpha$ as claimed.  A similar approach works for the other two distributions.  If you remain stuck in the calculation, I will amend this answer to include those computations.


text:
Q: What is the simplest method to write a file with Chrome file interface? Chrome implements the file interface as described here http://www.html5rocks.com/en/tutorials/file/filesystem/, just adding the webkit prefix. The documentation covers several aspects of the interface, but what are the simplest steps, for example, to prompt the user with a file saving dialog, or to tell him that the file has been saved somewhere? For example, let's say we want to save some text data for the user.
I'm mainly referring to lines of code as a metric of simplicity, but within the 80 characters per line (and common sense). I'm also referring to Chrome 26.

A: This is what i found. Naturally, it's use is quite limited, and it is better to refer to the main article linked above
function error(e) { console.log(e); };
webkitRequestFileSystem(TEMPORARY, Math.pow(2, 10), function(fs) {
    fs.root.getFile( 'exported.txt', {create:true}, function(fileEntry) {
        fileEntry.createWriter(function(fileWriter) {
            fileWriter.onwriteend = function() {
                alert('content saved to '+fileEntry.fullPath);
            };
            var blob = new Blob(['Lorem Ipsum'], {type: 'text/plain'});
            fileWriter.write(blob);
        });
    }, error);
}, error);


text:
Q: Media keys won't work with iTunes after spotify starts automatically I have Spotify set to start with Windows, but not iTunes. Right now I would like to use the media keys with iTunes. I closed Spotify and restarted iTunes, but the keys still don't do anything.
Apart from changing the startup programs and/or restarting my computer, is there anything I can do to get the media keys to control iTunes?

A: I ended the itype.exe process with task manager and the media keys are working with iTunes again!


text:
Q: Hive query giving incorrect output I'm facing this issue where the hive query is giving the output :
Last cycle cut for US: hive.exec.stagingdir=.hive-staging
2022-10-27
But the correct output should be :
Last cycle cut for US: 2022-10-27.
Query being used -
cycle_cut=$(hive -e "set mapred.job.queue.name=test;SET hive.cli.print.header=false;

;SELECT '2022-10-27'");
echo " Last cycle cut for US: $cycle_cut "

A: The simplest way is use the silent mode. Add "-S" in the command.
eg : hive -S -e "SELECT '2022-10-27'"
You can get more info from: https://cwiki.apache.org/confluence/display/hive/languagemanual+cli
And about the info "hive.exec.stagingdir", Maybe because you did not set the hive.exec.stagingdir, so the client will use the default settings, and print that on terminal.
<property>
    <name>hive.exec.stagingdir</name>
    <value>.hive-staging</value>
</property>

Maybe you can try to add the settings in your query
"SET hive.exec.stagingdir=/tmp/"

eg: cycle_cut=$(hive -e "set mapred.job.queue.name=test;SET hive.cli.print.header=false;SET hive.exec.stagingdir=/tmp/;SELECT '2022-10-27'"); echo " Last cycle cut for US: $cycle_cut "
I`m not sure it work or not ,Looking forward to your feedback!


text:
Q: PHP: mysqli_multi_query with mysql_rollback I've been doing some research and have not found a complete answer if I can use mysqli_multi_query that may contain both Updates/Deletes, while using mysql_rollback in the event that one of the queries fails.  Does anyone know if this can be done?  If so, any simple example I could build off of?
The only examples and information I have seen is simple query by query with auto commit disabled, then committing at the end, with the option of rollback in the event of an issue.


text:
Q: Splitting multivariate normal into individual (correlated) components I have a multivariate normal variable $X$ with mean zero and variance $\Sigma$. I would like to write every component $X_i$ of $X$ as:
$$
X_i = \phi_i Z_i
$$
where $\phi_i$ is a scalar and $Z_i$ is a scalar standard normal random variable (for every $i$). Question: what are the values of $\phi_i$ (given $\Sigma$), and what is the correlation matrix of the random variables $Z$?

A: Using the standard properties of variance and covariance, we have that $\phi_i = \sqrt{\Sigma_{i,i}}$ and
$$\displaystyle \operatorname{cov}(Z_i,Z_j)=\operatorname{cov}(\phi_i^{-1}X_i,\phi_j^{-1}X_j)= \frac{\Sigma_{i,j}}{\phi_i\phi_j}=\frac{\Sigma_{i,j}}{\sqrt{\Sigma_{i,i}}\sqrt{\Sigma_{j,j}}} = \rho_{i,j}$$ where $\rho_{i,j}$ is
the correlation coefficient of $X_i$ and $X_j$ (and also of $Z_i$ and $Z_j$).


text:
Q: Barplot for two groups using ggplot2 I know this has been asked many times before. However, I can't find the solution for my problem.
I extended the mtcars data set by a dummy indicating whether the car was sold or bought by a car seller (buy = 0 -> Sell, buy = 1 -> Buy) and the date of the transaction:
data(mtcars)
mtcars$buy <- c(0,0,1,0,0,1,1,0,0,1,0,1,0,0,0,1,1,0,0,0,1,0,1,0,1,1,0,0,0,1,0,1)
mtcars$date <- as.Date(c('2011-01-01','2011-01-06','2011-01-10','2011-01-20','2011-01-23',
             '2011-01-25','2011-01-31','2011-02-01','2011-02-06','2011-02-15',
             '2011-02-22','2011-02-26','2011-03-05','2011-03-15','2011-03-20',
             '2011-03-22','2011-03-27','2011-04-10','2011-04-25','2011-04-28',
             '2011-05-05','2011-05-15','2011-06-05','2011-06-06','2011-06-17',
             '2011-06-25','2011-07-05','2011-07-11','2011-07-25','2011-07-31',
             '2011-08-23','2011-08-25'))

Now I want to use ggplot to get a barplot with the monthly sells and buys as separate bars. However, I can only create a summary plot of all transactions:
mtcars$month <- as.Date(cut(mtcars$date, breaks="month"))
mtcars$counter <- 1
ggplot(mtcars, aes(month,counter)) + stat_summary(fun.y=sum, geom="Bar")

How can I create the same graph, but with two bars for each month (one with the number of buys and the other with the number of sells)?
Thanks for your help!

A: I believe the buy vector needs to be strings instead of numbers.
ggplot(mtcars, aes(month)) + geom_bar(aes(fill=as.character(buy)),position = "dodge")


text:
Q: How to add dynamic checkboxes in a Blazor-server app that use a list of booleans? To clarify my question more I'll first show you add a checkbox using the blazor component library I'm using:
<MudCheckBox @bind-Checked="@Basic_CheckBox1"></MudCheckBox>
@code{
public bool Basic_CheckBox1 { get; set; } = false;
}

the code above creates a checkbox and then toggles the boolean Basic_CheckBox1 to true or false based on if the checkbox is checked or not.
here is my code
 @for (int i = 0; i < checkboxNames.Count; i++)
        {

            <MudCheckBox @bind-Checked="@checkboxBools[i]" Label="@checkboxNames[i]"></MudCheckBox>
        }

this code works until I check or uncheck my created checkboxes, then I get the index out of range error, how can I fix this? I need to use a list of booleans because I don't know how many checkboxes I will need until runtime, if there is any other solution please let me know.

A: Think of it like the bind isn't done there and then in the loop, but later. By the time the bind comes to be done, the value of i is off the end of the array Length, having been incremented repeatedly. Instead, you can save the current value of your loop variable i into another variable, then use that other variable in your bind:
    @for (int i = 0; i < checkboxNames.Length; i++)
    {
        var x = i;
        <MudCheckBox @bind-Checked="@checkboxBools[x]" Label="@checkboxNames[i]"></MudCheckBox>
    }

checkBoxBools should be an array/list that is the same length (initalized to have the same number of elements as) checkBoxNames.. For example:
    string[] checkboxNames = new string[]{"a","b","c"};
    bool[] checkboxBools = new bool[3];

Or, if something else is providing a variable number of names:
    checkboxNames = context.People.Select(p => p.Name).ToArray();
    checkboxBools = new bool[checkBoxNames.Length];

https://try.mudblazor.com/snippet/GamQEFuFIwdRbzEx


text:
Q: Two JFrames with grids in one class I'm trying to program a battleship game, and using an if statement to call the class BatShip3, which will generate two JFrames with clickable grids for battleship placement. I've tried implementing my code two times in the method, generating new variables for each one, but I can't seem to figure out what's going wrong. When i select the game mode, it creates both windows, giving them both black backgrounds, but the second one doesn't have a grid on it. Any Pointers?
package batship2;

import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
*
 * @author William
*/
public class BatShip3 extends JFrame implements ActionListener{

    public JButton buttons [][] = new JButton [100][100];
    public JPanel panel;
    public JButton clicks [][] = new JButton [100][100];
    public JPanel canvas;
    Container contentArea = getContentPane ();
    Container contentArea2 = getContentPane ();

    public void BatShip3(){
            JFrame window1 = new JFrame("Window 1");{
                   setSize (800, 600);
                   setVisible (true);
                   setBackground (Color.black);
                   setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

                   panel = new JPanel();
                   GridLayout experimentLayout = new GridLayout(100, 100);
                   panel.setLayout (experimentLayout);
                   panel.setBackground(Color.black);

                   for(int rows = 0; rows <100 ; rows++){
                      for(int cols = 0; cols < 100 ; cols++){
                          buttons [rows][cols] = new JButton ();
                          buttons [rows][cols].setBackground(Color.blue);
                          buttons [rows][cols].addActionListener(this);
                          panel.add(buttons [rows][cols]);
                      }
                   }
                   contentArea.add(panel);
                   window1.setContentPane(contentArea);
    }

      JFrame window2 = new JFrame("Window 2");{
           window2.setSize (800, 600);
           window2.setVisible (true);
           window2.setBackground (Color.black);
           window2.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);

           canvas = new JPanel();
           GridLayout experimentLayout2 = new GridLayout(100, 100);
           canvas.setLayout (experimentLayout2);
           canvas.setBackground(Color.black);

             for(int rows1 = 0; rows1 <100 ; rows1++){
                 for(int cols1 = 0; cols1 < 100 ; cols1++){
                     clicks [rows1][cols1] = new JButton ();
                     clicks [rows1][cols1].setBackground(Color.blue);
                     clicks [rows1][cols1].addActionListener(this);
                     canvas.add(clicks [rows1][cols1]);
                 }
             }
              contentArea2.add(canvas);
              window2.setContentPane(contentArea2);
              }
              }
    public void actionPerformed(ActionEvent ev){

        for(int rows = 0; rows < 100 ; rows++){
            for(int cols = 0 ; cols < 100 ; cols++){
                 if(ev.getSource() == buttons [rows][cols]){
                      buttons[rows][cols].setBackground(Color.green);
                 }
            }
        }
        for(int rows1 = 0; rows1 < 100 ; rows1++){
            for(int cols1 = 0 ; cols1 < 100 ; cols1++){
                if(ev.getSource() == clicks [rows1][cols1]){

                   clicks[rows1][cols1].setBackground(Color.green);
                 }
            }
        }
}}

A: Define model classes that describe a Battleship game.  Here's what I thought of after a few minutes.
package com.ggl.battleship.model;

import java.util.List;

public class BattleshipGame {
    private int numberOfPlayers;
    private int widthOfBattleshipGrid;
    private List<BattleshipGrid> grids;
}

.
package com.ggl.battleship.model;

import java.util.List;

public class BattleshipGrid {
    private List<Ship> ships;
    private Cell[][] grid;
}

.
package com.ggl.battleship.model;

import java.awt.Point;
import java.util.List;

public class Ship {
    private int length;
    private String name;
    private List<Point> cellLocations;
}

.
package com.ggl.battleship.model;

import java.awt.Point;

public class Cell {
    private boolean isHit;
    private Point coordinates;
}

You can create all the appropriate getters, setters, and drawing methods.
Define one or more view classes that creates a JFrame and a JPanel.  The JPanel draws the model classes.
Create one instance of the JFrame view class for player 1, and another instance for player 2.


text:
Q: I cant figure out why my array is not working correctly I have a game here called mancala but I cannot figure out why when one side is empty why it doesn't add it to the correct bin. The function gameover is supposed to add beadArray[0-5] to side 1 and beadArray[7-12] to side 2 and if side 1 ever equals 0 then it is to add side 2 to beadArray[6] and if side 2 ever equals 0 then it is to add side 1 to beadArray[13]. But it never does that when one of the sides empties and then it wont output who the winner is. Any help would be greatly appreciated! :)
Mancala rules here: http://boardgames.about.com/cs/mancala/ht/play_mancala.htm
except on mine it goes clockwise
#include <iostream>
#include <iomanip>
using namespace std;
const int MAX=14;
void startArray(int beadArray[MAX]);//Creates the array that gets printed out
void printArray(int beadArray[MAX]);//Prints out the array
void board(int beadArray[MAX]);     //Creates the board out of stars
void makeSolidLine(int numStars);   //makeSolidLine makes a line out of numStars
void line();                        // A line of stars with 6 spaces inbetween
void topBinNum();                   //Numbers in top of the board
void bottomBinNum();                //Numbers in the bottom bin
void topBinNumValue();                  //Values of each slot in the top bin
void bottomBinNumValue();               //Values of each slot in the bottom bin
void binSelection(int beadArray[MAX], int player, int &binNum, int winner);
void binDrop(int beadArray[MAX], int &binSelection, int player);
int gameOver(int beadArray[MAX]);       //Declares the winner by adding bins and comparing the totals
int answer;                         //Players answer to who goes first
int response;

/*Calls the functions in proper order so the code will run smoothly
 parameter=n/a
 return value=n/a
 */
int main()
{
    cout<<"Who goes first?(1=player1, 2=player2)\n";
    cin>>answer;
    int player=answer;                  //Players aswer to who goes first
    int binNum;                         //The number of each bin location
    int beadArray[MAX];                 //The values of each bin location
    startArray(beadArray);              //Begins the array to build the board
    board(beadArray);                   //Creates the board itself
    int winner=gameOver(beadArray);     //Sees if there is a winner or if game still needs to be played
    gameOver(beadArray);
    do
    {
        binSelection(beadArray, player, binNum, winner);
        binDrop(beadArray, binNum, player);
        board(beadArray);
        int winner=gameOver(beadArray);
        gameOver(beadArray);
        if (winner==-1)
        {

            if (binNum==13||binNum==6)
            {

            }
            else if(player==1)
            {
                player=2;

            }
            else
            {
                player=1;

            }
        }
    }while(winner==-1);
    cout<<winner;
    system ("pause");
    return 0;
}
/*The function topBinNum creates the top bin numbers for the board by using the for loop by  outputting a star with four spaces then outputting a number which starts at 0 then one is added every time it loops, then the number is followed by 2 spaces and a star which is the end of the for loop that stops looping once the number reaches 5.
 parameter=n/a
 return value=n/a
 */
void topBinNum()
{
    cout<<"*      ";
    for(int i=0; i<6; i++)
    {
        cout<<"*"<<setw(4)<<i<<setw(2)<<" ";
    }
    cout<<"*";
    cout<<"      *\n";

}
/*The function bottomBinNum creates the top bin numbers for the board by using the for loop by  outputting a star with four spaces then outputting a number which starts at 12 then one is subtracted every time it loops, then the number is followed by 2 spaces and a star which is the end of the for loop that stops looping once the number reaches 5.
 parameter=n/a
 return value=n/a
 */
void bottomBinNum()
{
    cout<<"*      ";
    for(int i=12; i>6; i--)
    {
        cout<<"*"<<setw(4)<<i<<setw(2)<<" ";
    }
    cout<<"*";
    cout<<"      *\n";
}
/*Prints out a solid line of *
 parameter=int numStars
 return value=n/a
 */
void makeSolidLine(int numStars)
{
    for (int count=0; count<numStars; count++)
    {
        cout<<"*";
    }
}
/*Prints out a line of * with six spaces inbetween
 parameter=n/a
 return value=n/a
 */
void line()
{
    for (int count=0; count<8; count++)
    {
        cout<<"*";
        for(int count=0; count<6; count++)
        {
            cout<<" ";
        }
    }
    cout<<"*\n";
}
/*gives each slot a value
 parameter=it takes the function int beadArray[MAX] and allows startArray to use beadArray in its function
 return value=n/a
 */
void startArray (int beadArray[MAX])
{
    for(int i=0; i<MAX; ++i)
    {
        beadArray[i]=4;
    }
    beadArray[6]=0;
    beadArray[13]=0;
}
/*Finds data needed to print out the numbers in the correct order
 parameter=it takes the function int beadArray[MAX] and allows printArray to use beadArray in its function
 return value=n/a
 */
void printArray (int beadArray[MAX])
{

    for(int i=0; i<MAX; i++)
    {
        cout<<beadArray[i];
        cout<<endl<<endl;
    }
}
/*
 topBinNumValue calls the parameter int beadArray[MAX] which is the slot scores from 0-4 and outputs five 4's with no return value
 parameter=it takes the function int beadArray[MAX] and allows topBinNumValue to use beadArray in its function
 return value=n/a
 */
void topBinNumValue(int beadArray[MAX])
{
    cout<<"*      ";
    for(int i=0; i<6; i++)
    {
        cout<<"*"<<setw(4)<<beadArray[i]<<setw(2)<<"  ";
    }

    cout<<"*";
    cout<<"      *\n";
}
/*
 bottomBinNumValue calls the parameter int bead array[max] which is the slot scores from 6-13 and outputs a 0 then five 4's and another 0 with no return value
 parameter=it takes the function int beadArray[MAX] and allows bottomBinNumValue to use beadArray in its function
 return value=n/a
 */
void bottomBinNumValue(int beadArray[MAX])
{
    for(int i=13; i>5; i--)
    {
        cout<<"*"<<setw(4)<<beadArray[i] <<setw(2)<<" ";
    }

    cout<<"*\n";

}
/*Creates the board with numbers in proper location by calling all the previously created codes the print out the board.
 parameter=it takes the function int beadArray[MAX] and allows board to use beadArray in its function
 return value=n/a
 */
void board(int beadArray[MAX])
{
    makeSolidLine(57);
    cout<<endl;
    line();
    topBinNum();
    line();
    topBinNumValue(beadArray);
    line();
    cout<<"*  13  ";
    makeSolidLine(43);
    cout<<"   6  *";
    cout<<endl;
    line();
    bottomBinNum();
    line();
    bottomBinNumValue(beadArray);
    line();
    makeSolidLine(57);
    cout<<endl;
}
/*Adds the totals to beadArray[13 & 6] checks to see which slot is higher and displays the winner if there is one.
 parameter=int beadArray[MAX] keeps array from going above the MAX
 return value=winner, who ever won the game is the return value
 */
int gameOver(int beadArray[MAX])
{
    int winner=0;
    int side1=0;
    int side2=0;
    for(int i=0; i<6; i++)
    {
        side1=side1+beadArray[i];
    }
    for(int i=12; i>6; i--)
    {
        side2=side2+beadArray[i];
    }
    if(side1==0||side2==0)
    {

        beadArray[6]=beadArray[6]+side1;
        beadArray[13]=beadArray[13]+side2;
        if(beadArray[6]>beadArray[13])
        {

            winner=1;
        }
        else
        {

            winner=2;
        }
    }
    else
    {
        winner= -1;
    }
    return winner;

}
/*
 Asks the player which bin they would like to select and making sure that their bin selection is in the correct range and then passes back the binNum by reference.
 paramter=int beadArray[MAX] so the function can use the array, int player chooses which players turn it is, int&binNum includes the players choice of bin in the function
 return value=n/a
 */
void binSelection(int beadArray[MAX], int player, int &binNum, int winner)
{
    cout<<"Player "<<player<<" Choose bin.\n"<<winner;
    cin>>binNum;

    while(player==1 && ((binNum<0||binNum>5) || beadArray[binNum]<1))
    {
        if(beadArray[binNum]==0)
        {
            cout<<"Make selection with value other then 0 and ";
        }
        cout<<"Make selection with beads between 0 and 5.\n";
        cin>>binNum;
    }
    while(player==2 && ((binNum>12||binNum<7) || beadArray[binNum]<1))
    {
        if(beadArray[binNum]==0)
        {
            cout<<"Make selection with value other then 0 and ";
        }
        cout<<"Make selection with beads between 7 and 12.\n";
        cin>>binNum;
    }
}
/*
 Drops beads into the bin when a player makes a binselection, making sure each bead is distrubuted correctly
 return value=n/a
 parameteres= int beadArray[MAX] allowing the function to use the values of the bin in the function, int &binSelection allows the function use the bin that player has selected to move, int player allows the function to use which player is going in the function
 */
void binDrop(int beadArray[MAX], int &binSelection, int player)
{

    int hand=0;
    do
    {
        hand=beadArray[binSelection];
        beadArray[binSelection]=0;
        while(hand>0)
        {
            binSelection++;
            if (player==1&& binSelection==13)
            {
                binSelection=0;
            }
            if (player==2&& binSelection==6)
            {
                binSelection=7;
            }
            if(binSelection>13)
            {
                binSelection=0;
            }
            beadArray[binSelection]++;
            hand--;
            board(beadArray);
        }
    }while(binSelection!=13 && binSelection!=6 && beadArray[binSelection]>1);
}
//I cant figure out how why it wont add all beads from player 2's side to player 1's total if player 1 clears their side first and vice versa.

A: The problem is here
int winner=gameOver(beadArray);
gameOver(beadArray);
do
{
    binSelection(beadArray, player, binNum, winner);
    binDrop(beadArray, binNum, player);
    board(beadArray);
    int winner=gameOver(beadArray);
    gameOver(beadArray);
    ...
}while(winner==-1);

Notice you have two winner variables, one before the do while loop, and one inside the the do while loop. The variable that controls the do while loop is the first one, that's why you never get a winner.
The fix is very simple, change the code so you only have one winner variable (which I'm sure is what you meant all along).
int winner=gameOver(beadArray);
gameOver(beadArray);
do
{
    binSelection(beadArray, player, binNum, winner);
    binDrop(beadArray, binNum, player);
    board(beadArray);
    winner=gameOver(beadArray);
    gameOver(beadArray);
    ...
}while(winner==-1);

BTW why do you call gameOver twice in a row? Can't see any reason for that.


text:
Q: RelativeLayout Not displaying an image Ok, so here is where I sit: I cannot for the life of me figure out why the image to the left will not display. It should be the same image as the one to the right of notifications. I have gone over it a few different ways and cannot get that image to display on the left side of notifications.
<LinearLayout
        android:orientation="vertical"
        android:id="@id/notificationCart"
        android:background="#000000"
        android:visibility="gone"
        android:layout_width="fill_parent"
        android:layout_height="@dimen/status_bar_expanded_notification_category_height">

    <RelativeLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

        <ImageView
                android:layout_gravity="left|center"
                android:layout_toLeftOf="@id/latestNotificationText"
                android:layout_width="wrap_content"
                android:layout_height="@dimen/tw_close_handle_height"
                android:src="@drawable/tw_quick_panel_plnm_setting_dv"
                android:scaleType="fitXY"/>

        <TextView
                android:textSize="@dimen/status_bar_expanded_notification_category_text_size"
                android:textStyle="bold"
                android:layout_gravity="center_horizontal"
                android:textColor="@color/notification_category_color"
                android:gravity="center"
                android:id="@id/latestNotificationText"
                android:paddingLeft="10.0dip"
                android:paddingRight="10.0dip"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:text="@string/status_bar_latest_events_title"/>

        <ImageView
                android:layout_gravity="right|center"
                android:layout_toRightOf="@id/latestNotificationText"
                android:layout_width="wrap_content"
                android:layout_height="@dimen/tw_close_handle_height"
                android:src="@drawable/tw_quick_panel_plnm_setting_dv"
                android:scaleType="fitXY"/>
    </RelativeLayout>
</LinearLayout>

A: If you need to place two images left and right of  the TextView
why do you need the RelativeLayout?
 <LinearLayout  android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

       <LinearLayout android:orientation="horizontal"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ....>
            <ImageView
                android:layout_gravity="center_vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <TextView
                android:layout_gravity="center_vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <ImageView
                android:layout_gravity="center_vertical"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        <LinearLayout />
 <LinearLayout />

Note that the parent FrameLayout has it's width set to match_parent.


text:
Q: typing next to iframe How can I type next to my YouTube video? What do I need to add in my html code to have 3 testimonials (with pictures) nice and clear under each other?

Thanks in advance!
Kr,
Sven

A: Here is my HTML code:


text:
Q: Error in tree implementation with Python I am trying to implement a tree in Python but I get an error inside a method declaration.
I believe that it is due to the self instance I used:
class Node:

   def __init__(self, data=None, l=None, r=None):
       self.data = data
       self.l = l
       self.r = r

class Tree:
   def __init__(self):
       self.root = Node()

I am trying to send a node for inserting but if nothing is sent I want to reference it with the root
  def insert(self,data,root1=self.root):
      '''function definition'''

t = Tree()
t.insert(1)

A: You cannot use self inside a method signature, the class doesn't know how to handle it, because self is only define inside the method (thanks to the first parameter).
You could use a pattern like the following :
def insert(self, data, root1=None):
    if root1 is None:
        root1 = self.root
    else:
        [...]

A: Instance methods are created when a class is defined and the default argument is added to the unbound method as member data. This all occurs before the class could ever be instantiated, thus there is no such self to reference. This is tangentially related to the common mutable default argument issue. Consider the following piece of code:
class Test:
    def method(self, arg='default argument'):
        pass

print(Test.method) # <unbound method Test.method>
print(Test.method.__func__.func_defaults) # ('default argument',)

Here, how would Test.method have any idea what self is when no instance of the class has ever been created? Instead you probably want to use the following pattern:
def insert(self, data, root=None):
    if root is None:
        root = self.root
    # ...


text:
Q: fscanf in C - commas, new lines, and %*c I am trying to use fscanf() to read a file which is made up of a list of doubles separated by commas and new lines. The file looks something like this
    3.000000,1.000000,1180.000000,1955.000000,221900.000000
    3.000000,2.250000,2570.000000,1951.000000,538000.000000
    2.000000,1.000000,770.000000,1933.000000,180000.000000
    4.000000,3.000000,1960.000000,1965.000000,604000.000000
    3.000000,2.000000,1680.000000,1987.000000,510000.000000

Each line will have the same amount of doubles as the others but the file will have a random amount of lines
What I am using right now to scan the file is
    while((fscanf(train, "%lf %*c", &k)) != EOF)
    {
        printf("%lf ", k);
    }

Using this I get
    3.000000 1.000000 1180.000000 1955.000000 221900.000000
    0.000000 2.250000 2570.000000 1951.000000 538000.000000
    0.000000 1.000000 770.000000 1933.000000 180000.000000
    0.000000 3.000000 1960.000000 1965.000000 604000.000000
    0.000000 2.000000 1680.000000 1987.000000 510000.000000

The problem with this is that a the beginning of each new line, the %*c skips the first part of the double, and prints 0.000000. Is there anyway to fix this?

A: When fscanf(train, "%lf %*c", &k) is reading the last number, the whitespace character swallows the newline, and the %*c swallows the first digit of the next number. So, the subsequent application of the fscanf call will only see .000000 when it tries to read the first number of the next line.
Since there isn't actually any whitespace between the numbers and commas, just get rid of it in your format string.
while((fscanf(train, "%lf%*c", &k)) != EOF)

While fscanf will return EOF when it encounters the end of file, it will otherwise return the number of successful elements scanned into your arguments. Since you pass in 1, you expect to get 1 in return. On bad input, fscanf report 0 arguments saved in your case. However, the bad data is left in the input buffer, so a subsequent call will fail in the same way. So, the EOF check would result in an infinite loop. You can change your code to check if the scan succeeded. (This point was noted in comments by chux.)
while((fscanf(train, "%lf%*c", &k)) == 1)

A: Use fgets and then parse the line:
double d;
char *lineBuf = malloc(MAX_LINE + 1); // Or size more appropriately to your needs.

while (fgets(lineBuf, MAX_LINE + 1, inputFile) == lineBuf)
{
    d = atolf(lineBuf); // Stops at first comma or whitespace.
    printf("%lf", d);
}

If you're interested in more than one field, use strtok to break out the fields.


text:
Q: A better way to check for authorization of API requests using Express JS I have a super redundant server.js file, since nearly every method in it belonging to the REST API starts like that, as I have to check at the API requests whether the client is authorized to ask for the particular thing.
var jwt = require('jsonwebtoken');

// ...

app.get('/getsomething', function(req, res) {
  "use strict";
  var token = req.headers[tokenName];
  if (token) {
    jwt.verify(token, app.get('some_secret'), {
      ignoreExpiration: false
    }, function(err, decoded) {
      if (err || typeof decoded === "undefined") {
        res.json({
          status: 401,
          message: "unauthorized"
        });
      }
      else { // actual code starts here...

What would be a better way?

A: You should have a middleware that checks every request coming in, something like this:
// AUTHENTICATION
app.use(async (req) => {
    try {
        const token = req.headers.authorization
        const { person } = await jwt.verify(token, SECRET)
        req.person = person
        return req.next()
    } catch (e) {
        return req.next()
    }
})

In this example, both success or fail allows the user to pass through to the route, but req.person is only populated if the user is logged in. Keep in mind, this is an asynchronous function due to async keyword. It returns a promise and we are using try/catch architecture. This allows us to use await which halts execution until jwt.verify() has populated person. This then makes req.person available in every route. In this example, person is a property that you specified when you did jwt.sign() to create the JWT. Here is an example to jog your memory:
jwt.sign({
  person: 'some unique identifier'
}, 'secret', { expiresIn: '1y' })

In this way, req.person can only ever be populated by decoding a valid JWT. Do not be confused by const { person } = await jwt.verify(token, SECRET). This is the same as writing:
const decodedJWT = await jwt.verify(token, SECRET)
const person = decodedJWT.person

In every protected route, you can simply make the first line of code something like:
// PROTECTED
app.get('/radical', async (req, res, next) => {
    try {
        // If req.person is falsy, the user is not logged in
        if (!req.person) return res.status(403).render('error/403')
        // Otherwise, the user is logged in, allow him/her to continue
        // Replace res.render() with res.json() in your case.
        return res.render('radical/template', {
            person: req.person
        })
    } catch (e) {
        return next(e)
    }
})

This example demonstrates EJS View Templating Engine:

*

*See: https://www.npmjs.com/package/ejs
Then, after all your routes, put a splat route, and an error handling middleware:
// SPLAT ROUTE
app.get('*', (req, res, next) => {
    return res.status(404).render('error/404')
})

// ERRORS
app.use((err, req, res, next) => {
    res.status(500).render('error/500')
    throw err
})

The error handling middleware needs to come last, and it has an additional 4th parameter which is err and it contains the value of the parameter of next() only if you pass a parameter to it, ie: next('Error happened').
This above code works without any changes for GraphQL as well. To handle authentication in GraphQL, simply examine this:
// GRAPHQL
app.use('/graphql', bodyParser.json(), graphqlExpress((req) => {
    const context = {
        person: req.person
    }
    return {
        schema,
        context,
        rootValue: null,
        formatError: (error) => ({
            message: error.message,
            locations: error.locations,
            stack: error.stack,
            path: error.path
        }),
        debug: true
    }
}))

The GraphQL endpoint must be mounted after the authentication middleware. The logged in user will be available in every resolver as context.person, or if the request is illegal, context.person will be falsy. I mention this for any others searching in the future.


text:
Q: A uniqueness proposition involving Erf, the error function This is a MathOverflow cross-post (currently no answer there) and a generalization of a previous MathOverflow question, "Reducing system of equations involving Erf, Error Function".
Consider the system of equations:
$$1/2 + {\rm Erf}(x) - \alpha {\rm Erf}(\frac{x+y}{2})=0$$
$$-1/2 + {\rm Erf}(y) - \alpha {\rm Erf}(\frac{x+y}{2})=0,$$
where $x \le y$ and ${\rm Erf}$ is the Error Function. By ansatz it is clear that one solution is $(x,y)=(-{\rm Erf}^{-1}(1/2),{\rm Erf}^{-1}(1/2))$,  independent of $\alpha$. The question is to prove the uniqueness of this solution, for any $\alpha$.
(Update: Robert's visual below demonstrates how there are clearly multiple solutions for a robust interval of $\alpha \in (0.5, \approx 0.8)$, and so the general $\alpha$ formulation was not helpful. I am revising my question to specifically focus on uniqueness in the case of $\alpha =1/2$.)
I am particularly interested in a proof for $\alpha = 1/2$, but I hope that by phrasing the problem in terms of a general $\alpha$, someone may see an elegant elementary proof.
Observe that proving that $x+y=0$ is sufficient. My previous MO question includes a proof of uniqueness in this way for the case where $\alpha=1$, with two proofs (one by Noam Elkies, one by myself). Unfortunately these proofs do not appear to generalize to other values of $\alpha$ (Noam's proposition is false for $\alpha = 1/2$, my approach does not appear to generalize), even though I strongly suspect the general statement.
Numerics:
I have embarked on some numerical exploration. If one considers the equation
$${\rm Erf}(x) + {\rm Erf}(y) = 2\alpha {\rm Erf}(\frac{x+y}{2}),$$
For $\alpha=1$ we know that $y=-x$ and $y=x$ are solutions. Numerically, it appears as through $y=-x$ is always a solution, while the second solution is $\alpha$-dependent, and not always so nice. For $\alpha=1/2$ the second equation appears to be ${\rm Erf}(c_{1/2} y) - {\rm Erf}(c_{1/2}x) =1$ where $c_{1/2} \approx 0.57285884$. For other values of $\alpha$ the equation appears to be of the form ${\rm Erf}(c_\alpha y - d_\alpha) - {\rm Erf}(c_\alpha x +d_\alpha) =1$. Any insight on what the value of $c_{1/2}$ might be analytically or why $d_{1/2}$ might be zero would be much appreciated.

A: The solution is not always unique.  For $1/2 < \alpha < .79654774210531568819$ approximately, there are two other solutions.  For example with $\alpha = 0.6$ the other solutions are approximately
$x = -1.910219091, y = .006118254868$ and $ x = -.006118254868, y =  1.910219091$.  This can  be seen graphically: here are the curves given by your two equations (the first in red, second in blue) for different values of $\alpha$ from $0.3$ to $1$.
The value near 0.8 is actually the value of $\exp{-(\text{erf}^{-1}(1/2))^2}$.  This is the value of $\alpha$ for which the two curves have the same slope at the point $(-\text{erf}^{-1}(1/2), \text{erf}^{-1}(1/2))$.


text:
Q: Rspec for building nested attributes I have following code snippet in my CompaniesController
class CompaniesController < ApplicationController
  def new
    @company  = Company.new
    @company.employees.build
  end

In my Rspec how can I check that build method is called inside new action?
I tried something like this
expect(assigns(:company).employees).to have_received(:build)

but I am getting following error message:
#<Employee::ActiveRecord_Associations_CollectionProxy:0x007fe2ca2141e8> expected to have received build, but that object is not a spy or method has not been stubbed.

Do I need to stub employee first?
Update:
Rspec for new action
describe "GET 'new'" do

before { get :new }

it 'assigns @domain_name' do
  expect(assigns(:domain_name)).to eq(request.host)
end

it 'assigns @company' do
  expect(assigns(:company)).to be_a_new(Company)
end

it 'renders the new template' do
  expect(response).to render_template('new')
end

end
Thanks

A: You can do it like this
before { expect_any_instance_of(Company.new.employees.class).to receive(:build) }

A: How about checking the outcome instead of checking whether the method call took place?
it 'builds an employee on @company' do
  expect(assigns(:company).employees.length).to eq(1)
  # and/or
  expect(assigns(:company).employees.first).to be_a_new(Employee)
end


text:
Q: Combine InfoWindow data when overlapping polygons clicked? Is it possible to combine all polygon data (description & name) at a specific point into one InfoWindow when clicked? I have some overlapping polygons and the InfoWindow only displays the data from the topmost one. It seems this should be possible using Fusion Tables and a click listener on the map so that when someone clicks on the map, a query is sent to Fusion Tables to find all the Polygons that intersect with the point that was clicked (using ST_INTERSECTS with a CIRCLE and a very small radius). The only columns in my Fusion Table are Name, Description, and Geometry (containing standard KML ).
This is as far as I am with it. Polygons are displaying and circle is being rendered and centered onclick. InfoWindow is displaying [object Object].
var lat = 37.4;
var lng = -122.1;
var tableid = '1mxcz4IDL1U7ItrqulVzt01fMasj5zsmBFUuQh6iM';
var meters = 10000;

layer = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
    from: tableid,
}
});

layer.setMap(map);

google.maps.event.addListener(layer, 'click', function(event) {
changeCenter(event);
});

function changeCenter(event) {
lat = event.latLng.lat();
lng = event.latLng.lng();
circle.setCenter(event.latLng);
}

circle = new google.maps.Circle({
center: new google.maps.LatLng(lat, lng),
radius: meters,
map: map,
fillOpacity: 0.2,
strokeOpacity: 0.5,
strokeWeight: 1,
});

comboname = new google.maps.FusionTablesLayer({
query: {
select: 'name',
from: tableid,
where: 'ST_INTERSECTS(geometry, CIRCLE(LATLNG(' + lat + ',' + lng + '),' + meters + '))'
}
});

google.maps.event.addListener(layer, 'click', function(e) {
      // Display all of the names in the InfoWindow
e.infoWindowHtml = comboname;
    });

}

A: A FusionTablesLayer doesn't provide any data related to the displayed features.
When you want to get data from the FusionTable you must request them via the REST-API (this also happens when the API will open an InfoWindow, when you take a look at the Network-Traffic you'll see that there is a request which loads the data for the InfoWindow).
The REST-API supports JSONP, so you may request the data directly via JS.
Requirements for SELECT

*

*a valid google-API-key

*the service Fusion Tables API must be enabled for the project

*The FusionTable must be configured as downloadable (the table in your example already is downloadable)

Sample-implementation:
function initialize() {
  var goo       = google.maps,

      //your google maps API-key
      gooKey    = 'someGoogleApiKey',

      //FusionTable-ID
      ftId      = '1mxcz4IDL1U7ItrqulVzt01fMasj5zsmBFUuQh6iM',

      //1km should be sufficient
      meters    = 1000,

      map       = new goo.Map(document.getElementById('map_canvas'),
                    {
                      zoom: 6,
                      center: new goo.LatLng(36.8,-111)
                    }),
      //we use our own InfoWindow
      win       = new goo.InfoWindow;

      //function to load ft-data via JSONP
      ftQuery   = function(query,callback){
                    //a random name for a global function
                    var fnc     = 'ftCallback'+   new Date().getTime()
                                               +  Math.round(Math.random()*10000),
                        url     = 'https://www.googleapis.com/fusiontables/v2/query?',
                        params  = {
                                    sql       : query,
                                    callback  : fnc,
                                    key       : gooKey
                                  },
                        get     =[],
                        script  = document.querySelector('head')
                                    .appendChild(document.createElement('script'));
                    for(var k in params){
                      get.push([encodeURIComponent(k),
                                encodeURIComponent(params[k])
                               ].join('='));
                    }
                    window[fnc]=function(r){
                      callback(r);
                      delete window[fnc];
                      document.querySelector('head').removeChild(script);
                    }
                    script.setAttribute('src',url+get.join('&'));

                  },

      ftLayer   = new goo.FusionTablesLayer({
                    query: {
                        select: 'geometry',
                        from: ftId,
                      },
                    map:map,
                    suppressInfoWindows:true
                  });

      goo.event.addListener(ftLayer,'click',function(e){

        var sql ='SELECT name  FROM ' + ftId +
                 ' WHERE  ST_INTERSECTS(geometry,'+
                 ' CIRCLE(LATLNG(' +e.latLng.toUrlValue()+ '),'+ meters + '))',
            cb  = function(response){
              if(response.error){
                try{
                    alert(response.error.errors[0].message);
                }
                catch(e){
                    alert('error while retrieving data from fusion table');
                }
                return;
              }

              var content = [];
              for(var r = 0; r < response.rows.length; ++r){
                content.push(response.rows[r][0]);
              }
              //open the infowindow with the desired content
              win.setOptions({
                content:'

'+content.join('

')+'

',
                map:map,
                position:e.latLng
              });
            };
        ftQuery(sql,cb);
      });
}

google.maps.event.addDomListener(window, 'load', initialize);

Demo: http://jsfiddle.net/doktormolle/ckyk4oct/


text:
Q: SQL - trying to add an IDENTITY but the joining table already has an ID I'm trying to update a mail table with random bank names from a fake bank name table. Issue is the mail table already contains an identity field so I'm getting the error

Multiple identity columns specified for table 'generic_banks'. Only one identity column per table is allowed.

Here's my code:
ALTER TABLE generic_banks ADD ID_new INT NOT NULL IDENTITY(1,1)

CREATE UNIQUE NONCLUSTERED INDEX ix ON generic_banks(ID_new)

UPDATE m
SET m.alias = b.bank_alias
FROM mail_detail_lz m
INNER LOOP JOIN generic_banks b ON b.ID_new = (1 +  ABS(CRYPT_GEN_RANDOM(8)%50000))

Please help

A: If you want to assign a random name from one table to another, I might suggest something more like this:
with toupdate as (
      select m.*, row_number() over (order by newid()) as seqnum
      from mail_detail_lz m
     ),
     gb as (
      select gb.*, row_number() over (order by newid()) as seqnum
      from generic_banks gb
    )
update toupdate
    set alias = gb.bank_alias
    from toupdate join
         gb
         on toupdate.seqnum = gb.seqnum;

This is a generic approach that doesn't allow duplicates.  If it doesn't work for you then something similar should work.

A: Only one identity column can be created per table. MS Link
You will either need to create ID_new field as a non-identity field or remove the existing identify field.


text:
Q: Customizing Clone in Standard Page Layout I'm in a need to create a custom button that will be placed on the standard page layout and that button will call to clone the record which the user is on and I could have used the standard clone functionality but my requirement is that the user does not want all the fields to be clone so it will be selected fields that needs to be cloned so when the user click on the button.
What are the options I have in this particular scenario ?
One thing I have think of is creating a Detail page button and write the javascript code and that JS will call the APEX controller something like this:
{!REQUIRESCRIPT("/soap/ajax/28.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/28.0/apex.js")}

var myId = "{!Employee__c.Id}";

//this apex class method will clone the record
sforce.apex.execute('apexControllerClass','CloneME',{sObjectId: myId });

apexControllerClass:
webService static void CloneME(Id sObjectId)
{
   //clone the record?
}

Is that even possible doing this on standard page layout?

A: How about using Flow and custom button? I mean without code it is possible.
P.S. :- Currently JavaScript is not supported in Lightning Experience.

A: You can use the same what you have written, just use the below code in your "CloneME" function : -
cloneOpp = eachOpp.clone(false);
where cloneOpp is the newly created record instance and eachOpp is the existing record instance.
if you want to clone all the fields then you need to use eachOpp.clone(true).
After using the parameter as "False" use can manipulate the field value for newly created record like below: -
eachOpp.Field1__c = some value;
eachOpp.Field12__c = some value;
then you can insert the new record.Hope this will serve your purpose.


text:
Q: Optimizing an algorithm that approximates the euler number (e) in C For starters, I'm reinventing the wheel here. I know there is a constant in C for Euler's number. As I find it easier to create scientific programs than any other type of problem, I use these problems to practice and become a good developer.
/* calculating euler number */

#include <stdio.h>
int fat(int x);
int main(void)

{
    int n; int y; double en = 1.0; //en = euler number

    printf("Entre com o valor de n para a aproximação do número de Euler: \n");//prompt
    scanf("%d", &n);//read n
    //n big enough -> aproximation for en is close of real value of euler number
    if (n < 0){ //if the user input a negative value
        printf("Error!\n");
    }
    else {//if the user is not a troll and enter a positive integer
        for (y = 1; y <= n; y++){
            en = en + (1.0/(fat(y))); // en = summation(1/fat(y))
            //printf("y = %d and en = %.9lf\n", y, en); this line is for studying when en return 'inf'

        }
        printf("O valor aproximado de e é aproximadamente %.9lf\n", en);//print euler number aproximation
    }
}
int fat(int x){//defining the factorial function
    int factorial = 1;
    int f;
    for (f = 1; f <= x; f++){
        factorial = factorial * f;
    }
    return factorial;
}

I compiled and ran the code a few times, and I noticed that the approximate value exceeds the Euler value by n=19, en=2.718281835 (the last two digits should be 28). For n greater than 33, the program returns en = inf. Probably because factorial of 34 is already too huge a value for my code.
My question is: how to take advantage of the idea behind this code and make a more optimized program, for example, an algorithm that does not exceed the value of the Euler number.
I know, my code isn't very good, but it's what I managed to build without consulting anything but a math book on how to get the Euler number. Thanks in advance!

A: You can avoid calculating the factorial completly, if you store this 1.0/(fat(y)) in a variable, and divide it by progressing ys.
That way you should only hit an obstacle when the precision of your datatypes starts failing.
double term = 1.0;
for (y = 1; y <= n; ++y){
    term /= y;
    en += term; // en = summation(1/fat(y))
}

Otherwise the usual step would help, to use wider/preciser datatypes, like long int. But I supposed that is not the optimisation aspect you are looking for here.

A: Would you please try the following:
#include <stdio.h>
#include <stdlib.h>

int
main()
{
        int i, n;
        long double en = 1.0;   // Euler's number
        long double f = 1.0;    // factorial number

        printf("Enter the value of n to approximate Euler's number: ");
        scanf("%d", &n);

        if (n < 1) {
                printf("Error\n");
                exit(1);
        }

        for (i = 1; i <= n; i++) {
                f *= i;
                en += 1 / f;
        }
        printf("n = %d and en = %.9Lf\n", n, en);

        return 0;
}

It outputs for n = 12:
n = 12 and en = 2.718281828

and keeps the same en value for larger n's.


text:
Q: Understanding the warning: This class 'SwiftUI.AccessibilityNode' is not a known serializable element I put together a simple project to build upon understand using classes and structs in swift. I recieve the following warning when running this code on the simulator:
ContentView.swift
import SwiftUI

struct ContentView: View {
    @EnvironmentObject var app: App

    var body: some View {
        VStack{
            ForEach(app.users.names, id: \.self) { name in
                Text("\(name)")
            }
            Spacer()
            Button(action: {self.app.users.add()}) {
                Text("add")
            }
        }
    }
}

class App: ObservableObject {
    @Published var users = Users()
}

struct Users {
    var names = ["Mac", "Alex", "Kevin"]

    mutating func add() {
        names.append("NEW GUY")
    }
}

SceneDelegate.swift
var app = App()
let contentView = ContentView().environmentObject(app)

output:

2019-10-23 14:55:51.207032-0500 ExtendedClassDemo[43035:1908988] [AXRuntimeCommon]  class 'SwiftUI.AccessibilityNode' is not a known serializable element and returning it as an accessibility element may lead to crashes

The warning appears when running on a simulator. It pops up on the initial down click of the add button. If I run on an actual device I don't receive the warning. I'm concluding it is a simulator issue not an actual device issue.
An explanation of why this warning is produced and any suggestions to improve my implementation are most appreciated.


text:
Q: Laravel Sail share 1 database between 2 projects My site has a separate admin project. Both connect to the same database.
How do I get this working locally so when I run sail up in the admin project it does not try to create a new container for the database. I want to connect to the same database that my main application connects to. I do not need both projects to run at the same time locally.
Adding both docker.compose.yml to make it clearer.
Main:
version: '3'
services:
    laravel.test:
        build:
            context: ./docker/8.0
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-8.0/app
        extra_hosts:
            - 'host.docker.internal:host-gateway'
        ports:
            - '${APP_PORT:-80}:80'
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
            - selenium
    mysql:
        image: 'mysql:8.0'
        cap_add:
            - SYS_NICE
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment:
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
        volumes:
            - 'sailmysql:/var/lib/mysql'
        networks:
            - sail
        healthcheck:
          test: ["CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}"]
          retries: 3
          timeout: 5s
    selenium:
        image: 'selenium/standalone-chrome'
        volumes:
            - '/dev/shm:/dev/shm'
        ports:
            - '${FORWARD_SELENIUM_PORT:-4444}:4444'
            - '${FORWARD_SELENIUM_HEADFUL_PORT:-7900}:7900'
        networks:
            - sail

networks:
    sail:
        driver: bridge
volumes:
    sailmysql:
        driver: local

Second:
version: '3'
services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/8.0
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-8.0/app
        extra_hosts:
            - 'host.docker.internal:host-gateway'
        cap_add:
            - SYS_NICE
        ports:
            - 81:80 #'${APP_PORT:-80}:80'
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
    # mysql:
    #     image: 'mysql:8.0'
    #     ports:
    #         - '${FORWARD_DB_PORT:-3306}:3306'
    #     environment:
    #         MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
    #         MYSQL_DATABASE: '${DB_DATABASE}'
    #         MYSQL_USER: '${DB_USERNAME}'
    #         MYSQL_PASSWORD: '${DB_PASSWORD}'
    #         MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
    #     volumes:
    #         - 'sailmysql:/var/lib/mysql'
    #     networks:
    #         - sail
    #     healthcheck:
    #       test: ["CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}"]
    #       retries: 3
    #       timeout: 5s
networks:
    sail:
        driver: bridge
volumes:
    sailmysql:
        driver: local

A: I tried the given solution but didn't work for me, after spending a couple of hours.
I found out that we need to run both projects under one network of docker, and to do this I just add COMPOSE_PROJECT_NAME=myprettyproject in both projects' env and remove the DB service from the docker-compose.yml file from project-2.
DB ENVs will be the same for both projects.

A: To set up 2 projects using same local DB, the 1º project, it's sail default with some custom changes, explained in comments. My .envhas DB_HOST=mysql.
version: '3'
services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/7.4 #change here for php 7.4
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-7.4/app #change here for php 7.4
        extra_hosts:
            - 'host.docker.internal:host-gateway'
        ports:
            - 81:80 #'${APP_PORT:-80}:80' # I use the port 82 for the 1º project
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
            XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}'
            XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}'
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
    mysql:
        image: 'mariadb:10.5.15' #I use this version, but you can use other.
        ports:
            - '${FORWARD_DB_PORT:-3306}:3306'
        environment:
            MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ROOT_HOST: "%"
            MYSQL_DATABASE: '${DB_DATABASE}'
            MYSQL_USER: '${DB_USERNAME}'
            MYSQL_PASSWORD: '${DB_PASSWORD}'
            MYSQL_ALLOW_EMPTY_PASSWORD: 1
        volumes:
            - 'sail-mysql:/var/lib/mysql'
            - './vendor/laravel/sail/database/mysql/create-testing-database.sh:/docker-entrypoint-initdb.d/10-create-testing-database.sh'
        networks:
            - sail
        healthcheck:
            test: [ "CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}" ]
            retries: 3
            timeout: 5s
networks:
    sail:
        driver: bridge
volumes:
    sail-mysql:
        driver: local

(This creates container with DB and PHP).
On my 2ºproject, I did this docker-compose.yml.
version: '3'
services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/7.4
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
        image: sail-7.4/app
        extra_hosts:
            - 'host.docker.internal:host-gateway'
        ports:
            - 82:80 #'${APP_PORT:-80}:80'
        environment:
            WWWUSER: '${WWWUSER}'
            LARAVEL_SAIL: 1
            XDEBUG_MODE: '${SAIL_XDEBUG_MODE:-off}'
            XDEBUG_CONFIG: '${SAIL_XDEBUG_CONFIG:-client_host=host.docker.internal}'
        volumes:
            - '.:/var/www/html'
        networks:
            - sail
        depends_on:
            - mysql
    #mysql:
    #    image: 'mariadb:10.5.15'
    #    ports:
    #        - '${FORWARD_DB_PORT:-3306}:3306'
    #    environment:
    #        MYSQL_ROOT_PASSWORD: '${DB_PASSWORD}'
    #        MYSQL_ROOT_HOST: "%"
    #        MYSQL_DATABASE: '${DB_DATABASE}'
    #        MYSQL_USER: '${DB_USERNAME}'
    #        MYSQL_PASSWORD: '${DB_PASSWORD}'
    #        MYSQL_ALLOW_EMPTY_PASSWORD: 1
    #    volumes:
    #        - 'sail-mysql:/var/lib/mysql'
    #        - './vendor/laravel/sail/database/mysql/create-testing-database.sh:/docker-entrypoint-initdb.d/10-create-testing-database.sh'
    #    networks:
    #        - sail
    #    healthcheck:
    #        test: [ "CMD", "mysqladmin", "ping", "-p${DB_PASSWORD}" ]
    #        retries: 3
    #        timeout: 5s
networks:
    sail:
        driver: bridge
volumes:
    sail-mysql:
        driver: local

In here, I just commented the service for db. The .env is DB_HOST=host.docker.internal.


text:
Q: How to clone user accounts via Apple Remote Desktop - Mountain Lion I am trying to configure a middle school lab of 25 new iMacs running 10.8 Mountain Lion. I would have liked to have cloned them over the network, but we don't have a Mac server. Right now they are all turned on and configured with a basic Admin and Student account. I want to synchronize the preferences and parental controls on the student account on all of the systems.
My question is this: Is there any downside to simply copying the 'student' user folder from the properly configured system to all of the others? It appears to work, but I'm not sure if it will lead to any problems down the road, I don't have a lot of experience with this.

A: I don't have a experience with OS X 10.8, but I've done plenty of computer-lab admin work back around OS X 10.3 / 10.4 / 10.5. I'll edit and/or remove my answer if better answers come along.
I'd venture that your basic application preferences -- for browsers, word processing apps, etc. -- will duplicate OK (with the notable exception of certain licensed software, i.e. Adobe CS Suite, Filemaker Pro, etc.) -- but probably the Parental Controls settings live outside of user home folders, somewhere under /Library (the System-level /Library, not ~/Library.)
You may have success hand- or scripted-copying the relevant directories and files from /Library, but there could be other issues lurking.
I have little doubt that, without a lot of toil and expertise on your part, your students are probably going to "tear the machines up" software-wise. You'd better have an easy method for wiping & refreshing machines on a regular basis if you want to keep a semblance of consistency.
It'd be much better to run OS X Server 10.8 and use the workgroup-management features built into it, that would give you a robust, easy-to-manage setup.


text:
Q: Bitlocker: hardware or software encryption without a TPM? I'm about to setup a Samsung 840 EVO SSD as the system drive with Windows 8.1 Pro, attached to an Asus P8Z68-V Pro mobo (which doesn't have a TPM). I'll also attach a Western Digital Black HDD for extra storage (no hardware encryption). I know I can enable Bitlocker without the TPM by editting group policy settings.
1st question: Without the TPM, will it still enable Samsung's hardware encryption, or will it be software encryption only? And is the answer conditional upon using Samsung Magician?
2nd question: Assuming I can enable the hardware encryption on the SSD via Bitlocker, will it then use software encryption when writing to the HDD? Is Bitlocker smart enough for that? :p

A: Q1: To encrypt your Samsung 840 Evo through built-in hardware encryption you need motherboard which has support for Self Encrypting Drives (SED) and enabled HDD password in BIOS (Admin password for BIOS should be set earlier). There is no need for TPM as HDD password is stored on drive. After procedure you can check Samsung Magician if encryption is enabled.You can also check this thread for some additional information.
Q2: BitLocker has no relation with hardware encryption so far. It can use TPM to store encryption keys, which are automatically loaded on machine boot, so in that case remember to set power-on password or Windows password.


text:
Q: Change global array when I press a button When I press, the code runs but the array pcs[5] isn't changing. Anybody knows why? The Array is global

function ausfuehrenbutton() {
  var aktion = document.Aktionsformular.aktionen.options[document.Aktionsformular.aktionen.selectedIndex].value;
  pcs[5] = false;
  if (aktion == 1) {
    for (var i = 0; i < 15; i++) {
      var tmp = i + 1;
      if (document.getElementById("PC" + tmp).checked) {
        pcs[i] = false;
      } else {

      }
    }
  } else if (aktion == 2) {

  } else if (aktion == 3) {

  } else {

  }
}
<form name="Aktionsformular">
  <select name="aktionen">
    <option value="">Aktionen</option>
    <option value="1">Ein</option>
    <option value="2">Zwei</option>
    <option value="3">Drei</option>
  </select>
  <input type="button" onclick="ausfuehrenbutton()" value="Ausführen" />
</form>

A: When you call ausfuehrenbutton() you set pcs[5] to false regardless of what its value was before. If it was false before calling the function it will not have changed ...

A: it will never change - you have only 4 buttons - and in the array they create the last index is pcs[3]  so you never rich pcs[5]

A: Not seeing the HTML I guess this will give you some hints to continue
NOTE if you want only the checked boxes, you can change to
[...document.querySelectorAll("[id^=PC]:checked")] but then pcs[5] may fail if less than 6 boxes are checked

let pcs = [];
document.getElementById("ausfuehrenbutton").addEventListener("click", function() {
  const aktion = document.getElementById("aktionen").value;
  pcs = [...document.querySelectorAll("[id^=PC]")].map(chk => chk.checked)
  if (aktion == 1) {
    pcs[5] = false; // set to false regardless - this is PC6 by the way
    console.log(pcs);
  } else if (aktion == 2) {

  } else if (aktion == 3) {

  } else {

  }
});
<form id="Aktionsformular">
  <select id="aktionen">
    <option value="">Aktionen</option>
    <option value="1">Ein</option>
    <option value="2">Zwei</option>
    <option value="3">Drei</option>
  </select>
  1 <input type="checkbox" id="PC1"/>
  2 <input type="checkbox" id="PC2"/>
  3 <input type="checkbox" id="PC3"/>
  4 <input type="checkbox" id="PC4"/>
  5 <input type="checkbox" id="PC5"/>
  6 <input type="checkbox" id="PC6"/>
  7 <input type="checkbox" id="PC7"/>
  8 <input type="checkbox" id="PC8"/>
  9 <input type="checkbox" id="PC9"/>
  10 <input type="checkbox" id="PC10"/>
  11 <input type="checkbox" id="PC11"/>
  12 <input type="checkbox" id="PC12"/>
  13 <input type="checkbox" id="PC13"/>
  14 <input type="checkbox" id="PC14"/>
  15 <input type="checkbox" id="PC15"/>
  <input type="button" value="Ausführen" id="ausfuehrenbutton" />
</form>


text:
Q: SQL group related rows in a list I'm a bit stuck with this...
I have items table:
id | name
 1 | item 1
 2 | item 2
 3 | item 3
 4 | item 4

and related items table:
id | item_id | related_item_id
 2 |      1  | 2
 3 |      1  | 4

so this means that item 1 is related to items 2 and 4.
Now I'm trying to display these in a list where related items follow always the main item they are related to:
item 1
item 2
item 4
item 3

Then I can visually show that these items 2 and 4 are related to item one and draw something like:
item 1
-- item 2
-- item 4
item 3

To be honest, haven't got any ideas myself. I quess I could query for items which are not related to any other item and get a list of "parent items" and then query relations separately in a script loop. This is not definately the sexiest solution...

A: I am assuming that this question is about ordering the items list, without duplicates.  That is, a given item does not have more than one parent (which I ask in a comment).
If so, you can do this with a left outer join and cleverness in the order by.
select coalesce(r.related_item_id, i.id) as item_id
from items i left join
     related r
     on i.id = r.related_item_id
order by coalesce(r.item_id, i.id),
         (r.related_item_id is null) desc;

The left outer join identifies parents because they will not have any rows that match.  If so, the coalesce() finds them and uses the item id.

A: In my opinion , rather than implementing this logic in a query , you should move it to your actual code.
assuming that item_ids are sequential, you can find the largest number of item_id, then in a loop
you can find related_item_id to each item_id and make a convenient data structure out of it.

A: This functionality comes under the category of hierarchical queries. In Oracle its handled by connect by  clause not sure about mysql. But you can search "hierarchical queries mysql" to get the answer.


text:
Q: phantom php echo? im getting this error:
Parse error: syntax error, unexpected T_ECHO in /home/labvc/public_html/AT/site/getimages.php on line 26

from this code:
<?php

echo '
';
echo '
';

function getDirTree($dir,$p=true) {
    $d = dir($dir);$x=array();
    while (false !== ($r = $d->read())) {
        if($r!="."&&$r!=".."&&(($p==false&&is_dir($dir.$r))||$p==true)) {
                $x[$r] = (is_dir($dir.$r)?array():(is_file($dir.$r)?true:false));
        }
    }

    foreach ($x as $key => $value) {
        if (is_dir($dir.$key."/")) {
                $x[$key] = getDirTree($dir.$key."/",$p);
        }
    }

    ksort($x);
    return $x;
}

$tree = getDirTree("./res/gallery/painting/");

foreach($tree as $element => $eval) {
    if (is_array($eval)) {
        foreach($eval as $file => $value) {
                if (strstr($file, "png")||strstr($file, "jpg")||strstr($file, "bmp")||strstr($file, "gif")) {
                        $item = $tree.'/'.$element.$file;
            $itemthumb = $tree.'/thumbs/'.$element.$file;
                        echo '';
                }
        }
    }
}

echo '
';

echo '
';

echo 'tree: '.$tree.'
';
echo 'element: '.$element.'
';
echo 'file: '.$file.'
';

$abc="res/gallery/painting";
$def="01.png";
echo'';

echo '
';

line 26 is not an echo, theres not even an echo close to line 26
foreach($tree as $element => $eval) {

Any ideas?

A: I know it sounds silly, but are you actually looking at / editing the file you are debugging?
Any number of times it turned out I was in directory A/foo.c, when the code was being run out of directory B/foo.c. I always feel stooooopid after doing this.
Stick a print "foo!" in there to see if you are actually in the file you think you are.

A: This seems a suspicious line:
$item = $tree.'/'.$element.$file;

$tree should be an array, so if you get the error at runtime (as opposed to compile time) then it would make sense it would complain about this.


text:
Q: What maths is being used to calculate this interest? I'm curious about how my bank is calculating the interest on my credit card. No matter what I do, I cannot make the numbers add up!
Below is a photo of my latest statement. It's for 13th June - 12th July. There were no purchases, but an opening balance of £907.19, and a payment of £9.07  on 8th July.
The statement says that interest for my entire balance (all purchases) is "0.026% per day (9.95% APR)". The statement clearly says on the back that interest is calculated daily.
So, I took the opening balance and added 0.026% per day, then subtracted £9.07 on 8th July, then continued adding 0.026% per day, until 12th July. I ended up with a closing balance of £904.98 (theirs is £906.73).
I've subsequently tried all sorts of different calculations, and cannot come to their figure without increasing the rate quite a bit. Even if I round up every days value to the nearest penny, I only get £905.32.
So; how are they calculating this? Or is their maths wrong and I'm being charged higher than the rate being claimed?
-- Update: 03/08/2013 --
Spoke to someone at my banks credit card department today. She didn't really seem to understand the maths. When I told her I'd multiplied by 1.00026^30 she asked where there was a 1!
She did, however, say:

*

*Yearly rate: 9.95%

*Monthly rate: 0.793% (this wasn't on the bill)

*Daily rate: 0.026%

*Interest is calculated daily

*The interest period was 29 days (though this makes the numbers slightly further out, not closer!)

However, this good information (well, confirmation of what I had) was somewhat undermined when she said "Some interest will be calculated from the opening balance (£907.19) and some from the closing balance (£906.73). This doesn't really make sense (how can you calculate interest using a figure that is derived from the interest?!).
So said she'd have to pass the info on to their "back office" who can send me a full breakdown.
I look forward to receiving it! :-/

A: Ok; this didn't really turn out to be a maths question; but rather just an overly-simplified bill. I had a letter from my bank explaining how it worked (which was quite confusing, but I managed to get my head around it!).
With my bank, if you pay off your credit card balance before the end of the month; no interest is charged on that months purchases. However; the interest is still calculated for the period between the purchase and the end of the month, and it is deferred to the following month.
So if you make a purchase on 1st month and pay it off on 30th (assuming billing cycle is each month, which it's not in my case, but makes it easier ;-)), then you will pay no interest. However, if you do not pay it off, then the following month you will pay two months interest for the purchases (the deferred interest from the first month, which wasn't added on previously, in case you paid it off the same month, and also the interest from the second month, which can be added on immediately, since there's no way you can "avoid" this interest because the purchase was made in a different month).
So, in short; you will see "double" the interest for purchases on a month after making purchases, making up for the first months interest not being on the first bill, due to the "pay it off same month, don't pay the interest" rule.
Helpfully, they included the previous few months breakdown, so I could see the amount of interest calculated for May purchases, then charged in June, then June purchases, which was included in July. I checked my May statement, and say there was no interest charged, despite purchases that month.
Another thing this letter did also highlight, is that the daily rate is 0.026082%! Not the 0.026% shown on the bill! ;-O
An interesting think that I misunderstood, is how they calculate interest. Their "daily rate" is not compounded; they instead add up all of the balances for each day, and then simply multiply by the daily rate.
Eg., instead of doing (for a £10,000 balance over 30 days):
10000 * (1.00026082 ^ 30)

They're actually doing:
10000 * 30 * 0.00026082

I think this is slightly confusing. By "charging interest daily", I presumed they meant it was being compounded each day; however I believe what they actually mean is that your balance for each day is taken into account, so if for 3 days in the middle of the month your balance was really high; it will be taken into account, rather than interest just being based on a single value that is your closing balance.


text:
Q: Why no menu bar in LibreOffice When you move your cursor to the top of the screen in Libreoffice you don't get a menu.  You do for other applications like Firefox and Thunderbird but not for Libreoffice.

A: Try:

sudo apt-get remove libreoffice-gtk

It will remove the global menu bar and replace it with a basic one, but it might give you functionality. That worked for me anyways.
You can also try getting updates - there may have been a bug fix for it:

sudo apt-get update

Or just use the GUI updater.

A: Ubuntu software center -> search for "lo-menubar" and install. Now you have a unity menu for Libre Office. Make it so.

A: Just updated Ubuntu. Latest updates included several LibreOffice updates. This appears to have fixed the problem.

A: I've been updating my ubuntu 12.10 and this problem still occurred.
Here is what I've done and it worked for me:
sudo apt-get purge libreoffice-gtk
sudo apt-get install libreoffice-gtk

Hope it helps!

A: I'm using Ubuntu 12.10 with LibreOffice 3.6.2.2 and this is what worked for me:
sudo apt-get remove libreoffice-gtk

Then opened LibreOffice and there was the menu, no need to install lo-menubar.

A: (I know this is an old question but happened to me again now)
For me, changing the Java Runtime fixed the problem, instead of using the Oracle one I choose the Ubuntu and the bar appears again.


text:
Q: WPF C# Отображение объектов на Canvas (2d Map) Задача: Создать приложение "Создание карт исследований месторождений".
1) Есть панель, на панели расположены кнопки с изображением которое мы хотим отобразить на экране, далее его параметры, и его координаты.
2) Размещаем изображения на экране нажав на кнопку и перетащив на экран (это у нас Toggle Button)
3) Соединяем размещенные изображения стрелками
Вот какой должен быть конечный вариант "Примерно")):

Нашел более менее достойный пример, переделал по максимуму под свои задачи, добавил объекты, убрал лишнее и т.д.
Вопросы:
1) Могу добавлять изображения на Canvas не более одного, не пойму в чем проблема, приложение написано по MVVM. При нажатии на кнопку, выделяются обе кнопки, то тащит объект тот который был последним положен на canvas.
2) Все формируется в Node/NodesEditor.xaml, в canvas, в canvas даю ссылки на изображения, панель лежит отдельно Menu/ButtonsPanel.xaml кнопки Toggle Button берут те же изображения для вида, так же Toggle Button принимает ссылку из класса Node/MainViewModel.cs от метода CreatingNewNode.
3) Где лежит проблема не пойму, один метод не может через Binding (Menu/ButtonsPanel.xaml) использоваться на несколько кнопок? Перестроить логику canvas (Node/NodesEditor.xaml)? Переделать метод CreatingNewNode (Node/MainViewModel.cs)?
Ссылка на гитхаб: https://github.com/talasbaev/LabApp.git

A: Посмотрите на ArcGIS Runtime SDK for .NET https://community.esri.com/community/developers/
Этот фреймворк специально разработан для работы с картами


text:
Q: Is there a rate limit for APIs hosted on Heroku? I'm hosting my API on Heroku (example endpoint: https://some-api.herokuapp.com/some/request). I'm not currently paying for any subscription on Heroku.
Is there a limit to the number of calls to this API that I can make, eg. per hour?

A: There is no limit on requests your application can receive. You should implement rate limiting in your own code.

A: the limit seems to be 4500 calls per hour.
https://devcenter.heroku.com/articles/limits


text:
Q: CommonsMultipartFile - FileNotFoundException I am trying to develop an application where user will upload a file from screen, the file will be processed in server side.
I am using Adobe Flex for UI, Spring 3.2 as middle-ware and Java 5. I can successfully upload the file and in server side and can get the file name. But when I am trying to get the InputStream, I get the FileNotFoundException. It seams it is trying to create a temporary file in some location inside the application server and trying to read that temporary file for processing, but failed to create the temporary file. Following is the code snippet where I tries to get the file -
public List<TransactionVO> populateVO(VoucherUploadCommandForm object,
Connection conn) throws XenosException {
   log.debug("InVoucherVOPopulatorForExcelUpload.populateVO()");
     if(object == null){
     log.debug(" No file uploaded :(");
   }else{
     CommonsMultipartFile file = object.getFileName();
     log.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Excel file uploaded :)");
     log.debug("Excel file= "+ file.getOriginalFilename());
     try {
        log.debug("Excel Size= "+ file.getSize());
        log.debug("Excel fileItem= "+ file.getFileItem().getInputStream());
     } catch (IOException e) {
         log.error(e);
     }
   }
   return null;
}

The stackTrace of the error is as follows -
SEVERE: Exception loading sessions from persistent storage
java.io.FileNotFoundException: C:\apache-tomcat-6.0.20\work\Catalina\localhost\rui-1.1-xenos\upload_375f4172_d416_4ae2_975f_bc5e908a8303_00000007.tmp (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:106)
at org.apache.commons.fileupload.disk.DiskFileItem.readObject(DiskFileItem.java:663)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:946)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1809)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1719)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1908)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1832)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1719)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1908)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1832)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1719)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1305)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:348)
at org.apache.catalina.session.StandardSession.readObject(StandardSession.java:1441)
at org.apache.catalina.session.StandardSession.readObjectData(StandardSession.java:942)
at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:394)
at org.apache.catalina.session.StandardManager.load(StandardManager.java:321)
at org.apache.catalina.session.StandardManager.start(StandardManager.java:637)
at org.apache.catalina.core.ContainerBase.setManager(ContainerBase.java:438)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4358)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:526)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:630)
at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:556)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:491)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1206)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:314)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:722)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:583)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Nov 25, 2013 2:56:18 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8084
Nov 25, 2013 2:56:18 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
Nov 25, 2013 2:56:18 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/20 config=null
Nov 25, 2013 2:56:18 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 45220 ms

A: Configure your CommonsMultipartResolver to use something other then the default directory. For this set the uploadTempDir property of the CommonsMultipartResolver.
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="uploadTempDir" value="d:/temp" />
</bean>

A note on your code, you should be programming to interfaces and not concrete classes. In your controller change CommonsMultipartFile to MultipartFile.
In your code you are retrieving the underlying FileItem directly, you should be using the MultipartFile convenience methods for that. You can simply call getInputStream() on the MultipartFile instance you have.
public List<TransactionVO> populateVO(VoucherUploadCommandForm object, Connection conn) throws XenosException {
    log.debug("InVoucherVOPopulatorForExcelUpload.populateVO()");
    if(object == null){
        log.debug(" No file uploaded :(");
    }else{
        MultipartFile file = object.getFileName();
        log.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Excel file uploaded :)");
        log.debug("Excel file= "+ file.getOriginalFilename());
        try {
            log.debug("Excel Size= "+ file.getSize());
            log.debug("Excel fileItem= "+ file.getInputStream());
        } catch (IOException e) {
            log.error(e);
        }
    }
    return null;
}


text:
Q: Unable to install helm chart on private Google Kubernetes Engine (timeout error) I have created a private cluster in gke with the follwoing
gcloud container clusters create private-cluster-0 \
--create-subnetwork name=my-subnet-0 \
--enable-master-authorized-networks \
--enable-ip-alias \
--enable-private-nodes \
--enable-private-endpoint \
--master-ipv4-cidr 172.16.0.32/28 \
--zone us-central1-a

Then I did
gcloud container clusters get-credentials --zone us-central1-a private-cluster-0

I was trying to install a helm chart from my local machine but I got the following error:
Error: INSTALLATION FAILED: Kubernetes cluster unreachable: Get "https://172.16.0.34/version?timeout=32s": dial tcp 172.16.0.34:443: i/o timeout

Can anyone please tell me how to resolve this error.
How to deploy an helm chart from a local machine to a private cluster in gke?

A: You created a private cluster and trying to install helm from local machine.
This won't work because 172.16.0.0/12 range is non-routable, your PC is looking for the cluster in your own LAN.
You can find information on accessing private GKE clusters on google docs.
There are also more general tutorials on installing helm on GKE from google and medium.

A: First you need basic connectivity to access your private cluster.
For example, SSH to a VM on a subnet that master-ipv4-cidr allows.
I had this basic connectivity but was still unable to install a helm chart as the install couldn't access services within the cluster.
I could only see this issue after adding verbosity to helm install and logging the output.
helm install -v10 my-chart  >log.txt 2>&1

With the get-credentials command
gcloud container clusters get-credentials --zone us-central1-a private-cluster-0

Try adding the argument --internal-ip
This controls whether to use the internal IP address of the cluster endpoint. It made the difference for me.


text: Q: Ubuntu - KDE plasma login issue I am using Ubuntu 22.04.1 LTS so I decided to try the plasma desktop and went ahead to install it and selected it to load up. After rebooting I get an error login details failed. I've tried ctrl + alt + 5 it asks for my ubuntu login and I put that. It does not allow me to go past that. Shows a 'welcome to Ubuntu message' and disappears then I'm left to type again my credentials. What could be the issue and how do I go about resolving it?


text:
Q: jQuery => PHP Form validation Hi this is the first time I've written php to process form data, I have already implemented the jQuery to validate, and I have written the PHP to process the form, and also encryption, salting escaping and filtering, before I write the code to insert the data into the db, I am just wondering how to send the results of the php validation back to the front end.
There is a level of security in the jQuery, however this might be turned off, but the level of security through the php is greater, especially regarding email validation. The PHP is in a seperate file, so I'm wondering the best way to connect the PHP programs back to the front end to inform the user as to whether their data is acceptable.
I've heard of session redirects, and also Ajax but would not want to use this in case JS is turned off.
Thanks
Ant

A: Use AJAX for that, that will allow you to send the data to your PHP script, and keep the user on the current page. You can then return something like true or false depending if everything passed PHP's validation.
If a user has Javascript disabled, then they don't get to have fancy websites doing fun and interesting things. Take a look here for how to handle if a user does not have javascript enabled.
Essentially, you will need to do a regular form and have the user submit/reload the page with whatever error/success message(s) needed for them to know they are done or fix their errors.