text:
Q: Universal non-bash `time` benchmark alternative? For comparing run times of scripts between different shells, some SE answers suggest using bash's built-in time command, like so:
time bash -c 'foo.sh'
time dash -c 'foo.sh'

...etc, for every shell to test.  Such benchmarks fail to eliminate the time taken for each shell to load and initialize itself.  For example, suppose both of the above commands were stored on a slow device with the read speed of an early floppy disk, (124KB/s), dash (a ~150K executable) would load about 7x faster than bash (~1M), the shell loading time would skew the time numbers -- the pre-loading times of those shells being irrelevant to measuring the run times of foo.sh under each shell after the shells were loaded.
What's the best portable and general util to run for script timing that can be run from within each shell?  So the above code would look something like:
bash -c 'general_timer_util foo.sh'
dash -c 'general_timer_util foo.sh'

NB: no shell built-in time commands, since none are portable or general.

Better yet if the util is also able to benchmark the time taken by a shell's internal commands and pipelines, without the user having to first wrap them in a script.  Artificial syntax like this would help:
general_timer_util "while read x ; do echo x ; done < foo"

Some shells' time can manage this.  For example bash -c "time while false ; do : ; done" works.  To see what works, (and doesn't), on your system try:
tail +2 /etc/shells |
while read s ; do
    echo $s ; $s -c "time while false ; do : ; done" ; echo ----
done

A: I use the GNU date command, which supports a high resolution timer:
START=$(date +%s.%N)
# do something #######################

"$@" &> /dev/null

#######################################
END=$(date +%s.%N)
DIFF=$( echo "scale=3; (${END} - ${START})*1000/1" | bc )
echo "${DIFF}"

And then I call the script like this:
/usr/local/bin/timing dig +short unix.stackexchange.com
141.835

The output unit is in milliseconds.

A: The time utility is usually built into the shell, as you have noticed, which makes it useless as a "neutral" timer.
However, the utility is usually also available as an external utility, /usr/bin/time, that may well be used to perform the timing experiments that you propose.
$ bash -c '/usr/bin/time foo.sh'

A: Here is a solution that:

*

*
eliminate[s] the time taken for each shell to load and initialize itself

*
can be run from within each shell

*Uses

no shell built-in time commands, since none are portable or general

*Works in all POSIX-compatible shells.

*Works on all POSIX-compatible and XSI-conforming systems with a C compiler, or where you can compile a C executable in advance.

*Uses the same timing implementation on all shells.

There are two parts: a short C program that wraps up gettimeofday, which is deprecated but still more portable than clock_gettime, and a short shell script that uses that program to get a microsecond-precision clock reading both sides of sourcing a script. The C program is the only portable and minimal-overhead way to get a sub-second precision on a timestamp.
Here is the C program epoch.c:
#include <sys/time.h>
#include <stdio.h>
int main(int argc, char **argv) {
    struct timeval time;
    gettimeofday(&time, NULL);
    printf("%li.%06i", time.tv_sec, time.tv_usec);
}

And the shell script timer:
#!/bin/echo Run this in the shell you want to test

START=$(./epoch)
. "$1"
END=$(./epoch)
echo "$END - $START" | bc

This is standard shell command language and bc and should work as a script under any POSIX-compatible shell.
You can use this as:
$ bash timer ./test.sh
.002052
$ dash timer ./test.sh
.000895
$ zsh timer ./test.sh
.000662

It doesn't measure system or user time, only non-monotonic wall-clock elapsed time. If the system clock changes during the execution of the script, this will give incorrect results. If the system is under load, the result will be unreliable. I don't think anything better can be portable between shells.
A modified timer script could use eval instead to run commands outside of a script.

A: Multiple times revised solution using /proc/uptime and dc/bc/awk in large parts thanks to the input by agc:
#!/bin/sh

read -r before _ < /proc/uptime

sleep 2s # do something...

read -r after _ < /proc/uptime

duration=$(dc -e "${after} ${before} - n")
# Alternative using bc:
#   duration=$(echo "${after} - ${before}" | bc)
# Alternative using awk:
#   duration=$(echo "${after} ${before}" | awk '{print $1 - $2}')

echo "It took $duration seconds."

Assumes obviously that /proc/uptime exists and has a certain form.

A: You should note that time is specified by POSIX, and AFAICT the only option that POSIX mentions (-p) is supported correctly by various shells:
$ bash -c 'time -p echo'

real 0.00
user 0.00
sys 0.00
$ dash -c 'time -p echo'

real 0.01
user 0.00
sys 0.00
$ busybox sh -c 'time -p echo'

real 0.00
user 0.00
sys 0.00
$ ksh -c 'time -p echo'

real 0.00
user 0.00
sys 0.00


text:
Q: Read an input number and redirect it to a column in a file I have a file with a table like this:

I have done that my program returns me the values (max, min and mean) from the line of the gene that I'm looking for. Now my goal is the same, but instead of words, the user will print the number of the column. Ego to obtain these values but only from one column.
Here there is my code:
#!/bin/bash

FICHERO="affy.txt"

function OPTIONS
{
   echo "_____________OPTIONS_____________"
   echo ""
   echo "   1. Select one gene and its test results"
   echo "  2. Select one column and its test results"
   echo "               3. Exit"
}

function gene
{
   if [ -e "affy.txt" ]; then  # Si el fichero existe...
      echo "Print the name of the gene you are looking for: "
      read -p "Name:" NAME
      OLDIFS=$IFS
      IFS=",";
      # Calcular max, min y mean.
      min=` grep -m1 "$NAME" affy.txt |tr -s ',' '.' | tr -s ' ' '\n' | cut -d' ' -f3- |  sort -n | head -1`
      max=` grep -m1 "$NAME" affy.txt  | tr -s '  ' ' ' |tr -s ',' '.' | cut -d ' ' -f3- | tr -s ' ' '\n' | sort -n | tail -1`
      mean=` grep -m1 "$NAME" affy.txt | tr -s '  ' ' ' |tr -s ',' '.' | cut -d ' ' -f3- | tr -s ' ' '\n' | awk '{sum+=$1} END {print sum/NR}'`

      echo "Min value: "$min
      echo "Max value: "$max
      echo "Mean value: "$mean

   else
      echo "Invalid gene name!"
   fi

   echo
}

function column
{
   if [ -e $FICHERO ]; then
      echo "Print the column number you are looking for: "
      read -p "Name: " NAME

   else
      echo "El fichero no existe o no contiene entradas en la agenda"
   fi
}

opc=0
exit=5

while [ $opc -ne $exit ];
do
   clear
   OPTIONS  # Dibujamos el menu en pantalla
   read -p "Opcion:..." opc  # Escogemos la opcion deseada

   if [ $opc -ge 1 ] && [ $opc -le 5 ]; then
      clear
      case $opc in   # Acciones para las diferentes opciones del menu

         1)gene
            ;;

         2)column
            ;;
      esac
  else
  echo "Insert a correct option!!"

  fi
  echo "Press any key..."
  read
  done

OPTION NUMBER 1 IS WORKING.
I tried something like this in the function named column, but it doesn't works...:
    function column
{
   if [ -s $FICHERO ]; then
      echo "Print the column number you are looking for: "
      read -p "column: " column
      for i in "$column"
      do
         col+="${i#-}"","
         echo "You are working with column number:" $col
      done

   else
      echo "El fichero no existe o no contiene entradas en la agenda"
   fi

   if [ "$col" = "" ]; then
          echo "Insert Columns please!"
   else
      for i in $col;
      do
      echo
      echo minim columna= `tr -s ',' '.' affy.txt | tr -s ' ' '\n' | cut -d' ' -f"$col" |  sort -n | head -1`
      echo maxim columna "$i"= `grep "$col" affy.txt | tr -s '  ' ' ' |tr -s ',' '.' | cut -d ' ' -f"$i" | sort -n | tail -1`
      echo average columna "$i"= `grep "$col" affy.txt | tr -s '  ' ' ' |tr -s ',' '.' | cut -d ' ' -f"$i" | awk '{sum+=$0} END {print sum/NR}'`

      shift
      done
   fi

A: Awk is a good tool for such column manipulation exercises; the following block shows how to get all the information on the column COL using awk:
  awk 'BEGIN{min=999;sum=0} # Set initial values
  { if(NR <= 1){ next }     # Skip first line which is the column name
    if ($COL<min){min=$COL} # Store minimum so far
    if($COL>max){max=$COL}  # Store maximum so far
    sum+=$COL; }            # Store sum of the column
    END { print "minim columna="min;
        print "maxim columna="max;
        print "average columna="sum/(NR-1);}' file.txt;

Note that because we skip the header line, we calculate the average using sum/(NR-1) not sum/NR.
With your program it is important to be able to get the value of COL from the bash script. This can be done by using awk's -v parameter:
awk -v "COL=$col" 'BEGIN{ ...

Put this together in a simplified columns function yields:
#!/bin/bash

FICHERO="affy.txt"

function column
{
    if [ -s $FICHERO ]; then
      echo "Print the column number you are looking for: "
      read -p "column: " column
      col="${column#-}"
      echo "You are working with column number:" $col
    else
      echo "El fichero no existe o no contiene entradas en la agenda"
    fi

    if [ "$col" = "" ]; then
      echo "Insert Columns please!"
    else
      echo
      let col+=1 # Add 1 to column name as we assume that 1 will be the first column of data
      awk -v "COL=$col" 'BEGIN{min=999;sum=0}
      { if(NR <= 1){ next }     # Skip first line which is the column name
        if ($COL<min){min=$COL} # Store minimum so far
        if ($COL>max){max=$COL}  # Store maximum so far
        sum+=$COL; }            # Store sum of the column
        END { print "minim columna="min;
              print "maxim columna="max;
          print "average columna="sum/(NR-1);}' $FICHERO;
     fi
}

column

This will print the information for one column in the file, which has a format as you described. From the code you posted it was unclear whether you wanted to be able to handle multiple columns in the same input; if so I'll leave it as an exercise for yourself.

A: There is a simpler way. Forget about the entire program and just focus on the problem at hand. How would you generally get a column to print? Given your file.
GENE  RESULT1 RESULT2 RESULT3
GENE1    1       6       9
GENE2    2       6       7
GENE3    2       4       9
GENE4    1       6       9

GOAL: Obtain RESULT values by positional number (1, 2, 3, etc..).
INPUT: A positive integer >= 1, yet <= 3     {x| 1 <= x <= 3}
OUTPUT: A column of numbers.
Implicit truths: Column 1 ($1) is for labels and no returned column should ever have header information in it. That makes the following the real playing field:
1       6       9
2       6       7
2       4       9
1       6       9

Solution:
User input.

*

*The first this section of your program should do make it possible to use the number 1. Right now, $1 would refer to the column of GENE lables. Thus, when any value is entered, add 1 to it so that you always get the column that you really want. Thus, zero and negative numbers are not acceptable replies from the user. Also, there are only three total columns in play. Thus, the number 3 is the largest number your program should handle (right now).

*The second thing you should consider is using a command that will print all lines except the first line. The head and tail commands have many options.
tail -n 4
This is yeilds ...
GENE1    1       6       9
GENE2    2       6       7
GENE3    2       4       9
GENE4    1       6       9

Thus, when the a command above is piped to awk
read $REPLY  (2)  *<----User inputs 2*

REPLY=$(($REPLY + 1))

tail -n 4 | awk "{print $REPLY}"       (where $REPLY really = 3)

6
6
4
6

Boom! The second column is printed.
I think you may prefer integrating this solution into your program than others listed here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to create json using gson I have to make dynamic hashes, so the class example won't work since the class variables are static. I am sending in a hashmap object to toJson but it isn't working. Any suggestions on what to do?

A: If you can't work out the Gson problem, you might look at Crockford's JSON classes for Java, they deal with this exact use case. Not an answer for the Gson issue, though; just an end-run.


text:
Q: How do I implement a raycast / laserpointer to Oculus controller? I want to implement a graphic raycaster/ laserpointer to the left Oculus controller, so I can interact with UI buttons in Unity.
I have seen a lot of tutorials etc. but nothing has helped.
I want a laserbeam or laserpointer/graphic raycast to shoot out from Oculus controller when a button os pressed on the controller. I need the laserbeam to interact with UI buttons in Unity.

A: You can use a normal raycast
I recomend you make this:

*

*Create a script on your hand,and add a component called line renderer

*In the script attach the lineRenderer component

*make a simple raycast hit

*get the position of the hit object

*set the first position of the actual hand and the second to the hit object like this:
lineRenderer.SetPosition(0,transform.position);
lineRenderer.SetPosition(1,hitObject.transform.position);
And it draw a line from your hand to the hit object, remember to change the lineRender parameter to make a beautiful line
hope it helps

A: I created a project that uses unity's event system. It is a laser pointer which you can interact with unity's UI and 3d objects in the scene. If you want to check it out here's the link: https://github.com/balataca/oculus-laser-pointer


text:
Q: Using Headers with Google Community Connector How would you use authorization headers when writing a Google Community Connector?
eg. When calling the URL in getData() would it be something as simple as this:
var response = JSON.parse(UrlFetchApp."https://api_example.com", {
    "method": "GET",
    "headers": {
        "host": *********,
        "key": ************}
)).root.station;
I am continuously getting a data connection error in Google Data Studio but I can't be sure if it is because of poor authorisation such as above or if I have improperly formatted by getData().

A: Yes, KEY authtype is supported: https://developers.google.com/datastudio/connector/reference#authtype


text:
Q: VHDL - FPGA implementation - Pulse trigger generated only once on mutiple button pushes Hello everyone I wrote some VHDL code that implement a UART-TX from my FPGA to my desktop. To trigger data sending I use the signal(debounced ofc) coming from the on-board switch.
As long as the button is pressed data is being sent. Inevitably, for as quick as I can be pushing and releasing this switch, the FPGA sends many UART packet duplicates to the laptop. This is because i directly connected the button signal to the start bit of the UART-TX entity. Therefore, I removed this direct connection and instead use the button to actually generate a short bit pulse to trigger the UART-TX entity just once.
So I did this:
--start_deb is the start bit (debounced? coming from the switch

i_TX_DV_gen: process(start_deb, clk) is
variable counter: natural := 0;
begin
if rising_edge(start_deb) then
    i_TX_DV <= '1';
end if;
if i_TX_DV = '1' and rising_edge(clk) then
    counter := counter + 1;
    if counter > 10_000 then
        i_TX_DV <= '0';
        counter := 0;
    end if;
end if;
end process;

So the trigger bit to the UART entity is set to '1' when I press the button and then after a number of clock cycles (which I unsured smaller than the ones necessary to send one packet) it goes to '0' again avoiding the send any duplicates.
This works in simulation, I attached the waveform:

These are the signals description
clk:system clock
start_n: button signal (pressed when low)
start: not(start_n)
shift_input_n: button signal to select the next byte code.
o_TX_serial: serial output of the TX entity
packet: byte to be sent
i_TX_DV: trigger bit to start UART-TX trasmission
start_deb: start signal but debounced

The problem is that when I download it to my FPGA, the i_TX_DV is set to '1' only the first time.
[
To visualize this I used a FPGA-built-in LED, which produces a light burst every time the i_TX_DV is set to '1'( for its very short amount of time).
]
Therefore, the UART-TX entity is triggered only the first time I pressed the button. Apparently when on FPGA for some reason, i_TX_DV is not set to '1' anymore, or is set to '0' just right after.
I am using the fpga Crosslink-NX Family 8MG289C from Lattice Semiconductor.

A: Thank you guys, I thought of others ways to include it in a FSM and I ended up modifying the FSM of the UART-TX entity. Basically I don't go back to the idle state as long as the input start button is still pressed. This is a section of the FSM which contains the part I modified
        when s_Cleanup =>
            o_TX_Active <= '0';
            r_TX_Done   <= '1';
            ***if i_TX_DV = '1' then
                r_SM_Main <= s_Cleanup;
            else
                r_SM_Main <= s_Idle;
            end if;***

Anyway back at my original implementation, this was the netlist analyzer output for the pulse trigger generator:

It uses a register and a full adder to implement the counter. A register stores the value of i_TX_DV. The two multiplexer at the left are apparently used to either hold the value of the counter, updating it with the next value or "reset" it. The reset apparently is carried in this way: it comes from the d1 constant input data of bottom-left multiplexer wihch is tied to a 0. Therefore at the next clock cycle, when it holds the value it should be resetting itself. For some reason this still didn't work.
I apologize for my careless when writing the VHDL code, but when wiriting the code I just assumed that as long the simulation went well, the synthesis tool would have done the rest. Also I decided to not include too much code in order to be more coincise, because I had done several testing and made sure that all the other entities and modules were working correctly.


text:
Q: Show formula which does not have quantifier elimination in theory of infinite equivalence relations. Let $T^-$ be theory which fulfills following axioms:

(i) $\sim$ is an equivalence relation;
  (ii) every equivalence class is infinite;

Find formula which is not $T^-$-equivalent to any formula without quantifiers.
I cannot work out such formula.

A: There is a feature of $T^-$ which is quite useful here: it is incomplete. In a complete theory, every sentence is either provable from the theory or disprovable from the theory, hence equivalent (over the theory) to either $\top$ or $\perp$. Because of this, if you want to show that a certain complete theory does not have quantifier elimination, you need to work with formulas with free variables - this amounts to analyzing the definable sets of an arbitrary model, and can often be quite complicated.
With an incomplete theory, however, we have a potentially simpler (at least, intuitively simpler) opportunity: we can look for a sentence which is not equivalent (over the theory) to any quantifier-free sentence. Specifically, we'll be done if we can do the following two things:

*

*Show that any two models of our theory have the same parameter-free quantifier-free theory.

*Show that there are two models of our theory which are not elementarily equivalent.
Analyzing the parameter-free quantifier-free sentences is generally much easier than looking at arbitrary formulas with free variables. In particular, it's often the case - as it is here - that the language of the theory we're studying simply doesn't allow for many quantifier-free sentences:

What are the quantifier-free sentences in the language of $T^-$? (There won't be very many, even if you allow "$\top$" and "$\perp$" as logical constants - which is a minor point of inconsistency between presentations of the subject.)

And the second bulletpoint is just the fact that our theory is incomplete, which in this case is easy:

Two countable models of $T^-$ are determined entirely by the number of equivalence classes; conversely, any number (from $1$ to $\omega$) of equivalence classes is allowed by $T^-$. So can you find a sentence which distinguishes (say) the two-class model from the one-class model?


text:
Q: $\mu$ is a finite Borel measure on $\Bbb R$, absolutely continuous w.r.t. to the Lebesgue measure $m$. Prove that $x \mapsto \mu(A+x)$ is continuous. Let $\mu$ be a finite Borel measure on $\Bbb R$, which is absolutely continuous with respect to the Lebesgue measure $m$. Prove that $x \mapsto \mu(A+x)$ is continuous for every Borel set $A \subseteq \Bbb R$.
Thoughts: $\mid \mu(A+x) -\mu(A-x) \mid = \mid \int_{-\infty}^{A+x} d\mu - \int_{-\infty}^{A+x_0} d\mu \mid = \mid \int_{A+x_0}^{A+x} d\mu \mid =\mid x-x_0 \mid$, hence continuous. I'm not sure whether this is a correct arguement.
2nd thought: sorry, I regarded $\mu$ as a distribution function in probability. Another question, why can we use Radon-Nikodym to write $\mu$ as a convolution?


text:
Q: Decode a nested object in Swift 5 with custom initializer I have an API which returns a payload like this (just one item is included in the example).
{
  "length": 1,
  "maxPageLimit": 2500,
  "totalRecords": 1,
  "data": [
    {
      "date": "2021-05-28",
      "peopleCount": 412
    }
  ]
}

I know I can actually create a struct like
struct Root: Decodable {
  let data: [DailyCount]
}

struct DailyCount: Decodable {
  let date: String
  let peopleCount: Int
}

For different calls, the same API returns the same format for the root, but the data is then different. Moreover, I do not need the root info (length, totalRecords, maxPageLimit).
So, I am considering to create a custom init in struct DailyCount so that I can use it in my URL session
let reports = try! JSONDecoder().decode([DailyCount].self, from: data!)

Using Swift 5 I tried this:
struct DailyCount: Decodable {
  let date: String
  let peopleCount: Int
}

extension DailyCount {
  enum CodingKeys: String, CodingKey {
    case data
    enum DailyCountCodingKeys: String, CodingKey {
      case date
      case peopleCount
    }
  }
  init(from decoder: Decoder) throws {
    // This should let me access the `data` container
    let container = try decoder.container(keyedBy: CodingKeys.self
    peopleCount = try container.decode(Int.self, forKey: . peopleCount)
    date = try container.decode(String.self, forKey: .date)
  }
}

Unfortunately, it does not work. I get two problems:

*

*The struct seems not to conform anymore to the Decodable protocol

*The CodingKeys does not contain the peopleCount (therefore returns an error)

A: This can't work for multiple reasons. You are trying to decode an array, so your custom decoding implementation from DailyCount won't be called at all (if it were to compile) since at the top level your JSON contains an object, not an array.
But there is a much simpler solution which doesn't even require implementing Decodable yourself.
You can create a generic wrapper struct for your outer object and use that with whatever payload type you need:
 struct Wrapper<Payload: Decodable>: Decodable {
     var data: Payload
 }

You then can use this to decode your array of DailyCount structs:
let reports = try JSONDecoder().decode(Wrapper<[DailyCount]>.self, from: data).data

This can be made even more transparent by creating an extension on JSONDecoder:
extension JSONDecoder {
     func decode<T: Decodable>(payload: T.Type, from data: Data) throws -> T {
          try decode(Wrapper<T>.self, from: data).data
     }
}

A: Sven's answer is pure and elegant, but I would be remiss if I didn't point out that there is also a stupid but easy way: dumpster-dive into the "data" without using Codable at all. Example:
// preconditions
let json = """
{
  "length": 1,
  "maxPageLimit": 2500,
  "totalRecords": 1,
  "data": [
    {
      "date": "2021-05-28",
      "peopleCount": 412
    }
  ]
}
"""
let jsonData = json.data(using: .utf8)!
struct DailyCount: Decodable {
    let date: String
    let peopleCount: Int
}

// okay, here we go
do {
    let dict = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [AnyHashable:Any]
    let arr = dict?["data"] as? Array<Any>
    let json2 = try JSONSerialization.data(withJSONObject: arr as Any, options: [])
    let output = try JSONDecoder().decode([DailyCount].self, from: json2)
    print(output) // yep, it's an Array of DailyCount
} catch {
    print(error)
}


text:
Q: Python: clear stdin Buffer This is possibly a nooby question but i cant find a way to do it!
I need to clear the stdin buffer in python.
Imagine i have following bash script running:
i=0
for (( ; ; ))
do
    echo "$i"
    ((i++))
done

run from the command line like so: ./loop.sh | python myProg.py
in myProg.py i wish to have something as follows:
count = 100
f = fileinput.input()
while True:
    sleep(2)
    # clear stdin somehow ...
    # and read the most recent 100 lines
    i = 0
    while i < count:
        myBuffer[i] = f.readline()
        if len(myBuffer[i]) > 0:
            i += 1
    print myBuffer

i don't think i can just read all the lines, before it because it is spitting them out at a high rate and if sleep (just for testing atm) is a few minutes it seems silly ... is there a way to set the stdin buffer size in python? Or just truncate/clear it? Btw im using python 2 so no bufsize argument
I had a look here How to avoid Python fileinput buffering
Any python way of doing it? But ill try unbuffer too: https://unix.stackexchange.com/questions/25372/turn-off-buffering-in-pipe
Update:
no luck with unbuffer or stdbuf ...

A: Just in case anyone else has this issue i have been on an extensive search and come to the conclusion it is not possible due to kernel implementation etc ...
I wrote the following work around to do what i wanted. I created two files: textFilter.py and getLatest.py. Essentially you run ./loopPrinting.sh | python textFilter.py and get the Latest 100 lines. I am reasonably sure this is atomic and reliable (though if it isn't please tell me!!!). It creates 16 files and changes the count (similar to the apple live streaming i think).
textFilter.py
import sys
import os
import time

def mainLoop(size):
    myBuffer = [0]*size
    count = 0

    while True:
        for i in range(size):
            myBuffer[i] = sys.stdin.readline()

        f = open('/home/development/textFilter/' + repr(count) + '.dat', 'w')
        f.write(''.join(myBuffer))
        f.close()

        f = open('/home/development/textFilter/count.dat~', 'w')
        f.write(repr(count))
        f.flush()
        os.fsync(f.fileno())
        f.close()
        time.sleep(0.01)
        os.rename('/home/development/textFilter/count.dat~','/home/development/textFilter/count.dat')

        count += 1
        count = count % 16

if __name__ == "__main__":
    try:
        mainLoop(int(sys.argv[1]))
    except Exception:
        mainLoop(100)

getLatest.py
import sys
import time

def getData():
    f = open('count.dat', 'r')
    count = f.read()
    f.close()

    count = int(count)
    oldCount = count

    while oldCount == count:
    time.sleep(0.1)
    f = open('count.dat', 'r')
    count = f.read()
    f.close()
    count = int(count)

    f = open(repr(count) + '.dat', 'r')
    data = f.readlines()
    f.close()

    for row in data:
    print row,

    return 0

if __name__ == "__main__":
    try:
    getData()
    except Exception as inst:
    sys.stderr.write('ERROR')
    sys.stderr.write(inst)


text:
Q: Error in Creating Views in Fragment I have created a Activity with 3 Fragment layout where the user will swipe the screen to display another fragment.
On my first fragment I plan to have a ListView to display out the information of the user.
However the codes I normally used for the extends Activity do not work with extends Fragment.
I researched a little and finally got rid of the red lines but my app crashes when I display the fragment.
Here is my code:
public class LayoutOne extends ListFragment {
ListView myInfoList;
String[] items = {"Item 1", "Item 2"};
ArrayAdapter<CharSequence> adapter;

public static Fragment newInstance(Context context) {
    LayoutOne f = new LayoutOne();

    return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.layout_one, container, false);

    return view;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    myInfoList = getListView();
    adapter = new ArrayAdapter<CharSequence>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, items);
    myInfoList.setAdapter(adapter);
}

}

And here is my log cat:

06-16 17:57:16.150: D/AndroidRuntime(20378): Shutting down VM
  06-16 17:57:16.150: W/dalvikvm(20378): threadid=1: thread exiting with uncaught exception (group=0x40ff9930)
  06-16 17:57:16.158: E/AndroidRuntime(20378): FATAL EXCEPTION: main
  06-16 17:57:16.158: E/AndroidRuntime(20378): java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.support.v4.app.ListFragment.ensureList(ListFragment.java:344)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.support.v4.app.ListFragment.onViewCreated(ListFragment.java:145)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:884)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:622)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1416)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:431)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:139)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.support.v4.view.ViewPager.populate(ViewPager.java:804)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1016)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.View.measure(View.java:15523)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.View.measure(View.java:15523)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.View.measure(View.java:15523)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.View.measure(View.java:15523)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4825)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2434)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.View.measure(View.java:15523)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1874)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1089)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1265)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.Choreographer.doCallbacks(Choreographer.java:562)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.Choreographer.doFrame(Choreographer.java:532)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.os.Handler.handleCallback(Handler.java:725)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.os.Handler.dispatchMessage(Handler.java:92)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.os.Looper.loop(Looper.java:137)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at android.app.ActivityThread.main(ActivityThread.java:5233)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at java.lang.reflect.Method.invokeNative(Native Method)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at java.lang.reflect.Method.invoke(Method.java:511)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
  06-16 17:57:16.158: E/AndroidRuntime(20378):   at dalvik.system.NativeStart.main(Native Method)

A: you never initialize myInfoList. Ihmo your class should extends ListFragment instead of Fragment.
your onCreateView should inflate the layout that contains a ListView and you should move
adapter = new ArrayAdapter<CharSequence>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, items);
myInfoList.setAdapter(adapter);

inside onActivityCreate:
public void onActivityCreated(Bundle savedInstanceState) {
    myInfoList = getListView();
    adapter = new ArrayAdapter<CharSequence>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, items);
    myInfoList.setAdapter(adapter);
}

the id for your ListView has to be
android:id="@id/android:list"


text:
Q: How to disable vim strikethrough in vimrc Its been like forever, I really dont know how to disable this striketrough in my vim.
Currently I'm using gvim in my ubuntu. Probably there is something wrong with my vimrc setting.
Tried google many months already could not find any solution. Please help

Below is my vimrc
set nocompatible              " be iMproved, required
filetype off                  " required

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')

" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'
Plugin 'scrooloose/nerdtree'
Plugin 'ctrlpvim/ctrlp.vim'
Plugin 'tpope/vim-vinegar'
Plugin 'jistr/vim-nerdtree-tabs'
Plugin 'scrooloose/syntastic'
Plugin 'flazz/vim-colorschemes'
Plugin 'chrisbra/Recover.vim'
Plugin 'MarcWeber/vim-addon-mw-utils'
Plugin 'tomtom/tlib_vim'
Plugin 'garbas/vim-snipmate'
Plugin 'honza/vim-snippets'
Plugin 'posva/vim-vue'

call vundle#end()            " required
filetype plugin indent on    " required
" To ignore plugin indent changes, instead use:
"filetype plugin on
"
" Brief help
" :PluginList       - lists configured plugins
" :PluginInstall    - installs plugins; append `!` to update or just :PluginUpdate
" :PluginSearch foo - searches for foo; append `!` to refresh local cache
" :PluginClean      - confirms removal of unused plugins; append `!` to auto-approve removal
"
" see :h vundle for more details or wiki for FAQ
" Put your non-Plugin stuff after this line

"let base16colorspace=256 " Access colors present in 256 colorspace
"set t_Co=256 " 256 color mode
"set background=dark
"colorscheme base16-ocean

let g:ctrlp_max_files=0
let g:ctrlp_max_depth=40

" Store temporary files in a central spot
let vimtmp = $HOME . '/.tmp/' . getpid()
silent! call mkdir(vimtmp, "p", 0700)
let &backupdir=vimtmp
let &directory=vimtmp

syntax on
syntax enable
"colorscheme Monokai
"colorscheme zenburn
"colorscheme gruvbox
"colorscheme lucius
colorscheme Monokai
"colorscheme getafe
"colorscheme CandyPaper
"colorscheme tomorrow-night-eighties
map <C-n> :NERDTreeToggle<CR>
let NERDTreeShowHidden=1
set guitablabel=%N:%M%t " Show tab numbers
set hlsearch
"set incsearch
set relativenumber
set laststatus=2
set linespace=15
set clipboard=unnamedplus
set guifont=Monospace\ 12

filetype plugin indent on
" show existing tab with 4 spaces width
set tabstop=4
" when indenting with '>', use 4 spaces width
set shiftwidth=4
" On pressing tab, insert 4 spaces
set expandtab

map <C-F12> :tabe ~/.vimrc<CR>
map <C-F11> :tab sp<CR>:e ~/.vim/snippets/php.snippets<CR>
map <C-F10> :tab sp<CR>:e sudo /etc/hosts<CR>
map <C-F9> :tab sp<CR>:e ~/Code/AdminLTE-2.3.0/pages/UI/icons.html<CR>

A: After playing around changing colorscheme to gruvbox and add this line,
let html_no_rendering=1

suddenly the strikethrough all disappear. But the colorscheme I need to chose is not the one I want. Anyway if somebody can advise. Please comment.
set nocompatible              " be iMproved, required
filetype off                  " required

" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')

" let Vundle manage Vundle, required
Plugin 'VundleVim/Vundle.vim'
Plugin 'scrooloose/nerdtree'
Plugin 'ctrlpvim/ctrlp.vim'
Plugin 'tpope/vim-vinegar'
Plugin 'jistr/vim-nerdtree-tabs'
Plugin 'scrooloose/syntastic'
Plugin 'flazz/vim-colorschemes'
Plugin 'chrisbra/Recover.vim'
Plugin 'MarcWeber/vim-addon-mw-utils'
Plugin 'tomtom/tlib_vim'
Plugin 'garbas/vim-snipmate'
Plugin 'honza/vim-snippets'
Plugin 'posva/vim-vue'

call vundle#end()            " required
filetype plugin indent on    " required
" To ignore plugin indent changes, instead use:
"filetype plugin on
"
" Brief help
" :PluginList       - lists configured plugins
" :PluginInstall    - installs plugins; append `!` to update or just :PluginUpdate
" :PluginSearch foo - searches for foo; append `!` to refresh local cache
" :PluginClean      - confirms removal of unused plugins; append `!` to auto-approve removal
"
" see :h vundle for more details or wiki for FAQ
" Put your non-Plugin stuff after this line

"let base16colorspace=256 " Access colors present in 256 colorspace
"set t_Co=256 " 256 color mode
"set background=dark
"colorscheme base16-ocean

let g:ctrlp_max_files=0
let g:ctrlp_max_depth=40

" Store temporary files in a central spot
let vimtmp = $HOME . '/.tmp/' . getpid()
silent! call mkdir(vimtmp, "p", 0700)
let &backupdir=vimtmp
let &directory=vimtmp

syntax on
syntax enable
"colorscheme Monokai
"colorscheme zenburn
"colorscheme gruvbox
"colorscheme lucius
colorscheme gruvbox
"colorscheme getafe
"colorscheme CandyPaper
"colorscheme tomorrow-night-eighties
map <C-n> :NERDTreeToggle<CR>
let NERDTreeShowHidden=1
set guitablabel=%N:%M%t " Show tab numbers
set hlsearch
"set incsearch
set relativenumber
set laststatus=2
set linespace=15
set clipboard=unnamedplus
set guifont=Monospace\ 12

filetype plugin indent on
" show existing tab with 4 spaces width
set tabstop=4
" when indenting with '>', use 4 spaces width
set shiftwidth=4
" On pressing tab, insert 4 spaces
set expandtab
let html_no_rendering=1
map <C-F12> :tabe ~/.vimrc<CR>
map <C-F11> :tab sp<CR>:e ~/.vim/snippets/php.snippets<CR>
map <C-F10> :tab sp<CR>:e sudo /etc/hosts<CR>
map <C-F9> :tab sp<CR>:e ~/Code/AdminLTE-2.3.0/pages/UI/icons.html<CR>


text:
Q: How to define multiple values in routes from a view template in Play 2 In my Play 2.4.4 project I have a view template that i want to return 2 values, a Long and a String.
I have a button that calls the appropriate method in my controller:

  @Messages("orders.rollback")

The method in my controller calls a function on a model object:
def rollbackStatus(id: Long, status: String) = Action {
  Order.demoteStatus(id, status)
  Redirect(routes.Orders.list())
}

In my routes file I have defined the HTTP method, URI and controller method:
GET  /orders/:id/:status  controllers.Orders.rollbackStatus(id: Long, status: String)

When I press the button however i get the following message:

BAD REQUEST
  For request 'GET /orders/3,PLACED' [Cannot parse parameter id as Long: For input string: "3,PLACED"]

I have managed to pass single values in the same way successfully.
Here is the rest of the routes defined for /orders:
GET /orders             controllers.Orders.list
GET /orders/pickorder   controllers.Orders.getOrder
GET /orders/:id         controllers.Orders.show(id: Long)
GET /orders/:id/:status controllers.Orders.rollbackStatus(id: Long, status: String)

A: Well I found the answer, When you specify the first parameter you use '/:' to define the name of the parameter.
All subsequent parameters are separated with just '/'.
I believe this is because the ':' specifies the start of the arguments however this is not clear from the Play documentation
Here is the corrected routes listing, all other code is unchanged from the code provided in the question:
GET /orders             controllers.Orders.list
GET /orders/pickorder   controllers.Orders.getOrder
GET /orders/:id         controllers.Orders.show(id: Long)
GET /orders/:id/status controllers.Orders.rollbackStatus(id: Long, status: String)


text:
Q: How to prevent memory leak in Mono MVC3 application? Mono MVC 3 shopping cart Web applications are running under Apache in Mono.
In top output below there are 3 applications with pids 31398, 30851, 30854
Processes are sorted by %MEM.
After some time there is lot of mono processes which take all on memory and Linux OOM starts to kill
them.
After that processes are started again and memory usage continues to increase.
How to fix or diagnose this so that mono does not eat all memory?
Using Mono 2.10 with .NET 4
It looks like simply vieweing web pages or google bot access causes this issue.
top - 16:12:25 up 26 days,  4:34,  1 user,  load average: 0.23, 0.17, 0.11
Tasks:  65 total,   1 running,  64 sleeping,   0 stopped,   0 zombie
Cpu(s):  0.3%us,  0.3%sy,  0.0%ni, 98.6%id,  0.7%wa,  0.0%hi,  0.0%si,  0.0%st
Mem:   1048576k total,  1023596k used,    24980k free,        0k buffers
Swap:        0k total,        0k used,        0k free,   582340k cached

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
31398 www-data  20   0  254m 122m 5692 S  0.3 11.9   0:29.38 mono
30851 www-data  20   0  202m  71m 4552 S  0.0  6.9   0:13.70 mono
30854 www-data  20   0  245m  51m 4196 S  0.0  5.0   0:05.74 mono
31413 postgres  20   0  117m  47m  29m S  0.0  4.6   0:16.04 postgres
32235 postgres  20   0  111m  40m  27m S  0.0  3.9   0:00.59 postgres
31803 postgres  20   0  106m  35m  28m S  0.0  3.5   0:01.96 postgres
30342 postgres  20   0 99888  26m  25m D  0.3  2.6   0:02.49 postgres
  882 postgres  20   0  103m  23m  19m S  0.0  2.3   0:00.13 postgres
  973 postgres  20   0  102m  17m  13m S  0.0  1.7   0:00.07 postgres
  942 postgres  20   0  102m  16m  12m S  0.0  1.6   0:00.15 postgres
30867 www-data  20   0 58172  14m 2604 S  0.0  1.4   0:00.71 mono
30849 www-data  20   0 51212  12m 2604 S  0.0  1.2   0:00.66 mono
32234 postgres  20   0 99.4m  11m 9388 S  0.0  1.2   0:00.02 postgres
30847 www-data  20   0 50000  11m 2560 S  0.0  1.2   0:00.63 mono
30863 www-data  20   0 50000  11m 2560 S  0.0  1.1   0:00.64 mono
32568 postgres  20   0 99.6m  10m 8304 S  0.0  1.1   0:00.05 postgres
30439 postgres  20   0 99.3m  10m 8120 S  0.0  1.1   0:00.03 postgres
  616 postgres  20   0 99.5m  10m 7324 S  0.0  1.0   0:00.06 postgres
  971 postgres  20   0 99.4m 9.8m 7196 S  0.0  1.0   0:00.01 postgres
  954 postgres  20   0  101m 9288 6544 S  0.0  0.9   0:00.00 postgres
32225 postgres  20   0 98.7m 8812 6344 S  0.0  0.8   0:00.02 postgres
31410 postgres  20   0 98.7m 8708 6272 S  0.0  0.8   0:00.06 postgres
  946 postgres  20   0 99.2m 8648 5928 S  0.0  0.8   0:00.01 postgres
  785 postgres  20   0 99.3m 7912 5152 S  0.0  0.8   0:00.00 postgres
  972 postgres  20   0 99.2m 7808 5136 S  0.0  0.7   0:00.00 postgres
32297 postgres  20   0 99.2m 7688 5016 S  0.0  0.7   0:00.02 postgres

A: There's this little memory leak bug in MonoFastCGI which could be well affecting the Apache ModMono integration as well (as both of them share some code).
If using FastCgi, there is a workaround: use unix domain sockets instead of local ports. So, you could try switching to use this technology (which is implemented by many web servers, not only Apache). In my case I used it with nginx and I was pretty satisfied. More info here.
Also, if I were you I would upgrade to Mono 3.x as well.


text:
Q: Neo4J Browser Issue I am not able to see the graph icon on the Neo4J browser launched from the Desktop application. Does anyone know how to get that button?

A: The graph icon is not visible if you return the tabular data like you just return a few fields of a node. It's only visible when you return a graph(Nodes/Relationships) in your query. From your screenshot looks like you are returning text "node" instead of node, Please check your query and make sure you are returning nodes.


text:
Q: PHP Time to String from SQL Server value doesn't match I have a table with one record, there is a column which is time formatted.
The real value inside it is 23:15:12.1170000, but when I try to get the data in PHP, it shows me 23:03:12.
The question is, why the output is not match ? Could somebody help me please ? Do I need to include the timezone set before parsing it ?
EDIT : I mean the Hour, Minute, Second value ( The number ). not the format I converted into.
This is my conversion code :
<?= date_format( $row["time"], "H:m:s" ) ?>

A: Change the time format: m represents month and not minutes, use i for minutes.
<?= date_format( $row["time"], "H:i:s" ) ?>


text:
Q: In R, split a column in to 2 columns I am trying to split data frame hire into 2 columns based of percentage.
  group                    percentage
 0 hired                     60%
 0 hired next_month          65%
 0 or 1 hired                68%
 0 or 1 hired next_month     70%
 1 hired                     79%
 1 or 2 employee             80%
 2 retired                   85%
 2 or 3 fired                92%
 3 not-retired               96%

I want 2 columns group and decision output should be (column percentage and decision should be as it is no change, column group should be 0 if percentage is between 60% to 69% (3rd row), group should be 1 if percentage is between 70% to 79% (4th row), group should be 2 if percentage is between 80% to 89%, group should be 3 if percentage is between 90% to 99% )
  group   decision         percentage
    0     hired              60%
    0     hired next_month   65%
    0     hired              68%
    1     hired next_month   70%
    1     hired              79%
    2     employee           80%
    2     retired            85%
    3     fired              92%
    3     not-retired        96%

my code:
df1 <- structure(list(
           group = c("0 hired", "0 hired next_month ", "0 or 1 hired",
            "0 or 1 hired next_month", "1 hired", "1 or 2 employee",
            "2 retired", "2 or 3 fired", "3 not-retired"),
           percentage = c("60%", "65%", "68%", "70%", "79%", "80%", "89%", "90%", "96%") ),
         .Names = c("group", "percentage"), class = "data.frame", row.names = c(NA, -9L))

df2 <- df1 %>% extract(group, into = c('group', 'decision'), "^(\\d+).*(hired|hired next_month|employee|retired|fired|not-retired)")%>% mutate(group = replace(group, parse_number(percentage)>=100, 3))

can anyone help. Thanks in advance

A: You can do this in base R like this
df2 = data.frame(percentage = df1$percentage)
df2$decision = sub(".*\\d\\s*", "", df1$group)
df2$group = as.numeric(cut(as.numeric(sub("%", "", df1$percentage)),
    breaks = c(59, 69, 79,89,100))) - 1
df2 = df2[,3:1]
df2
  group          decision percentage
1     0             hired        60%
2     0 hired next_month         65%
3     0             hired        68%
4     1  hired next_month        70%
5     1             hired        79%
6     2          employee        80%
7     2           retired        89%
8     3             fired        90%
9     3       not-retired        96%


text:
Q: Affine coordinate ring, k- vector space Let
$$
  P_1 = (0, 0), \quad
  P_2 = (1, 0), \quad
  P_3 = (0, 1), \quad
  P_4 = (1, 1).
$$
Let $Y = \{P_1, P_2, P_3, P_4\}$ and
let $I \subset k[x, y]$ be the ideal of $Y$ .

*

*Show that the affine coordinate ring $A(Y) = k[x, y]/I$ of Y has dimension $4$ as $k$-vector space.

*Show that $I = (f, g)$, where $f = x^2 − x$ and $g = y^2 − y$.
Hint: show that $(f, g) \subseteq I$, then that
$(1, x, y, xy)$ gives a k-basis for $k[x, y]/(f, g)$ using divisions with remainder, then that the natural morphism $k[x, y]/(f, g) \to A(Y)$ is an isomorphism.
For question 1 I think that a $k$-algebra morphism
$$
  k[x, y] \to k^4,
  \qquad
  f \mapsto (f(P_1), f(P_2), f(P_3), f(P_4))
$$
will do the job but I am really lost with the structure of the spaces to form it.
Can anyone offer some help?

A: Well, the coordinate ring is $k[x,y]/J$, where $J$ is the ideal
$$J=\langle x,y\rangle\cap\langle x-1,y\rangle \cap\langle x,y-1\rangle\cap \langle x-1,y-1\rangle,$$
which is equal to $k[x,y]/\langle x^2-x,y^2-y\rangle$.
See Showing that two ideals are equivalent. for more details.
Moreover, the standard monomial basis of $k[x,y]/J$ consists of $1,x,y,xy$ and so the coordinate ring is 4-dimensional over $k$.


text:
Q: Get the column difference in Excel? I created a pivot table below and wanna calculate the count of 2016 - count of 2015 for each row. How can I do it in pivot table? Cheers
2015,2016 is value of a field 'year'.

A: You can follow the instructions in the GIF below.
I've created a data table according to your questions and tested it.

*

*The main thing in this solution is the Show Values As > Difference
From option in Pivot Table.

*Positive result means 2016 is bigger, negative result means 2015
is bigger.

*I hid the irrelevant columns that were populated, I suggest you do
the same.


text:
Q: How to accept the props value while not keep on repeating the object I'm a newbie in this framework and this is my inline-template
<edit-profile inline-template :user="{{ $user }}">

export default {

  props: ['user'],

 form : {
        display_name : "",
        username  : "",
        email : "",
        first_name : "",
        middle_name : "",
        last_name : "",
        telephone : "",
        mobile : "",
        skype : "",
        facebook: "",
        twitter : "",
        instagram  : "",
        bio : ""
      },
};

But i don't want to repeat the this.user.xxxx like this.form.username in every field in the form object. How can I not repeat it ? ?

A: Well, if you think about it. user is just an object and, maybe, you can just assign it to form when the component is mounted()?
export default {

    props: ['user'],

    data: {
        form: {}
    },

    mounted()
    {
        this.form = this.user;
    }

};

Is this what you are looking for?


text:
Q: How do I dynamically determine the propTypes of a react component? I have a react component as follows:
import {
  dataType,
} from './types.js';

class TableUp extends React.Component {
  static propTypes = {
    palette: t.object,
    title: t.string,
    data: dataType.isRequired,
    selection: t.object,
    querySearch: t.object,
    pagination: t.object,
    onMount: t.func,
  };

And in the types.js
import t from 'prop-types';

export const dataValueType = t.shape({
  id: t.oneOfType([
    t.string,
    t.number,
  ]).isRequired,
  name: t.string,
  status: t.string,
});
export const dataValuesType = t.arrayOf(dataValueType);

export const dataColumnType = t.shape({
  key: t.string.isRequired,
  label: t.string.isRequired,
  numeric: t.bool,
});
export const dataColumnsType = t.arrayOf(dataColumnType);

export const dataType = t.shape({
  values: dataValuesType,
  columns: dataColumnsType,
});

When I instantiate the <TableUp> component, I need to pass data that may vary from case to case.
So the following will FAIL to work
const data = {
  values: [
    {description: "10 percent", allocated: 10.00},
    {description: "50 percent", allocated: 50.00},
    {description: "40 percent", allocated: 40.00},
  ],
  columns: [
    {key: 'attributes.description', label: 'Milestone'},
    {key: 'attributes.allocated',   label: 'Percent', numeric: true},
  ]
};
return (
  <TableUp inputProps={{name:"gr_table"}} data={data} />
);

I was wondering if there's a way I can dynamically determine the dataType when I instantiate the TableUp component.


text:
Q: Why does Roxygen recognize some functions and S3Methods and rename some functions in NAMESPACE? I am taking over an R project and I am attempting to keep the naming as consistent as possible from the person who worked on the project before me.
I have created several functions for a package being developed. Above each function, I have the #' @export which is used to create the NAMESPACE file in roxygen2:
#' @export
a.function = function(x){
# do stuff
}

#' @export
another.function = function(x){
# do stuff
}

When I create the documentation using roxygen2, the NAMESPACE file created will categorize some functions as methods. Periods (.) will also be converted into commas (,). For example, the namespace for the functions above might appear as
S3method(a.function)
export(another.function)

Furthermore, the person who worked on the project before me occasionally used 3 periods when naming a function:
yet.another.function = function(x){
# do stuff
}

But Roxygen2 converts the first period into a comma in all functions with 3 periods in the NAMESPACE file. By this I mean that the function above would appear as
export(yet,another.function)

in the NAMESPACE file.
My questions are as follows:

*

*How does Roxygen distinguish some functions as S3method and some as functions and use export in NAMESPACE?

*Is it possible to force or coerce Roxygen to recognize all functions as functions and to use export?

*Is it possible to stop Roxygen from converting periods in the function name to commas in the NAMESPACE file?
Unfortunately I was not able to directly find the answer to these in either the Roxygen documentation or other posts on stack Overflow.


text:
Q: setDownloadProgressBlock in AFHTTPClient subclass I created subclass of AFHTTPClient.
It works, but progress block return only final value (1.0). What should I change to get all the calculated values from setDownloadProgressBlock?
- (void)exploreVenuesCenter:(CLLocationCoordinate2D)coordinate inRadius:(int)radiusMeters success:(void (^)(NSArray *venues))success failure:(void (^)(NSError *error))failure progress:(void (^)(float progress))progress{
    NSDictionary *parameters = @{@"limit": @"10",
                                 @"client_id":kFoursquareClientID,
                                 @"client_secret":kFoursquareClientSecret,
                                 @"radius":@(radiusMeters).stringValue,
                                 @"ll":[NSString stringWithFormat:@"%g,%g",coordinate.latitude, coordinate.longitude],
                                 @"v":kFoursquareVersion};
    NSMutableURLRequest *request = [self requestWithMethod:@"GET" path:@"venues/explore" parameters:parameters];

    AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request
                                                                      success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                                                          NSArray *items = responseObject[@"response"][@"groups"][0][@"items"];
                                                                          if (success)
                                                                          {
                                                                              success(items);
                                                                          }
                                                                        }
                                                                      failure:^(AFHTTPRequestOperation *operation, NSError *error) { if (failure) {
        failure(error);
        NSLog(error.localizedDescription);
    } }];
    [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
        //
        float progressNo = ((float)totalBytesRead) / totalBytesExpectedToRead;
        if (progress) {
            progress(progressNo);
        }
    }];

    [self enqueueHTTPRequestOperation:operation];
}


text:
Q: How do I register a parameter for a DbContext with Autofac? I am using Entity Framework and Sql to work with a database.
My context class is:
 public class AnimalBreedsContext : DbContext
 {
        public DbSet<AnimalBreed> AnimalBreeds { get; set; }

        public AnimalBreedsContext(DbContextOptions<AnimalBreedsContext> options) : base (options)
        {

        }
  }

The class AnimalBreeds is a class that has some string properties like Name, etc.
Now I want to register the AnimalBreedsContext class with Autofac. I tried something like that:
class ContainerConfig
 {
     public static IContainer Configure()
     {
         var builder = new ContainerBuilder();

         var options = new DbContextOptionsBuilder<AnimalBreedsContext>()
                         .UseSqlServer("configString")
                         .Options;

         builder.RegisterType<AnimalBreedsContext>().WithParameter(options).AsSelf();

         return builder.Build();
      }
 }

But the problem is that "parameter options can't be converted from AnimalBreedsContext to Autofac.Parameter".
Is there any other option so that I can register this class with Autofac?

A: It looks like you aren't providing the correct arguments to WithParameter.  Here is the Autofac documentation showing all of the overloads.
Without wrapping the argument in one of the Autofac Parameter objects, it looks like you can provide the string name of the parameter as the first argument, then your actual parameter object as the second:
builder.RegisterType<AnimalBreedsContext>()
       .AsSelf()
       .WithParameter("options", options);


text:
Q: Android FTP File Download So i get a NullPointerException when I try to read from a file which I downloaded from a FTP Server. My guess is that it doesn't find the file because i just know a part of the filename. Is there any way where i can open a file where I just search for a part of the Name and it takes the file which is called similar like the searching value. I'm talking about following line, where the star stands for random chars:

InputStreamReader isr = new
  InputStreamReader(client.retrieveFileStream("/" + "jerichTNT*"));

Can I search in that way or do i have to know the full filename with its ending?
SOLVED
Solution: I just had to type the full filename :(


text:
Q: How to avoid java.lang.NoSuchMethodError on earlier java versions I got the following error today:
java.lang.NoSuchMethodError: javax.swing.JList.getSelectedValuesList()Ljava/util/List;
We have some customers still using old java6 versions out there. (Some old posready/embedded-version of windows that doesn't accept installing 1.8 directly..)
Therefore I use compiler compliance level 1.6 in eclipse. However, after an upgrade of our software, some customers reported errors/freezing. I logged in, and found the following error:
java.lang.NoSuchMethodError: getSelectedValuesList()Ljava/util/List;
It appears that this particular JList method in was introduced in 1.7, and I have started using it since getSelectedValues() is deprecated.
But this breaks things on 1.6, since the method does not exist in 1.6.
I have made a workaround, instead of calling getSelectedValuesList() I now call the following method:
public static <E> java.util.List<E> getSelectedValuesList(javax.swing.JList<E> l) {
    try {
        return l.getSelectedValuesList();
    }catch(java.lang.NoSuchMethodError err) {
        ArrayList<E> v = new ArrayList<E>();
        Object[] oo = l.getSelectedValues();
        for (Object o : oo) {
            v.add((E)o);
        }
        return v;
    }
}

This seems to work ok. But my question is, since source level is 1.6, how do I detect similar errors? Since I don't even have 1.6 installed, how can I know for sure that all my swing methods that I call actually works in 1.6? I don't want to introduce yet another bug later on. :-)


text:
Q: array 1D i need to ask the user to check index and print value I have to ask the user for a number and check whether the number is present in the array or not I wrote my code but it doesn't seem to be working we are not allowed to use find function or any other built in function since we are not taught any of this in class yet . Here is the exact question from my assignment and the code I have written till yet.
`l= [13, 99, 6, 76, 11, 83, 27, 84, 28, 67, 66, 22, 96, 46, 63, 21, 65, 48, 8, 14 , 84, 22, 28, 11, 83, 87, 11, 76, 6,83,27]`

question: Write a program to search a given element in the array.
#include <iostream>
using namespace std;

int main() {

    int x;
    int i, j;
    int array[31] = {13, 99, 6, 76, 11, 83, 27, 84, 28, 67, 66, 22, 96, 46, 63, 21, 65, 48, 8, 14 , 84, 22, 28, 11, 83, 87, 11, 76, 6, 83, 27};

    for(i = 0; i <= 31; i++){
        for( j = 0; j <=
            cout << "enter the number to locate in array";
            cin >> x;

            if(array[i] == x){
                cout << x << "found at [" << i << "]" << "\n";
            }
            else{
                cout << "the number was not found in the array" << endl;
            }
        }

    return 0;
}

A: As a simple example you can declare a boolean variable so inside loop if the value at least found once then assign it true otherwise if the loop returns and the value not found then inform the user that search not found.
Also you do not need an inner loop only one loop and input the search value outside the loop.
Also if you need the string comment mark in your string text you must precede it with backslash: "Hello there \"how are you?" otherwise the compiler thinks the string ends at the first double-quoted comma: "Hello there" then how are you undeclared identifier.
The program can look like:
int x;
bool isFound  = false;
int array[31] = {13, 99, 6, 76, 11, 83, 27, 84, 28, 67, 66, 22, 96, 46, 63, 21, 65, 48, 8, 14 , 84, 22, 28, 11, 83, 87, 11, 76, 6, 83, 27};

cout << "enter the number to locate in array";
cin >> x;

for(int i = 0; i < 31; i++){ //here: don't write i <= 31
    if(array[i] == x){
        isFound = true;
        cout << x << " found at: " << i << endl;
    }
}

if(!isFound)
    cout << "The value doesn't exist in the array!" << endl;

*

*Arrays are indexed from 0 to n - 1 not n so if you write array[n] is an Undefined behavior Because the memory doesn't belong to it.


text:
Q: Non-discrete locally compact Hausdorff groups which do not satisfy the second axiom of countability I think non-discrete locally compact Hausdorff groups which do not satisfy the second axiom of countability are pain in the ass. The major trouble is that the Haar measures on them are not necessarily $\sigma$-finite.
I wish we could do math all right without them.
Are there important examples of such groups which we cannot dispense with?

A: As noted in my comment, there is a large supply of compact, but not second countable groups, e.g. every uncountable product
$$
\prod_{i \in I} G_i,
$$
where $I$ is uncountable and each $G_i$ is a compact group consisting of more than one element. These groups do not even fulfill the first axiom of accountability.
But from the formulation of your question, it is not entirely clear if you want to have examples. of relevant groups which are not second countable, or which are not $\sigma$-compact.
Here, you should observe that second countability implies $\sigma$-compactness, but not vice versa (as the example of the product of compact groups shows).


text:
Q: Migrate data from one Google Analytics Property to Other We by mistake created a Google Analytics Property of type Apps + Web(as in image). But it restricts us from using many Web specific features (like adding custom dimensions and connection with Google Tag Manager).

So we create a new property of type Web (as we anyway won't need App related things anytime sooner), but now how can we migrate all analytics data(of 4-5 months) to the new property.
We tried to go through the docs and didn't find any related help.
Any input would be helpful.

A: There is no way to migrate the data from one Account, web property or view in google analytics to another.  Once the data has been sent the data is there forever unless you delete the account.


text:
Q: timeout dynamic HTTP outbound gateway request-factory I have configured timeouts for the HTTP Outbound Gateway providing a reference to a ClientHttpRequestFactory bean using the request-factory attribute:
<int-http:outbound-gateway request-channel="channelGetByCustomer"
    request-factory="requestFactoryGetByCustomer"
    reply-channel="jsonToObjectChannel" url="${getbycustomer.endpoint.url}"
    http-method="GET" expected-response-type="com.mbracero.integration.dto.Item[]">

    <int-http:uri-variable name="customerid" expression="payload.customerid"/>

</int-http:outbound-gateway>

<beans:bean id="requestFactoryGetByCustomer" class="org.springframework.http.client.SimpleClientHttpRequestFactory">
    <beans:property name="connectTimeout" value="${getbycustomer.timeout}"/>
    <beans:property name="readTimeout" value="${getbycustomer.timeout}"/>
</beans:bean>

But I want to load these attributes dynamically from DDBB (or programmatically) and not from Spring initial boot.
How can I do this?

A: Programmatically you can do that just from any your service injecting that requestFactoryGetByCustomer bean and using its setters:
@Autowired
private SimpleClientHttpRequestFactory requestFactoryGetByCustomer;

....

this.requestFactoryGetByCustomer.setConnectTimeout(30_000);

To read those options from the DB and populate them to the bean definition using Spring Container features (e.g. Property Placeholder like in your current case) you should take a look to the Commons Configuration framework and populate Properties object from the DB SELECT.


text:
Q: Lifting a probability measure to the power set Let $X\neq\emptyset$ be a set and let $\mu:{\cal P}(X)\to [0,1]$ be a probability measure. Is there a probability measure $$\bar{\mu}:{\cal P}({\cal P}(X))\to [0,1]$$ with the following property?

For all $S\subseteq X$ we have $\bar{\mu}({\cal P}(S)) =\mu(S)$.

A: If $|X|>2$, then there is a single solution: $\overline{\mu}(\{x\})=\mu(x)$ and $\overline{\mu}(S)=0$ for any other set $S$.
Indeed, let $a=\overline{\mu}(\emptyset)$. By the condition for $S=\{x\}$, $\overline{\mu}(\{x\}) =\mu (x)-a$. By the condition for $S=\{x,y\}$ with $x\neq y$, $\overline{\mu}(\{x,y\}) =a$.
Now if $|X|>2$, there are at least $1+|X|$ two-element subsets. Thus, $\sum_{|S|\leq 2} \overline{\mu}(S) \geq a+ \sum_{x\in X}\mu (x) =1+a$. This forces $a=0$.
Now it is easy to show that for all larger subsets $\overline{\mu}(S)=0$.

A: For notational and conceptual simplicity, assume that $X$ and $P(X)$ are disjoint.
As Bugs Bunny implicitly suggested:
Let $\mathcal E = \{\{n\}:  n \in X \}$ be the set of singletons.  This is a subset of $P(X)$. The measure $\bar\mu$ will concentrate on this set.
For any $\mathcal A \subseteq P(X)$, we will have $\bar \mu(\mathcal A)=\bar \mu(\mathcal A\cap\mathcal E)$;  note that $\mathcal A\cap\mathcal E$ is morally the same as a subset of $X$, so $\mu$ will measure it.
Formally, let $S_{\mathcal A} = \{n\in X: \{n\}\in \mathcal A\}$ be the ``singleton support'' of $\mathcal A$.  Define $\bar \mu (\mathcal A) := \mu(S_{\mathcal A})$.


text:
Q: Number of couples sitting at same table The Problem
$ab$ couples are sitting at $a$ tables with $2b$ seats each. Call a couple a "good" couple if they are seated at the same table.
(1) What is the probability that, in total, there are exactly $k$ "good" couples?
My Approach so Far
Recurrence Relations One possible approach is to set up a recurrence relation, with $p_{a,b,n}$ denoting the probability of having exactly $k$ "good" couples. However, the issue with this is to recurrence equation between $p_{a+1,b,k}$ and $p_{a,b,k}$ will not be simple as one will have to consider the different combinations of people on the additional table.
Principle of Inclusion and Exclusion Another possible approach is to use PIE. We denote $P_S$ as the probability that only the couples in $S$ are good. While $P_S$ for $|S|=1$ is easy ($P={b-1}/{ab}$), I'm not sure how to proceed.

A: Recall: $a$ tables, $2b$ people at each table. Label the couples $1,\ldots,ab$. Define the event $C$ as follows:
$$
C = \{\mbox{couples $1,\ldots,k$ are good and all others are bad}\}.
$$
By symmetry, observe that
$$
\mathbb{P}(\mbox{exactly $k$ good couples}) = \left(\begin{array}{c}
ab \\ k
\end{array}\right)\
\mathbb{P}(C).
$$
We'll compute $\mathbb{P}(C)$ with an inclusion-exclusion argument.
Let $\pi_n$ be the probability that couples $1,\ldots,n$ are good (regardless of whether any other couple is good). Note that by symmetry again, $\pi_n$ is the probability that any particular set of $n$ couples are good. Define the events $A$ and $A_n$ as follows for $n=k+1,\ldots,ab$:
\begin{eqnarray}
A &=& \{\mbox{couples $1,\ldots,k$ are good} \} \\
A_n &=& \{\mbox{couples $1,\ldots,k$, and $n$ are good}\}.
\end{eqnarray}
Observe
$$
C = A \setminus \bigcup_{i=k+1}^{ab} A_i.
$$
Inclusion-exclusion:
$$
\mathbb{P}(C) = \mathbb{P}(A) - \sum_{t=1}^{ab-k} \sum_{i_1,\ldots,i_t} (-1)^{t+1} \mathbb{P}(A_{i_1}\cap\cdots\cap A_{i_t}).
$$
Again by symmetry, $\mathbb{P}(A_{i_1}\cap\cdots\cap A_{i_t})=\pi_{k+t}$, and there are $\left(\begin{array}{c}ab - k \\ t\end{array}\right)$ terms of this form in the sum above. Thus, we may write
$$
\mathbb{P}(C) = \sum_{t=0}^{ab-k} (-1)^t\ \left(\begin{array}{c}ab - k \\ t\end{array}\right) \ \pi_{k+t}.
$$
We can move on to computing $\pi_n$.
Let us count the number of ways in which each of the $2ab$ people can be assigned tables in which couples $1,\ldots,n$ are good. Suppose that among these $n$ couples, $n_1$ are seated at table 1, $n_2$ at table 2, $\ldots$, and $n_a$ are seated at table $a$. Thus, $n_1+\cdots +n_a = n$. There are $\left(\begin{array}{c}n \\ n_1,\ldots,n_a\end{array}\right)$ ways of choosing which of the $n$ couples sit at which table. There are $\left(\begin{array}{c}2ab-2n \\ 2b-2 n_1,\ldots,2b-2n_a\end{array}\right)$ ways to choose the tables at which the remaining $2ab-2n$ people sit. Thus, the total number of ways of assigning people to tables in such a way that couples $1,\ldots,n$ are good is
$$
\sum_{n_1+\cdots+n_a=n} \ \left(\begin{array}{c}n \\ n_1,\ldots,n_a\end{array}\right)\ \left(\begin{array}{c}2ab-2n \\ 2b-2 n_1,\ldots,2b-2n_a\end{array}\right).
$$
The total number of ways of assigning all $2ab$ people is just $\frac{(2ab)!}{(2b)!^a}$. Thus,
$$
\pi_n = \frac{(2b)!^a}{(2ab)!} \sum_{n_1+\cdots+n_a=n} \ \left(\begin{array}{c}n \\ n_1,\ldots,n_a\end{array}\right)\ \left(\begin{array}{c}2ab-2n \\ 2b-2 n_1,\ldots,2b-2n_a\end{array}\right).
$$
Alternatively, note that $\pi_n$ can be written
$$
\pi_n = \frac{(2b)!^a \ n! \ (2ab - 2n)!}{(2ab)!} C_n
$$
where $C_n$ is the coefficient of $X^n$ in the polynomial
$$
\left(\sum_{i=0}^b \frac{1}{i! (2b - 2i)!} X^i\right)^a.
$$


text:
Q: Fake the date in header when printing in Chrome? When printing a webpage to PDF in Google Chrome, the header includes the date of the print by default.
Is there any way this date info can be faked?

A: Yes, by setting your computer's clock backwards. Or by editing the PDF file using one of the dozens of (free and paid) PDF authoring tools that are available.
There are ways to detect that a PDF file has been edited after creation – for example, there are actually a few more timestamps in a PDF file (not just on the page, but also in metadata) – but none of those would reveal whether it was simply "printed" with the clock showing the wrong date.
If there is a need to prove that the PDF was created no later than a specific date, then various "trusted timestamping" services could be used.


text:
Q: elliptic pde question Suppose $\Omega$ is a smooth bounded domain in $ R^N$ and suppose  we have
$$-\Delta u(x) = (u(x)_+)^3 \qquad \mbox{ in } D$$
and $$ -\Delta u(x) = (u(x)_-)^3 \qquad \mbox{ in }  \Omega \backslash \overline{D}$$
where $D$ is some unknown open set which is contained in $\Omega$ (assume it has smooth boundary).     Here $ u = u_+ + u_-$ and $ u_+, u_- \ge 0$ (note $u_-$ is not quite the usual negative part of $u$).
Let $\Omega_+:=\{x \in \Omega: u(x)>0 \}$.
Question.  Suppose $u$ is somewhat nice (so assume $ u \in H_0^1(\Omega)$) and maybe a little more. Is $D=\Omega_+$?  (Of course if we take $u$ smooth then this might be trivial by using continuity of $ x \mapsto \Delta u(x)$ and the pde.)
I have tried some (what i consider) natural approaches but I don't seem to be getting anywhere yet I think this is probably a trivial question.


text:
Q: How / Where can I see all TSLint errors for current project in WebStorm? May be I am missing something but I have not found a dedicated place in WebStorm where I can see (and navigate) all errors reported by TSLint.
In the best case I can find the errors while opening a file and pressing F2 (to go to Next Highlighted Error) which not always working as well.
PS. There is a dedicated TypeScript Pane/l in WebStorm but it doesn't show any TSLint errors, neither these reported in Event Log Pane/l.

A: *

*Select npm tab  from the bottom left side.

*Run linting script (you must have it in package.json).
See screenshot below for example:
List of tslint errors/warnings


text:
Q: Get the error from Fragment with different activities when passing data using bundle I am using Bundle to passing data from my MainActivity to Fragment but it prompts out with the JAVA.NULLPOINTER.EXCEPTION. Error is occur when IgetArguments()` in list_fragments2 in second activity
MainActivity
list_fragment2 fragment = new list_fragment2();
Bundle b = new Bundle();
b.putString("test","text");
fragment.setArguments(b);
Toast.makeText(this, "" + b, Toast.LENGTH_SHORT).show();

list_fragment2
String name = getArguments().getString("test");
ntab2.setText(name);

Logcat
01-02 07:19:52.549 15797-15797/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                      java.lang.NullPointerException
                  at net.simplifiedcoding.androidtablayout.Tab2.list_fragment2.onCreateView(list_fragment2.java:62)
                  at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
                  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
                  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
                  at android.support.v4.app.Fragment.performStart(Fragment.java:1983)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1102)
                  at android.support.v4.app.FragmentManagerImpl.performPendingDeferredStart(FragmentManager.java:926)
                  at android.support.v4.app.FragmentManagerImpl.startPendingDeferredFragments(FragmentManager.java:1272)
                  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1630)
                  at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
                  at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
                  at android.support.v4.view.ViewPager.populate(ViewPager.java:1106)
                  at android.support.v4.view.ViewPager.populate(ViewPager.java:952)
                  at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1474)

A: Here is solution you have to change a little code in list_fragment2
First you have to make bundle and then get String like
Bundle bundle = getArguments();
    if (bundle != null) {
    String name = bundle.getString("test");
    ntab2.setText(name);
  }

Problem solve.

A: change this line of your code.

String name = getArguments().getString("test");

to

String name = this.getArguments().getString("test");

it will work.

A: On your second fragment use like this
call getArguments() in your List_fragment2's onCreateView() metod:
 public View onCreateView(LayoutInflater inflater,ViewGroup containerObject,
         Bundle savedInstanceState){
         //here is your arguments
         Bundle bundle=getArguments();

        //your string
        String test=bundle.getString("test");
     }
}


text:
Q: How to define keyspaces for a timeseries data in Cassandra? There are 100s of data points, each data point has its own seperate table with schema and queries as mentioned below:
Current Schema in SQLite

*

*Table Name: Name of Data Point e.g. Tempearature

*Column-1: Name: Timestamp Type: TEXT (yyyy-MM-dd HH:mm:ss.ttt format) PRIMARY KEY

*Column-2: Name: Value Type: FLOAT

*Column-3: Name: Quality Type: TEXT ("GOOD", "BAD")

Queries for SQLite

*

*SELECT * FROM data-point-name;

*SELECT * FROM data-point-name WHERE Timestamp BETWEEN timesamp-1 AND timestamp-2;

*INSERT INTO data-point-name (Timestamp, Value, Quality) VALUES ("2016-01-01 00:00:05.254", 123.25454, "GOOD"); (this is an example)

Currently I have SQLite db where I have a table per data-point with above schema, essentially I have 100s of tables. This way reads/writes are not disturbing queries running on different data-points.
How to translate this schema to be used in Cassandra?

A: In your case, you can store all your data points in a single table :
CREATE TABLE datapoints (
    datatype varchar(30),
    time timestamp,
    value float,
    quality varchar(4),
    PRIMARY KEY (datatype, time)
);

With this structure, you can run queries like :
SELECT *
FROM datapoints
WHERE datatype = 'data-point-name';

SELECT *
FROM datapoints
WHERE datatype = 'data-point-name'
   AND time >= '2016-01-01 00:00:00'
   AND time <= '2016-01-02 00:00:00';

But with this structure, cassandra will partition data by datapoint name,
if you have many points, your partition will be huge and you can have query performence issues.
You can also refine the partitionning by decompose the time :
CREATE TABLE datapoints (
   datatype varchar(30),
   year int,
   month int,
   day int,
   milisecondsinday int,
   value float,
   quality varchar(4),
   PRIMARY KEY ((datatype, year, month, day), milisecondsinday)
) WITH CLUSTERING ORDER BY (milisecondsinday ASC);

In this case, this structure allow cassandra to store datas in more small partition than the first exemple and it's more powerfull if you query you data by day :
SELECT *
FROM datapoints
WHERE datatype = 'data-point-type'
   AND year = 2016
   AND month = 1
   AND day = 1;

get all points for 'data-points-type'
for the 2016-01-01
between 00:00 AM and 01:00 AM
SELECT *
FROM datapoints
WHERE datatype = 'data-point-type'
   AND year = 2016
   AND month = 1
   AND day = 1
   AND milisecondsinday >= 0
   AND milisecondsinday <= 3600000;

Of course, you can partition by day (like exemple) or others time scale (hours, minutes, seconds and miliseconds). If you can, small partition will be good for performence.
Hope this can help you.


text:
Q: jquery conflict in custom wordpress plugin using jquery in my custom WordPress plugin on init I get the following error Type Error: $.effects.effect is undefined. Another problem: live event is getting ignored and I'm getting jQuery(...).live is not a function. I have been trying to load in my plugin the newest Jquery but even like that the problem persist
public function init()
    {
        wp_deregister_script('jquery');
        wp_register_script('jquery', ("http://code.jquery.com/jquery-1.9.1.js"), false, '');
        wp_enqueue_script('jquery-ui-js', 'http://code.jquery.com/ui/1.10.1/jquery-ui.js');
        wp_enqueue_script('jquery');
        wp_enqueue_script( 'konfigurator_ajax', plugin_dir_url( __FILE__ ) . 'config.js', array( 'jquery' ) );
        wp_localize_script( 'konfigurator_ajax', 'Konfigurator', array(
                'ajaxurl' => admin_url( 'admin-ajax.php') ,
                'nonce' => wp_create_nonce( 'konfigurator_ajax-nonce' )
        ) );

A: I dont see your config.js but I think it uses jQuery UI effect. You need to separate register and enqueue for right wp_enqueue_script work. Also your code is non-WP standart, im suggest you to use this code (right-installed WordPress 3.5+):
public function init() {
   wp_register_script('konfigurator_ajax', plugin_dir_url(__FILE__) . 'config.js', array( 'jquery', 'jquery-ui-core', 'jquery-effects-core' ));
   wp_localize_script( 'konfigurator_ajax', 'Konfigurator', array(
       'ajaxurl' => admin_url( 'admin-ajax.php') ,
       'nonce' => wp_create_nonce( 'konfigurator_ajax-nonce' )
   ));
}
add_action('admin_init', 'init'); //or if OOP add_action('admin_init', array(&$this, 'init'));

public function print_scripts() {
    wp_enqueue_script('jquery-ui-core');
    wp_enqueue_script('jquery-effects-core');
    wp_enqueue_script('konfigurator_ajax');
}
add_action('admin_print_scripts', 'print_scripts'); //or if OOP add_action('admin_print_scripts', array(&$this, 'print_scripts'));


text:
Q: Multiple conditions in custom format I would like to have multiple formatting conditions eg.
561 -> 561
1,100 -> 1.10K
2,220,000 -> 2.22M
45,200,000 -> 45.20B

I came up with following solution but it wont work:
[>=1000000000]#.00,,,"B";[>=1000000]#.00,,"M";[>=1000]#.00,"K";###

What can be done in this situation?

A: I would go with conditional formatting rules instead of custom formatting. The difference is actually in the words themselves -> Conditional vs Custom.

"Excel custom number formats have a specific structure. Each number
  format can have up to four sections, separated with semi-colons as
  follows:" Exceljet

*

*1) Positive values

*2) Negative values

*3) Zero values

*4) Text values

Since you have specified conditions for different types of positive values it won't fit in the custom format parameters! Go for conditional formatting instead, with three rules applied on e.g. column A:A:

*

*If value is greater or equal to 1000 then custom format: #.00,"K"

*If value is greater or equal to 1000000 then custom format: #.00,,"M"

*If value is greater or equal to 1000000000 then custom format: #.00,,,"B"
Put them in, in this order so on column A:A the order of the rules is reversed!

Mind you, in above example you'll notice my system uses a comma as seperator!


text:
Q: Are fixed positioned images what I need? Im having some issues with some fixed/absolute positioned images.
Please see the example for reference:
http://www.warface.co.uk/clients/warface.co.uk/
At the moment they are correctly positioned, but when the user clicks the red arrow box (top centre) you'll notice that the fixed positioned images are static and don't slide down the page as desired. Im sure they have to be positioned relative but they all seem to jump around when the browser is re-sized.
Any ideas on suggested methods are much appreciated :)
Many thanks
CSS
.minipeak {
    background: url("styles/images/home-peak2.png")no-repeat 0 0;
    width:206px;
    height:138px;
    display:block;
    float:right;
    top:288px;
    right:91%;
    position: fixed;
    z-index: 0;
    }
.twinpeaks {
    background: url("styles/images/home-peaks.png")no-repeat 0 0;
    width:624px;
    height:349px;
    display:block;
    position:fixed;
    float:left;
    left:56%;
    top:220px;
    z-index: 0;
    overflow: hidden;
    }
.riflebg {
    background: url("styles/images/home-rifle2.png")no-repeat 0 0;
    width:254px;
    height:199px;
    display:block;
    top:110px;
    left:330px;
    position: relative;
    float:left;
    z-index: 1;
    }
.tank {
    background: url("styles/images/home-tank.png")no-repeat 0 0;
    width:520px;
    height:285px;
    display:block;
    top:150px;
    overflow: hidden;
    right:-340px;
    position:relative;
    z-index: 2;
    float:right;
    }
.snipers {
    background: url("styles/images/home-snipers.png")no-repeat 0 0;
    width:520px;
    height:285px;
    display:block;
    top:230px;
    right:66%;
    float:right;
    position:fixed;
    z-index: 3;
    }
.privatejoker {
    background: url("styles/images/home-privatejoker.png")no-repeat 0 0;
    width:421px;
    height:397px;
    display:block;
    top:80px;
    position: absolute;
    float:left;
    z-index: 4;
    }
.rifle {
    background: url("styles/images/home-rifle.png")no-repeat 0 0;
    width:520px;
    height:285px;
    display:block;
    top:250px;
    left:330px;
    position: absolute;
    float:left;
    z-index: 5;
    }

A: Create a parent container that wraps all your "main"-Content (snipers etc) and make it position: relative; (so all "absolute" childs refer to this as the anchor.
Use position: absolute; on all your elements (sniper etc) and tweak the positions via left/right/top/bottom OR (negative) margins to bring everything back to its position again.
Your "jump around" can be explained since you use relative values (percentages) in some places - these will depend on viewport size. Either you use constant pixel-values or you accept the fact, that most people won't resize the window while browsing your site.

A: Your 'snipers' & 'twinpeaks' are outside of the wrapper hence why it did not slide together whenever you click to slide down.
Try putting it inside the wrapper along with the 'rifle', 'privatejoker' & such (^_^)


text:
Q: What is a simple C library for a set of integer sets? I've got to modify a C program and I need to include a set of unsigned integer sets.  That is, I have millions of sets of integers (each of these integer sets contains between 3 and 100 integers), and I need to store these in some structure, lets call it the directory, that can in logarithmic time tell me whether a given integer set already exists in the directory.  The only operations that need to be defined on the directory is lookup and insert.
This would be easy in languages with built-in support for useful data structures, but I'm a foreigner to C and looking around on Google did (surprisingly) not answer my question satisfactorily.  This project looks about right:
http://uthash.sourceforge.net/
but I would need to come up with my own hash key generator.
This is a standard, simple problem, so I hope there is a standard and simple solution.

A: It depends on what you are going to do with the data. But maybe tsearch does already what you want. You could also build a sorted array for each set and look up the values with bsearch, although the performance may suffer during the insertion.
EDIT: If you are looking for an (external) library, you'll find a comparision of some C and C++ hash table implementation here. The author of the article has written a generic header implementation called khash. So you're compiled binary don't have any additional dependencies.

A: EDIT: sorry, I started answering as it's C++ and not C. Yes then you should find your hash function and code it by yourself.. since you already know the average dimension of a set it's not so difficult, just choose a good hash function! But you'll need to codify a whole set in a single number if you want to check if a directory is already there.
You can try by iteratively hashing the single numbers of the set:
int hashcode = initvalue
for (int i = 0; i < 0; ++i)
  hashcode = calc_code(hashcode, number_set[i], i);

in a way that the hashfunction depends on its previous value, the current number and the current index.
What about STL sets?
#include <set>

int nums[6] = {1,6,34,2,67,41};
set<int> numbers;

for( int i = 0; i < 6; ++i ) numbers.insert(nums[i]);

for( set<int>::const_iterator iter = numbers.begin(); iter != numbers.end(); ++iter )
  cout << *iter << ' ';

Using this data structure you can easily store all your sets, but you need also a way to check if a set is already included in the directory. It's not clear: do you want to know if a set that have all the SAME elements exists already in the directory?
You can do it manually by checking all the elements but since you have millions of them you should find a way to hash the elements of the set in an unique number and use a map of sets..

A: If I understand you correctly, you want to represent a set of sets of integer which I don't think is particularly trivial.
The first point is to represent a set of integers. The simplest way would be use a variable size array like this:
typedef struct {
  int size;
  int elems[1];
} intset;

than you can create a new set (with a fixed number of elements) with
intset *newset(int size)
{
  intset *set;
  set = malloc(sizeof(intset) + sizeof(int)*(size-1));
  if (set) set->size = size;
  return set;
}

and store the elements with set->elems[0]=i1; ....
Another option would be to use bit arrays but the implementation would depend of the nature of the integers to store (e.g. are they within a fixed range? Do they usually appear in groups in a set?).
Once you have your set of integers you will need a compare function (to determine whether two sets have the same elements). If you opted for an array to represent a set and you keep that array sorted, is quite simple to check if two sets are identical; if it's a bitmap, it will depend on how you implemented it.
Now, for the set of sets you can choose a (sorted) vector, that you might need to resize from time to time while inserting elements, or an hash table.  In the latter case you'll need to write an hash function for your sets of integer (possibly using existing functions!).
As I said, it seems not trivial to me, I'm not surprised google didn't help.
It's not extremely complicated, though, you just have to take some decisions before proceeding.

A: Implement a simple hash table yourself. It will make you a better programmer, when you know how to implement one on your own.
http://en.wikipedia.org/wiki/Hash_table


text:
Q: I can't access frontend or backend after changing file/directory permissions I installed Magento 1.9.2.4 and completed all the instructions in the "Setting Privileges and Ownership After You Install Magento" section found here: http://devdocs.magento.com/guides/m1x/install/installer-privileges_after.html
Now I can't access any part of my website...did I miss a step?

A: what error can you see? Have you check logs?
You can open index.php at root and write echo "index.php"; exit; and can run website with index.php url.
One more thing you can do is run this script. it will set required folder/files permissions.
http://www.everyuseful.com/useful_tools/magento-cleanup.zip
Let me know if this works.

A: Go to the .htaccess file
#RewriteBase /magento/

remove comment from above line
RewriteBase /magento/

Change magento name with your sub directory name

A: it might be permission issue. You can try to set these permissions
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 711 {} \;
find ./media -type d -exec chmod 775 {} \;
find ./var -type d -exec chmod 775 {} \;
find ./media -type f -exec chmod 664 {} \;
find ./var -type f -exec chmod 664 {} \;
find ./media -type d -exec chmod u+s,g+s {} \;
find ./var -type d -exec chmod u+s,g+s {} \;
chmod 640 ./app/etc/*.xml
and check if the website will open.
Also when you are opening any different page, you need to have index.php on the url part.
So to include index.php on url, go to system->configuration->web->search engine optimisation. and disable 'Use Web Server Rewrites' Hope it helps.


text:
Q: Integration by parts for specific problem I am trying to do the following integral:
$$\int_0^L x \sin((m+\frac{1}{2})\frac {\pi x} {L}) dx$$
Where $m$ is an integer, $L$ a constant and $x$ a variable using integration by parts. I have first removed the bounds to make it an indefinite integral and set:
$$u = x,$$
$$du=dx,$$
$$dv = \sin((m+\frac 1 2)\frac {\pi x} {L})\,dx$$
and
$$v = \frac{-L}{(m+\frac 1 2)\pi}\cos((m+ \frac 1 2)\frac {\pi x} {L})$$
assuming $\int u \,dv = uv-\int v \,du$
$$\int x \sin((m+\frac{1}{2})\frac {\pi x} {L}) \,dx=\frac{-Lx}{(m+\frac 1 2)\pi}\cos((m+ \frac 1 2)\frac {\pi x} {L})+ \int \frac{-L}{(m+\frac 1 2)\pi}\cos((m+ \frac 1 2)\frac {\pi x} {L})\,dx$$
The integral on the right hand side easily solved by substitution:
$$\frac{-Lx}{(m+\frac 1 2)\pi}\cos((m+ \frac 1 2)\frac {\pi x} {L})+ \frac{L^2}{(m+\frac 1 2)^2\pi^2}\sin((m+ \frac 1 2)\frac {\pi x} {L})$$
Now reverting to the definite integral:
$$\biggl[\frac{-Lx}{(m+\frac 1 2)\pi}\cos((m+ \frac 1 2)\frac {\pi x} {L})+ \frac{L^2}{(m+\frac 1 2)^2\pi^2}\sin((m+ \frac 1 2)\frac {\pi x} {L})\biggr]^L_0$$
Which simplifies to:
$$\biggl[\frac{-L^2}{(m+\frac 1 2)\pi}\cos((m+ \frac 1 2)\frac {\pi L} {L})+ \frac{L^2}{(m+\frac 1 2)^2\pi^2}\sin((m+ \frac 1 2)\frac {\pi L} {L})\biggr]-\biggl[\frac{-L(0)}{(m+\frac 1 2)\pi}\cos((m+ \frac 1 2)\frac {\pi (0)} {L})+ \frac{L^2}{(m+\frac 1 2)^2\pi^2}\sin((m+ \frac 1 2)\frac {\pi (0)} {L})\biggr]$$
The expression in the second square bracket is $0$. The expression in the first square bracket simplifies to:
$$\biggl[\frac{-L^2}{(m+\frac 1 2)\pi}\cos((m+ \frac 1 2)\pi)+ \frac{L^2}{(m+\frac 1 2)^2\pi^2}\sin((m+ \frac 1 2)\pi)\biggr]$$
The first term in the above expression is equal to $0$ for any integer $m$ and thus we are left with:
$$\int x \sin((m+\frac{1}{2})\frac {\pi x} {L}) \,dx = \frac{L^2}{(m+\frac 1 2)^2\pi^2}\sin((m+ \frac 1 2)\pi)$$
I have run this integral through a symbolic software package (SymPy) which output the following result:
$$\begin{cases}0,&m=0\\-\frac{L^2}{\pi m} \cos(\pi m) + \frac{L^2}{\pi^2 m^2}\sin(\pi m), &\text{otherwise}\end{cases}$$
I am not happy with this because plugging in $m = 5$ and $L=2$ yields a result of $0.255$ for the SymPy result and $-0.0134$ for my hand result. Which is right and if they are both right how come there are two different results? It seems to me only one can exist for this integral.


text:
Q: distroless java docker image error When I attempt to create a docker image using the distroless java base image,
I get the following error when I include any shell command like 'mkdir' , 'chmod'
any help on this is really appreciated.

OCI runtime create failed: container_linux.go:348: starting container process caused "exec: \"/bin/sh\": stat /bin/sh: no such file or directory": unknown

A: distroless provides a debug image that contains a shell so that you can exec into it:
gcr.io/distroless/java:debug

The debug images contain busybox. You can run this image with Docker by:
docker run -it --entrypoint "/busybox/sh" gcr.io/distroless/java:debug

If you would like to build a Java Docker image directly in a Maven or Gradle project using distroless as the base, check out Jib.

A: If you look at the list of things in the distroless base image it just doesn't include a shell, or mkdir, or chmod, or anything else like that.  The Java image adds the JVM, and that's it.  It's probably not going to be possible to build an image based on that that does much more than COPY in a prebuilt jar and set a CMD to point to it, maybe setting some default ENV variables along the way.
If you need the base tools that are included in a standard Linux distribution, then you want to start from a more featureful base image like the standard openjdk image.

A: distroless provides a debug image that contains a shell . In pom or running docker from command prompt :
Steps as below :
Pom Change :
<from>
    <image>gcr.io/distroless/java:11-debug</image>
</from>

docker command:
docker exec -it  sh


text:
Q: How to detect in post.message null var? Hello I need detect if child.php not send message to parent.php, I use the post.message .
I try with:
if (message == null), == false, == "", but not work ..

My code:
parent.php (get the message "work" from child.php if its open)
<button id="open-child-window-2">Open Child Window</button>

<script>

var __CHILD_WINDOW_HANDLE_2 = null;

$("#open-child-window-2").on('click', function() {
    __CHILD_WINDOW_HANDLE_2 = window.open('child-2.php', '_blank');
});

window.addEventListener('message', function(e) {
    ProcessChildMessage_2(e.data);
} , false);

function ProcessChildMessage_2(message) {
    alert(message);
}

</script>

child.php (send to parent.php the message "work" every 0.5 seconds)
<script>

setInterval(function(){

    window.opener.postMessage("work", "*");

},500);

</script>

I need detect if chiel.php not send "work" to parent.php, for example:

*

*if closed the child.php

*if go another page from the child.php

Thanks you so much

A: Then why don't you use [window.onbeforeunload](https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload)?
(Yesterday my reputation is 53 and it fell to 49 again today so I can't comment.)