text:
Q: "Almost uniformly convergent" Implies "Uniformly convergent almost everywhere" . Is there something wrong? I find a tricky proof shows "almost uniformly convergent" implies "uniformly convergent almost everywhere". I know it is wrong, for there is a counterexample. Can anyone help me why this proof is wrong?
I got the inspiration from the proof that shows "almost uniformly convergent" implies "convergent almost everywhere":
It says $\forall \epsilon, \exists B_\epsilon, \mu(B_\epsilon)<\epsilon$ outside of which $f_n$ converges uniformly to $f$ and prove $B\equiv\bigcap_{n\in\mathbb{N}}B_{\frac{1}{n}}$ is zero-measure. I think in this case, outside $B$, $f_n \to f$ no only converges pointwise (as the proof says) but also converges uniformly (for it is true outside any $B_\frac{1}{n}$). Since $\mu(B)=0$, it implies $f_n \to f$ converges uniformly almost everywhere.

A: Consider a simple example:
$x^n \to 0$ almost uniformly on $[0,1]$. Indeed, for every $\varepsilon > 0$ we have $x^n \to 0$ uniformly on $B_\varepsilon^c = [0,1-\varepsilon]$ where $B_\varepsilon = [1-\varepsilon, 1]$ has measure $\varepsilon$.
However on $$B^c = \left(\bigcap_{n=1}^\infty B_{\frac1n}\right)^c = \left(\bigcap_{n=1}^\infty \left[1-\frac1n,1\right]\right)^c = \{1\}^c = [0,1\rangle$$ the convergence $x^n \to 0$ is not uniform. It is only uniform on segments $B_{\frac1n}^c=\left[0,1-\frac1n\right]$.

A: You have that $\{f_n\}$ converges uniformly on each set $B_{\frac 1n}^c$. There is no reason why it should converge uniformly on $\displaystyle \bigcup_n B_{\frac 1n}^c$.


text:
Q: Google Spreadsheet formatting a column to turn into multiple ones by splitting them I have a Google Spreadsheet that has many, many rows that look like this:
Abdrashitov         Ablai        DLPNQ915    1138     4    0    OR
These are all in one cell though. I am trying to get it to be the same values in different cells.
This is what I have tried:
=SPLIT(ARRAYFORMULA(Info!A1:A982), "") (Info! is the sheet the values are in)
After this, I get the error:
Function SPLIT parameter 1 value should be non-empty.

Which does not allow me to do this. I have tried googling and looking through StackOverFlow, though I cannot find anything...
The closest thing that I was able to find was this:
=ARRAYFORMULA(IFERROR(REGEXEXTRACT(" "&Info!A1:A982,
"^"&REPT("\.[^ ]*",COLUMN(OFFSET(Info!A1,,,1,4))-1)&"\.([^ ]*)")))

Though, it does not do anything and stays blank.
Thanks for the help!

A: Try this:
=transpose(split(join(" ",Info!A1:A)," "))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Add animation when elements are moved I am learning Javascript and jQuery now, and I ran into the following problem:
I have a script that adds boxes to the screen, and they always stay in center. Lets assume I have added one box and it is horizontally aligned in center. Now when I add another box, the first box will automatically move a little to the left, so that they both are aligned in the center. In my case this movement to the left is instantaneous. How can I add animation to it?
<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="sort.css">

<Title>Sorting</Title>

<input type="button" id="done" value="Done"></input>
<input type="text" id="entry"></input>

Javascript:
$(document).ready(function(){

    //Done button clicked
    $("#done").on('click', function(){
        //Action code goes here!
        getNumbers();

        //Hide all the numbers
        $(".boxed:not(.onScreen)").css({
            display : 'none'
        });
        $('.boxed').fadeIn(1000).addClass("onScreen");

    });

    $("#entry").on("keyup", function(){

        if(event.keyCode == 13){
            $("#done").click();
        }

    });

});

//For every Number in the array wil create a box with two classes: "onScreen and boxed"
function addElement(numbers){
    console.log("addElement " + numbers);

    for(var i = 0; i<numbers.length; i++){

        if (isNumber(numbers[i])){
            console.log("Creating element " + numbers[i]);
            var para = document.createElement("div");
            para.className = "boxed";
            var node = document.createTextNode(numbers[i]);
            para.appendChild(node);
            var element = document.getElementById("array");
            element.appendChild(para);

        }
    }

}

//Will get the numbers from the input.
//Will pass an array of elements to addElement
function getNumbers(){
    console.log("getNumbers");
    var elements = document.getElementById("entry").value;
    document.getElementById("entry").value = "";
    var numbers = elements.split(",");
    console.log(numbers);
    addElement(numbers);

}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

CSS:
body{
    background-color: #DDE9E9;
}

.boxed{
    margin-right: 5px;
    margin-left: 5px;
    margin-top: 10px;

    border: 0px solid #232525;
    border-radius: 15px;

    width: 20px;
    height: 20px;
    padding: 25px;

    text-align: center;

    background-color: grey;
    color: white;
    box-shadow: 2px 2px 20px #888888;

    display: inline-block;
}

.onScreen{

}

#array{

    text-align: center;

}

Adding transition to an array did not work. For some reason it also appears blurred in chrome developer window

A: To make this possible with your code took a bunch edits but basically, I've added a wrapper around each box (so that the width can be set to 0), then I applied the box-shadow and margins to the containers. Next set width to 0  > Insert into document > set width to natural (I had to do a check by moving the box outside of the document to get the width then set to 0 and move back into the document).

$(document).ready(function() {
  //Done button clicked
  $("#done").on('click', function() {
    //Action code goes here!
    getNumbers();
  });
  $("#entry").on("keyup", function() {
    if (event.keyCode == 13) {
      $("#done").click();
    }
  });
});
//For every Number in the array wil create a box with two classes: "onScreen and boxed"
function addElement(numbers) {
    console.log("addElement " + numbers);
    for (var i = 0; i < numbers.length; i++) {
      if (isNumber(numbers[i])) {
        console.log("Creating element " + numbers[i]);
        var wrap = document.createElement("div");
        wrap.className = "boxed";
        var para = document.createElement("div");
        para.className = "boxed-inner";
        var node = document.createTextNode(numbers[i]);
        para.appendChild(node);
        wrap.appendChild(para);
        wrap.style.visibility = 'hidden';
        wrap.style.left = '-100%';
        var element = document.getElementById("array");
        element.appendChild(wrap);
        var width = window.getComputedStyle(wrap, null).width;
        wrap.style.width = '0px';
        wrap.style.left = '0px';
        wrap.style.visibility = 'initial';
        wrap.style.opacity = '0';
        $(wrap).animate({
          'opacity': '1',
          'width': width
        });
      }
    }
  }
  //Will get the numbers from the input.
  //Will pass an array of elements to addElement

function getNumbers() {
  console.log("getNumbers");
  var elements = document.getElementById("entry").value;
  document.getElementById("entry").value = "";
  var numbers = elements.split(",");
  console.log(numbers);
  addElement(numbers);

}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
body {
  background-color: #DDE9E9;
}
.boxed {
  display: inline-block;
  overflow: hidden;
  position: relative;
  border-radius: 15px;
  box-shadow: 2px 2px 20px #888888;
  margin-right: 5px;
  margin-left: 5px;
  margin-top: 10px;
}
.boxed-inner {
  border: 0px solid #232525;
  border-radius: 15px;
  width: 20px;
  height: 20px;
  padding: 25px;
  text-align: center;
  background-color: grey;
  color: white;
  box-shadow: 2px 2px 20px #888888;
  display: inline-block;
}
#array {
  text-align: center;
}

<input type="button" id="done" value="Done">
<input type="text" id="entry">

A: You need to transition the width of the added box. Start the newly added box with width 0 and animate/transition it to be full width.

A: To build on humble.rumble.6x3's answer, you can add the transition value, add your selectors, timing, and easing. Then, you can use javascript to set the value of anything and animate it. Just note that CSS3 animations are only supported with newer browsers.


text:
Q: Java Convert UTC Date to local Date with Joda This code is working, but I want to use Joda-Time
public static Date dateFromUTC(Date date){
        return new Date(date.getTime() + Calendar.getInstance().getTimeZone().getOffset(date.getTime()));
    }

I tried this, but it's not working - what's the problem with this?
public static Date dateFromUTC(Date date){
        return new DateTime(date).withZone(DateTimeZone.getDefault()).toDate();
    }

A: tl;dr
Use java.time classes instead.
Instant.now()        // Capture current moment in UTC. Always in UTC, by definition.

…and…
ZonedDateTime.now()  // Capture current moment as seen through the wall-clock time of the people in the region of the time zone used by default in this JVM.

Details
As others said, you misunderstood the concepts involved in these classes. A java.util.Date represents a moment in UTC, always in UTC†, never in some other time zone. So the code seen in the Question is non-sensical. You are working too hard!
java.time
The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. Many of the concepts are similar between Joda-Time and java.time as both projects are led by the same man, Stephen Colebourne.
When you are ready to migrate, use Instant in place of java.util.Date.
Instant instant = Instant.now() ;  // Capture the current moment in UTC.

instant.toString(): 2018-01-23T12:34:56.123456789Z

Instead of java.util.Calendar, use ZonedDateTime to represent a moment seen through the wall-clock time of a particular region (a time zone).
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment, same point on the timeline, different wall-clock time.

As a shortcut, you can skip the Instant if you want only the zoned time.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;  // Capture the current moment as seen by people in a certain time zone.

You can get to UTC from there by extracting an Instant object.
Instant instant = zdt.toInstant() ;  // Same moment, same point on the timeline, but viewed with the wall-clock time of UTC.

† Actually, there is a time zone assigned deep within a java.util.Date but is irrelevant to our discussion here. Confusing? Yes. One of many reasons to avoid the awful mess that is the old Date/Calendar and related legacy date-time classes.

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, Java SE 10, and later

*

*Built-in.

*Part of the standard Java API with a bundled implementation.

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

A: Try this:
new DateTime(date, DateTimeZone.UTC)
    .toLocalDateTime() // value without timezone
    .toDateTime() // convert to default timezone
    .toDate();

Your code actually does nothing to the date, because new DateTime(date) creates a DateTime object with default timezone. And then you just convert it back to java.util.Date.

A: First of all, read the article linked in the comments: https://codeblog.jonskeet.uk/2017/04/23/all-about-java-util-date/
A java.util.Date doesn't have a timezone. It actually represents a point in time: the number of milliseconds since unix epoch (Jan 1st 1970, at midnight, in UTC).
When you print the Date, though, it uses the JVM default timezone to convert the Date to date/time values, but the Date itself doesn't have a timezone.
That's why converting a Date object to another timezone doesn't make sense.
If you want to know the date (day, month, year) and time (hour, minute, second, millisecond) that corresponds to the Date in a specific timezone, then you can use Joda-Time:
// java.util.Date
Date date = new Date();

// the Date converted to UTC
DateTime utc = new DateTime(date, DateTimeZone.UTC);

// the Date converted to JVM default timezone
DateTime convertedToDefaultTz= new DateTime(date, DateTimeZone.getDefault());

The conversion can also be made using another DateTime:
DateTime convertedToDefaultTz = utc.withZone(DateTimeZone.getDefault());

Joda's DateTime has a timezone attached to it, so now it makes sense to convert to another one. But the Date objects returned by it will always be the same, because all of them represent the same instant (the same point in the timeline):
Date d1 = utc.toDate();
Date d2 = convertedToDefaultTz.toDate();
System.out.println(d1.equals(d2)); // true

All because - again - a Date doesn't have a timezone.


text:
Q: How to find out if this function is characteristic I need to find out if $\phi$ is a characteristic function
$$
\phi(t_1,t_2) = (p\cos(t_1+t_2) + 1 - p)^n, \quad 0 < p < 1, n \in \mathbb{N_{>0}}
$$
What I've tried:

*

*Instead I'm trying to prove that $p\cos(t_1+t_2) + 1 - p$ is characteristic because if it is then it's n-th power also is characteristic.

*I've tried converting $\cos$ to trig form and then doing Fourier transform to get p.d.f. and got
$$
p \pi \delta_{x-1} \delta_{y-1} +
p \pi \delta_{x+1} \delta_{y+1} +
2 \pi \delta_{x} \delta_{y} +
2 p \pi \delta_{x} \delta_{y}
$$
but I'm not sure if this is a p.d.f.

*Also, $\phi$ looks like a characteristic function of $Bin(n,p)$:
$$
{\displaystyle \!\,(1-p+pe^{it})^{n}}
$$
but I don't know if there is any connection between them.

A: You have the right hunch.
You can check the characteristic function of the following random variable:
$$X=(B_1+...+B_n,B_1+...B_n)$$
where $B,B_1,...,B_n$ are iid random variables, B equals 0 with probability 1-p, B equals 1 with probability p/2, -1 with probability p/2


text:
Q: Postgres casting between varchar and double precision suddenly stopped working I have been importing data into PostgreSQL tables all day using ogr2ogr and then spatially enabling the data with no issues up to now. I have been cutting and pasting the code and this is what I have been using:
ALTER TABLE mytable ADD COLUMN geom geometry(POINT,4326);
UPDATE mytable SET geom = ST_SetSRID(ST_MakePoint(cast (lon AS double precision),cast (lat AS double precision ) ),4326);

On the last table, I suddenly get this error:
ERROR:  invalid input syntax for type double precision: "#VALUE!"

Nothing has changed, at least as far as I know, I was importing a csv file, same as all the others.
I checked the csv file for spaces or unusual characters but it looks in order

Column lon, lon are of type character varying

here is a sample of the data
id,name,name_alt,lat,lon,description
1,Abbott Seamount,,31.8,174.3,A seamount located north of Midway Islands (US) in the North Pacific Ocean; name origin unknown.
2,Abra Canyon,,17.51667,120.36667,An undersea canyon located off the northwest coast of the Philippine island of Luzon in the South China Sea; named after the Abra River
3,Abraham Canyon,Abraham Sea Valley,52.61667,172.33333,An undersea canyon in the area of the Aleutian Islands in the North Pacific Ocean; named in association with Abraham Bay; Attu Island; Alaska (US).
4,Abrolhos Bank,,-18.5,38.75,A bank located off the coast of Brazil in the Atlantic Ocean; upon which sits the Arquipélago dos Abrolhos (archipelago).
5,Abrolhos Seamounts,Abrolhos Ridge; Cadeia dos Abrolhos,-17.33333,36.5,Seamounts located off the coast of Brazil in the Atlantic Ocean; named in association with the Abrolhos Bank and Arquipélago dos Abrolhos (archipelago).
6,Abubacer Ridge,,36.8,1.65,An undersea ridge located off the coast of Spain in the western Mediterranean Sea; named for Ibn Tufayl (known as Abubacer to Europeans); 12th-century Spanish-Arab philosopher and physician.
7,Aby Canyon,,4.25,-3.66667,An undersea canyon located off the coast of Côte d'Ivoire; named in association with Lagune Aby; Côte d'Ivoire (lagoon)

What am I missing here?

A: For future users:
This problem was caused by bad data. There was the "#" Character on one cell of the csv that I missed that just happened to be the word "#VALUE!" (actually generated by someones formula at one stage I would guess)
The error:
ERROR:  invalid input syntax for type double precision: "#VALUE!"

was being reported by PostgreSQL as that exactly what it was seeing in the data, which was invalid. I had a lot of rows and just missed it.
Moral of the story, check your data carefully. If preparing CSV files for uploading and later GeoSpatial uses, sort on the lat and lon columns, that will show any non numeric values in there quickly.


text:
Q: How to parse DNS Question field with python raw sockets? I'm trying to parse question field in a DNS packet where I can read domain and DNS response from a DNS server. I can extract a DNS header, but I'm having trouble to parse the question field because the size of the data is unknown.
I follow this example, but the part of extracting the question field is not working.

What I need is someone to show me the way to do it properly.
I have this code where everything is right...
This is my code:
#!/usr/bin/env python3
from socket import *
import struct
import binascii

def ethernet_frame(raw_data):
    mac_dest, mac_src, protocol = struct.unpack('! 6s 6s H',
    raw_data[:14])
    return byte_to_hex_mac(mac_dest), byte_to_hex_mac(mac_src),
            htons(protocol), raw_data[14:]

def byte_to_hex_mac(mac_bytes):
    addr = binascii.hexlify(mac_bytes).decode("ascii")
    return ":".join([addr[i:i+2] for i in range(0,12,2)])

def data_packet_udp(data):
    tuple_data_udp = struct.unpack('! H H H H', data[:8])
    port_src = tuple_data_udp[0]
    port_dest = tuple_data_udp[1]
    udp_len = tuple_data_udp[2]
    udp_checksum = tuple_data_udp[3]
    return port_src, port_dest, udp_len, udp_checksum, data[8:]

def data_packet_ipv4(data):
    tuple_data_ipv4 = struct.unpack("!BBHHHBBH4s4s", data[:20])
    version = tuple_data_ipv4[0]
    header_len = version >> 4
    type_service = tuple_data_ipv4[1]
    length_total = tuple_data_ipv4[2]
    identification = tuple_data_ipv4[3]
    offset_fragment = tuple_data_ipv4[4]
    ttl = tuple_data_ipv4[5]
    protocols = tuple_data_ipv4[6]
    checksum_header = tuple_data_ipv4[7]
    ip_src = inet_ntoa(tuple_data_ipv4[8])
    ip_dest = inet_ntoa(tuple_data_ipv4[9])
    length_header_bytes = (version & 15) * 4
    return version, header_len, type_service, + \
          length_total, identification, offset_fragment, + \
          ttl, protocols, checksum_header, ip_src, ip_dest,
             data[length_header_bytes:]

def data_packet_dns(data):
    tuple_data_dns = struct.unpack('!HHHHHH', data[:12])
    identification = tuple_data_dns[0]
    flags = tuple_data_dns[1]
    number_queries = tuple_data_dns[2]
    number_response = tuple_data_dns[3]
    number_authority = tuple_data_dns[4]
    number_additional = tuple_data_dns[5]
    qr = (flags & 32768) != 0
    opcode = (flags & 30720 ) >> 11
    aa = (flags & 1024) != 0
    tc = (flags & 512) != 0
    rd = (flags & 256) != 0
    ra = (flags & 128) != 0
    z = (flags & 112) >> 4
    rcode = flags & 15
    return identification, flags, number_queries, number_response, + \
          number_authority, number_additional, qr, opcode, aa, tc, + \
          rd, ra, z, rcode

sock = socket(AF_PACKET, SOCK_RAW, ntohs(0x0003))

while True:
    raw_dados, addr = sock.recvfrom(65536)
    mac_dest, mac_src, protocol, payload = ethernet_frame(raw_dados)
    if protocol == 8:
         ( version, header_len, type_service,
        length_total, identification, offset_fragment,
        ttl, protocols, checksum_header,
        ip_src, ip_dest, data ) = data_packet_ipv4(payload)
        if protocols == 17:
             port_src, port_dest, udp_len, udp_checksum, data =
              data_packet_udp(data)
            print("--------- HEADER UDP ----------")
            print("Port Source : {}".format(port_src))
            print("Port Dest : {}".format(port_dest))
            print("UDP Length : {}".format(udp_len))
            print("UDP Checksum : {}\n".format(udp_checksum))
            if  port_src == 53 or port_dest == 53:
                  (identification, flags, number_queries, \
                   number_response,number_authority,number_additional, \
                   qr, opcode, aa, tc, rd, ra, z, rcode) = data_packet_dns(data)
             print("\t--------- HEADER DNS ----------")
             print("\tidentification : {}".format(identification))
             print("\tFlags : {}".format(flags))
             print("\tnumber_queries : {}".format(number_queries))
             print("\tnumber_response : {}".format(number_response))
             print("\tnumber_authority : {}".format(number_authority))
             print("\tnumber_additional : {}".format(number_additional))
             print("\tQr : {}".format(qr))
             print("\tOpcode : {}".format(opcode))
             print("\tAA : {}".format(aa))
             print("\tTC : {}".format(tc))
             print("\tRD : {}".format(rd))
             print("\tRA : {}".format(ra))
             print("\tZ : {}".format(z))
             print("\tRCODE : {}".format(rcode))


text:
Q: Linefeeds in zend framework controlloer response I m using zend modular structure.Every controller action returns result with extra \n at end.
When i comment line 'resources.modules[] =' in application.ini, response from controller actions is proper but after reloading page modules are not working.
For eg. echo 'here' returns as '\n here'.
can anyone help me come out of wit this issue?

A: Make sure if you have plugins, action helpers.. and use the preDispatch or any ...dispatch method at all. Make sure that these does not echo any \n.
Basically by using resources.modules[]= "" loads all the modules bootstraps files.


text:
Q: How to navigate from tab bar controller to other view controler and vice-versa I have a tab bar controller with 4 tabs. I am using storyboard to make connections between them.
But the view controller in 4th tab has 3 buttons. Each button should lead to different UIViewController. Well the forward navigation is fine using segue. But facing problem in back navigation. If I am adding a back segue then I am losing the tab bar controls.
Kindly help me.

A: Assume that your view controller in 4th tab has 3 buttons. Each button should lead to different viewControllers, Each viewControllers(the one which you are wish to enter from the button) should be embedded in navigationController and add push segues to each button.


text:
Q: gspread - get specific columns by column name I have a sheet with the struct below.
COLUMN1 | COLUMN2 | COLUMN3
0       | 3       | 1
1       | 3       |
2       | 5       | 4
4       | 2       | 2

How can I return just the column 1 and 2 by its column name? Not by the index.
Using the wks.get_all_values() as shown bellow, it will return all columns of the sheet.
My code:
ss = gs.open(args['name'])
wks = ss.worksheet(args['worksheet'])
data = wks.get_all_values()
headers = data.pop(0)
df = pd.Dataframe(data, columns=headers)

I was needing something like, wks.get_columns(['COLUMN1','COLUMN2'])
I hope someone can help me.
Thanks

A: I believe your goal is as follows.

*

*You want to retrieve the columns by the header values.

*You want to achieve this using gspread for python.

In this case, how about the following modification?
Modified script:
In this modification, the specific columns are retrieved from the values retrieved with wks.get_all_values(). In this case, one API call is used. For example, when the specific columns are retrieved after the header row was retrieved, 2 API calls are retrieved. So I proposed this method.
headers = ["COLUMN1", "COLUMN3"] # Please set the header values you want to retrieve.

ss = gs.open(args['name'])
wks = ss.worksheet(args['worksheet'])
values = wks.get_all_values()
data = zip(*(e for e in zip(*values) if e[0] in headers))
df = pd.DataFrame(data, columns=headers)

*

*When this script is run using your sample sheet in your question, the following result is obtained.
  0  COLUMN1  COLUMN3
  1        0        1
  2        1
  3        2        4
  4        4        2

*When you want to retrieve data as a list, please modify data = zip(*(e for e in zip(*values) if e[0] in headers)) to data = [list(f) for f in zip(*(e for e in zip(*values) if e[0] in headers))].


text:
Q: Phaser - Create player object I'm following this tutorial, https://phaser.io/examples/v2/sprites/extending-sprite-demo-2, and I have the following:
MonsterBunny = function (game, x, y, rotateSpeed) {
    Phaser.Sprite.call(this, game, x, y);
    var test = game.add.sprite(x, y, 'player');
    test.rotateSpeed = rotateSpeed;
};
MonsterBunny.prototype = Object.create(Phaser.Sprite.prototype);
MonsterBunny.prototype.constructor = MonsterBunny;
MonsterBunny.prototype.update = function() {
    this.angle += this.rotateSpeed;
    console.log('a');
};

var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create });

function preload() {
    game.load.crossOrigin = 'anonymous';
    game.load.image('player', 'http://examples.phaser.io/_site/images/prize-button.png');
}

function create() {
    var wabbit = new MonsterBunny(game, 0, 100, 1);
    var wabbit2 = new MonsterBunny(game, 150, 100, 0.5);
}

JSFiddle
The sprites don't spin and the update function doesn't log to the console any more. How do I fix this? Thanks.

A: There are two bugs in your code.
First, in your MonsterBunny constructor you are adding 2 sprites not 1. The var test = game.add.sprite.. shouldn't be there, because a sprite is already added by calling the sprite constructor Phaser.Sprite.call.
Second, in the call to the Phaser.Sprite constructor you forgot to add the key parameter, so which image to use, in your case it's called 'player'. Because of this, it actually adds a sprite but it doesn't display at all.
So, something like this should work:
MonsterBunny = function (game, x, y, rotateSpeed) {
    // call sprite constructor to create sprite
    Phaser.Sprite.call(this, game, x, y, 'player');

    // set extra variables
    this.rotateSpeed = rotateSpeed;
    this.anchor.setTo(0.5, 0.5); // for centered rotation

    // add sprite to game world
    game.add.existing(this);
};


text:
Q: Unexpected non-void return value in void function I am doing the HTTP request and getting response in my func. It return the value of response. I am doing it this way:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
        stringResponse = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
        if stringResponse == "0" {
            return false
        } else if stringResponse == "1" {
            return true
        } else {
            return false
        }
    }

But on all returns I have error Unexpected non-void return value in void function How to fix this?

A: Do this if you want the value after you get response.
func getResponse(completionHandler : ((isResponse : Bool) -> Void)) {

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
        println(NSString(data: data, encoding: NSUTF8StringEncoding))
        stringResponse = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
        if stringResponse == "0" {
           completionHandler(isResponse : false)
        } else if stringResponse == "1" {
           completionHandler(isResponse : true)
        } else {
           completionHandler(isResponse : false)
        }
    }
}

Now you call it as below from where ever you are calling.
classObject.getResponse {(isResponse) -> Void in

//Do your stuff with isResponse variable.
}

A: The last parameter of sendAsynchronousRequest is a completion handler with type (NSURLResponse!, NSData!, NSError!) -> Void. Note it doesn't have any return type, so don't return anything.
The completion handler is called by the connection framework, it doesn't need any return type.
It's pretty obscure what you are trying to achieve by that returns but you can't do it this way.


text:
Q: Sun CC: where does symbol "PointZERO" come from? It's not in my source code This is a really weird problem. I'm compiling a C++ project on Solaris 10, with cc "Sun C 5.7 2005/01/07" and Bison 1.25 (if that matters). After finally getting the libs built, it still fails to link the executables, with following error message:
Undefined                       first referenced
 symbol                             in file
PointZERO                           /export/build/proj/lib/libMainLib.so
ld: fatal: Symbol referencing errors. No output written to bin/the_exe
Does anyone know this "PointZERO" symbol? It's not in my code; nor is the string contained in any of my libraries. I've never seen this name before. And I haven't found anything about this on Google...

A: Well, ouch... The error was induced by an #include <...> statement in one of the source files, which (for unknown reasons) was used to include a file from a completely different project.
Very embarrassing for a number of reasons. Lesson: more thorough code reviews before checking in.


text:
Q: A question related to vector spaces and cyclic modules. Let $V$ be a vector space over the field $F$ and $T\in \mathcal L(V)$,then $V$ is an $F[X]$-module with the scalar multiplication $p(X).v=p(T)v$.
Now let us come to another definition. For a module $M$ over the ring $R$ and for $x\in M$ define $Rx=\{r.x:r\in R\}$. We say that $M$ is a cyclic $R$-module if $M=Rx$ for some $x\in M$.I am looking for a necessary and sufficient condition that $V$ as $F[X]$-module is cyclic. Can someone help me to find such a condition?
My guess is that there should exist $v\in V$ such that $\{p(X).v:p\in F[X]\} $ is the whole vector space $V$. But can I do anything more simple?


text:
Q: How can I force multiple y-axis in Highcharts to have a common zero See this JSFiddle. How do I get the y-axis zero to align?

A: An easy workaround until this feature is added is to make sure the ratio of max/min is the same for both axis.  For example is the min and max for the primary y-axis are -20 and 40 for example, then the max/min ratio is -2.  Now say we have a max value for the secondary y-axis of 25.  If we set the min for this axis to 25/-2 (=-12.5), then the y=0 line will be aligned for the two axes.
Would be much nicer to have a flag to set this automatically though ;-)
EDIT: Some thing like below worked OK for me:
yAxis0Extremes = chart.yAxis[0].getExtremes();
yAxisMaxMinRatio = yAxis0Extremes.max / yAxis0Extremes.min;
yAxis1Extremes = chart.yAxis[1].getExtremes();
yAxis1Min = (yAxis1Extremes.max / yAxisMaxMinRatio).toFixed(0);
chart.yAxis[1].setExtremes(yAxis1Min, yAxis1Extremes.max);

A: You can set min / max value for first yAxis and use linkedTo to second axis, but I'm not sure if you expect this effect:
http://jsfiddle.net/qkDXv/2/
yAxis: [{ // Primary yAxis
            labels: {
                format: '{value}°C',
                style: {
                    color: '#89A54E'
                }
            },
            title: {
                text: 'Temperature',
                style: {
                    color: '#89A54E'
                }
            },
            min:-250,
            max:50
            //linkedTo:1
        }, { // Secondary yAxis
            title: {
                text: 'Rainfall',
                style: {
                    color: '#4572A7'
                }
            },
            labels: {
                format: '{value} mm',
                style: {
                    color: '#4572A7'
                }
            },
            opposite: true,
            linkedTo:0
        }],

A: The short answer is: you can't.
You can tweak axis scaling, padding, and tick positions and the like and possibly get what you want, but there is no setting to accomplish this.
There is a feature request though, that you can add your votes and/or comments to:
http://highcharts.uservoice.com/forums/55896-general/suggestions/2554384-multiple-axis-alignment-control
EDIT:
OTOH, I have to mention that dual axis charts like this are most often a very poor way to show the data, and invites the user to make comparisons that aren't valid.
While most people are always trying to put everything in one chart, multiple charts are very often the better solution.
FWIW

A: I know it's been two year. However, I did found a better solution compare to exist solution which was given in previous answers. My solution is still using setExtremes to set min, max for yAxis but with better exception handling which are extremely good to show() and hide() any plot.
Solution: link
Github: link

A: The simplest way is to just provide the same min/max for each axis.  It would be a pretty simple to determine a good min/max based on the data before the plot call (combine the arrays, take the min/max round down/up to nearest int, would be my approach).
pretend this is code so I can link to jsFiddle

Updated fiddle.

A: you can do it easily by following the below code-
you just need to find which point of opposite y -axis meets zero of first y-axis and set the min of opp y-axis to (that point * -1)
In my case yaxis[1] forms the main y-axis and yaxis[0] forms the opposite y-axis
 }, function(chart) { // on complete
        var factor = chart.yAxis[1].min  / chart.yAxis[1].tickInterval
        var tick = chart.yAxis[0].tickInterval;
        var _min = chart.yAxis[0].tickInterval * factor
        chart.yAxis[0].update({ min: _min });
        chart.yAxis[0].update({ tickInterval: tick });

    });

A: I've had issue with all the answers as it didn't support values on negative Y axis. To center on 0, i applied below logic
Find min/max of the series and pad it so 0 comes in center
if(max > 0  && min < 0){
{
   const diff = max + min;
   if(diff > 0){
      min = min - diff
   }
   else{
      max = max + -1 * diff
   }
}
else if (max > 0){
   max = min * -1
}
else{
   min = max * -1
}

Then when defining axis on chart, use the min/max values from above, this will ensure 0 shows in center


text:
Q: Good resource on ECMs/VECMs? I am trying to understand ECMs and VECMs and what the relationship between a regression model with stationary residuals or time series errors.  Is there a good website/book that goes into the assumptions behind the ECM and what makes it different from the regression model?  Also how the estimated coefficients and interpretation are related to each other.
Thanks!


text:
Q: How Do I Package a Django Website for Debian (Not a Python Package or Egg)? I have been searching for the last two weeks and chased myself into multiple dead ends trying to figure out the path that takes me where I want to go. However I finally have to admit that my answer isn't clearly posted anywhere, and here we are.
I'll start off my clarifying: I don't want to build a redistributable Django "App" which seems to mean "plugin" - This isn't a python plugin, it's a full fledged website with an FCGI server, /etc/init.d script, config file in /etc/djangoapps and a requirements.txt for the plugins my site uses.
I want to build a deb package to allow me to deploy to a Dev and Prod server from a build server (I'm using Bamboo, but Jenkins should be the same principle.)
I also want to do this on Debian 7 Wheezy, not Ubuntu. PKGME Seems to do the job on Ubuntu and Debian 8, however it fails to install in a functional state in Wheezy, and I was unable to find a way to fix it.
So I went with trying setuptools, stdeb, and debuild to create my package, which causes me to wind up with an egg, inside a deb, that does not contain any of my /etc or /usr files.
So what is the proper method here?

A: A .deb file obviously can install files under /etc and /usr, otherwise your Debian 7 system could not be installed in the first place using such files, so that is the way to go.
Your problems seem to come from the tools you are using in trying to achieve the task, either you use them in the wrong way, or their "easy-of-use" hides capabilities of the .deb based packages that you need to achieve your task.
A .deb file is just an ar archive that contains 3 files: a version number file and two tar archives (usually compressed). It is easy to unpack with a few commands (ar x ... resp. tar xvf ..) and put together again (
tar cvzf ... resp. ar mc ....). Please note that the `debian_version file has to be first to be moved into the archive.
When I have to make .deb packages I start from an existing package that already does part of what I need and add/change the things as necessary.
More detailed information is of course available if you need to understand how the installers execute the various special scripts that can be in the packages, as well as adding dependencies.


text:
Q: Control my web radio player from notification with NotificationCompat.MediaStyle and MediaSessionCompat I have an app that reproduces from the service a webradio (using AACDecoder lib) and show on a simple ongoing notification what is playing while the activity is not resumed.
What i want is to add by NotificationCompat.MediaStyle a button to stop (and eventually re-start) the playing from notification, without the need of opening the activity. Despite it is a webradio player and not a player with a reprodution list, i need only a play-pause button.
But even after reading various guides (like this) im not enable to correctly understand and implement this function, mainly because of the recent deprecations and newly compatibility classes on this scenario.
This is how my notification appears:

And this is how i want (approximately, just need the pause-play button):

Any help is welcome. Thanks in advance!

A: What you are looking for is more along the collapsed version of the MediaStyle notification. While I'm not sure how to force it to stay collapsed, this should set you on the right path. I used a bit of the code found in the UniversalMusicPlayer that is part of the sample code provided for Android.
Specifically - You want to check out the MediaNotificationManager and MusicService classes.
https://github.com/googlesamples/android-UniversalMusicPlayer/blob/master/mobile/src/main/java/com/example/android/uamp/MediaNotificationManager.java
Both of which are a bit overly complex for what you are trying to achieve, but could be a good place to refer to. Specifically, the createNotification method (see a Play/Pause version below).
private Notification createNotification() {
    if (mMetadata == null || mPlaybackState == null) {
        return null;
    }

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(mService);
    int playPauseButtonPosition = 0;

    addPlayPauseAction(notificationBuilder);

    MediaDescriptionCompat description = mMetadata.getDescription();

    String fetchArtUrl = null;
    Bitmap art = null;
    if (description.getIconUri() != null) {
        // This sample assumes the iconUri will be a valid URL formatted String, but
        // it can actually be any valid Android Uri formatted String.
        // async fetch the album art icon
        String artUrl = description.getIconUri().toString();
        art = ChannelImageCache.getInstance().getBigImage(artUrl);
        if (art == null) {
            fetchArtUrl = artUrl;
            // use a placeholder art while the remote art is being downloaded
            art = BitmapFactory.decodeResource(mService.getResources(),
                    R.drawable.ic_default_art);
        }
    }

    notificationBuilder
            .setStyle(new NotificationCompat.MediaStyle()
                    .setShowActionsInCompactView(
                            new int[]{playPauseButtonPosition})  // show only play/pause in compact view
                    .setMediaSession(mSession.getSessionToken()))
            .setColor(mNotificationColor)
            .setSmallIcon(R.drawable.ic_notification)
            .setVisibility(Notification.VISIBILITY_PUBLIC)
            .setUsesChronometer(true)
            .setContentIntent(createContentIntent(description))
            .setContentTitle(description.getTitle())
            .setContentText(description.getSubtitle())
            .setLargeIcon(art);

    setNotificationPlaybackState(notificationBuilder);
    if (fetchArtUrl != null) {
        fetchBitmapFromURLAsync(fetchArtUrl, notificationBuilder);
    }

    return notificationBuilder.build();
}

private void addPlayPauseAction(NotificationCompat.Builder builder) {
    String label;
    int icon;
    PendingIntent intent;
    if (mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING) {
        label = mService.getString(R.string.mr_media_route_controller_pause);
        icon = R.drawable.uamp_ic_pause_white_24dp;
        intent = mPauseIntent;
    } else {
        label = mService.getString(R.string.mr_media_route_controller_play);
        icon = R.drawable.uamp_ic_play_arrow_white_24dp;
        intent = mPlayIntent;
    }
    builder.addAction(new NotificationCompat.Action(icon, label, intent));
}

This Notification will use a MediaSession in your service (where I am assuming you AACDecoder/AACPlayer is living). When you get your ID3 Metadata from the player, you'll want to update the Metadata and set it to the mediaSession.
private void updateMetadata() {

    final MediaMetadataCompat track = generateMediaMetadataCompat(currentMetaData);

    mediaSession.setMetadata(track);
}

    private MediaMetadataCompat generateMediaMetadataCompat(SomeMetadataModelObject streamMetadata)
{
    currentMediaMetadataCompat = new MediaMetadataCompat.Builder()
            .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, streamMetadata.getMediaId())
            .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, streamMetadata.getAlbumName())
            .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, streamMetadata.getArtistName())

            .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ART_URI, "http://somealbumart.png" )
            .putString(MediaMetadataCompat.METADATA_KEY_TITLE, streamMetadata.getSongTitle())

            .build();
    return currentMediaMetadataCompat;
}


text:
Q: Expecting http://127.0.0.1:5000/; But only 'Process finished with exit code 0' New to Python. Use Pycharm to test Flask simpliest web application.
Supposed to output: http://127.0.0.1:5000/
But I got 'Process finished with exit code 0'
Please check out the images below.
Code

Console

Configuration

A: Never mind. I found the solution on reddit:
remove ALL spaces before and after '='
Type in Console:
Line 1: set FLASK_APP=hello.py
Line 2: flask run

A: Process finished with exit code 0 means your program has compiled successfully without any errors. Pycharm returns 0 when it has found no errors.

A: in picture 3, where is the "hello.py"? does your app file is named as "FLASK_APP.py"?


text: Q: Create an executable application in Ubuntu with many dependencies? We have coded an application with many dependencies. Right now, we can use a makefile to compile source code. What we want to do next is create an executable application (we don't want to release our source code) with the dependencies. Just a compressed file, other users can extract and use it directly. we don't want to provide source code, it seems that debmake can't work.  How to compress the dependencies along with the executable main application?  Thanks for any suggestions.


text:
Q: How can I add breakpoint into menu depend on screen size with twitter bootstrap I have a reddit like top menu. the thing is there are too many items. How I can add a hamburger menu if screen size is x size but I don't want to take all the items into hamburger menu. just menu items which don't fit the screen.
The menu expands like this if you change the screen size

and if you change the screen size to smaller size all the items hidden into hamburger menu.
For example on a particular screen size how can I hide search box and some items into hamburger menu? It doesn't even have to add into hamburger menu. how I can hide them entirely.
I have tried this approach
@media (min-width: 769px) {
  .nav.navbar-nav > li {
    display: none;
  }
  .nav.navbar-nav > li:nth-child(1),
  .nav.navbar-nav > li:nth-child(2),
  .nav.navbar-nav > li:nth-child(3) {
    display: block;
  }
  .lt-ie9 .nav.navbar-nav > li:first-child,
  .lt-ie9 .nav.nav.navbar-nav > li:first-child + li,
  .lt-ie9 .nav.navbar-nav > li:first-child + li + li {
    display: block;
  }
}
@media (max-width: 790px) {
  .header-navbar .nav-icons,
  .header-navbar .nav.navbar-nav > li.nav-all {
    margin-right: 0px;
  }
  .header-navbar:after {
    display: none;
  }
}
@media (min-width: 899px) {
  .nav.navbar-nav > li:nth-child(4) {
    display: block;
  }
  .lt-ie9 .nav.navbar-nav > li:first-child + li + li + li {
    display: block;
  }
}
@media (min-width: 1200px) {
  .nav.navbar-nav > li:nth-child(5),
  .nav.navbar-nav > li:nth-child(6),
  .nav.navbar-nav > li:nth-child(7),
  .nav.navbar-nav > li:nth-child(8),
  .nav.navbar-nav > li:nth-child(9),
  .nav.navbar-nav > li:nth-child(10),
  .nav.navbar-nav > li:nth-child(11),
  .nav.navbar-nav > li:nth-child(12),
  .nav.navbar-nav > li:nth-child(13),
  .nav.navbar-nav > li:nth-child(14) {
    display: block;
  }
  .lt-ie9 .nav.navbar-nav > li:first-child + li + li + li {
    display: block;
  }
}

A: Assuming your html follows standard structure for a Bootstrap navbar:

Item

    ...

@media (max-width: 1280px) {
    .navbar-nav .hideMe {
        display: none;
    }
}

A: Have something like this:

* {box-sizing: border-box; padding: 0; margin: 0; list-style: none; font-family: 'Segoe UI';}
a {text-decoration: none;}

nav ul li {display: inline-block;}
nav ul li a {display: block; width: 100px; text-align: center; line-height: 1.5; padding: 5px; border: 1px solid #ccc;}

@media screen and (max-width: 460px) {
  li + li + li + li ~ li {display: none;}
}

@media screen and (max-width: 555px) {
  li + li + li + li + li ~ li {display: none;}
}

@media screen and (max-width: 640px) {
  li + li + li + li + li + li ~ li {display: none;}
}
<meta name="viewport" content="width=device-width, initial-scale=1" />

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Item 7

Item 8

Item 9

Item 10

Check the example in the emulator view.


text:
Q: Matching based on patern in one of two files - Linux I have two files of different formats and number of records. I'd like to search for lines in File2 based on the records in File1 and save the entire matched line(s) from File2 in a new file. The file examples are below:
Input File 1
991888
16889000
567899
....
....

Input File 2
16889000    xxxx    yyyy
687398793
5778
567899      aaaa    bbbb
999178
.....

Output file
16889000    xxxx    yyyy
567899      aaaa    bbbb

I've tried playing with various grep options, but no luck. Any help to solve this using out of the box tools would be helpful.
Thanks!

A: awk 'FNR==NR {if (NF > 0) a[FNR""] = $0; next}; {for (x in a) {if ($1 ~ a[x]) {print}}}' input_file1.txt input_file2.txt


text:
Q: phpMyAdmin access has suddenly become very slow I used to be able to access and export database from phpmyadmin fine but it has suddenly become very very slow and trying to export a 20 mb data results in Network Failure Error. I had created another instance using the same server a month ago and I can access that just fine.
The only changes in the past few days are enabling logging and adding a cron job in cron.daily to back up the database.
I have tried restarting the instance and also cleared browser cache. Tried using two different computers.

A: Is this in a shared hosting environment? Is it possible the machine is under heavy load due to other factors? Have you tried enabling the slow query log to look for slow queries? From the phpMyAdmin main page, there's a Status tab which contains some means you can look throiugh; for instance the process list might help identify long-running processes. Have you tried disabling the logging? Check to see whether your cron job got hung up in some way (for instance, ps on the command line). Again at the command-line, check your system load (perhaps with top).


text:
Q: imp.load_source loads wrong module I have two supposedly identical systems. On both systems, I run the same software, but on one of the two it doesn't function correctly.
I'm trying to run function in a user-supplied .py file. I've reduced this to the following basic code that reproduces the error:
import imp
with open("test_scripts/load_offsets.py") as fp:
    module = imp.load_source("load_offsets", "test_scripts", fp)

dir(module)

On the first system, the output is correct:
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'os', 'test_load_offsets']

I see one function called test_load_offsets, as expected.
On the second system, I get the following output:
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'test_reset_position']

Note that I see a different function now: test_reset_position. However, on both systems, the file test_scripts/load_offsets.py is identical! More importantly, there is no function test_reset_position in this file.
There is, however, a function test_reset_position in a different file, namely test_scripts/reset_position.py. In addition, in the directory where I executed the code sample, there is a file test_scriptsc (this is the case on both systems). It contains, I think, byte code, but on the system where I see the problem I can recognise parts of the file test_scripts/test_reset_position.py in it. If I remove test_scriptsc, it works fine again, until load a different file and then the problem starts again.
So, my conclusion is that on the system with the problem, the file test_scriptsc is not updated correctly. However, I do not understand why, nor do I understand why the problem is only on one of the two systems. The only difference I can find between the two systems is that the problematic system runs Python Python 2.7.12 on Ubuntu Linux 16.04.1 while the system without the problem runs Python 2.7.11+ on Ubuntu 16.04.
Can someone help me find out what is going on here? I have no clue what to look for...

A: The reason why it is failing is because I'm doing it wrong. The second argument to load_source should be the full path to the source file, not just to the directory containing it Python 2.7.12 documentation.
I'm not sure why I came up with my implementation, nor do I know why Python 2.7.11 was accepting it anyway, but the solution is to do it the right way:
with open("test_scripts/load_offsets.py") as fp:
    m = imp.load_module("load_offsets", fp, "test_scripts/load_offsets.py", ("py","r",imp.PY_SOURCE))

dir(m)

This correctly gives:
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'os', 'test_load_offsets']

I think the file test_scriptsc was an attempt of byte compiling a .py file, but since I didn't give the full path, I ended up with something that was a sort-of-compiled directory. Apparently Python 2.7.11 handled this differently than Python 2.7.12.


text:
Q: Update Object or Create it if it doesn't exists? Im digging though some cloud code to do some manipulation of data and save it as a new class.
I have a situation where I read a row from another class, do some math functions, then save the manipulated data to another class which is then read by our client.
The problem is that If the other object already exists in the new class, I just want to update it instead of creating a new one.  I know in the parse documentation
it lists creating an object and updating but not really functionality to update if exists, and if not create.
Here is just some example code.. the out data is the data prepped to save for the new class.  I can crate the new class object, but when I update some value that
should trigger a update instead of a create new is where things fall apart.
Please understand JS is not my first language so this might be hacked or completely going about it the wrong way, but I should stress I do not know the objectId of
the new class.
if(out.length > 0) {

  var game = Parse.Object.extend("Gamers");
  var query = new Parse.Query(game);
  query.equalTo("playername", player);  // using this to find the player since I dont have the objectid
  query.find({
    success: function(results) {

    // Successfully retrieved the object.
    if (results && results.length == "1") {

      var playerObjectId = results[0].id
      /// save only updated data to the local class ????

    } else {
      // no results, create a new local
      console.log('no results')

      // save as a new object
      var gamers = new game();

      gamers.set("somevalue", somevalue);
      gamers.set("somevalue2", somevalue2);

      gamers.save(null, {
        success: function(gamers) {
          // Execute any logic that should take place after the object is saved.
          console.log('New object created with objectId: ' + gamers.id);
        },
        error: function(gamers, error) {
          // Execute any logic that should take place if the save fails.
          // error is a Parse.Error with an error code and message.
          console.log('Failed to create new object, with error code: ' + error.message);
        }
      });
    }

  },
  error: function(error) {
    console.log("Error: " + error.code + " " + error.message);
  }
});

} else {
console.log('array is empty, something went wrong')
 //this array is empty
}

A: A create or update function has three distinct bits: find, update, or possibly create.  Lets build the three separately.
function findGamerWithName(name) {
    var game = Parse.Object.extend("Gamers");
    query.equalTo("playername", name);
    return query.find();
}

function updateGamer(gamer, someValue, someValue2) {
    gamer.set("somevalue", someValue);
    gamer.set("somevalue2", someValue2);
    return gamer.save();
}

function createGamer(someValue, someValue2) {
    var Gamer = Parse.Object.extend("Gamers");
    var gamer = new Gamer();
    return updateGamer(gamer, someValue, someValue2);
}

Now we can understand and test these separately (you should test them).  And now, it's easy to write create or update logic...
function createOrUpdateGamer(name, someValue, someValue2) {
    return findGamerWithName(name).then(function(gamer) {
        return (gamer)? updateGamer(gamer, someValue, someValue2) : createGamer(someValue, someValue2);
    });
}


text:
Q: PHP isset for GET variable in ternary operator I have a <select> field and I want to have the appropriate <option> selected based on what the GET value is
So I have used a ternary statement to output a selected attribute like so:
<select name="data" id="data">
    <option value="1" <?php echo $_GET['data'] == '1' ? 'selected' : '' ; ?>>One</option>
    <option value="2" <?php echo $_GET['data'] == '2' ? 'selected' : '' ; ?>>Two</option>
    <option value="3" <?php echo $_GET['data'] == '3' ? 'selected' : '' ; ?>>Three</option>
</select>

The problem is, the when the page is first loaded there is no $_GET array so I get a php error in my select box:

Notice:  Undefined index: data in...

So I tried using isset to first check if the array is set before checking if the value matches:
    <option value="1" <?php echo isset($_GET) && $_GET['data'] == '1' ? 'selected' : '' ; ?>>One</option>

This returns the same error.
What is the best way to concisely handle this error and achieve what I'm after?

A: try this,
<option value="1" <?php echo isset($_GET['data']) ? ($_GET['data'] == '1' ? 'selected' : '') : ''; ?>>One</option>

A: You could utilise a for loop, and only print out the $selected variable when your requirement is true. This will save you repeating yourself.
<select name="data" id="data">
    <?php for ($i = 1; $i <= 3; $i++) { ?>
        <?php $selected = (isset($_GET['data']) && $_GET['data'] === $i) ? 'selected' : ''; ?>
        <option value="<?=$i?>" <?=$selected?>><?=$i?></option>
    <?php } ?>
</select>

Note: I use PHP 5.4, so can legitimately use PHP short echo's which, in my opinion, are much nicer in views / templates
If you want to display text for numbers and don't want to do it manually, using an array, you can check out Pear's Numbers_Words package.

A: Try like
<option value="1" <?php echo ( isset($_GET['data']) && $_GET['data'] == '1') ? 'selected' : '' ;?> >One</option>


text:
Q: Is it possible to pass a reference to a consteval function and use it as additional return value? Sometimes the result of a function can not be represented by a single return value. For example: A function that intersects two lines. One might want the function to return both the actual point of intersection as well as their relation to each other (that is parallel, identical, intersecting or skewed).
Let us assume this example where the point of intersection is represented by some sort of class and the lines positional relation by an integer holding a specified value for each of the 4 possibilities:
int IntersectLines(Line l1, Line l2, Point& point);

Point point{};
int result = IntersectLines(l1, l2, point);

That is how I would have implemented it to this day but now I am wondering whether it is possible to have a similar implementation but with a consteval function. Line and Point have constexpr constructors and everything and the calculation itself can be compile time evaluated as well. The only problem is that I can't think of a way to have two return values. I already thought of std::pair but a solution more similar to passing a reference would be prefered. If such a solution doesn't exist I will have to fall back to std::pair.
It doesn't work by passing point by reference (Point& point) because "the expression did not evaluate to a constant" but passing by const reference (const Point& point) won't work either because I wouldn't be able to assign the result to point. Is there a way to get this working?

A: You can return a std::pair<Point, Relationship>.
Example:
consteval std::pair<Point, Relationship> IntersectLines(const Line& l1, const Line& l2)
{
    // replace with the real calc below, this is just for show:
    const Point pnt{l1.p1.x + l2.p1.x, l1.p1.y + l2.p1.y};
    const Relationship rel = Relationship::parallel;
    return {pnt, rel};
}

And call it like so:
int main() {
    constexpr Line l1({1,2}, {3,4}), l2({5,6}, {7,8});
    constexpr auto pr = IntersectLines(l1, l2);
    auto&[pnt, rel] = pr;

    return pnt.x + pnt.y; // 14
}

With optimization, the resulting assembly is likely to become something like
main:
        mov     eax, 14
        ret

Demo

A: You cannot pass a reference to a consteval function and have the function modify the target of the reference, except if you do so in inside another consteval function.
The call to a consteval function must be on its own a constant expression, assuming it is not called inside another consteval function.
However, a constant expression cannot modify an object outside of the evaluation of the constant expression itself.

In both a consteval and usual function, you can however return a std::pair or std::tuple of multiple return values and e.g. retrieve them at the call site as a structured binding.


text:
Q: Cartan determinants of subsets Let $n \geq 3$ be fixed.
We associate to every subset $S \subseteq \{1,...,n-1 \}$ a number, which we call Cartan determinant of $S$ (see the end of this post for a representation theoretic background).
Define for $k,t \in \{1,...,n \}: m_{k,t}:= t-max(0,t-k)=min(k,t)$ (so $m_{k,t}=t$ for $k>t$ and $m_{k,t}=k$ for $t \geq k$).
Write $S= \{s_1,...,s_{r-1} \}$ with the $s_i$ in increasing order and $r-1$ the cardinality $|S|$ of $S$ and set $s_r:=n$.
Let $a_{i,j}:=m_{s_i,s_j}=min(s_i,s_j)$ for $i,j \in \{1,...,r\}$.
Let $A_S$ be the matrix with entries $a_{i,j}$, called the Cartan matrix of $S$ and let $d_S$ be defined as the determinant of $A_S$, called the Cartan matrix of $S$.
We set $A_{\emptyset}=n$ and thus $d_{\emptyset}=n$.

Question 1: Is there an explicit formula for $d_S$?
Question 2: I can prove that $d_S$ is non-zero. Is it more general true that $d_S >0$?

Now call $S$ great in case the following holds.
-In case $n$ is even, $|S|$ is odd,$min(S)$ is odd and $max(S)$ is odd and all differences $s_i-s_{i-1}$ are odd for $i=2,...,r-1$.
-In case $n$ is odd, $|S|$ is even, $min(S)$ is odd, $max(S)$ is even and all differences $s_i-s_{i-1}$ are odd for $i=2,...,r-1$.
-$\emptyset$ is great if and only if $n$ is odd.

Question 3: Is it true that $d_S$ is odd if and only if $S$ is great? Are the great subsets $S \in \{1,...,n-1  \}$ enumerated by the Fibonacci numbers $F_n$?

Question 2 and 3 have a positive answer for $n \leq 14$ and thus there is good evidence that it is true and something nice is going on. I can prove (looking at entries mod 2) that if $S$ is great, then $d_S$ is odd, but Im not sure about the converse. The result being so nice, I would think that there is a short proof that avoids heavy computations.
Now here come some more weird observations that might be much harder to show.

Question 4:
Call a subset $S$ prime in case $d_S$ is prime. When is $S$ prime?
For $n \leq 20$ it was true that the number of prime $S$ is given by  $\sum\limits_{k=1}^{m}{\pi(k)}$, where $\pi(k)$ is the prime counting function. See https://oeis.org/A046992 . Is this true in general?

Some other findings that occured in the oeis:

The number of subsets $S$ with $d_s=1 mod 3$ seems to be given by the seqeunce https://oeis.org/A075111 , related to the tribonacci numbers. Is this true?
The number of subsets $S$ with $d_S=1 mod 4$: https://oeis.org/A005252 .
With $d_S=3 mod 4$: https://oeis.org/A024490.

Note that all the 3 previous sequences are related to the Fibonacci sequence, which might indicate that this all has a secret connection to Fibonacci combinatorics (which I can not see at the moment).

The number of $S$ with $d_S$ such that $Gcd(d_S,n)=1$ seem to be given by https://oeis.org/A100347.

Representation theoretic background.
Let $A=A_n=K[x]/(x^n)$. Then there is a unique indecomposable $A$-module $M_i$ of dimension $i$ for $i=1,...,n$.
The subsets $S \subseteq \{1,...,n-1 \}$ are in bijection with the (faithful) module $M_S := A \oplus \bigoplus\limits_{i \in S}^{}{M_i}$. Then $d_S$ is the Cartan determinant of the algebra $End_A(M_S)$.

A: If $s_1<s_2<\ldots<s_{r-1}<s_r=n$, the matrix $A_S$ is the matrix of the quadratic form
$$
s_1(x_1+\ldots+x_r)^2+(s_2-s_1)(x_2+\ldots+x_r)^2+\\(s_3-s_2)(x_3+\dots+x_r)^2+\ldots+(s_r-s_{r-1}) x_r^2.
$$
This quadratic form is obviously positive-definite which already implies $d_S>0$. Next, we get $$(A_Sx,x)=(D_STx,Tx)\Rightarrow A_S=T^tD_ST,$$
where $D_S$ is diagonal with elements $s_1,s_2-s_1,\ldots,s_r-s_{r-1}$ and $T$ is the triangular map $x\to (x_1+\ldots+x_r,x_2+\ldots+x_r,\ldots,x_r)$. Thus
$$
\det A_S=\det D_s=s_1(s_2-s_1)(s_3-s_2)\ldots (s_r-s_{r-1})
$$
which answers other questions.

A: For any set $S=\{s_1,\dots,s_k\}\subset[0,\infty)$ with $s_1<\dots<s_k$, the matrix $A_S=(\min(s_i,s_j))_{i,j=1}^k$ is the covariance matrix of the random vector $(B(s_1),\dots,B(s_k))$, where $B(\cdot)$ is a standard Brownian motion. So, $A_S$ is positive semidefinite. Moreover, since the random variables $B(s_1),\dots,B(s_k)$ are clearly linearly independent, $A_S$ is positive definite, and hence $\det A_S>0$.


text:
Q: Multiple selected items RecyclerView in Activity.java I have a RecyclerView with data from local JSON in CardView. I need to implement on selected items when one or some item clicked(change background the item selected or highlight) (like edit in Line App ) but without Button or longpress. But I don't want to use StateListDrawableor (using XML) because I have some JSON data which need to process later.
I need a state in my Activity like a boolean value or something to save every item which I clicked but I don't have any solution again. I have read and try some tutorial but it's not working. This is below my Activity now :
adapter.setOnRecyclerViewClickedListener(new Adapter.OnRecyclerViewItemClickedListener() {
        @Override
        public void OnRecyclerViewItemClicked(int position) {
            boolean selectedItem = false;

            adapter.setOnRecyclerViewClickedListener(new Adapter.OnRecyclerViewItemClickedListener() {

        @Override
        public void OnRecyclerViewItemClicked(int position)  {

    /* ------ boolean variabel for adapter but still not work ----- */
            JSONObject filteredtableList= null;

            try {
                filteredtableList= new JSONObject("response").getJSONObject("tTisch");
            }
            catch (JSONException e) {
                e.printStackTrace();
            }

                if (recyclerView == null) {
                    try {
                        filteredtableList.has("true");
                        filteredtableList.put(status, true);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                else {
                    try {
                        filteredtableList.put(status, true);

                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            adapter.updateData(filteredTableList);

//----------------------------------------------------
            try {
                Toast.makeText(TableActivity.this, filteredTableList.getJSONObject(position).getString("tischnr"), Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });

Adapter.java
public int lastCheckedPosition = -1;
.........
.........
.........
    @Override
public void onBindViewHolder(ViewHolder holder, int position) {

    if (position == lastCheckedPosition) {
        holder.itemView.setBackgroundResource(R.color.colorRedTableOcc);
    } else {
        holder.itemView.setBackgroundResource(R.color.colorTableGreen);
    }

    try {
        currItem = list.getJSONObject(position);
        holder.txt_no_table.setText(currItem.getString("tischnr"));

    } catch (JSONException e) {
        e.printStackTrace();
    }
}

@Override
public int getItemCount() {
    return list.length();
}

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public TextView txt_no_table;

    public ViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);

        txt_no_table = (TextView) itemView.findViewById(R.id.txt_no_table_empty);
    }

    @Override
    public void onClick(View itemView) {

        recyclerViewItemClickedListener.OnRecyclerViewItemClicked(getAdapterPosition());

        lastCheckedPosition = getAdapterPosition();
        notifyItemRangeChanged(0,list.length());
    }
}

JSON.json
..............
"t-tisch": [
            {
                "tischnr": 1,
                "departement": 1,
                "normalbeleg": 0,
                "kellner-nr": 0,
                "bezeich": "TABLE 01",
                "roomcharge": false,
                "betriebsnr": 0
            },
            {
                "tischnr": 2,
                "departement": 1,
                "normalbeleg": 0,
                "kellner-nr": 0,
                "bezeich": "TABLE 02",
                "roomcharge": false,
                "betriebsnr": 0
            },
............

This is my Activity looks like

Update
Output now:

It's now highlight when I click the item (Thanks to @Burhanuddin Rashid) but its still half for my case. I only can select one item (I can't selected multiple/more items). I need to unselect again when I click the highlight item.
EDITED : I try to write new object and key in my JSON (JSON code above). In my logic, it will make a flag for every item is selected or not, but it still not work.
EDITED : this is my log error :
                  --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.development_laptop.vhp_restotemp, PID: 3590
              java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONObject.put(java.lang.String, boolean)' on a null object reference
                  at com.example.development_laptop.vhp_restotemp.TableActivity$1.OnRecyclerViewItemClicked(TableActivity.java:74)
                  at com.example.development_laptop.vhp_restotemp.com.example.development_laptop.vhp_restotemp.recyclerview.source.Adapter$ViewHolder.onClick(Adapter.java:97)
                  at android.view.View.performClick(View.java:5198)
                  at android.view.View$PerformClick.run(View.java:21147)
                  at android.os.Handler.handleCallback(Handler.java:739)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A: You can apply setOnClickListener like this:-
View itemView;
    Context context;

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_view, parent, false);
        this.context=parent.getContext();
        return new ViewHolder(itemView);
    }
    @Override
        public void onBindViewHolder(final ViewHolder holder, int position) {

            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        holder.linearLayout.setBackgroundColor(context.getResources().getColor(R.color.colorAccent,null));
                    }
                    else {
                        holder.linearLayout.setBackgroundColor(context.getResources().getColor(R.color.colorAccent));

                    }
                }
            });
        }

A: Try this:
onBindViewHolder:
if (position == lastCheckedPosition) {
            holder.itemView.setBackgroundResource(R.drawable.ic_item_selection_background);
        } else {
            holder.itemView.setBackgroundResource(R.drawable.ic_item_deselection_background));
        }

And this on ViewHolder:
    itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        lastCheckedPosition = getAdapterPosition();
                         notifyItemRangeChanged(0,getItemCount());
                     }
                });

Create lastCheckedPosition as global variable

A: Follow Below Code :
Put this code in your onBindViewHolder() Method.
  @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
    final DataModel dataModel = arraylist.get(position);
            final boolean isSelected = dataModel.isSelected();
            if (isSelected) {
               llParentLayout.setBackgroundColor(Color.Black);
            } else {
               llParentLayout.setBackgroundColor(Color.Green);
            }
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public TextView txt_no_table;
    public ViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);

        txt_no_table = (TextView) itemView.findViewById(R.id.txt_no_table_empty);
    }

    @Override
    public void onClick(View itemView) {
final DataModel dataModel = arraylist.get(getAdapterPosition());
        recyclerViewItemClickedListener.OnRecyclerViewItemClicked(dataModel);

    }
}

In your Activity :
adapter.setOnRecyclerViewClickedListener(new Adapter.OnRecyclerViewItemClickedListener() {
        @Override
        public void OnRecyclerViewItemClicked(DataModel dataModel) {

dataModel.setSelected(!dataModel.isSelected());
adapter.notifyDataSetChanged();

        }
    });

A: I totally change my code but its now work powerfully, here my code looks like :

*

*I change my Adapter into generic adapter. Its not process any data, but its throw to my activity.
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
public int lastCheckedPosition = -1;

private static OnRecyclerViewItemClickedListener recyclerViewItemClickedListener;

public void setOnRecyclerViewClickedListener (OnRecyclerViewItemClickedListener l) {
recyclerViewItemClickedListener = l;
}

public interface OnRecyclerViewItemClickedListener {
  void OnRecyclerViewItemClicked(int position);
  void OnRecyclerViewItemBind(ViewHolder holder, int position);
  int OnRecyclerViewItemCount();

}
public Adapter() {
  super();
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
  View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.table_item_empty, parent, false);
  return new ViewHolder(v);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
recyclerViewItemClickedListener.OnRecyclerViewItemBind(holder,position);
}

@Override
public int getItemCount() {
  return recyclerViewItemClickedListener.OnRecyclerViewItemCount();
}

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

public TextView txt_no_table;

public ViewHolder(View itemView) {
    super(itemView);
    itemView.setOnClickListener(this);

    txt_no_table = (TextView) itemView.findViewById(R.id.txt_no_table_empty);
}

@Override
public void onClick(View itemView) {

    recyclerViewItemClickedListener.OnRecyclerViewItemClicked(getAdapterPosition());
     }
   }
}

*And My Activity become like this :
/*Add Click Listener*/
adapter.setOnRecyclerViewClickedListener(new Adapter.OnRecyclerViewItemClickedListener() {

    @Override
    public void OnRecyclerViewItemClicked(int position)  {
        try {
            JSONObject currTable = filteredTableList.getJSONObject(position);

            if (currTable.has("selected")) {
                currTable.put("selected", !currTable.getBoolean("selected"));
            } else {
                currTable.put("selected",true);
            }

            adapter.notifyItemChanged(position);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        try
        {
            Toast.makeText(TableActivity.this, filteredTableList.getJSONObject(position).getString("tischnr"), Toast.LENGTH_SHORT).show();
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void OnRecyclerViewItemBind(Adapter.ViewHolder holder, int position) {
        try {
            JSONObject currTable = filteredTableList.getJSONObject(position);

            holder.txt_no_table.setText(currTable.getString("tischnr"));

            int queasy33Index = ProgramMethod.getJSONArrayIndex(queasy33List,"number2", currTable.getInt("tischnr"));

            if (queasy33Index >= 0) {
                holder.txt_no_table.setText(holder.txt_no_table.getText() + "-" +  queasy33List.getJSONObject(queasy33Index).getString("key"));
            }

            if (currTable.has("selected") && currTable.getBoolean("selected")) {
                holder.itemView.setBackgroundResource(R.color.colorRedTableOcc);
            } else {
                holder.itemView.setBackgroundResource(R.color.colorTableGreen);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

*Now the click listener save any state and save into boolean value in my JSON file like below :

Thanks to everyone with suggest and great answer :)

A: Try below code
Inside
public Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)

Put
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_image_and_text, parent, false);
v.setOnClickListener(new MyOnClickListener());

And create this class anywhere you want it
class MyOnClickListener implements View.OnClickListener {
    @Override
    public void onClick(View v) {
       int itemPosition = recyclerView.indexOfChild(v);
       Log.e("Clicked and Position is ",String.valueOf(itemPosition));
    }
}

I've read before that there is a better way but I like this way is easy and not complicated.

A: All Above are very good answer but i am sure you will choose this one
this gives you more flexibility than others
 recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new SideMenuClickListener() {
            @Override
            public void onClick(View view, int position) {

            }

            @Override
            public void onLongClick(View view, int position) {
            }
        }));

static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {

        private GestureDetector gestureDetector;
        private SideMenuClickListener clickListener;

        public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final SideMenuClickListener clickListener) {
            this.clickListener = clickListener;
            gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }

                @Override
                public void onLongPress(MotionEvent e) {
                    View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
                    if (child != null && clickListener != null) {
                        clickListener.onLongClick(child, recyclerView.getChildPosition(child));
                    }
                }
            });
        }

        @Override
        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
            View child = rv.findChildViewUnder(e.getX(), e.getY());
            if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
                clickListener.onClick(child, rv.getChildPosition(child));
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean b) {
        }
    }


text:
Q: Como trazer os valores unicos de uma Array tipo lista conforme a data mais nova Javascript Boa tarde
esse script só funciona se o meu Array sempre estiver ordenador da data mais antiga para a mais nova
Como daria

var dados = [

        ["09/01/2020","JOAO"],
        ["13/01/2020","PAULO"],
        ["23/01/2020","JOAO"],
        ["01/01/2020","JOAO"],
        ["01/01/2020","PAULO"],
        ["02/01/2020","JOAO"],
        ["02/01/2020","PAULO"],
        ["03/01/2020","JOAO"]
    ]

    var novo_dados = []

    ar = []
    function addArr(el,str){
        if(!el.includes(str)){
            el.push(str)
            return true
        }
    }

    for(i=dados.length-1;i>0;i--){
        nome = dados[i][1]
        if(addArr(ar,nome)){
            novo_dados.push(dados[i])
        }

    }
    console.log(novo_dados)

A:

  let dados = [
      ["09/01/2020", "JOAO"],
      ["13/01/2020", "PAULO"],
      ["23/01/2020", "JOAO"],
      ["01/01/2020", "JOAO"],
      ["01/01/2020", "PAULO"],
      ["02/01/2020", "JOAO"],
      ["02/01/2020", "PAULO"],
      ["03/01/2020", "JOAO"]
    ];

    const resultado = [];

    dados
      // Primeiro efetua o parse da Data
      .map(a => {
        const ddMMyyyy = a[0].split('/');

        return [
          new Date(ddMMyyyy[2], +ddMMyyyy[1] - 1, ddMMyyyy[0]),
          ...a
        ]
      })
      // Ordena os registros de acordo com o novo campo Date
      .sort((a, b) => {
          if (a[0] < b[0]) {
            return 1;
          } else if (a[0] > b[0]) {
            return -1;
          } else {
            return 0;
          }
      })
      // Os itens agora estão ordenadas, então podemos garantir que a lógica abaixo irá funcionar
      // Para cada item...
      .forEach(item => {
        const nome = item[2];

        // ...verifica se o nome já foi incluido no resultado
        if (!resultado.some(x => x[1] === nome)) {
          resultado.push([item[1], item[2]]);
        }
      });

    console.log(resultado);


text:
Q: Corrplot. correlation error: 'x' must be numeric. all fields are numeric The purpose:
I have a dataset that contains many loan processing data (dataset: coor_data). Wish to find if their measure of p-values correlation using cor() for a corrplot().
However, my error message:

Error in cor(coor_data) : 'x' must be numeric.

Here is what has been done:
factored serveral attributes in dataset. sapply() to convert character to numeric data for status attribute in dataset. Selected columns.
df_factored_loans <- df_loans %>% mutate(status = as.character(status), state = factor(state), term = factor(term), grade = factor(grade), employment = factor(employment), length = factor(length), home = factor(home), verified = factor(verified), reason = factor(reason))
df_factored_loans$status <- sapply(as.character(df_factored_loans$status), switch, "Charged Off" = 100, "Fully Paid" = 200, "Current" = 300, "Charged Off" = 400, "In Grace Period" = 500, USE.NAMES = F)
coor_data <- select(df_factored_loans, status, amount, rate, payment, income, debtIncRat, delinq2yr, inq6mth, openAcc, pubRec, revolRatio, totalAcc, totalRevLim, accOpen24, avgBal, bcOpen, bcRatio, totalLim, totalRevBal, totalBcLim, totalIlLim)

Here is a sample of dataset: coor_data
dim(coor_data)
[1] 50000    21
length(dimnames(coor_data))
[1] 2
dput(coor_data[1,])
structure(list(status = list(100), amount = 8000, rate = 0.14,
               payment = 272.07, income = 49966, debtIncRat = 30.05, delinq2yr = 0,
               inq6mth = 0, openAcc = 11, pubRec = 0, revolRatio = 0.55,
               totalAcc = 15, totalRevLim = 8100, accOpen24 = 8, avgBal = 4369,
               bcOpen = 43, bcRatio = 95.7, totalLim = 60629, totalRevBal = 48054,
               totalBcLim = 1000, totalIlLim = 52529), row.names = 1L, class = "data.frame")
typeof(coor_data[1,])
[1] "list"

Perform the correlation:
corrplot(cor(coor_data), method="number", na.rm = TRUE, type = "full")

Error in cor(coor_data) : 'x' must be numeric


text:
Q: add a row above the selected row in jquery I am trying to add a row above the selected row to the table in jquery. How to achieve this using jquery. Suppose the table has 4 rows, if i am selecting the 3rd row and click on the add row button a new row should be added above the top of the 3rd row.

A: If I have not misunderstood your question, I have worked on a solution for this. I hope this helps. Plus, always provide the code snippet in your question as that helps to get to the root of the problem.
Here is the dummy HTML for that:

    <button>
      Click1
    </button>

    <button>
      Click2
    </button>

    <button>
      Click3
    </button>

    <button>
      Click4
    </button>

And here is the basic jQuery for that purpose, as suggested earlier, I have used insertBefore() jQuery function:
$('table tr td button').click(function(){
    var appendThis =$("
Added
");
    appendThis.insertBefore($(this).closest("tr"));
});

I hope this helps.
Thanks.


text:
Q: Countdown Timer Objects - Javascript I would like to create a simple timer in Javascript that counts down from a given time until it hits 0. I found this tutorial which worked perfectly. My problem is that I need to place multiple timers on the same page. This tutorial obviously won't do that because it uses global variables (I'm new to JS/Programming so I might not be using the right terms). I tried to re-create the same thing only creating each timer as it's own Object so that they don't interfere with eachother. This is what I have.
function taskTimer(name, startTime) {
  this.timer = name;
  this.totalSeconds = startTime;
  this.tick = function() {
    if (this.totalSeconds <= 0) {
      return;
    }
    this.totalSeconds -= 1;
    this.updateTimer();
    // window.setTimeout("this.tick()", 1000);
  };
  this.updateTimer = function(){
    this.seconds = this.totalSeconds;

    this.hours = Math.floor(this.seconds / 3600);
    this.seconds -= this.hours * (3600);

    this.minutes = Math.floor(this.seconds / 60);
    this.seconds -= this.minutes * (60);

    this.timeString = this.leadingZero(this.hours) + ":" + this.leadingZero(this.minutes) + ":" + this.leadingZero(this.seconds);
    return this.timeString;
  };
  this.leadingZero = function(time){
    return (time < 10) ? "0" + time : + time;
  };
}
var testTimer = new taskTimer("timer", 30);
testTimer.tick();

I created one at the end there. Running
testTimer.updateTimer(); returns 00:00:30 which is correct, but running testTimer.tick(); returns no value. There is obviously something wrong with that part of the code I just can't figure it out.

A: You've got a few problems.

*

*You're calling updateTimer() inside of your tick method, so it
won't ever reach outside of there unless you return it.

*With your current setup, you'd have to call tick manually every time you wanted to update the clock, and if you don't do that precisely every one second the timer will be inaccurate.

*To go with #2, you shouldn't decrement totalSeconds like you are because it isn't guaranteed that it will be exactly one second between triggers of your timeout. Use dates instead.

Here's what I would do: http://jsfiddle.net/R4hnE/3/
// I added optional callbacks. This could be setup better, but the details of that are negligible.
function TaskTimer(name, durationInSeconds, onEnd, onTick) {
    var endTime,
        self = this, // store a reference to this since the context of window.setTimeout is always window
        running = false;
    this.name = name;
    this.totalSeconds = durationInSeconds;

    var go = (function tick() {
        var now = new Date().getTime();
        if (now >= endTime) {
            if (typeof onEnd === "function") onEnd.call(self);
            return;
        }
        self.totalSeconds = Math.round((endTime - now) / 1000); // update totalSeconds placeholder
        if (typeof onTick === "function") onTick.call(self);
        window.setTimeout(tick, 1000 / 12); // you can increase the denominator for greater accuracy.
    });

    // this is an instance method to start the timer
    this.start = function() {
        if (running) return; // prevent multiple calls to start

        running = true;
        endTime = new Date().getTime() + durationInSeconds * 1000; // this is when the timer should be done (with current functionality. If you want the ability to pause the timer, the logic would need to be updated)
        go();
    };
}
// no reason to make this an instance method :)
TaskTimer.prototype.toTimeString = function() {
    var hrs = Math.floor(this.totalSeconds / 60 / 60),
        min = Math.floor(this.totalSeconds / 60 - hrs * 60),
        sec = this.totalSeconds % 60;

    return [hrs.padLeft("0", 2), min.padLeft("0", 2), sec.padLeft("0", 2)].join(" : ");
};

var task = new TaskTimer("task1", 30, function() {
    document.body.innerHTML = this.toTimeString();
    alert('done');
}, function() {
    document.body.innerHTML = this.toTimeString();
});

A: I always have problems with this and in one instance, within the function, I had to redefine it:
this.tick = function() {
  self=this;
  if (self.totalSeconds <= 0) {
    return;
  }
  self.totalSeconds -= 1;
  self.updateTimer();
   // window.setTimeout("self.tick()", 1000);
};

Here is another post about that: var self = this?

A: My version, you can see at:
http://fiddle.jshell.net/hmariod/N7haK/4/
var tmArray = new Array();
var timerRef, timerId=0;

function newTimer(){
    try{
        if(tmArray.length > 4) throw "Too much timers";
        var countDown = parseInt(document.getElementById("tCountown").value,10);
        if(isNaN(countDown)) throw "tCountown is NaN";
        var tmName = document.getElementById("tName").value;
        var nt = new taskTimer(++timerId, tmName, countDown);
        createTmElement(timerId, tmName);
        tmArray.push(nt);
        if(!timerRef) timerRef = setInterval(timerFn, 1000);
        showTimers();
    }catch(er){
        alert("newTimer:" + er);
    }
}

function taskTimer(id, name, tCountown) {
    this.id = id;
    this.tName = name;
    this.tCountown = tCountown;
}

function timerFn(){
    try{
        var i;
        killTimer = true;
        for(i = 0; i < tmArray.length; i++){
           tmArray[i].tCountown--;
            if(tmArray[i].tCountown < 0){
                tmArray[i].tCountown = 0;
            }else{
                killTimer = false;
            }
        }
        if(killTimer) clearInterval(timerRef);
        showTimers();
    }catch(er){
        clearInterval(timerRef);
        aler("timerFn: " + er);
    }
}


text:
Q: Notice: Undefined variable: successMessage in I am getting the following error message on my site.
"Notice: Undefined variable: successMessage in /home/sites/synapsetechnologies.com/public_html/Login.php on line 107 Notice: Undefined variable: error in /home/sites/synapsetechnologies.com/public_html/Login.php on line 107"
Code: https://jsbin.com/biwutacufe/edit?html,output
I took a look at my codes but cannot figure out what is wrong. I have tried the console in Chrome but it doesn't give me a lot of info.
Thanks


text:
Q: Layout issues in IE 6.0 Im having some issues with my layout in IE6 (corporate business, ideally id tell them to shove ie6 :P)
Link to the site is http://www.clickcommercial.co.uk
Ive just applied the twinhelix png fix method and that "appears" to have worked ok - but I was under the impression it should fix the issue with repeat backgrounds?
As you can see, the site works great in IE7+, firefox, safari etc :)
Any help on this is appreciated! :)

A: To fix position of right navigation add this to your code:
#homebox-right { overflow:hidden }

Regarding other issues, I'd reccomend you to install IE Tester where you can preview stuff on IE6 quite easily. You must play a little with margins for IE6.
Plus, I'd recomment to add: img { border:none; } to remove ugly borders from link-images.


text:
Q: Improving the solution to Codejam's 'Infinite House of Pancakes' I'm trying to solve the Codejam 2015's Infinite House of Pancakes problem in the most efficient way. My current solution is similar to the one given in the analysis (but in Python instead of C++):
def solve():
    T = int(input())  # the number of test cases

    for case in range(1, T+1):
        input()  # the number of diners with non-empty plates, ignored
        diners = [int(x) for x in input().split()]

        minutes = max(diners)  # the max stack of pancakes (= the max time)

        # try to arrange all pancakes to stacks of equal height
        for ncakes in range(1, minutes):
            s = sum([(d - 1) // ncakes for d in diners if d > ncakes])  # number of special minutes
            if s + ncakes < minutes:
                minutes = s + ncakes

        print(f'Case #{case}: {minutes}')

The time complexity of this solution is O(D*M), where D is the number of diners and M is the maximum number of pancakes.
However, the analysis also mentions another solution which is O(D*sqrt(M) + M):

Although the algorithm above is fast enough to
  solve our problem, I have an even faster algorithm. Notice that the
  list of ceil(a/1), ceil(a/2), ... only changes values at most
  2*sqrt(a) times. For example, if a=10, the list is: 10, 5, 3, 3, 2, 2,
  2, 2, 2, 1, 1, .... That list only changes value 4 times which is less
  than 2 * sqrt(10)! Therefore, we can precompute when the list changes
  value for every diner in only O(D*sqrt(M)). We can keep track these
  value changes in a table. For example, if Pi=10, we can have a table
  Ti: 10, -5, -2, 0, -1, 0, 0, 0, 0, -1, 0, .... Notice that the prefix
  sum of this table is actually: 10, 5, 3, 3, 2, 2, 2, .... More
  importantly, this table is sparse, i.e. it has only O(sqrt(M))
  non-zeroes. If we do vector addition on all Ti, we can get a table
  where every entry at index x of the prefix sum contains sum of
  ceil(Pi/x). Then, we can calculate sum of ceil(Pi/x)-1 in the code
  above by subtracting the xth index of the prefix sum with the number
  of diners. Hence, only another O(M) pass is needed to calculate
  candidate answers, which gives us O(D*sqrt(M) + M) running time. A
  much faster solution!

Can anyone give me a hint how to translate this to Python?


text:
Q: Casting a char array to an integer Basically I am reading a binary format where 4 bytes specify the size of the string to follow. So i want to cast 4 chars I am reading from a buffer to 1 integer.
Here is what I have.
int FileReader::getObjectSizeForMarker(int cursor, int eof, char * buffer) {
  //skip the marker and read next 4 byes
  int cursor = cursor + 4; //skip marker and read 4
  char tmpbuffer[4] = {buffer[cursor], buffer[cursor+1], buffer[cursor+2], buffer[cursor+3]};
  int32_t objSize = tmpbuffer;
  return objSize;

}

thoughts?

A: It's pretty easy to do the unpacking manually:
unsigned char *ptr = (unsigned char *)(buffer + cursor);
// unpack big-endian order
int32_t objSize = (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];

A: assuming these are stored MSB (i.e. big endian).
unsigned char *p = (unsigned char*)buffer + cursor;
uint32_t uiSize = (unsigned int)*p <<24 |
                  (unsigned int)*(p+1) << 16 |
                  (unsigned int)*(p+2) << 8 |
                  (unsigned int)*(p+3);

Cast the result to a signed int after assembly. Hideous I know, but so are my typing skills.
Note:I honestly can't remember if the implicit up-cast extends the sign from a char to an int or not but if it does, and any of the single bytes being or'd together here are top-bit-lit, you may be in for a surprise if *p was not. Thus the seemingly paranoid unsigned cast-o-festival, and the followup to cast to signed-int only after full assembled.

A: This should do the trick:
objSize = 0;
for (int i = 0; i < 4; ++ i)
    objeSize += ((int)tmpbuffer[i]) << (8 * i);

OR
objSize = 0;
for (int i = 0; i < 4; ++ i)
    objeSize += ((int)tmpbuffer[i]) << (8 * (3 - i));

for big endian as nneonneo pointed out

A: What you have should work fine but replace this
int32_t objSize = tmpbuffer;

for this
int32_t objSize = *((int32_t*)tmpbuffer);

*

*It must be stored and read in the same architecture.

A: You can use the ntohl function to convert from network to host byte-order.  No need to reinvent the wheel.  This also has the advantage of being somewhat portable and will work on big-endian and little-endian OSes as long as the correct headers are used.  Below is a Windows example, but the function is available on Linux as well:
#include <winsock.h>
#include <iostream>

int main()
{
    char buffer[] = "MARK\x00\x00\x00\x08";
    // Point to the 4-byte network (big-endian) order value.
    unsigned long * size = (unsigned long *)(buffer + 4);
    // Dereference and convert it.
    std::cout << ntohl(*size) << std::endl;
    return 0;
}

Output:
8


text:
Q: Configuring Host Name is Not Working in IIS I'm trying to host the web application through IIS7 and assigning an Host Name for accessing it.I have an Static IP assigned to my system.
Added an Static IP as well 127.0.0.1 along with host name in etc file and nothing worked out.
For example : If test.com is my Host Name and if i type test.com in browser it should redirect to my local website which i have hosted in IIS7. But it's referring to Online(Internet) and opening some other hosted site