text:
Q: calculate the time difference. R I have a a dataframe with 2 column:
   StartTime             EndTime
1. 2019-05-06 08:34:15   2019-05-06 08:48:30
2. 2019-05-06 10:07:18   2019-05-06 10:21:34
3. 2019-05-06 15:13:10   2019-05-06 15:27:26
4. 2019-05-06 15:35:52   2019-05-06 15:50:07
5. 2019-05-06 16:14:18   2019-05-06 16:33:58
6. 2019-05-06 16:58:14   2019-05-06 17:13:36
7. 2019-05-06 20:28:50   2019-05-06 21:05:11
8. 2019-05-06 21:55:53   2019-05-06 22:16:50
9. 2019-05-06 22:42:21   2019-05-06 22:57:46
10.2019-05-06 23:26:59   2019-05-07 00:03:46
11.2019-05-07 00:36:43   2019-05-07 00:53:44

I want to add a new column(IdlingTime) to calculate the idle time.
let's say the first row IdlingTime is:
2nd row of StartTime - 1st row of EndTime = 1 HR 18 min 48 sec and convert to minutes.
Thank you advance.

A: Update if your data is already POSIXct: then
library(dplyr)
df %>%
  mutate(IdlingTime = round(lead(StartTime)-EndTime))

Output:
  StartTime           EndTime             IdlingTime
   <dttm>              <dttm>              <drtn>
 1 2019-05-06 08:34:15 2019-05-06 08:48:30  79 mins
 2 2019-05-06 10:07:18 2019-05-06 10:21:34 292 mins
 3 2019-05-06 15:13:10 2019-05-06 15:27:26   8 mins
 4 2019-05-06 15:35:52 2019-05-06 15:50:07  24 mins
 5 2019-05-06 16:14:18 2019-05-06 16:33:58  24 mins
 6 2019-05-06 16:58:14 2019-05-06 17:13:36 195 mins
 7 2019-05-06 20:28:50 2019-05-06 21:05:11  51 mins
 8 2019-05-06 21:55:53 2019-05-06 22:16:50  26 mins
 9 2019-05-06 22:42:21 2019-05-06 22:57:46  29 mins
10 2019-05-06 23:26:59 2019-05-07 00:03:46  33 mins
11 2019-05-07 00:36:43 2019-05-07 00:53:44  NA mins

First answer:
After getting the correct class datetime we could use lead function from dplyr package:
library(dplyr)
library(lubridate)
df %>%
 #mutate(across(contains("Time"), ~ymd_hms(.)))
         IdlingTime = lead(StartTime)-EndTime)

output:
   StartTime           EndTime             IdlingTime
   <dttm>              <dttm>              <drtn>
 1 2019-05-06 08:34:15 2019-05-06 08:48:30  78.800000 mins
 2 2019-05-06 10:07:18 2019-05-06 10:21:34 291.600000 mins
 3 2019-05-06 15:13:10 2019-05-06 15:27:26   8.433333 mins
 4 2019-05-06 15:35:52 2019-05-06 15:50:07  24.183333 mins
 5 2019-05-06 16:14:18 2019-05-06 16:33:58  24.266667 mins
 6 2019-05-06 16:58:14 2019-05-06 17:13:36 195.233333 mins
 7 2019-05-06 20:28:50 2019-05-06 21:05:11  50.700000 mins
 8 2019-05-06 21:55:53 2019-05-06 22:16:50  25.516667 mins
 9 2019-05-06 22:42:21 2019-05-06 22:57:46  29.216667 mins
10 2019-05-06 23:26:59 2019-05-07 00:03:46  32.950000 mins
11 2019-05-07 00:36:43 2019-05-07 00:53:44         NA mins

A: This is how I would do it.
df %>%
  mutate_all(dmy_hm)  %>%
  mutate(
    IdlingTime = as.double(lead(StartTime)-EndTime, units = "mins")
  )

A: You just subtract the columns.
Here is the (reproducible, with your data !!) code given the updated question.  I use data.table which parse the data columns to POSIXct when reading, and makes lead/lag easy too
Code
library(data.table)
data <- fread(text="StartTime,EndTime
2019-05-06 08:34:15,2019-05-06 08:48:30
2019-05-06 10:07:18,2019-05-06 10:21:34
2019-05-06 15:13:10,2019-05-06 15:27:26
2019-05-06 15:35:52,2019-05-06 15:50:07
2019-05-06 16:14:18,2019-05-06 16:33:58
2019-05-06 16:58:14,2019-05-06 17:13:36
2019-05-06 20:28:50,2019-05-06 21:05:11
2019-05-06 21:55:53,2019-05-06 22:16:50
2019-05-06 22:42:21,2019-05-06 22:57:46
2019-05-06 23:26:59,2019-05-07 00:03:46
2019-05-07 00:36:43,2019-05-07 00:53:44")

data[, minElapsed := as.numeric(EndTime - StartTime)]
data[, idleMin := as.numeric(StartTime - shift(EndTime))]
data

Output
> library(data.table)
> data <- fread(text="StartTime,EndTime
+ 2019-05-06 08:34:15,2019-05-06 08:48:30
+ 2019-05-06 10:07:18,2019-05-06 10:21:34
+ 2019-05-06 15:13:10,2019-05-06 15:27:26
+ 2019-05-06 15:35:52,2019-05-06 15:50:07
+ 2019-05-06 16:14:18,2019-05-06 16:33:58
+ 2019-05-06 16:58:14,2019-05-06 17:13:36
+ 2019-05-06 20:28:50,2019-05-06 21:05:11
+ 2019-05-06 21:55:53,2019-05-06 22:16:50
+ 2019-05-06 22:42:21,2019-05-06 22:57:46
+ 2019-05-06 23:26:59,2019-05-07 00:03:46
+ 2019-05-07 00:36:43,2019-05-07 00:53:44")
>
> data[, minElapsed := as.numeric(EndTime - StartTime)]
> data[, idleMin := as.numeric(StartTime - shift(EndTime))]
> data
              StartTime             EndTime minElapsed   idleMin
 1: 2019-05-06 08:34:15 2019-05-06 08:48:30    14.2500        NA
 2: 2019-05-06 10:07:18 2019-05-06 10:21:34    14.2667  78.80000
 3: 2019-05-06 15:13:10 2019-05-06 15:27:26    14.2667 291.60000
 4: 2019-05-06 15:35:52 2019-05-06 15:50:07    14.2500   8.43333
 5: 2019-05-06 16:14:18 2019-05-06 16:33:58    19.6667  24.18333
 6: 2019-05-06 16:58:14 2019-05-06 17:13:36    15.3667  24.26667
 7: 2019-05-06 20:28:50 2019-05-06 21:05:11    36.3500 195.23333
 8: 2019-05-06 21:55:53 2019-05-06 22:16:50    20.9500  50.70000
 9: 2019-05-06 22:42:21 2019-05-06 22:57:46    15.4167  25.51667
10: 2019-05-06 23:26:59 2019-05-07 00:03:46    36.7833  29.21667
11: 2019-05-07 00:36:43 2019-05-07 00:53:44    17.0167  32.95000
>

Original Answer below
Code
data <- read.csv(text="StartTime,EndTime
2019-05-06 08:34:15,2019-05-06 08:48:30
2019-05-06 10:07:18,2019-05-06 10:21:34
2019-05-06 15:13:10,2019-05-06 15:27:26
2019-05-06 15:35:52,2019-05-06 15:50:07
2019-05-06 16:14:18,2019-05-06 16:33:58
2019-05-06 16:58:14,2019-05-06 17:13:36
2019-05-06 20:28:50,2019-05-06 21:05:11
2019-05-06 21:55:53,2019-05-06 22:16:50
2019-05-06 22:42:21,2019-05-06 22:57:46
2019-05-06 23:26:59,2019-05-07 00:03:46
2019-05-07 00:36:43,2019-05-07 00:53:44")

data$StartTime     <- as.POSIXct(data$StartTime)
data$EndTime       <- as.POSIXct(data$EndTime)

data$IdlingTime    <- data$EndTime - data$StartTime
data$IdlingTimeMin <- as.numeric(data$EndTime - data$StartTime)

Output
> data
             StartTime             EndTime   IdlingTime IdlingTimeMin
1  2019-05-06 08:34:15 2019-05-06 08:48:30 14.2500 mins       14.2500
2  2019-05-06 10:07:18 2019-05-06 10:21:34 14.2667 mins       14.2667
3  2019-05-06 15:13:10 2019-05-06 15:27:26 14.2667 mins       14.2667
4  2019-05-06 15:35:52 2019-05-06 15:50:07 14.2500 mins       14.2500
5  2019-05-06 16:14:18 2019-05-06 16:33:58 19.6667 mins       19.6667
6  2019-05-06 16:58:14 2019-05-06 17:13:36 15.3667 mins       15.3667
7  2019-05-06 20:28:50 2019-05-06 21:05:11 36.3500 mins       36.3500
8  2019-05-06 21:55:53 2019-05-06 22:16:50 20.9500 mins       20.9500
9  2019-05-06 22:42:21 2019-05-06 22:57:46 15.4167 mins       15.4167
10 2019-05-06 23:26:59 2019-05-07 00:03:46 36.7833 mins       36.7833
11 2019-05-07 00:36:43 2019-05-07 00:53:44 17.0167 mins       17.0167
>


text:
Q: Decompose a float into mantissa and exponent in base 10 without strings Are there functions in the Python library or numpy that take a float as input and return its decimal scientific notation decomposition, i.e. mantissa and exponent? Or is there a BRIEF way to accomplish this without resorting to string conversions or using a for loop to determine the exponent? Writing such a function wouldn't be difficult, I'm just shocked that I'm having trouble finding an existing one in math, decimal or numpy.
e.g. if fexp and fman are the functions giving the exponent and mantissa of the decimal floating point representation of a float then we'd expect the following statements to all return true:
fexp(154.3) == 2.0
fman(154.3) == 1.543
fexp(-1000) == 3.0
fman(-1000) == -1.0

In short, this would be a "decimal version" of math.frexp.

A: One way to avoid string conversions is to implement the methods using Decimals:
from decimal import Decimal

def fexp(number):
    (sign, digits, exponent) = Decimal(number).as_tuple()
    return len(digits) + exponent - 1

def fman(number):
    return Decimal(number).scaleb(-fexp(number)).normalize()

Note that using floating point numbers, its not possible to calculate mantissa and exponent without rounding. The reason is that floating point numbers are stored as base 2 fractions. For example stored float value for 154.3 is 154.30000000000001136868377216160297393798828125. Floats are displayed in console as accurate numbers, because (in CPython) they are always rounded when serialized using a hard-coded precision of 17.

A: I'm hoping there's a better answer but I came up with
from math import floor, log10

def fexp(f):
    return int(floor(log10(abs(f)))) if f != 0 else 0

def fman(f):
    return f/10**fexp(f)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java - crossover algorithm I working on android app for TSP problem.
I have a crossover algorithm and i want minimize number of loops for faster algorithm.
How I can do it?
This is the code:
public static Path crossover(Path dad, Path mom) {
    //Create new child path
    Path child = new Path();

    //Get start and sub path positions for dads path
    double startPos = (double) (Math.random() * dad.pathSize());
    double endPos = (double) (Math.random() * dad.pathSize());

    //Loop and add the sub path from dad to our child
    for (int i = 0; i < child.pathSize(); i++) {
        //If our start position is less than the end position
        if (startPos < endPos && i > startPos && i < endPos) {
            child.setDestination(i, dad.getDestination(i));
        } // if our start position is larger
        else if (startPos > endPos) {
            if (!(i < startPos && i > endPos)) {
                child.setDestination(i, dad.getDestination(i));
            }
        }
    }

    // Loop through mom destination path
    for (int i = 0; i < mom.pathSize(); i++){
        // If child doesn't have the destination add it
        if (!child.containsDestination(mom.getDestination(i))) {
            // Loop to find a spare position in the child's path
            for (int j = 0; j < child.pathSize(); j++) {
                //Spare position found, add destination
                if (child.getDestination(j) == null) {
                    child.setDestination(j, mom.getDestination(i));
                    break;
                }
            }
        }
    }
    return child;
}

A: If I understand the GA crossover correctly, you may only employ one for loop returning a child from parents.
Please have a look at my sample code:
public Chromosomes crossoverChrom(Chromosomes inpChrom1, Chromosomes inpChrom2){
        // offspring chromosome has the same size as the target chromosome
        Chromosomes offspring = new Chromosomes(inpChrom1.getGenes().length);

        for (int i = 0; i < offspring.getGenes().length;i++){
            double randOffspring = Math.random();
            //          System.out.println("i_offspring [" + i + "] , randOffspring = " + randOffspring);
            if(randOffspring <= crossoverRate){
                //              System.out.println("gene from chrom 1");
                offspring.setGenes(i, inpChrom1.getGenes()[i]);
            } else {
                //              System.out.println("gene from chrom 2");
                offspring.setGenes(i, inpChrom2.getGenes()[i]);
            }
        }
        //      System.out.println("Offspring      = " + offspring + " | Fitness = " + offspring.getFitness());
        //      System.out.println("--------------------------------------------------");
        return offspring;
    }


text:
Q: Binary Search on a List in Java I want my function to return "YES" if the element is found in List and "NO
" if it is not found.
I have written the following code(binary search) but some test-cases are failing.
However, I wrote the code for Linear Search and all test-cases passed.
I have written this program
static String findNumber(List<Integer> arr, int k) {

    int l=0;
    int r= arr.size()-1;
    int flag=0;

    while(l<=r){
        int m = l + (r - l) / 2;
        if(arr.get(m)==k){
            return "YES";
            //flag=1;
        }
        else if(arr.get(m)<k){
            l=m+1;
        }
        else
           r = m-1;

    }
    // if(flag==1){
    //     return "YES";
    // }

    return "NO";
}

However the same code works with arrays and all test-cases gets passed.

A: Your binary search function is correct. Maybe something else makes it wrong. Ensure that your list is sorted and all numbers in input fit in int (long is not needed).


text:
Q: Copula generation (Gaussian, t and Gumbel) with the help of correlation matrix using R I have a set of data of 2 variates. I have generated correlation matrix between the variates. Using copula package of R, I computed t-copula using correlation matrix. I used the following technique for that:

*

*With the help of correlation matrix for example let it be corr_mat, I computed parameter vector, lets say param_vect.

*Then I computed tcopula object, let it be t_object, using
tCopula(param_vect, dim =..., dispstr="un", df =...)

*Lastly I simulated 1000 sample from the copula using rcopula(1000,t_object).
The above procedure works fine for t-copula. Can someone please suggest me amethod to simulate samples from the Gaussian and Gumbell copulas? I  tried with the gumbelcopula function, but it fails with errors.
Could anyone one suggest the method to simulate copula using correlation matrix?

A: Correlation is problematic because it depends on the marginal distribution.
Change the margins (which doesn't alter the copula) and the correlation changes. A specific correlation is not associated with a given copula and vice-versa.
The correlation matrix that is an input to a t-copula doesn't define the correlation of the resulting variables that have that copula, so you may not be achieving what you think you are when you use the t-copula function. Similarly with the correlation in a Gaussian copula - you can specify the value of the parameter $\rho$, but that doesn't mean that the correlation of the variables you generate with that Gaussian copula is $\rho$. If they also have Gaussian margins, then the correlation is $\rho$, otherwise it will generally not be $\rho$, but some function of it that depends on what the margins are.
This is why many people focus on nonparametric correlations like Kendall's tau or Spearman's rho. Those are specified by a given copula, and apply to any (continuous) margin.
For a number of specific copula families there are often relatively simple relationships between the parameters of the family and one or both of those common measures of nonparametric correlation.


text:
Q: Why cant I take a value from the current state and use that inside of my useState hook? Currently, an object for the logged in user is set to the current state, which from the doe below you can see i am bringing in from the authContext. I am trying to take the user.firstName value and set that to the author inside of the useState hook. When i run this inside of my application, I look in the database where Log object is stored but the author value is blank. I am very new to coding so any advice would be greatly appreciated!
import React, { useState, useContext } from "react";
import M from "materialize-css/dist/js/materialize.min.js";
import LogContext from "../context/logs/logContext";
import AuthContext from "../context/auth/authContext";

const AddLogModal = () => {
  const logContext = useContext(LogContext);
  const authContext = useContext(AuthContext);

  const { user } = authContext;

  const { addLog } = logContext;

  const [log, setLog] = useState({
    title: "",
    description: "",
    attention: "",
    author: user.firstName,
    date: new Date(),
  });

  const { title, description, attention, author } = log;

  const onChange = (e) => setLog({ ...log, [e.target.name]: e.target.value });

  const onSubmit = (e) => {
    e.preventDefault();
    if (title === "" || description === "" || attention === "") {
      M.toast({ html: "Please enter a title and description.." });
    } else {
      setLog({ ...log, [e.target.name]: e.target.value });
    }

    addLog(log);

    setLog({
      title: "",
      description: "",
      attention: "",
      author: user.firstName,
    });
  };

  return (
    <form id="add-log-modal" className="modal" style={modalStyle}>

Open New Issue

            <input type="text" name="title" value={title} onChange={onChange} />

              Log Title

          <input
            type="text"
            name="description"
            value={description}
            onChange={onChange}
          />

            Log Description

          <input type="text" name="author" value={author} onChange={onChange} />

            Created By:

                <input
                  type="radio"
                  name="attention"
                  checked={attention === "Needs Attention"}
                  value="Needs Attention"
                  onChange={onChange}
                />
                Needs Attention

                <input
                  type="radio"
                  name="attention"
                  checked={attention === "Issue Resolved"}
                  value="Issue Resolved"
                  onChange={onChange}
                />
                Issue Resolved

          Enter

    </form>
  );
};

const modalStyle = {
  width: "75%",
  height: "75%",
};

export default AddLogModal;

AuthContext
import React, { useReducer } from "react";
import axios from "axios";
import AuthContext from "./authContext";
import setAuthToken from "../setAuthToken";
import authReducer from "./authReducer";
import {
  REGISTER_SUCCESS,
  REGISTER_FAIL,
  LOGIN_FAIL,
  LOGIN_SUCCESS,
  LOGOUT,
  USER_LOADED,
  AUTH_ERROR,
  CLEAR_ERRORS,
} from "../Types";

const AuthState = (props) => {
  const initialState = {
    token: localStorage.getItem("token"),
    isAuthenticated: false,
    loading: false,
    user: {},
    error: null,
  };

  const [state, dispatch] = useReducer(authReducer, initialState);

  // Load User
  const loadUser = async () => {
    if (localStorage.token) {
      setAuthToken(localStorage.token);
    }
    try {
      const res = await axios.get("/api/auth");

      dispatch({ type: USER_LOADED, payload: res.data });
    } catch (err) {
      dispatch({ type: AUTH_ERROR });
    }
  };

  // Register User
  const register = async (formData) => {
    const config = {
      headers: {
        "Content-type": "application/json",
      },
    };

    try {
      const res = await axios.post("/api/users", formData, config);

      dispatch({
        type: REGISTER_SUCCESS,
        payload: res.data,
      });

      loadUser();
    } catch (err) {
      dispatch({
        type: REGISTER_FAIL,
        payload: err.response.data.msg,
      });
    }
  };
  // Login User
  const login = async (formData) => {
    const config = {
      headers: {
        "Content-type": "application/json",
      },
    };

    try {
      const res = await axios.post("/api/auth", formData, config);

      dispatch({
        type: LOGIN_SUCCESS,
        payload: res.data,
      });

      loadUser();
    } catch (err) {
      dispatch({
        type: LOGIN_FAIL,
        payload: err.response.data.msg,
      });
    }
  };
  // Logout
  const logout = () => {
    dispatch({
      type: LOGOUT,
    });
  };
  // Clear Errors
  const clearErrors = () => {
    dispatch({
      type: CLEAR_ERRORS,
    });
  };

  return (
    <AuthContext.Provider
      value={{
        token: state.token,
        isAuthenticated: state.isAuthenticated,
        loading: state.loading,
        user: state.user,
        error: state.error,
        register,
        login,
        clearErrors,
        loadUser,
        logout,
      }}
    >
      {props.children}
    </AuthContext.Provider>
  );
};

export default AuthState;

A: React Docs:
If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value. Here's an example of a counter component that uses both forms of setState
React Example:
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>


text:
Q: Why Won't This Page Work in Firefox/Chrome I'm curious if anyone can help me figure out why this page won't work in Firefox or Chrome?  It seems to just keep refreshing.
https://easypaynet.adp.com/epn/Login.jsp

A: The page actively redirects any user with chrome or firefox, there might be a redirect loop or something.
But the page also uses a self signed security certificate which will make most people skip the page.
If the page is yours, create one without the certificate and skip the permanent redirect.


text:
Q: is it possible to expire in 1 min in model of particular data like stored otp in mongodb const mongoose = require("mongoose");
const expirationTime=10
let currentTime = Date.now();

const userSchema = new mongoose.Schema(
  {
    fullName: {
      type: String,
      required: false,
    },
    email: {
      type: String,
      required: false,
    },
    mobile_number: {
      type: String,
      required: false,
    },
    password: {
      type: String,
      required: false,
    },
    otp_instance: [{
            otp_id: {
                type: mongoose.Schema.Types.ObjectId,
                required: false
            },
            otp: {
                type: String,
        // index: {expires:'1m'},
                required: false
            },
      createdAt: {
        type: Date,
        default: Date()
      },
      expiration_time: {
        type: Date,
        default: new Date(currentTime+(expirationTime * 1000))
      },
      // otp: { type: String, index: { expires: 300 }}
        }],
    resetLink: {
      type: String,
      required: false,
    },
    isAccountVerified: {
      type: String,
      required: false,
    },
    token: {
      type: String,
      required: false,
    },
    activeStatus: {
      type: String,
      required: false,
      default: "0",
    },
    deletedStatus: {
      type: String,
      required: false,
      default: "0",
    },
  },
  { timestamps: true }
  );

// userSchema.createIndex( { otp: 1 }, { expireAfterSeconds: 36000 } )
const userModel = mongoose.model("user", userSchema);
module.exports = userModel;

is it possible to expire in 1 min in model of particular data like stored otp in mongodb
is it possible to expire in 1 min in model of particular data like stored otp in mongodb
is it possible to expire in 1 min in model of particular data like stored otp in mongodb> is it possible to expire in 1 min in model of particular data like stored otp in mongodb> is it possible to expire in 1 min in model of particular data like stored otp in mongodb> is it possible to expire in 1 min in model of particular data like stored otp in mongodb> is it possible to expire in 1 min in model of particular data like stored otp in mongodb


text:
Q: How do I log the programs I am running and when (on Ubuntu)? I would like an easy to read log of when a particular application was started. The log needs to include a timestamp and to record the actions I took, for example when I launched a browser or launched a game.

A: Bash records history of all the commands you run, and you can have it record a timestamp as well - see http://larsmichelsen.com/open-source/bash-timestamp-in-bash-history/ for more.
But the bash history doesn't hang around forever, and it still only records things you run from the command line.

A: Your own proposal is not bad at all. Such a script could be something of the form
#!/bin/bash

# Get the program you wish to launch from arguments
PROGNAME="$1"
# Shift script arguments to use the remaining ones later
shift

# Check that a PROGNAME was provided
if [ -z "$PROGNAME" ]; then
   echo "Usage: $0 <program> [program options]"
   exit 1
fi

# Log in your home directory, one directory per program
LOGDIR="$HOME/logs/$PROGNAME"

# Create log directory if it doesn't exist yet
if [ ! -d "$LOGDIR" ]; then
   mkdir -p "$LOGDIR"
fi

# Get the date now
DATE=$(date +'%Y%m%d%H%M%S')

# Start program with it's options and log into the logdir
eval "$PROGNAME" $@ >"${LOGDIR}/${PROGNAME}_${DATE}.log" 2>"${LOGDIR}/${PROGNAME}_${DATE}.err"

Now you could very well edit the entries in your desktop launch menu to use your wrapper everytime you launch a certain program.
Another option would be to use sudo, which logs to auth.log automatically, but use it in such a way that it doesn't launch the programs as root, that is:
sudo -u $USER firefox

which will launch firefox as yourself, using sudo.
For example:
$ sudo -u $USER ksnapshot
# I kill the program
$ tail -1 /var/log/auth.log
   Dec 28 08:20:07 jonah sudo:  raphink : TTY=pts/1 ; PWD=/home/raphink ; USER=raphink ; COMMAND=/usr/bin/ksnapshot

A: One possibility would be to write a small bash script of the form
$ myLogging firefox

that would log the time that, in this example, firefox started and then simply start firefox.
This would require, however, that I do all my actions, such as starting an application, from the command line. Also, what if I wanted to start firefox with some arguments of its own?

A: I don't know whether 'snoopy' is available for Ubuntu, but on Debian it logs every command you've run to /var/log/auth.log .


text:
Q: Chef convergence fails with ERROR: Unable to determine node name: configure node_name or configure the system's hostname and fqdn My server fails to converge with the following messages. I am unable to figure where this error is coming from.
I am copying and pasting the chef stacktrace AFTER the client.log messages below:
Weird thing is that the client.rb file stacktrace is refering to does not even exist on this box.
Any help will be appreciated!
[root@xyz chef]# tail client.log

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

[2016-04-21T11:47:24-06:00] INFO: *** Chef 11.12.8 ***
[2016-04-21T11:47:24-06:00] INFO: Chef-client pid: 7309
[2016-04-21T11:47:24-06:00] FATAL: Stacktrace dumped to /var/chef/cache/chef-stacktrace.out
[2016-04-21T11:47:24-06:00] ERROR: Unable to determine node name: configure node_name or configure the system's hostname and fqdn
[2016-04-21T11:47:24-06:00] ERROR: Chef::Exceptions::ChildConvergeError: Chef run process exited unsuccessfully (exit code 1)
[2016-04-21T11:47:24-06:00] ERROR: Sleeping for 3600 seconds before trying again
[2016-04-21T11:51:10-06:00] INFO: SIGTERM received, exiting gracefully

STACK TRACE:
cat /var/chef/cache/chef-stacktrace.out
Generated at 2016-04-21 11:47:24 -0600
Chef::Exceptions::CannotDetermineNodeName: Unable to determine node name:    configure node_name or configure the system's hostname and fqdn
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-  11.12.8/lib/chef/client.rb:299:in `node_name'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/client.rb:313:in `register'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/client.rb:416:in `do_run'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/client.rb:213:in `block in run'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/client.rb:207:in `fork'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/client.rb:207:in `run'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/application.rb:217:in `run_chef_client'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/application/client.rb:328:in `block in run_application'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/application/client.rb:317:in `loop'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/application/client.rb:317:in `run_application'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/lib/chef/application.rb:67:in `run'
/opt/chef/embedded/lib/ruby/gems/1.9.1/gems/chef-11.12.8/bin/chef-client:26:in `<top (required)>'
/usr/bin/chef-client:23:in `load'
/usr/bin/chef-client:23:in `<main>'[root@xyz chef]#

A: Alternatively to the above, fix your server so that hostname -f shows something.

A: As you noticed, the configuration file does not exist. You have to create it and define the mentioned options. See the documentation for details.

A: You need to configure a node_name in your /etc/chef/client.rb.  Sometimes Ohai can figure this out on its own, but it doesn't seem like it in your case.  check hostname, hostname -f, and the /etc/hostname file to see what your servers are configured for.
I personally always define my node_name in chef, and then use the node name to set the hostname and fqdn... not the other way around as the Chef doc's recommend,  depends on your setup.
For example, my client.rb looks like:
chef_server_url "..."
client_fork true
log_location "/var/log/chef/client.log"
validation_client_name "...-validator"
verify_api_cert true # you might not want this one unless you have a valid cert
node_name "my_node_name" # Add this line
...

From the chef client.rb docs

node_name
  The name of the node. Determines which configuration should be applied and sets the client_name, which is the name used when authenticating to a Chef server. The default value is the FQDN of the chef-client, as detected by Ohai. In general, Chef recommends that you leave this setting blank and let Ohai assign the FQDN of the node as the node_name during each chef-client run.

A: As someone else pointed out 11.12.8 is kind of ancient code at this point.  You do seem to have the patch that was added to add ohai[:machinename] to the detection of the node_name which means that it should fall back to hostname (which should at least be the empty string I would think?  can we set an empty string for the hostname?) which would then avoid the exception.
Maybe your ohai version is also too old to have node[:machinename]?  But the patch to ohai and chef-client went in at basically the same time.
I literally was the last person to touch the node_name detection code and I can't see how you would be hitting that exception...
Best I can suggest is to see if you can replicate it on a more recent version of the omnibus install of chef-client because that "should" never happen.  Probably in order to debug this we need to know what the output of ohai is on your machine (including hostname, machinename, fqdn and domain values in particular).  Also the output of running /bin/hostname and /bin/hostname -f.


text:
Q: Unable to write as root (but can as user) I have an NFS/NIS based file system. NFS and NIS servers are on different physical machines. When we log into our head node home directories are automounted. When logged in as a user I can write changes in my home directory. However, when I su root and try and write to my home directory I get a permission denied error.
Any ideas? Directories are mounted as rw (from the output of mount)
10.1.1.11:/data1/home/alex on /home/alex type nfs (rw,addr=10.1.1.11)

On the NFS server the /etc/exports defines the mounted /home directory (which contains each users home directory) as rw. I have a feeling I remember reading about you can set a flag so mounted NFS directories cannot be written to as a root?

A: This is usually caused by the configuration on the NFS server. NFS servers will often map UID 0 (root) to another user such as "nobody" or "nfsnobody". You need to specify on the NFS server which clients are allowed root access to the mount. On Linux, you usually need to specify no_root_squash in the /etc/exports file where the export is defined.
For example:
/data1/home        <mynfsclient.ip.or.dnsname>(rw,no_root_squash)

or
/data1/home       rw,no_root_squash

After this is set up, unmount and remount the export on the client and you should be able to access it as root.


text:
Q: Why do I get STATUS_WX86_BREAKPOINT instead of EXCEPTION_BREAKPOINT when debugging 32 bit application on 64 machine? I am trying to write a simple debugger on Windows to debug 32-bit applications, my machine is 64-bits. I am using C language.
When I add breakpoint (0xCC) at the specified address, I expect to get EXCEPTION_BREAKPOINT value in debugEvent.u.Exception.ExceptionRecord.ExceptionCode
However I get STATUS_WX86_BREAKPOINT(0x4000001F) instead.
MSDN website define it as "An exception status code that is used by the Win32 x86 emulation subsystem.". Without any further explanation for this behavior.
Can I handle this exception the same way as EXCEPTION_BREAKPOINT? So the code will be as
switch(debugEvent.u.Exception.ExceptionRecord.ExceptionCode)
{
...
   case EXCEPTION_BREAKPOINT:
   case STATUS_WX86_BREAKPOINT:
      HandleBreakPoint();
   break;
...
}

A: When breakpoint (int 3) exception was from code executed in WOW64 mode (32 bit code in 64 bit Windows) 64-bit debugger really got STATUS_WX86_BREAKPOINT. When breakpoint from 64-bit code - STATUS_BREAKPOINT . Also on single step exception 64-bit debugger got STATUS_SINGLE_STEP if this exception from 64-bit code and STATUS_WX86_SINGLE_STEP if exception from WOW64 code.

Can I handle this exception the same way as EXCEPTION_BREAKPOINT ?, so
  the code will be as

Yes, you can. Same is true for STATUS_WX86_SINGLE_STEP - you can handle it in the same way as STATUS_SINGLE_STEP. the WX86_ gives you additional information from which mode (WOW64 or native) was breakpoint. But in both case this is breakpoint exception. And logic how handle it usually common. However this is your choice decide what do and how handle breakpoint, single step or other exception.

Also note that STATUS_WX86_BREAKPOINT and STATUS_WX86_SINGLE_STEP got only 64bit debugger. 32-bit debugger always gets STATUS_BREAKPOINT where 64-bit debugger gets STATUS_WX86_BREAKPOINT and nothing got where x64 debugger got STATUS_BREAKPOINT. The same for single step. For example on WOW64 process startup - 64-bit debugger got 2 breakpoints - first STATUS_BREAKPOINT form 64-bit mode (inside 64-bit ntdll.LdrpDoDebugBreak) and then STATUS_WX86_BREAKPOINT from 32-bit ntdll.LdrpDoDebugBreak. While 32-bit debugger got only second breakpoint (from 32-bit code) with STATUS_BREAKPOINT.


text:
Q: Spark dense_rank window function - without a partitionBy clause I am using Spark 1.6.2, Scala 2.10.5 and Java 1.7.
Our use case necessitates for us to perform dense_rank() on a data set of over 200 million rows without using the partitionBy clause, only the orderBy clause is used. This currently runs in MSSQL and takes about 30 mins to complete.
I have implemented the equivalent logic in Spark as shown below:
val df1 = hqlContext.read.format("jdbc").options(
  Map("url" -> url, "driver" -> driver,
  "dbtable" -> "(select * from OwnershipStandardization_PositionSequence_tbl) as ps")).load()

df1.cache()

val df1_drnk = df1.withColumn("standardizationId",denseRank().over(Window.orderBy("ownerObjectId","securityId","periodId")))

I am submitting the job in Yarn-cluster mode as shown below. I have a 2 node Hadoop 2.6 cluster, each with 4 vCores and 32 GB memory.
spark-submit --class com.spgmi.csd.OshpStdCarryOver --master  yarn --deploy-mode cluster --conf spark.yarn.executor.memoryOverhead=3072 --num-executors 2 --executor-cores 3 --driver-memory 7g --executor-memory 16g --jars $SPARK_HOME/lib/datanucleus-api-jdo-3.2.6.jar,$SPARK_HOME/lib/datanucleus-core-3.2.10.jar,$SPARK_HOME/lib/datanucleus-rdbms-3.2.9.jar,/usr/share/java/sqljdbc_4.1/enu/sqljdbc41.jar --files $SPARK_HOME/conf/hive-site.xml $SPARK_HOME/lib/spark-poc2-14.0.0.jar

In the logs, I can see that the table of about 200 mil rows from MSSQL is getting imported & cached in Spark in 15 mins. I see that about 5 GB of memory is getting used until this stage and about 6.2 GB of memory is still free on one of the executors and 11 GB of memory is free on the other executor.
But, the step at dense_rank() is always failing with "GC Overhead limit exceeded" error after a few mins. I have even set the driver memory as high as 7g as you can notice in the spark-submit command above. But, to no avail!.
Of course, I understand that the lack of partitionBy clause is actually causing trouble in Spark. But, unfortunately, that is the use case we need to deal with.
Can you please shed some more light here ?  Am I missing something ? Is there an alternative to using the dense_rank window function in Spark ? Like, for example using the "zipWithIndex" function suggested by one of the experts elsewhere on this forum ? Will it yield the same results as dense_rank as I understand the "zipWithIndex" method replicates the row_number() function as opposed to dense_rank ?
Any helpful advice is appreciated!
Thanks a lot!

A: There are two different problems here:

*

*You load data over JDBC connection without providing partitioning column or partition predicates. This loads all data using single executor thread.
This problem is  usually pretty easy to solve, either by using one of the existing columns, or by providing artificial key.

*You use window functions without partitionBy. As a result all data is reshuffled to a single partition, sorted locally, and processed using a single thread.
In general there is no universal solution that can address that using only Dataset API but there are some tricks you can use:

*

*Creating artificial partitions reflecting required record ordering. I described this method in my answer to Avoid performance impact of a single partition mode in Spark window functions
A similar method could be used in your case but it would require multi-step process, equivalent to the one described below.

*With associative methods you can use two separate scans over sorted RDD (it should be possible to do similar thing without converting from Dataset as well) and additional action:

*

*Compute partial results for each partition (In your case rank for a given partition).

*Collect required summaries (in your case partition boundaries and accumulated rank value for each partition).

*Perform second scan to correct for partial aggregates from preceding partitions.

One example of this approach, which can be easily adjusted to fit your case, can be found in How to compute cumulative sum using Spark


text:
Q: How to get Table "tr" count on PHP submission For I want output like simliar :
Total Row: 3.
I know to get table tr count using jquery , but i need it from php. please help.

<?php
if(isset($_POST['submit'])){
  $rows = $table->find('#dataTable');
  $count = count($rows);
  echo $count;
}
?>
<form method="post" action="">

    Row 1

    Row 2

    Row 3

<input type="submit" name="submit" value="Get Table Count"/>
</form>

Example i have 3 rwo 2 column table with #dataTable, When i submit using php i want the table

A: You could enter the number of rows in a hidden input before sending the form

A: This will not work because the rows and its elements are not transmitted.
So I added a hidden field every row.
<?php
if(isset($_POST['submit'])){
  $rows = $_POST['hidden'];
  $count = count($rows);
  echo $count;
}
?>
<form method="post" action="">

    Row 1<input type="hidden" name="hidden[]" value="1">

    Row 2<input type="hidden" name="hidden[]" value="2">

    Row 3<input type="hidden" name="hidden[]" value="3">

<input type="submit" name="submit" value="Get Table Count"/>
</form>

btw., in your shown code it looks like you mix jQuery with PHP. Which doesn't work because jQuery is client side and PHP is server side.


text:
Q: How can i change the color of my name? I have been recently searching for a way to change a player's name color in version 1.12 (above the player, in scoreboards and in chat), and I have found many answers on forums offering to use a /nick command, but that is available only when using a mod.
I have heard that this is possible with the /scoreboard command, but I haven't figured out how.
Is there any way to change the color of a player's name in Vanilla Minecraft version 1.12?

A: Not sure if this still works but yes, you're right. Using /scoreboard teams add {{YOUR TEAM NAME}} & then /scoreboard teams option {{YOUR TEAM NAME}} color {{COLOR}} should turn your name to your chosen color.
If you're having trouble finding exact color names, I've grabbed a quick list of them from the minecraft wiki.

Enjoy!
By the way, the only place you would use /nick would be in a server that has the plugin.


text:
Q: Send radio button value to PHP from form Trying to learn how to do an autocomplete. I have the following in my html file (the code pasting function won't work so I have an image:

Between the head tags I have the following function:
function lookup(inputString) {
    if(inputString.length == 0) {
        // Hide the suggestion box.
        $('#suggestions').hide();
    } else {
        $.post("autocomplete_script.php", {queryString: ""+inputString+""}, function(data){
            if(data.length >0) {
                $('#suggestions').show();
                $('#autoSuggestionsList').html(data);
            }
        });
    }
} // lookup

I want to send the value of the checked radio button to autocomplete_script.php so I can do an if else within the php. I can't find any examples that are helping me, I though this would be an easy one. Can anyone help?

A: form.serialize() function gets all the data from the form, then you send it to the autocomplete_script.php, your lookup script looks something like this.
function lookup(inputString) {
    if(inputString.length == 0) {
        // Hide the suggestion box.
        $('#suggestions').hide();
    } else {
        $.ajax({
        url:'autocomplete_script.php',
        type:'POST',
        data:$("form").serialize(),
       success:function(data)
       {
              //SUCCESS do your thing, response as data
           }
    });
    }

} // lookup

Hope It Helps


text:
Q: How to Print the Particular bootstrap Div I would like to print a bootstrap div.
It is properly displayed in web browser but when I click on the print button then at print preview, the elements are floating and are not properly displayed.
what should I do to solve this problem ?
Div which I want to print with following this style

What I get the output at printing time which I dont want see on school name at the top

Button which call the print function:
<button class="btn btn-default" onclick="printDiv('printableArea')"> Print</button>

Print Function:
function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;

     document.body.innerHTML = printContents;

     window.print();

     document.body.innerHTML = originalContents;
}

Div which i Want to print

<?php echo "$school_name";?>

Annual Examination [ 2015-2016 ]

                            Time: 12 AM - 2 PM
                            Date: 30/12/2016

                        100 Marks

A: Check this solution: It is working. The
 is able to display for print.
Place your

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" media='all'
        integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

            this Element will not be printed

                    My custom content which I want to print

Another element

Nothing ... just another element

                <button id="printBtn" class="btn btn-success btn-sm shadow">
                    CLick Me !

                    (Dont worry I will not be printed)
                </button>

A: Call this function: PrintElem('printableArea')
function PrintElem(elem){
        var mywindow = window.open('', 'PRINT', 'height=400,width=600');

        var css = "";
        var myStylesLocation = "${pageContext.request.contextPath}/ui/css/bootstrap.min.css";

        $.ajax({
            url: myStylesLocation,
            type: "POST",
            async: false
        }).done(function(data){
            css += data;
        })

        mywindow.document.write('<title></title>');
        mywindow.document.write('');
      //  mywindow.document.write('<link rel="stylesheet" href="${pageContext.request.contextPath}/ui/css/bootstrap.min.css" type="text/css" media="print"/>');
        mywindow.document.write('');
        mywindow.document.write('
' + document.title  + '
');
        mywindow.document.write(document.getElementById(elem).innerHTML);
        mywindow.document.write('');
        mywindow.document.close(); // necessary for IE >= 10
        mywindow.focus(); // necessary for IE >= 10*/

        mywindow.print();
        mywindow.close();

        return true;
    }

A: You can try   @media print in css.
Like bellow
In css
 @media print
   {
      p.bodyText {font-family:georgia, times, serif;}
      .noprint
      {
        display:none
      }
   }

In Html

I dont want it on print

Prrintable Area

Fiddle

A: I was able to look for the section that was undesirably appearing in the print of the modal, and just hiding it, while using your print function:

  print() {
    let mainLayout = document.querySelector('app-main-layout') as HTMLDivElement;
    mainLayout.style.display = 'none';

    window.print();

    mainLayout.style.display = 'unset';
  }

And, make the buttons of my modal go away, by using this css:
@media print {
  button.close {display:none !important;}
}

A: you just need to link your js script properly

<!DOCTYPE html>

<?php echo "$school_name";?>

Annual Examination [ 2015-2016 ]

                            Time: 12 AM - 2 PM
                            Date: 30/12/2016

                        100 Marks

 asdads

<button class="btn btn-default" onclick="printDiv('printableArea')"> Print</button>


text:
Q: Is there "parallel all of" in Specman? Let's assume I have this unit
unit agent {
    init_all_regs() @clock is {…};
};

I have a list of agents, the number of agents vary. I want to call the method init_all_regs() all of the agents, so that all of them run in parallel.
Is there some combination of "all of" and "for each" syntax?

A: There is no "all of for each" syntax, but there is easy to implement with existing syntax.  For example, you can use objections. Define an objection_kind, and use it to synchronize.
for example:
extend objection_kind :[AGNETS_CHECK_REGS];

unit agent {
    init_all_regs()@clk is {
        raise_objection(AGNETS_CHECK_REGS);
        //...
        drop_objection(AGNETS_CHECK_REGS);
    };
};
extend env {
   my_method() @clock is {
        for each in agents {
        start it.init_all_regs();
        };

        wait cycle;
        while get_objection_total(AGNETS_CHECK_REGS) > 0 {
            wait cycle;
        };
   };
};

A: Another option is to use a counter, implemented with static member. One disadvantage is that it needs more lines.
Something like this -
unit agent {
    static active_counter : int = 0;
    static increase_active_counter() is {
        active_counter += 1;
    };
    ////....
    init_all_regs()@clk is {
        increase_active_counter();
        //....

        decrease_active_counter();
    };
};

extend env {
    scenario() @any is {

        agent::init_active_counter();

        for each in agents {
            start it.init_all_regs();
        };

        wait cycle;
        while agent::get_active_counter() > 0 {
            wait cycle;
        };
    };
  };


text:
Q: docker compose logs follow not running I am using docker compose on mac and since a recent docker update my docker-compose logs -f is displaying logs but not following, once the logs displayed the process is stopped.
I am only using docker compose on local
Docker Compose version v2.0.0-beta.6

Docker version 20.10.7, build f0df350

From time to time when running docker-compose logs I have Error response from daemon: configured logging driver does not support reading I do not know if this is related.


text:
Q: Is there a way to take the weighted average of a list of Decimal numbers using numpy in Python? I am attempting to take the weighted average of a list of Decimal numbers using numpy.average; however, I am receiving a TypeError. For example, consider the following.
>>> from decimal import *
>>> import numpy
>>> s = '1.00000001'
>>> l = []
>>> l.append(Decimal(s))
>>> l.append(Decimal(s))
>>> numpy.average(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/site-packages/numpy/lib/function_base.py", line 612
, in average
    avg = a.mean(axis)
TypeError: unsupported operand type(s) for /: 'Decimal' and 'float'

How do I take the weighted average of a list of Decimal numbers without converting to a float and losing precision of the values using numpy?

A: Err, the classic way...
>>> sum((decimal.Decimal(1), decimal.Decimal(2))) / 2
Decimal('1.5')


text:
Q: Query in QT doesn't get any data This is rows in my table.

With this code, I get "in" in console.
QSqlQuery qry;
qry.prepare("SELECT * FROM user");
qry.exec();
if(qry.size() > 0)
    qInfo() << "in";
else
    qInfo() << "error";

But with this code, I get "error".
QSqlQuery qry;
qry.prepare("SELECT age FROM user");
qry.exec();
if(qry.size() > 0)
    qInfo() << "in";
else
    qInfo() << "error";

A: Try
QSqlQuery qry;
qry.prepare("SELECT age FROM \"user\"");
qry.exec();

The problem is with the table name. Since user is a reserved word, some tools (PgAdmin) automatically add double quotes to the name "user" and you have to use double quotes when applying to the table. Unfortunately user in Postgres is a function (equivalent to current_user) hence the first query returns a row without error.
The best solution is to rename the table and not use reserved words as Postgres identifiers (the name of a table, column, view, function, etc).

A: QSqlQuery qry;
qry.prepare("SELECT age FROM user");
if(qry.exec()) {
    while(qry.next()) {
        qInfo()<<"in";
    }
} else {
    qInfo()<<"error";
}


text:
Q: Error when trying to pass image source from a component to its child component I'm currently creating a small example of React Native. The issue I'm having is that when I tried to pass the image source from my LoginScreen component to ImageHolder component, the Node shows error below:
Loading dependency graph, done.
error: bundling failed: Error: src\ImageHolder.js:Invalid call at line 7: require({
  imageSource: imageSource
})
    at C:\Users\Kuro\vuichoi_ui\node_modules\metro\src\JSTransformer\worker.js:247:19
at Generator.next (<anonymous>)
at step (C:\Users\Kuro\vuichoi_ui\node_modules\metro\src\JSTransformer\worker.js:40:30)
at C:\Users\Kuro\vuichoi_ui\node_modules\metro\src\JSTransformer\worker.js:51:15

Here is my code:
LoginScreen.js render:
render() {
        if (true) {
            return (
                <View>
                    <LoginText
                        imgSource="./img/account.png"
                        secureOption={false}
                        value={this.state.username}
                        placeholder="username"
                        onChangeText={username => this.setState(username)}
                    />
                </View>
            )
        }
    }

LoginText.js:
const LoginText = ({imgSource, secureOption, placeholder, value, onChangeText}) => {

    return (
        <View style={styles.containerStyle}>
            <ImageHolder imageSource={imgSource} />
            <InputField placeholder={placeholder} secureOption={secureOption} value={value} onChangeText={onChangeText}/>
        </View>
    )
}

ImageHolder.js:
const ImageHolder = ({imageSource}) => {
    return (
     <View style={styles.imgContainerStyle}>
            <Image source={require(imageSource)}></Image>
        </View>
    )
}

A: The issue is in the path of Image. If all the component on the same path then you can the same thing.
The solutions is that you need to pass Image from LoginScreen.js
render() {
        if (true) {
            return (
                <View>
                    <LoginText
                        imgSource={require('./img/account.png')}
                        secureOption={false}
                        value={this.state.username}
                        placeholder="username"
                        onChangeText={username => this.setState(username)}
                    />
                </View>
            )
        }
    }

ImageHolder.js
const ImageHolder = ({imageSource}) => {
    return (
     <View style={styles.imgContainerStyle}>
            <Image source={imageSource}></Image>
        </View>
    )
}

Replace the code above tow js and it will work for you.


text:
Q: PhaserJS: Animation objects dropping out and reappearing during animation I have a loop * 20 creating tweens of a set of randomly selected png (they're simple boxes for the moment). After creation, they do a simple X-axis sliding animation.
During the animations, some of the boxes will disappear/pop out. Later on, as the tweens are completing, some will reappear/pop in.
Did I miss something to keep them from popping out? I have onStart/onComplete events and they fire when they're supposed to, so it would seem that whatever pops out isn't completing early, only being removed from display.
(I attempted jsfiddle/codepen, but the script didn't work at all)
Here's the code:
<head>
<script src="phaser.min.js"></script>
<script>
const config = {
    preload: preload,
    create: create,
    update: update
};

const game = new Phaser.Game(1280, 480, Phaser.auto, '', config)

function preload () {
    game.load.image('qtrf', 'img/quarter_0000_quarter-fade.png');
    game.load.image('qtr', 'img/quarter_0003_quarter.png');
    game.load.image('halff', 'img/half_0001_half-fade.png');
    game.load.image('half', 'img/half_0004_half.png');
    game.load.image('fullf', 'img/full-fade.png');
    game.load.image('full', 'img/full.png');

}

function create () {
    game.stage.backgroundColor = "#90cfc7";

    const bars = [
        // field 1 = name of sprite and sprite definition
        // field 2 = drop rate for random picking
        {"qtr": game.add.sprite(-160,0, 'qtr'), "rate": 15 },
        {"qtrf": game.add.sprite(-160,0, 'qtrf'), "rate": 2},
        {"half": game.add.sprite(-320,0, 'half'), "rate": 20},
        {"halff": game.add.sprite(-320,0, 'halff'), "rate": 2},
        {"full": game.add.sprite(-640,0, 'full'), "rate": 5},
        {"fullf": game.add.sprite(-640,0, 'fullf'), "rate": 5}
    ];

    const barrates = [];
    const barsprites = [];
    bars.forEach(element => {
        barrates.push(element.rate);
        Object.entries(element).forEach(objE => {
            if (objE[0] != "rate") {
                barsprites.push(objE[1]);
            }
        });
    });
    let ratesum = barrates.reduce((a,b) => a+b, 0)
            ratetable = barrates.map(e => (Number.parseFloat(e / ratesum).toFixed(2)) * 100);

    for (let i = 0; i < 10; i++) {
        let randbar = game.rnd.between(1, 100);
        let randtime = game.rnd.between(5000, 20000);
        let randdelay = game.rnd.between(2000, 10000);
        let position = 0;
        for (let j = 0; j < ratetable.length; j++) {
            position += ratetable[j]
            if (randbar < position+1) {
                console.log(j, randtime, randdelay);
                game.add.tween(barsprites[j]).to({ x: game.width }, randtime, Phaser.Easing.Linear.None, true, randdelay, -1, true);
                break;
            }
        }
    }
}

function update () {
}

function getbar () {

}

    </script>

</head>


text:
Q: style.display ='inline not working in IE but its working fine FireFox Hi we are have a strange issue.
One of our clients is complaining, that in IE they are unable to see any value , when they select a value from the drop down.
The strange thing is , its working in fire Fox.Also we could not even replicate in IE on our end.
the code that gets executed in java script when a value is selected in a drop down
document.getElementById('GLSpan').innerHTML = pnumArr[0];
document.getElementById('GLCheckbox').style.display ='inline';

GLSpan is a span element
GLCheckbox is a check box element
Any ideas would be appreciated

A: Wow they couldn't be on ie 4 could they? http://msdn.microsoft.com/en-us/library/ms530751(VS.85).aspx
If so you might want to gently suggest they upgrade.

A: Sorry for my english ...
try with "block" or "" value for style.display, I am not sure but I think checkbox doesn't have attribute "inline" for display property for IE


text:
Q: Android SDK Version at compile time There are a variety of variables stored in the android.os.Build class that you can check for the current version of the given Android platform.  Of course, these only work in an emulator or device as the SDK returns null or 0 during compilation
Is there any other variables available within the Android SDK that represents the current SDK version that is available during compilation via the Java API?
FYI, I am trying to implement this feature: https://github.com/johncarl81/transfuse/issues/18
Thanks.

A: If you want to set a minimum SDK level, that can be done in the AndroidManifest.xml file. If you want to support multiple SDK levels, you'll have to do that at runtime since its implied that you won't know if you are running at SDK 8 or SDK 15 until you are actually running your app. If you want to avoid lint warning, I would use @TargetApi(...) that opatut referenced......


text:
Q: $\alpha < \beta$ implies that $\gamma+\alpha<\gamma+\beta$ and $\alpha+\gamma\le\beta+\gamma$ for ordinals This is an exercise from Kunen's book.
Show that $\alpha < \beta$ implies that $\gamma+\alpha<\gamma+\beta$ and $\alpha+\gamma\le\beta+\gamma$.  Given an example to show that the "$\le$" cannot be replaced by "$<$". Also show:
$$\alpha \le \beta \rightarrow \exists!\delta (\alpha+\delta=\beta).$$
What I've tried: I could give an example such that show the "$\le$" cannot be replaced by "$<$": $1+\omega = 2+\omega=\omega$, where $\alpha=1$, $\beta=2$ and $\gamma=\omega$. I could also see these two inequalities is obviously right, but I cannot how to use the set language to show. For the last question, I want let $\delta=\{\gamma:\alpha+\gamma\le\beta\}$ to prove. Am I right?
Could anybody help me? Thanks ahead:)

A:
$\alpha<\beta$ $\Rightarrow$ $\gamma+\alpha<\gamma+\beta$

$\alpha<\beta$ means: if $A$ has ordinal type $\alpha $ and $B$ has ordinal type $\beta$, then $A$ is isomorphic to some initial segment $B_a$ of the set $B$.
Using embedding $f \colon A\to B$ can you obtain similar embedding for the sets of ordinal types $\gamma+\alpha$ and $\gamma+\beta$?
Note: If you work with von Neumann's definition of ordinals, you could use $A=\alpha$, $B=\beta$.
(For this construction, you have $\alpha\le\beta$ $\Leftrightarrow$ $\alpha\subseteq\beta$ and $\alpha<\beta$ $\Leftrightarrow$ $\alpha\subsetneqq\beta$; moreover you know that $\alpha$ is an initial segment of beta.)

A different solution. Suppose we already have shown the second part. Then $\alpha<\beta$ implies that there is $\delta>0$ such that $\beta=\alpha+\delta$. And then $\gamma+\beta=\gamma+\alpha+\delta>\gamma+\alpha$.

Transfinite induction:
Starting point of induction is $\beta=\alpha+1$. (The smallest ordinal greater than $\alpha$.) We have $\gamma+\alpha<\gamma+\alpha+1$.
Inductive step - successor ordinal: We combine $\gamma+\alpha<\gamma+\beta$ and $\gamma+\beta<\gamma+\beta+1$.
Inductive step - limit ordinal: If $\beta=\sup_{i\in I}\beta_i$ and $\gamma+\alpha<\gamma+\beta_i$ for each $i\in I$, then $\gamma+\alpha<\gamma+\beta$.
(This was induction on the well-ordered set $\{\beta\text{ is an ordinal}; \beta>\alpha\}$.)

$\alpha\le\beta$ $\Rightarrow$ $(\exists\delta) \beta=\alpha+\delta$

You know that $\alpha\subseteq\beta$. What about trying ordinal type of the well-ordered subset $\beta\setminus\alpha$ for $\delta$?
(If you work with the naive definition of ordinals and their inequality, you'll have $B\setminus A$ instead; where $A$ and $B$ have ordinal types $\alpha$ and $\beta$, respectively.)

Transfinite induction: Similar as the first part. We will use $\alpha+\sup_{i\in I}\beta_i=\sup_{i\in I}(\alpha+\beta_i)$. (Right-continuity of the addition.)

$\alpha\le\beta$ $\Rightarrow$ $\alpha+\gamma\le\beta+\gamma$

One simple solution seems to be: Fix $\alpha$, $\beta$ and show this by transfinite induction on $\gamma$.
It is clear for $\gamma=0$.
For successor ordinals you need basically to know that $\alpha\le\beta$ $\Rightarrow$ $\alpha+1\le\beta+1$.
The inductive step for limit ordinals requires showing that $\alpha_i\le \beta_i$ $\Rightarrow$ $\sup_{i\in I}\alpha_i \le \sup_{i\in I}\beta_i$.
(Which is easy if you're working with von Neumann's definition - the supremum is just union of ordinals.)

The first two parts seem to be doable by transfinite induction, too (if someone prefers such solution).


text:
Q: how to import correctly the commons.apache.math libraries for my own project I want to use the commons.apache.maths classes for my own project but I don't know how to correctly import them into eclipse. I have visited the download page for the package mentioned above http://commons.apache.org/math/download_math.cgi   but I don't know if the jar file which i want to import is on the binaries zip files or the source zip files. I tried the binaries ones first and when I do the import i just get a list of empty packages. Could somebody who knows how to do a correct import please show me how to do it?
What i am doing at the moment i am downloading the zip file from the link above, extracting it and than right-click my project->properties->Java Build Path->Libraries->Add External Jars. My issue is i don't know which jars to add.
Thanks in advance.
Arlind.

A: You need to import this way.
import org.apache.commons.math

You can add the zip file in your build path or extract the jar files from the zip and add it to the build path. For example to add 2.1 of apache math you need this zip file commons-math-2.1.zip or extract commons-math-2.1.jar from the zip file and add it to your eclipse build path.
Another trick is - if you have the jar files or zip file added in your build path in eclipse then do ctrl+shift+o and eclipse will automatically import the packages for you.

A: There is commons-math-2.1.jar in the zip - add this to your project

A: download the jar file, extract it locally. Open eclipse, project-property-java build path-libraries-add library, where you add the extracted folder there. then you can use the import org.apache.commons.math3.


text:
Q: Elasticsearch - Searching for multiple values in multiple fields
*

*I'm trying to retrieve documents that have any of the values (France) OR (worldwide) OR (world wide) in any shipping_addr* fields but I need each document to be counted once even if there are several matches in document. Am I in right direction?

*In general, what should I read/search for to understand the counting hits logic in case of several matches?
 GET /data/_search
 {
     "query": {
     "bool": {
     "must": [
         {
         "query_string": {
         "default_field": "shipping_addr*",
         "query": "(France) OR (worldwide) OR (world wide)"
         }
         }
     ]
     }
 }
 }

A: You should use the explain API to understand how a particular search query is working and how some documents are matching or not matching.
Regarding your first point, I am not clear what exactly you want to achieve, you should always add some example to make it clear, but you can look at boolean query which is used to solve the issue, and I guess you are looking for should clause which is equivalent to OR.
Instead of query string would suggest you use the boolean query which is less strict in syntax and advised in official docs

If you don't need to support a query syntax, consider using the match
query. If you need the features of a query syntax, use the
simple_query_string query, which is less strict.


text:
Q: How do you ask the user questions in an OS X installer built with pkgbuild/productbuild? I'm building an installer using pkgbuild and productbuild, and I want part of the process to involve asking the user some simple questions. These questions can be answered by either check boxes (yes/no) or a small one-line text input field.
Once those questions are asked, I want to feed them to a postinstall script.
For more context, my product is a set of command-line tools that will live in /usr/local/X, where X is the name of my product. Then, a simple postinstall script is run to set some things up initially. pkgbuild already takes care of this nicely. What I'd really like is for the postinstall script to be provided the answers to my questions, maybe in an environment variable, so it can set things up accordingly.

A: This is impossible to do without writing custom plugins.


text:
Q: How to create a cartogram-heatmap (non-US) I want to create a map like:

edit: this screenshot is from Claus Wilkes book Fundamentals of Data Visualization
But as I'm living in Switzerland, I haven't found a package where I can use this out of the box. Also I haven't found something for Germany or Austria.
Then I discovered the package geofacet, which covers many countries (even smaller ones like CH) and allows to create a grid like:

After some tweeking arround a while, I managed to get to this point:

There are still some details, which I need to fix, but I'm facing two problems, that I don't know how to solve:

*

*How can I plot rounded squares (like in the initial picture)?

*How can I use the state/canton name in the middle of the plot, like a watermark? I my last attempt, I removed the facet label and used an annotation, but couldn't use the state values from the column.

I would appreciate any help. Also if there is anyone out there who has had the same problem in the past and found an easier solution than mine.
MWE
This is the code for the last plot:
library(ggplot2)
library(geofacet)

test = data.frame("state"=c("ZH", "AG", "TI", "BS"), value=c(1,2,3,4))

ggplot(data=test, aes(fill=value)) +
  geom_rect(mapping=aes(xmin=1, xmax=2, ymin=1, ymax=2), color="black", alpha=0.5) +
  annotate("text", x=1.5, y=1.5, label= "state") +
  facet_geo(~state, grid="ch_cantons_grid2") +
  theme_minimal() +
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.y=element_blank(),
        axis.text.y=element_blank(),
        axis.ticks.y=element_blank(),
        strip.placement = "bottom",
        plot.title = element_text(hjust = 5),
        strip.background = element_blank(),
        strip.text.x = element_blank())

A: Maybe something like this:
For rounded square, see hrbrmstr/statebins
library(ggplot2)
library(geofacet)
library(dplyr)
test = data.frame(state=c("ZH", "AG", "TI", "BS"), value=c(1,2,3,4))

# devtools::install_github("hrbrmstr/statebins")

grid_geo <- geofacet::ch_cantons_grid2$code

test$state <- factor(test$state, levels = grid_geo)

test <- dplyr::right_join(test, dplyr::tibble(grid_geo), by = c('state' = 'grid_geo'))

ggplot(data=test ) +
    statebins:::geom_rrect(data=test, mapping=aes(xmin=1, xmax=2, ymin=1, ymax=2),
                           fill = 'white',
                           color="black", alpha=0.5) +
    statebins:::geom_rrect(data=test %>%
                               dplyr::filter(!is.na(value)),
                                             mapping=aes(xmin=1, xmax=2, ymin=1, ymax=2, fill =  value),
              color="black", alpha=0.5) +
    geom_text(data=test, aes(x = 1.5, y = 1.5, label = state)) +
    # annotate("text", x=1.5, y=1.5, label= state) +
    facet_geo(~state, grid="ch_cantons_grid2") +
    theme_minimal() +
    theme(axis.title.x=element_blank(),
          axis.text.x=element_blank(),
          axis.ticks.x=element_blank(),
          axis.title.y=element_blank(),
          axis.text.y=element_blank(),
          axis.ticks.y=element_blank(),
          strip.placement = "bottom",
          plot.title = element_text(hjust = 5),
          strip.background = element_blank(),
          strip.text.x = element_blank(),
          line = element_blank())

Here is another code to mimick the visual that you show.
ggplot(data=test) +
    statebins:::geom_rrect(data=test, mapping=aes(xmin=1, xmax=2, ymin=1, ymax=2),
                           fill = '#d0e1e1',
                           color=NA, alpha=0.7) +
    statebins:::geom_rrect(data=test %>%
                               dplyr::filter(!is.na(value)),
                                             mapping=aes(xmin=1, xmax=2, ymin=1, ymax=2, fill =  value),
              color=NA, alpha=1) +
    geom_text(data=test, aes(x = 1.5, y = 1.5, label = state)) +
    # annotate("text", x=1.5, y=1.5, label= state) +
    facet_geo(~state, grid="ch_cantons_grid2") +
    scale_fill_gradient(low = "#dccbd7", high = '#564364', name = "Label value") +
    theme_minimal() +
    guides(fill = guide_legend(title.position = "top")) +
    theme(legend.position = c(0.2, 0.95),
          legend.direction="horizontal") +
    theme(axis.title.x=element_blank(),
          axis.text.x=element_blank(),
          axis.ticks.x=element_blank(),
          axis.title.y=element_blank(),
          axis.text.y=element_blank(),
          axis.ticks.y=element_blank(),
          strip.placement = "bottom",
          plot.title = element_text(hjust = 5),
          strip.background = element_blank(),
          strip.text.x = element_blank(),
          line = element_blank())

You can change guides(fill = guide_legend(title.position = "top")) by guides(fill = guide_colorbar(title.position = "top")) to have continuous color scale.


text:
Q: Showing that $-1\not\equiv x^2\mod 4$
Show that $-1\not\equiv x^2\mod 4$, i.e. $-1$ is a quadratic nonresidue.

If I consider first $x$, s.t. $1\equiv x^2\mod 4$ then this is fulfilled, if I take any odd number since then;
$1\equiv x^2\mod 4\iff x^2-1\equiv0\mod 4\iff (x+1)(x-1)\equiv0\mod 4$
because if $x$ is odd, then $x\pm1$ are even, and one of them has to be divisible by $4$
Now consider $-1\equiv x^2\mod 4$, then $x$ should be again odd, but any odd number squared is $1\mod 4$ by the first case.
Is this OK ?

A: Your proof is correct but is a little bit long. Since $4$ is not too big, you can list the squares mod $4$ :
$$0^2=0,\;    1^2=1,\;    2^2 \equiv 0,\;    3^2 \equiv 1,\; \dots$$
You immediately see that only $0$ and $1$ are quadratic residues mod $4$, but $-1 \equiv 3$ is not.


text:
Q: Is this harmonic number in lowest terms? Take the harmonic number
$$\sum_{n=1}^m \frac{1}{n}=\frac{a}{b}$$
Define $a$ and $b$ as the actual integers produced by the summation - i.e., treat the numerator and denominator separately and do no clear like terms. Are $a$ and $b$ coprime?
It is clear that $b=m!$. But is $\frac{a}{m!}$ automatically in lowest terms 'straight out of the box'?
Instinct says yes, because there will always be a term in the numerator's sum that has a factor that is not shared with the other terms. But instinct is fallible. I've tried to read around, but I'm still not 100% clear; the assumption always seems to be that the fraction is in lowest terms.
Is my instinct correct? How would one prove it?


text:
Q: Extremely confused how to install Babel ES6 I know this might be the wrong place to ask this question but ive been trying so hard to install babel. I just dont understand how this works.
I tried running this: npm install --save-dev babel-cli but it doesnt understand that command. I dont even have an installer or anything. I thought maybe there is an exe or something but I was wrong. I went to the plugins page and the same thing.
Can someone please tell me how the installation works? ...that is in baby steps.

A: You need to install npm first, but you probably want to install Node.js instead, as npm comes with Node.js. Once you have Node.js installed, you can use npm from the command line, which is Terminal (Mac/Linux) or Command Prompt (Windows).
Once you've done that, using the command line go to the folder/directory you want to use Babel in. (I'm assuming you know how to use the command line. If not, you need to learn that first.) Then, run npm init and fill in the fields with sensible info (or leave them blank).
Then, a sample installation of babel would be npm install --save-dev babel-cli babel-preset-es2015. This installs Babel and the stuff necessary to transform ES6 code. You can then use Babel by running babel foo.js --out-file bar.js --presets es2015. This will compile ES6 code in the file foo.js into ES5 code in bar.js. (ES2015 is another name for ES6). More information about using the Babel CLI (command line interface) is available in the docs.


text:
Q: C++ headers compilation error How can I run a C++ program containing header and namespaces(including filename.h) in one folder and the included header and namespaces in other folders?
The errors : "undefined reference to" and "no such directory".

A: If you mean including files from different folders, you have to add each of folders containing files to your include directories. And this differs, depending on your environment. E.g. in Visual Studio 2013 you would go:
Project->Properties->Configuration Properties->C/C++->General->Additional Include Directories

Then you can open dialog box and add as many directories, as you need. This will add all files to your possible include files and you don't have to specify which folder specified in ,,Additional Include Directories" you're going to use.

A: For linux you can use
g++ -I/direct/path/to/the/file/containing/files <file>.cpp


text:
Q: cannot dropping null values using pandas I am using the dataframe dropna function to drop all the null values but it is not working
df.dropna(how = 'all', inplace = True)
df1 = df.copy()
print(df1.isnull().sum())

OUTPUT:
Ind_ID                      0
Test_date                   0
Cough_symptoms            252
Fever                     252
Sore_throat                 1
Shortness_of_breath         1
Headache                    1
Corona                   3892
Age_60_above           127320
Sex                     19563
Known_contact          242741
dtype: int64

A: You are removing rows which contains only NaN. If you want to remove rows containing at least one NaN you need:
df.dropna(how = 'any', inplace = True) #lol


text:
Q: Accessing the nested Arrays using ng-repeat in angularjs JSFiddle
I'm not able to access the array images in the nested collection. Why am I not able to see any output?
The model:
var obj = [{
    "id": "7",
    "date": "1 Jan",
    "images": ["507f42c682882", "507e24b47ffdb", "507e2aeca02d5", "507e2b19663a9"]
}, {
    "id": "7",
    "date": "1 Jan",
    "images": ["507f42c682882", "507e24b47ffdb", "507e2aeca02d5", "507e2b19663a9"]
}];

This is the HTMl with ng-repeat:

{{img1}}

Can anyone point me to what I'm missing?

A: The problem is you are trying to repeat a list of li elements inside of a li element, which is invalid HTML. As such, angular will not render this.
Update your HTML to:

{{img1}}


text:
Q: Python 3.5: Assign variable value with changing variable name through looping I am trying to loop similar variable names with different values but found unable to do so. I attached the code below. Could you advise me as to what to do by looping in order to get the effect of version 1 code? Many thanks.
#Version 1: The intended effect
def test():

    global v1, v2, v3

    v1 = 1
    v2 = 2
    v3 = 3

    print (v1)
    print (v2)
    print (v3)

if __name__ == "__main__":
    test()

And:
#Version 2: The loop I tried but failed
def test():

    global v1, v2, v3

    for i in range (1,3):
        "v" + str(i) = i
        print ("v" + str(i))

if __name__ == "__main__":
    test()

A: # Version 3: What you should be doing

def test():
    v = []
    for i in range(1, 3):
        v.append(i)
        print(v[i-1])

if __name__ == '__main__':
    test()

Global scope, "variable variables", and all sorts of other solutions are superfluous and generally ugly (because they will eventually cause hard-to-debug breakage in larger apps) for this. Just use a list for this type of thing.
# Version 4: Bonus list comprehension version

def test():
    return [i for i in range(1, 3)]   # or list(range(1, 3))


text:
Q: Visualforce Editable Related List Save Error I am currently working on a Visualforce related list of ProjectTasks__c to put on the page layout of the related object Milestone__c, with an editable column for the status field, allowing users to change the status of the related ProjectTask__c record without having to go to the record itself to change the status.
I have tried tackling this a couple of different ways, and have gotten to a point where it is saving the page and the extension but it is not actually working on the page, on the page it appears that it will work, but when the Save button is clicked it brings to a message that says "Formula Expression is required on the action attributes."
Any help that could be given would be more than appreciated!
The vf page code that I have is as follows:
    <apex:page standardController="Milestone__c" extensions="TaskRelatedList">
<style>
.fewerMore { display:none;}
</style>
<apex:form >
    <apex:pageBlock id="PTs" title="Tasks To Be Completed">
        <apex:pageBlockButtons >
            <apex:commandButton action="{Save}" value="Save"/>
        </apex:pageBlockButtons>
        <apex:pageBlockTable value="{!PTs}" var="p" rendered="{!NOT(ISNULL(PTs))}">
            <apex:column value="{!p.TaskName__c}"/>
            <apex:column value="{!p.Active__c}"/>
            <apex:column value="{!p.TaskTeam__c}"/>
            <apex:column headerValue="Status"><apex:inputField value="{!p.Status__c}"/></apex:column>
            <apex:column value="{!p.TaskNumber__c}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:form>
</apex:page>

And the Extension Class I have is:
public class TaskRelatedList {

    private List<ProgramTask__c> PTs;
    private Milestone__c MI;
    public TaskRelatedList(ApexPages.standardController controller) {
        this.MI= (Milestone__c)controller.getRecord();
    }
    public List<ProgramTask__c> getPTs()
        {
            PTs = [Select Id, Name, TaskName__c, Active__c, TaskTeam__c, Status__c, TaskNumber__c from ProgramTask__c where CurrentUserTask__c = TRUE AND Story__r.Id = :MI.Id ORDER BY TaskNumber__c ASC];
            return PTs;
        }
    public pageReference saveStatusChange(){
    update this.PTs;
    return null;
    }
}

Thank you so much for your help in advance!

A: The immediate error is that instead of:
<apex:commandButton action="{Save}" value="Save"/>

you need to use:
<apex:commandButton action="{!saveStatusChange}" value="Save"/>

where as any controller reference - property or method - needs to be referenced via "{! }" and the method must exist in the controller. (And be the method you want to invoke; a save method is automatically provided but that would only save the single Milestone__c record not the list of ProgramTask__c).


text:
Q: Function not returning properly when set to a variable but is when console.logged The problem is in this function:
  function minimax(newBoard,player, depth = 0) {
    const availableSpots = emptySquares();
    // console.log(availableSpots)
    // console.log((checkGameStatus(newBoard,player) ? 'true' : 'false'))
    let score = {};

    if (checkGameStatus(newBoard, computerSymbol)) {
        console.log("Are we hitting here? 1")
        // console.log((onCheckWin(newBoard) === false))
        // console.log(newBoard,"o")
         score = { "score": (-100 + depth)}
         return score
    } else if (checkGameStatus(newBoard, playerSymbol)) {
        console.log("Are we hitting here? 2")
        // console.log(checkGameStatus(newBoard))
        // console.log(newBoard,"o")
        score =  { "score": (100 - depth)}
        return score
    } else if (availableSpots.length === 0) {
        console.log("Are we hitting here? 3")
        score = { "score": 0 }
        return score
    }
    let moves = [];

    for (let i=0; i<availableSpots.length; i++) {
        let move = {};
      move.index = newBoard[availableSpots[i]];
      newBoard[availableSpots[i]] = player;
      console.table(newBoard)
    if (player === computerSymbol) {
        let result = minimax(newBoard, playerSymbol , depth++);
        console.log(newBoard,"first");
        console.log(result)
        move.score = result["score"];
    } else {
        let result = minimax(newBoard, computerSymbol, (depth + 1));
        console.log(newBoard,"first");
        move.score = result.score;

    }
      console.log(moves,move)
      newBoard[availableSpots[i]] = move.index;
      moves.push(move);
      console.log(moves,move)
    } // end of for look

    let bestMove;

        if (player === computerSymbol) {
            let bestScore = -10000;
            for (let i=0; i<moves.length; i++) {
                if (moves[i].score > bestScore) {
                    bestScore = moves[i].score;
                    bestMove = i;
                    // console.log(bestMove)
                }
                // end of for loop
            }
            if (player === playerSymbol) {
                let bestScore = 10000;
                for (let i=0; i<moves.length; i++) {
                    if (moves[i].score < bestScore) {
                        bestScore = moves[i].score;
                        bestMove = i;
                        // console.log(bestMove)
                    }

                }
            }
        }

        return moves[bestMove];
    }

When I console.log the function inside of it, it returns an object, but when I set that function call to "result" like here:
 if (player === computerSymbol) {
        let result = minimax(newBoard, playerSymbol , depth++);
        console.log(newBoard,"first");
        console.log(result)
        move.score = result["score"];

I get undefined as the result and that I can't access property of undefined. Also, I seem to have a problem with my minimax algorithm where it's just constantly choosing the next open square. This might be because I am only using an empty board at the moment. I can add more code if need be, but it seems to me that the problem exists inside the function and not from one of my external or helper functions


text:
Q: How to run three VM at the same time in virtual-box? I am working on Seed Labs. I am using VirtualBox running Ubuntu 16.04.
I have created the VMs and now I need to run them at the same time, switching back and forth between them simultaneously in order to enter commands into the Ubuntu terminal. When I try to run them at the same time, I keep getting the following message:
Locking of attached media failed. A possible reason is that one of the media is attached to a running VM.

Result Code:
VBOX_E_INVALID_OBJECT_STATE (0x80BB0007)
Component:
SessionMachine
Interface:
IMachine {5047460a-265d-4538-b23e-ddba5fb84976}

I am just trying to get the virtual machines up and running and would be satisfied if I could just get that working at this point. Many thanks.
Other information: I am using MacBook Air


text:
Q: What is the purpose of this array after the returned object? Can someone describe the purpose of [this.props.currency] placed after the return object or a place I can read about this pattern, as I haven't seen it before.
I am not asking what this.props.currency is but rather it's purpose after the returned object.
Seen on this blog post:
https://javascriptplayground.com/react-extracting-logic/
export const getCurrencyData = currency => {
    return {
        GBP: { base: 100, symbol: '£' },
        USD: { base: 100, symbol: '$' },
      }[this.props.currency];
    };

A: All it does is it gets the value of the property with the key of this.props.currency - so if currency is "GBP", the value returned is { base: 100, symbol: "£" }. You can write it like this to make it clearer:
export const getCurrencyData = currency => {
    const obj = {
        GBP: { base: 100, symbol: '£' },
        USD: { base: 100, symbol: '$' }
      };
      return obj[this.props.currency];
};

You could also take advantage of the explicit return feature with arrow functions to remove the return keyword:
export const getCurrencyData = currency => ({
    GBP: { base: 100, symbol: '£' },
    USD: { base: 100, symbol: '$' },
}[this.props.currency]);

A: Currency is key of the part of the object you are looking for.
You could rewrite that as:
function getCurrencyData(currency) {
  const allAvailableData = {
    GBP: { base: 100, symbol: '£' },
    USD: { base: 100, symbol: '$' },
  }

  return allAvailableData[currency]
}

console.log(getCurrencyData('GBP'))
// { base: 100, symbol: '£' }
console.log(getCurrencyData('USD'))
// { base: 100, symbol: '$' }


text:
Q: How to append textfield with "0," if is empty and user clicked on comma/dot separator on a decimal numpad How could I detect if user clicked on comma or decimal numpad, so if a textfield is empty and the user clicked on comma or dot decimal separator on a decimal numpad I would like to append textfield text with "0,"? I know that I could use uitapgesture on the whole textfield, but that's not what I need.

A: override func viewDidLoad() {

        super.viewDidLoad()
        yourTextFiled.delegate = self

}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        if (string == "." || string == ",") && textField.text?.count == 0{

                textField.text = "0"
        }

        return true
 }

A: you can try Like Below Also
override func viewDidLoad() {
    super.viewDidLoad()
    yourTextField.addTarget(self, action: #selector(functionName), for: .editingChanged)
}

@objc func functionName(){
    guard let textFieldValue = yourTextField.text else {return}
    if yourTextField.count != 0 && (yourTextField == "," || yourTextField == "."){
        yourTextField.text = "0"
    }
}


text:
Q: Executing MySQL command via Shell script for auth socket plugin I'm trying to create a shell script to automate the process of installing PHP, MySQL and Nginx.
So far everything is working fine. However, I cannot switch its authentication method from auth_socket to mysql_native_password.
MYSQLPASS=$(openssl rand -base64 32)

sudo apt-get install -y expect

sudo apt-get install -y mysql-server

SECURE_MYSQL=$(expect -c "
set timeout 10
spawn mysql_secure_installation

expect \"Press y|Y for Yes, any other key for No: \"
send \"n\r\"

expect \"New password: \"
send \"$MYSQLPASS\r\"

expect \"Re-enter new password: \"
send \"$MYSQLPASS\r\"

expect \"Remove anonymous users? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect \"Disallow root login remotely? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect \"Remove test database and access to it? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect \"Reload privilege tables now? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect eof
")

I have to manually do it on the terminal.
sudo mysql
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '<password>';
FLUSH PRIVILEGES;
exit

A: Can you try this?
MYSQLPASS=$(openssl rand -base64 32)

sudo apt-get install -y expect

sudo apt-get install -y mysql-server

SECURE_MYSQL=$(expect -c "
set timeout 10
spawn mysql_secure_installation

expect \"Press y|Y for Yes, any other key for No: \"
send \"n\r\"

expect \"Enter current password for root (enter for none):\"
send \"$MYSQLPASS\r\"
expect \"Change the root password?\"
send \"n\r\"

expect \"Remove anonymous users? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect \"Disallow root login remotely? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect \"Remove test database and access to it? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect \"Reload privilege tables now? (Press y|Y for Yes, any other key for No) : \"
send \"y\r\"

expect eof
")

echo "$SECURE_MYSQL"

Change this part accordingly
For MariaDb/MySQL 5.5:
expect "Enter current password for root (enter for none):"
  send -- "\r"
  expect "Set root password?"
  send -- "y\r"
  expect "New password:"
  send -- "${$MYSQLPASS}\r"
  expect "Re-enter new password:"
  send -- "${$MYSQLPASS}\r"

For Mysql 8
    expect "Enter password for user root:"
    send "$MYSQLPASS\r"

    expect "Change the password for root ? ((Press y|Y for Yes, any other key for No) :"
    send "y\r"

    expect "New password:"
    send "$MYSQLPASS\r"

    expect "Re-enter new password:"
    send "$MYSQLPASS\r"
    expect "Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) :"
send "y\r"

As for MariaDB 10.x
       expect \"Enter current password for root (enter for none): \"
send \"n\r\"
expect \"Switch to unix_socket authentication \[Y/n\] \"
send \"n\r\"
expect \"Change the root password? \[Y/n\] \"
send \"y\r\"
expect \"New password: \"
send \"$MYSQLPASS\r\"
expect \"Re-enter new password: \"
send \"$MYSQLPASS\r\"


text:
Q: Using $E$ for "identity matix" I've noticed that a lot of users (especially those asking questions) tend to use $E$ instead of $I$ for the identity matrix.  Is this a common convention in certain languages?
I tried looking through the wiki pages for the identity matrix in different languages, but they all seem to use $I$ rather than $E$.  I'd imagine that in German, one might use $E$ for Einheitsmatrix rather than $I$ for Identitätsmatrix, but that's just a guess.

A: In Russian, Identity Matrix is translated as "Edinichnaya Matritsa". "Edinichnaya" from the word "Edinitsa" what weans $1$ (one), maybe thats why in Russian it is $E$


text:
Q: Gwt get Components I have a Vertiacal panel object and This object contains many radiobuttons
So can i get those radioButton objects through  Vertiacal panel object.
Maybe via iteration or ?
private void initCourse() {
    coursePopupPanel.clear();
    VerticalPanel verticalPanel = new VerticalPanel();
    coursePopupPanel.setWidget(verticalPanel);
    JsArray<JCourse> jCourseArray = JCourse.getList(stringMainData);
    for (int i = 0; i < jCourseArray.length(); i++) {
        final RadioButton courseRadioButton = new RadioButton("course");
        courseRadioButton.setText(jCourseArray.get(i).getName());
        courseRadioButton.getElement().setId(jCourseArray.get(i).getView());
        verticalPanel.add(courseRadioButton);

        //handler of course radio buttons
        courseRadioButton.addClickHandler(new ClickHandler() {
            public void onClick(ClickEvent event) {
            }
        });
    }
}

I have a reference to coursePopupPanel. but i have not reference to vertical panel, so can i get elements of vertical panel sonce holding reference to coursePopupPanel.

A: A GWT VerticalPanel is a subclass of ComplexPanel, an abstract class for Panels that contain more than one child widget.  In ComplexPanel (and so inherited by VerticalPanel) are methods for getting the number of child widgets, getting references to them by index, and so on.  You could build an iterator something like this:
Iterator<Widget> vPanelWidgets = myVerticalPanel.iterator();
while (vPanelWidgets.hasNext()){
  Widget childWidget = vPanelWidgets.next();
  if (childWidget instanceof RadioButton) {
    ...do stuff
  }
}

I tend not to query a widget for its members.  That ties me to the decisions I made about how to display the RadioButtons, following your example.  What if you decide later to display your radio buttons in the cells of a FlexTable in order to control vertical and horizontal arrangement?  To make that change means your widget iterator won't work.  FlexTable is a Panel but not a ComplexPanel.  The code I wrote above won't work if you decide to replace the VerticalPanel with a FlexTable.
If was to take something like this approach, I would keep my lists of related widgets (like a group of RadioButtons) in some sort of Java Collection.  I pass that Collection to my presentation class, and inside there I write the code to do the layout.  Usually that's a UiBinder class, with "@UiField(provided = true)" for these RadioButtons.  The code in the presenter then associates the RadioButton elements of the Collection I passed in to the UiField placeholders for the RadioButtons in the UiBinder layout.  So all my layout decisions are actually in the UiBinder xml file.  If I decide to rip out my Vertical Panel and replace it with a FlexTable, I might not have to touch a single line of Java code, assuming I separated things out correctly.
[Actually, I would probably keep my decision to use RadioButtons inside the presentation layer, and inside the XML file in particular.  That presentation class would fire a message on the EventBus to indicate the user had made a selection via a RadioButton ValueChangeHandler, and I wouldn't care if I used RadioButtons in a VerticalPanel or ToggleButtons in a FlexTable.]

A: You're not being to specific, add more details and maybe a code example.
I'm gonan try to guesstimate what you're trying to say here: You have a verticalPanel object. To it you add several radioButton objects. Later you want to retrive those radioButton objects (to maybe check if they're selected or not), right? There's several ways to do this. At any rate, why don't you check the code examples at the Gwt Showcase site here:
http://gwt.google.com/samples/Showcase/Showcase.html?locale=en_UM#!CwRadioButton
it has tons of visual examples, each with the attached code and css.

A: Since PopupPanel implements HasOneWidget interface you can coursePopupPanel.getWidget() to get a reference to your verticalPanel. And iterate widgets in it simply using
for (Widget w : verticalPanel){
    //Do Stuff
}


text:
Q: OCR using Tensor flow,Python I'm new to Python and ML.I'm trying to get a simple code for character recognition  using tensor flow. A simple python code which searches whether the entered text is present in the uploaded file or not and prints the same.
Could someone help me on this.
Thank You.

A: Sorry if you already have found answers by now.
I doubt anyone would like to give solutions straight away when there are no research details included. However, I could point you to some links which may be useful.
Deep Learning OCR using TensorFlow and Python
Github Implementation: https://github.com/argman/EAST
However, if you are new to ML I would suggest you take it slow and start off with a learning path. I am no expert myself and learning using various sources online.