text:
Q: MongoDB aggregation pipeline: counting occurrences of words in list field from matching documents? Here's a simplified example of what I'm trying to do. My documents all have various things and a keywords field with a list of strings as values. (The lists can contain duplicates, which are significant.) Suppose the following documents match the query:
{'original_id': 33, 'keywords': ['dog', 'cat', 'goat', 'dog']},
{'original_id': 34, 'keywords': ['dog', 'kitten', 'goat', 'moose']},
{'original_id': 35, 'keywords': ['moose', 'elk']}

I want to get back a map of the keywords found with the number of occurrences of each in the set of matching documents:
{'dog': 3, 'cat': 1, 'goat':2, 'kitten': 1, 'moose': 2, 'elk': 1}

(Note that dog in document 33 gets counted twice.)
I'm currently doing this from PyMongo by creating a Counter, calling collection_name.find(...) and then iterating through all the documents updating the counter with each keywords field. But I would like to make the process more efficient by doing it within MongoDB.
Is this kind of counting possible in an aggregation pipeline? If so, how?

A: *

*$unwind deconstruct keywords array

*$group by keywords and count total

*$group by null and construct array of key-value pair

*$arrayToObject convert above array to object key-value format

*$replaceRoot to replace above converted object to root

db.collection.aggregate([
  { $unwind: "$keywords"c },
  {
    $group: {
      _id: "$keywords",
      count: { $sum: 1 }
    }
  },
  {
    $group: {
      _id: null,
      keywords: {
        $push: {
          k: "$_id",
          v: "$count"
        }
      }
    }
  },
  { $replaceRoot: { newRoot: { $arrayToObject: "$keywords" } } }
])

Playground


text:
Q: Why is my character spawning at a 45 degree angle when I've coded it to be set to 0 degrees? The title describes my problem, as you can see here my character is spawning at a 45 degree angle. The character always spawns at (0, 0)
I have created some code for animations that uses the character's position and desired position to calculate at what angle the character should be at. This angle is determined by using the percentage of distance the character has travelled to its destination (these destinations are only Y values. X is increased by 1 every tick). I have made an equation to determine the angle based on the percentage travelled. The equation: -(9/500)X^2 + (9/5)X. This is a parabola that intersects point (0, 0), (50, 45) ← 45 degree angle and (100, 0).
The code I made to use this equation is as follows:
float GetRotationDegrees(int Current, int Target, int LaneWidth) {
    int numerator = Current - LaneWidth;
    int denominator = Target - LaneWidth;
    float X;
    if (denominator == 0) X = 0;
    else X = abs(numerator / denominator * 100);
    return -(9/500)*pow(X,2)+(9/5)*X; // function: -(9/500)X^2 + (9/5)X.
}

The LaneWidth is always 400, Current is the character's current Y coordinate and Target is the target Y coordinate. At Y = 0 the equation should be -400 / -400 * 100 = 100. And when you put 100 in the equation you get 0, this value of 0 is then used like this:
SetActorLocation(FVector(1, sin(angle * PI / 180), 0).Rotation());

I am really confused right now because whenever I manually try this it won't work.
It is probably something stupid I did, I tend to look over things a lot of the time and am not that good at maths (I am also new to C++, so the mistake might be there too). If someone could help me I would really appreciate it!
(By the way, I know that the way that GetRotationDegrees decides X the angle will only return positive angles, I want to get this to work first)

A: Fixed it with this:
float GetRotationDegrees(int Current, int Target, int LaneWidth) {
    if (Current == Target) return 0;
    int MovingFrom;
    if (Target != 0) MovingFrom = 0;
    else if (Target > Current) MovingFrom = -LaneWidth;
    else MovingFrom = LaneWidth;

    float Percentage = float(Current - MovingFrom) / float(Target - MovingFrom) * 100;
    if (Target < Current) Percentage = -Percentage;
    bool isNegative = Percentage < 0;
    if (isNegative) return -(-9 * pow(abs(Percentage), 2) / 500 + 9 * abs(Percentage) / 5);
    return -9 * pow(Percentage, 2) / 500 + 9 * Percentage / 5;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Integration of a second degree polynomial underneath a radical. I have a question about how to apply the substitution rule in an arc length problem. The problem asks for the arc length of $x^2$ on the interval $[-1,2]$.
Here is what I have come up with:
$$y=x^2
\frac {dy}{dx} = 2x
(\frac {dy}{dx}^2 = 4x^2$$
So, $$L = \int_{-1}^2 \sqrt {1+ \frac {dy}{dx}^2}dx
= \int_{-1}^2 \sqrt {1+4x^2}dx$$
So the question is, how do I solve the last step, i.e. $\int_{-1}^2 \sqrt {1+4x^2}dx$?
(If the mathjax is bad, please forgive me, I am just learning)

A: As you wrote, for your problem, the arc length is given by $$L = \int_{-1}^2 \sqrt {1+ \Big(\frac {dy}{dx}\Big)^2}dx
= \int_{-1}^2 \sqrt {1+4x^2}dx$$ For the calculation of the antiderivative, the change of variable $x=\frac{\sinh (y)}{2}$ seems to be a simple one and then $$\int \sqrt {1+4x^2}dx=\frac{1}{2}\int \cosh ^2(y) dy=\frac{1}{4}\int \Big(1+\cosh(2y)\Big)dy=\frac{y}{4}+\frac{1}{8} \sinh (2 y)$$ For $y$, the integration bounds are $-\sinh ^{-1}(2)$ and $\sinh ^{-1}(4)$.
I am sure that you can take from here.

A: I shall give you the indefinite integral using IBP:
$$I=\int \sqrt{4x^2+1}\ dx=x\sqrt{4x^2+1}-\int \frac {(4x^2+1)-1}{\sqrt{4x^2+1}}\ dx$$
This means, $$2I=x\sqrt {4x^2+1}+\frac 12 \int \frac {dx}{\sqrt{x^2+(\frac 12)^2}}$$
Now, $$\int \frac {dx}{\sqrt {x^2+a^2}}=\int \frac {1+\frac {x}{\sqrt {x^2+a^2}}}{x+\sqrt {x^2+a^2}}\ dx=\ln|x+\sqrt {x^2+a^2}|+C$$
Hence we get:
$$I=\frac {x\sqrt {4x^2+1}}{2}+\frac 14 \ln|x+\sqrt {x^2+\frac 14}|+C$$
Now you can put the required limits to obtain the answer.

A: This is a good problem. It demonstrates a lot of what is learned in integral calculus.
$$\int_a^b \sqrt{1+ (\frac{dy}{dx})^2} dx$$
Since $y=x^2$, $y'=2x$.
So the arc length formula becomes:
$$\int_a^b \sqrt{1+ 4x^2} dx$$
Trig sub gives you :
$$\sqrt{1+4x^2}=\sec{\theta}$$
$$\frac{1}{2}\tan{\theta}=x$$
$$\frac{1}{2}\sec^2{\theta}d\theta=dx$$
So:
$$\int \sqrt{1+4x^2}dx=\frac{1}{2}\int \sec^3{\theta}d\theta=\frac{1}{2}\int \sec{\theta}+\sec{\theta}\tan^2{\theta} \ d\theta$$
$$\int \sec{\theta} \ d\theta = \ln{|\sec{\theta}+\tan{\theta}|}+C$$
Use Integration by Parts to integrate the second term.
$$u=\tan{\theta}$$
$$dv=\sec{\theta}\tan{\theta}$$
$$du=\sec^2{\theta}$$
$$v=\sec{\theta}$$
$$\int \sec{\theta}\tan^2{\theta} \ d\theta=\sec{\theta}\tan{\theta}-\int \sec^3{\theta} \ d\theta$$
$$\int \sec^3{\theta} \ d\theta = \frac{1}{2}\ln{|\sec{\theta}+\tan{\theta}|}+\frac{1}{2}\sec{\theta}\tan{\theta}+C$$
So finally:
$$\int \sqrt{1+4x^2} \ dx = \frac{1}{4}\ln{|2x +\sqrt{1+4x^2}|}+\frac{1}{4}2x\sqrt{1+4x^2}+C$$
Plug in the end points to get the length.
A related problem, find the ratio of the  arclength of the curve $y=x^2$ to the length of the latis rectum between the points of intersection of the latis rectum to the parabola. This essentially establishes an analog to $\pi$ for parabolas, i.e. all parabolas are similar with a constant ratio between two characteristic lengths.


text:
Q: perlbrew and local::lib at the same time? So far I have been using the system perl (on Ubuntu 10.10) and I was using local::lib to install CPAN modules in my private directory ~/perl5
As I am trying to use perlbrew it seems that they don't know about each other. I installed perl-5.12.3 using perlbrew but when I switch to it using perlbrew use perl-5.12.3 I still see the PERL5LIB and PERL_MM_OPT set by local::lib.
That's not good:
$ cpan XML::Simple
/home/gabor/perl5/perlbrew/perls/perl-5.12.3/bin/perl: symbol lookup error: /home/gabor/perl5/lib/perl5/x86_64-linux-gnu-thread-multi/auto/Cwd/Cwd.so: undefined symbol: Perl_Gthr_key_ptr

while
$ which cpan
/home/gabor/perl5/perlbrew/perls/perl-5.12.3/bin/cpan

so it is using the right version of the cpan client but dues to the PERL5LIB environment variable it picks up the modules from the wrong place.
Does perlbrew have some compability mode or do I need to turn off PERL5LIB and PERL_MM_OPT manually?

A: It is possible, but not comfortable. If this is a single-user setup, you might be better off not using local::lib and just letting perlbrew manage the modules for you. Also if it's a multi-user setup on a homogenous network, where everyone has the same machine and OS, then you can just set PERLBREW_ROOT to e.g. /net/share/perlbrew and then your installed perls (and their modules) can be shared. As noted in the other answers, this will be a problem if you try to mix machines (and possibly also problematic if you have different operating systems).
On a very diverse network, we prefer to keep everything separate. You can simply setup your local::lib to be a function of your current perl and your current platform, e.g.
distro=lsb_release -d|cut -f2|tr ' ' '-'
arch=`uname -m`
platform="$distro-$arch"

export PERLBREW_ROOT=/net/share/perlbrew/$platform
# You will have to first do 'perlbrew init' (just once for all users)
# In this case you don't need (and shouldn't have) a ~/.perlbrew
source $PERLBREW_ROOT/etc/bashrc

perl5base=/net/share/perl
# When $PERLBREW_PERL is not defined, local::lib puts modules in $perl5base/$platform
perl5=$perl5base/$platform/$PERLBREW_PERL

# We also found that we needed to clean PERL5LIB in between
export PERL5LIB=`echo -n $PERL5LIB|sed "s|${perl5base}[^:]*||g"`
export PATH=`echo -n $PATH|sed "s|${perl5base}[^:]*||g"`

# Setup local lib, relative to the perl being used
lib=$perl5/lib/perl5
mkdir -p $lib
eval $(perl -I"$lib" -Mlocal::lib="$perl5")

This is not our exact script, in particular you would need to check that these directories all exist first. You need to run perlbrew init once per platform and you need to bootstrap local::lib each time as well.
I don't recommend this approach, but provide as an example of one way to make this work, which it does for our mixed network (even on Mac OS). Leaving local::lib out and just using perlbrew (ignoring the system perl), would be a cleaner approach.

A: perlbrew is quite happy to use local::lib and has been for some time -- there are even special options for it -- after running perlbrew install ..., you can create a new local-lib directory with perlbrew lib create ...
for example:
perlbrew install -j 9 --as 34.0 5.34.0
chmod -R a-w $HOME/perl5/perlbrew/perls/34.0
perlbrew lib create 34.0@std
perlbrew switch 34.0@std

This installs a new 5.34.0 build, locks down its modules so you can't change them, then creates a local-lib directory. This install can be used with perlbrew use 34.0@std -- you can create a new set of module installations by perlbrew use 34.0; perlbrew lib create 34.0@other_install, to use side-by-side with the existing one without having to build a new perl again.

A: As miyagawa said, it might not be necessary to use local::lib if you use the Perls installed by Perlbrew exclusively.
But if you still want to be able to switch back and forth between your brewed Perls and the system Perl, there is a script called Perlswitcher for this. It's not pretty but it works. All you need to do is download the script, you could save it as ~/perl5/userperls/bashrc and source it.
It provides two commands. perlswitch allows you to switch to a Perl that was installed by Perlbrew or to the system Perl. perlinfo tells you which Perl is currently being used. You can then use cpanm, which will install packages to your local lib when using the system Perl or directly into the site Perl when using a custom Perl.
After switching to a custom Perl using perlswitch, perlbrew list will also know which Perl is being used:
$ perlswitch perl-5.18.4
Setting new perl /var/www/perl5/perlbrew/perls/perl-5.18.4/bin/perl...
Using user perl (site_perl) instead of local::lib
$ perlbrew list
  perl-5.16.3
* perl-5.18.4
  perl-5.20.2

A: Since I started using perlbrew I stopped using local::lib for the shell use, because now that I have my own perl that i have write permissions to everything, just installing to site_perl is much more straightforward, and that allows me to have different versions of modules for each perl.
I still use local::lib (or more specifically, cpanm's -l or -L options that automatically sets up local::lib directory) to keep application specific dependencies inside an application directory.

A: local::lib was not designed to work with multiple versions of Perl installed at the same time.  Pure-Perl modules aren't usually a problem, but XS modules aren't compatible across major releases.
You can continue to use local::lib for pure-Perl modules (so you don't have to install them for every version of Perl you have brewed up, but XS modules should be installed into the perlbrew-created directories.  You don't need to clear PERL5LIB (and you shouldn't, as XS modules might have pure-Perl dependencies that are installed there), but you will need to clear PERL_MB_OPT and PERL_MM_OPT when installing XS modules to keep them from installing into the local::lib directory.
If you need to continue using local::lib for XS modules for the system Perl, then I suggest creating a second local::lib environment for that (perhaps in ~/perl5sys).  It might be easier to use perlbrew to install a copy of the same version of Perl as the system Perl, and then use that instead of the system Perl.
You can clean out the XS modules in your existing local::lib by removing the /home/gabor/perl5/lib/perl5/x86_64-linux-gnu-thread-multi directory.


text:
Q: What is the expected performance of While loops using `array.pop()` assignment vs other methods Recently I was asked to refactor some code that leverages JavaScript's array.reduce() method because other developers felt the code hard to read. While doing this I decided to play around with some JavaScript array iteration performance benchmarks, to help me validate various approaches. I wanted to know what the fastest way to reduce an array would be, but I don't know if I can trust the initial results:
http://jsbench.github.io/#8803598b7401b38d8d09eb7f13f0709a

I added the test cases for "while loop array.pop() assignments" to the benchmarks linked above (mostly for the fun of it) but I think there must be something wrong with the tests. The variation in ops/sec seem to large to be accurate. I fear that something is wrong with my test case as I don't understand why this method would be so much faster.
I have researched this quite a bit and have found a lot of conflicting information from over the years. I want to better understand what specificity is causing the high variance measured in the benchmark test linked above. Which leads to this post: Given the benchmark example (linked above and shown below), why would the While Loop test case, measure over 5000x faster than its the For Loop counterpart?
//Benchmark Setup
var arr = [];
var sum = 0; //set to 0 before each test
for (var i = 0; i < 1000; i++) {
  arr[i] = Math.random();
}

// Test Case #1
// While loop, implicit comparison, inline pop code
var i = array.length;
while ( i-- ) {
    sum += array.pop();
}

// Test Case #2
// Reverse loop, implicit comparison, inline code
for ( var i = arr.length; i--; ) {
    sum += arr[i];
}

*Edited
In response to the downvotes.
I want this post to be useful. I am adding images to provide context for the links. I removed unnecessary details and refined the content to focus on the questions I am seeking answers for. I also removed a previous example that was confusing.

A: I noticed in your current test framework that you are now playing around with copying the array prior to doing the summing.  I tried this myself and the change destroys the pop() performance advantage.  It's actually slower than the array indexing version.  The array indexing solution seems unaffected by this change.
I think this gives us a clue to what's going on here.  I believe the setup function being optimized together with the test function.  I noticed that the setup time is part of the performance test.  For example, putting console.log calls into setup will dramatically decrease the test operations per second.
When you build an array and then pop every element, you are left with an empty array.  What's likely happening is that the optimizer is able to determine that the array is irrelevant and eliminates it or at least eliminates filling it with values.  Then the function becomes simply a loop that adds numbers.  It may even be optimizing that further.  So while interesting, this experiment probably has little bearing on your real-world problem.


text:
Q: JAX-WS client with AXIS server; missing namespace in response I'm having a problem related to JAX-WS and AXIS. JAX-WS (2.1.7) as a client, Axis (1.4.x) as server.
Everything works OK, but the response can't be read to Java.
Response:
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <soapenv:Body>
  <ns1:myserviceResponse soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:ns1="http://my/service">
   <ns1:myserviceReturn xsi:type="xsd:string">responsestring</ns1:myserviceReturn>
  </ns1:myserviceResponse>
 </soapenv:Body>
</soapenv:Envelope>

The problem is that if ns1:-namespace declaration is removed from myserviceReturn, JAX-WS is able to return anything else than null.
Does anyone have a clue how to force JAX-WS to ignore namespaces, how to modify SOAP response manually to exclude "ns1", or other ideas for this kind of problem?

A: You need to write a custom WSDL file that does not include the name space.  This file goes in the META-INF directory.  You can start with the default one that your app has now, then save it here.


text:
Q: Upgrade to Play Framework 2.2 Securesocial problems Hi I am trying to upgrade to Play 2.2 and am having some problems getting securesocial to work.
I am using the latest snapshot as was suggested in the forums but get the error below. The verify error indicates compiled source incompatibility somewhere between binaries and the version I am using. I have tried switching between java 1.6 and 1.7 but get the same issue.
I know securesocial is only ready for Play 2.1 but there are examples of Play 2.2 using securesocial snapshot.
Perhaps I should just downgrade again.
My Build.scala
object ApplicationBuild extends Build {

  val appName = "rm-play"
  val appVersion = "1.0-SNAPSHOT"

  val appDependencies = Seq(
    // Add your project dependencies here,
    javaCore,
    javaJdbc,
    javaEbean,
    "com.google.guava" % "guava" % "15.0",
    "org.codehaus.jackson" % "jackson-core-asl" % "1.9.13",
    "com.dbdeploy" % "maven-dbdeploy-plugin" % "3.0M3",
    "postgresql" % "postgresql" % "9.1-901.jdbc4",
    "joda-time" % "joda-time" % "2.3",
    "com.github.mumoshu" % "play2-memcached_2.10" % "0.3.0.3",
    "net.spy" % "spymemcached" % "2.9.1",
    "com.amazonaws" % "aws-java-sdk"% "1.6.11",
    "ws.securesocial" %% "securesocial" % "master-SNAPSHOT"
  )

  val main = play.Project(appName, appVersion, appDependencies).settings(
    resolvers += Resolver.sonatypeRepo("snapshots"),
    javacOptions in Compile ++= Seq("-source", "1.7", "-target", "1.7")
  )

}

plugin.sbt
logLevel := Level.Warn

// The Typesafe repository
resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"

// Use the Play sbt plugin for Play projects
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % System.getProperty("play.version")

           _
 _ __ | | __ _ _  _
| '_ \| |/ _' | || |
|  __/|_|\____|\__ /
|_|            |__/

play 2.2.2-RC2 built with Scala 2.10.3 (running Java 1.7.0_04), http://www.playframework.com

> Type "help play" or "license" for more information.
> Type "exit" or use Ctrl+D to leave this console.

[rm-play] $ run
[info] Updating {file:/Users/zola/Development/play/receipt-manager/rm-play/}rm-play...
[info] Resolving org.fusesource.jansi#jansi;1.4 ...
[info] Done updating.

--- (Running the application from SBT, auto-reloading is enabled) ---

[info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000
[info] play - Listening for HTTPS on port /0:0:0:0:0:0:0:0:9443

(Server started, use Ctrl+D to stop and go back to the console...)

[warn] play - Using generated key with self signed certificate for HTTPS. This should not be used in production.
[info] Compiling 12 Scala sources and 19 Java sources to /Users/zola/Development/play/receipt-manager/rm-play/target/scala-2.10/classes...
[info] Compiling 8 Scala sources to /Users/zola/Development/play/receipt-manager/rm-play/target/scala-2.10/classes...
[error] application -

! @6h5hbne72 - Internal server error, for (GET) [/login] ->

play.api.PlayException: Cannot load plugin[Plugin [service.PersistantUserService] cannot been instantiated.]
    at play.api.WithDefaultPlugins$$anonfun$plugins$1$$anonfun$apply$9.apply(Application.scala:159) ~[play_2.10.jar:2.2.2-RC2]
    at play.api.WithDefaultPlugins$$anonfun$plugins$1$$anonfun$apply$9.apply(Application.scala:128) ~[play_2.10.jar:2.2.2-RC2]
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) ~[scala-library.jar:na]
    at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) ~[scala-library.jar:na]
    at scala.collection.immutable.List.foreach(List.scala:318) ~[scala-library.jar:na]
    at scala.collection.TraversableLike$class.map(TraversableLike.scala:244) ~[scala-library.jar:na]
Caused by: java.lang.VerifyError: Stack map does not match the one at exception handler 188 in method service.PersistantUserService.doSave(Lsecuresocial/core/java/Token;)V at offset 116
    at java.lang.Class.getDeclaredConstructors0(Native Method) ~[na:1.7.0_04]
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2404) ~[na:1.7.0_04]
    at java.lang.Class.getConstructor0(Class.java:2714) ~[na:1.7.0_04]
    at java.lang.Class.getConstructor(Class.java:1674) ~[na:1.7.0_04]
    at play.api.WithDefaultPlugins$$anonfun$plugins$1$$anonfun$apply$9.apply(Application.scala:130) ~[play_2.10.jar:2.2.2-RC2]
    at play.api.WithDefaultPlugins$$anonfun$plugins$1$$anonfun$apply$9.apply(Application.scala:128) ~[play_2.10.jar:2.2.2-RC2]

A: So it turns out it was a lot more innocuous than just a difference in compile versions.
What was causing the error was the line below, changing it to using the method rather than the field corrected the problem.
In the logs I found the error

Reason:
      Type 'securesocial/core/java/Token' (current frame, locals[4]) is not assignable to 'model/LocalToken' (stack map, locals[4])

localToken.uuid = token.uuid;

changed to below resolved the issue.
localToken.uuid = token.getUuid();

I am not exactly sure why this helped I don't have all that much experience with scala but the field call generates the method and perhaps it was this causing the problem.

A: SecuresSocial 2.1.3 and master-SNAPSHOT are supposed to work with Play 2.2.1.  I think that what's causing the problem is that your UserService implementation is being compiled for 1.7 but the code that is trying to load it was compiled for 1.6.
By default Scala 2.10 generates bytecode for 1.6. You can generate 1.7 but as far as I understand that feature is experimental.  1.6 is preferred.   I'd change the sbt file to generate 1.6 bytecode.  That should make it work.


text:
Q: Statut bar reappears when User click on uploading file option in an UIWebview on IOS7 I hide de statut bar in My IOS app. Since IOS7, when a user is in a UIWebView and click on a field with upload features (images for exemple), the statut bar appears alone.
How can I correct this bug ?


text:
Q: R dplyr: Creating groups from two identifiers ignoring permutations In the data below, each row includes a first entity ("Country1") and a second entity ("Country2"). I would like to have a variable that groups rows with (Country1,Country2) = (Country1,Country2) or (Country1,Country2) = (Country2,Country1), i.e., common elements but ignoring permutations.
Please comment on the script below, which appears to work but does things I do not understand with by_row().
library(tidyverse)
pairs0  <- read.table(header=TRUE, text="
Country1         Country2
A                B
B                A
A                C
")

## What I want to have:
## Country1        Country2        pairID
## A               B               1
## B               A               1
## A               C               2

pairs1  <- by_row(pairs0,.collate="cols",
                  ..f=function(this_row) {
                      this_row[1,c("Country1","Country2")] %>% unlist %>% sort %>% paste
                  }
                  )

pairs2  <- mutate(pairs1,pairID = group_indices(pairs1,.out1,.out2))

A: Explanation
pairs1  <- by_row(pairs0,.collate="cols",
                  ..f=function(this_row) {
                      this_row[1,c("Country1","Country2")] %>% unlist %>% sort %>% paste
                  }
                  )

by_row - perform rowwise operation  (on this_row)
pairs0 - data frame to operate on
..f=function(this_row) { - this is the operation per this_row
this_row[1,c("Country1","Country2")] - single row of pairs0
unlist - convert single-row data frame to vector
sort - sort elements of vector alphabetically
paste - collapse vector into single string
In the end, for each row, you get something like (i.e. a string)
"A B"

Finish explanation
The following will add an ID number per unique group
pairs2  <- mutate(pairs1,pairID = group_indices(pairs1,.out1,.out2))

mutate - change the following
pairs1 - data frame to operate on
pairID - column to operate on
group_indices - unique group ID


text:
Q: How do I call a python script.exe on click of a button? I have a test.exe written in Python and I want to call it from this location C:\Folder. I know calling .py is possible like the code below:
Code:
import sys
import os
from tkinter import *

window=Tk()

window.title("Running Python Script")
window.geometry('550x200')

def run():
os.system('opencv_video.py')

btn = Button(window, text="Click Me", bg="black", fg="white",command=run)
btn.grid(column=0, row=0)

window.mainloop()

Is there a similar code that calls the test.exe that I have? Any suggestion will be highly appreciated. Thank you very much


text:
Q: Counting higher-order corrections in "ABC theory" I am trying to understand how to enumerate higher-order Feynman diagrams.
In his book on Elementary Particle Physics, Griffiths considers a simple "ABC toy theory" which has:

*

*three (scalar, massive) particles A, B, and C (which are their own antiparticles), and

*only one allowed interaction vertex ABC.

He counts explicitly the number of higher-order diagrams for the process $A+A\to B+B$ at order $g^4$, i.e. with 4 vertices.
What confuses me is that his result changes in the 2nd edition:
In the first edition of his book (p. 207) he finds that there are 15 because each additional line can start at one of the 5 lines of the original $A+A\to B+B$ diagram and end on the same or another line, so enumerating

*

*$1\to1$, $1\to2$, ..., $1\to5$,

*$2\to2$, ..., $2\to5$,

*...

*$5\to5$,

we end up with 15. $\Rightarrow$ This makes sense naively.
However, in the second, revised edition, he talks about 8 diagrams only (p. 217): 5 self-energy diagrams ($i\to i$, a line "sprouts a loop"), two vertex corrections ("a vertex becomes a triangle") and one box diagram.
My question: How many diagrams are there? 15 or 8? Where have the other 7 gone, e.g. a line connecting an initial and a final-state particle? Was it wrong to include them? If so why? Are they equivalent to another diagram or ruled out for some reason?

A: The 8 is correct. The diagrams where you connect one outgoing and one incoming line are equivalent to the ones, where you connect one outgoing line and the internal line, as both lead to the vertex-correction diagram.


text:
Q: INSTALL_FAILED_INSUFFICIENT_STORAGE в eclipse Во время запуска эмулятора из эклипса все время выпадает ошибка
INSTALL_FAILED_INSUFFICIENT_STORAGE

В приложении использую очень простую активити, практически как в примерах. В чем может быть проблема?
A: Можно попробовать запустить через дебаг. Для этого идём в Debug configurations, там проставляем дефолтный эмулятор, который надо запускать, идём сюда: "additional emulator command line options" и прописываем
-partition-size 1024

Если на данный момент запущен какой-то эмулятор типа AVD, то убить. После запускаем дебаг режим. Ошибка не должна появляться. Подробнее здесь


text:
Q: Toggling of data not working with dynammic content using ajax in .net I am making a  live data portal in which I have to display live data using Ajax in asp.net using c#.
I have one table and a div which contains data but in different way/different style.
Every time my page loads after 4 secs of time to show updated data i.e table and div both refreshes to have updated data.
Initially when page loads first time, I have displayed table to show data and hiden the data which is in div's form, if I clicked button(toggle button) it will display data in div's form and hide table data.
Now problem is that when I clicked toggle button it does not display's data in div form but it reloads whole java script
and display data in table every time when I clicked the button.
I want to toggle between table and a div.
Below I have my code what I have done so far.
Please help me what I have done wrong.
Thank You.
Note Data comes from db which is SQL.
<form id="form1" runat="server">

                <%--

--%>

    <button>Toggle Data</button>
</form>

A: Problem
Your page reload since the button tag has by default type='submit' and that will refresh the page.
Solution
You should define your type as type='button' to prevent that behavior, e.g :
<button type='button'>Toggle Data</button>

Hope this helps.

A: Try to add a "return false;" at the end of your click button:
    $('button').live('click', function () {
        $('#div_f').toggle();
        $('#liveData').toggle();
        return false;
    });


text:
Q: Rails one-to-one works for belongs_to but not for has_one I have 2 tables scenarios and rental_details.
The relationships are:

*

*rental_details belongs_to scenarios

*scenarios has_one rental_detail
In the rental_details table I have the scenario_id as a column (note this is as data type INTEGER and not FOREIGN_KEY).
If I run the following in rails console:
rental_details_1 = RentalDetail.find(123)
rental_details_1.id
=> 123
rental_details.scenario.id
=> 22 #i.e. this is linked to scenario with id = 22

However, if I do the following:
scenario_1 = Scenario.find(22)
scenario_1.id
=> 22
scenario_1.rental_details.id

I receive the following error:

NoMethodError: undefined method `rental_details' for

Did you mean?  rental_detail
                 rental_detail=

If I change it to scenario_1.rental_details.id I still receive an error.
If I have a one-to-one relationship such as this, can I not access the rental_details table from the scenario object?  I thought that the foreign key is in the "belongs_to" table I can automatically call its contents from the "has_one" table's object.
(Sorry, I'm new to coding so my terminology is most probably wrong at points).

A: This is expected behavior.
You're still accessing the correct object — a RentalDetail object. If a Scenario has_many RentalDetail, then it'd be accessed using the pluralized form.

A: This is the convention:
Scenario has_one RentalDetail => scenario_1.rental_detail.id (has_one docs). It uses the singular form of RentalDetail.
class Scenario < ActiveRecord::Base
 has_one :rental_detail
end

Scenario has_many RentalDetail => scenario_1.rental_details.pluck(:id) (has_many docs). It uses the pluralized version of RentalDetail.
class Scenario < ActiveRecord::Base
 has_many :rental_details
end

As I said, this is the convetion but nobody stops you from naming the associations as you like. You just need to tell the ActiveRecord to use correct class_name, primary_key, foreign_key, etc. Check the docs.


text:
Q: Haskell - Adding a Tuple to a List of Tuples if not already existing else increase existing value of Tuple I have a Tuple representing a Product:
type Product = (String, Int, Float)
String is the name, Int the amount and Float the price or value.
Now i want to do the following:
I got a List of Products and into that List i want to add a new Product.
But if the Product is already in the List i just want to increase the amount.
(For now i dont care what happens if the price/value is not the same)
"If already in List then increase amount of that Product. Else add it to the List"
Example Input: ("Beer", 9, 3) [("Beer", 1, 3),("Milk", 3, 3),("Tea", 10, 3)]
Expected Output: [("Beer", 10, 3),("Milk", 3, 3),("Tea", 10, 3)]
or
Example Input: ("Apple", 2, 1) [("Beer", 1, 3),("Milk", 3, 3),("Tea", 10, 3)]
Expected Output: [("Beer", 1, 3),("Milk", 3, 3),("Tea", 10, 3),("Apple", 2, 1)]
(The List has no order so it does not matter where the new Product is inside the List)
addProduct :: Product -> [Product] -> [Product]
Sounds easy enough and actually i got a working method that does this:
-- check if a name is inside a List
nameInList :: String -> [Product] -> Bool
nameInList n [(a,b,c)]    = if (a == n) then True else False
nameInList n ((a,b,c):xs) = if (a == n) then True else nameInList n xs

-- add a product to a list if its not already in that list else just increase amount of that product
addProduct :: Product -> [Product] -> [Product]
addProduct (a,b,c) xs  = if nameInList a xs then newList else (a,b,c) : newList
  where newList = [ (a2,b2+b,c2) | (a2,b2,c2) <- xs, a2 == a ] ++ [ (a2,b2,c2) | (a2,b2,c2) <- xs, a2 /= a]

But i was wondering if i can somehow achieve the same using pattern matching and recursion. I also feel like it should be possible without another function that does some checking.

A: Provided you know your list of products will never have a duplicate name, this is indeed quite simple with pure recursion:
addProduct :: Product -> [Product] -> [Product]
addProduct p [] = [p]
addProduct product@(name, amount, price) (product'@(name', amount', price') : ps)
  | name == name' = (name, amount' + amount, price') : ps
  | otherwise = product' : addProduct product ps

(Notice that if the product is being added with a different price to the version currently in the list, this leaves the old price in place - I'll leave it up to your business requirements whether this is even possible and if so what should happen.)
Note the use of as patterns to allow the product tuples to be pattern-matched against while still retaining a way to refer to the whole thing in the recursive case. This isn't essential but makes the code much more readable. And also I've used guards rather than if-then-else - this is more of a personal preference but I think Haskellers generally prefer it this way.
A couple of small notes on your own code:

*

*please use understandable variable names. You'll see I've replaced (a, b, c) with (name, amount, price) because this clearly explains to a reader what the  values actually represent

*if (a == n) then True else False is redundant because it's exactly the same as simply a == n, so you should use the shorter, clearer version.

A: If you represented them as a Map you can make use of the insertWith function
insertWith :: Ord k => (a -> a -> a) -> k -> a -> Map k a -> Map k a

Insert with a function, combining new value and old value. insertWith f key value mp will insert the pair (key, value) into mp if key does not exist in the map. If the key does exist, the function will insert the pair (key, f new_value old_value).

This means you could implement it as follows, inserting what ever logic you want for the price
{-# Language BlockArguments #-}
{-# Language StandaloneKindSignatures #-}

import Data.Kind (Type)
import Data.Map (Map, insertWith)

type Product :: Type
type Product = Map String (Int, Float)

addProduct :: String -> (Int, Float) -> Product -> Product
addProduct = insertWith \(amount1, price) (amount2, _) -> (amount1 + amount2, price)

or if you're fine with biliftA2: addProduct = insertWith (biliftA2 (+) const)


text:
Q: GET Products API call with paging takes increasingly longer with each page number On behalf of an integration with a client using Magento 2, we are fetching products from their Magento system using the /v1/products GET REST API call for version 2.4.4.
They have a large number of products (10,000+), so we are fetching them in page sizes of 250.
The first pages we get go through fine, they take a second or two. But as we go through the page numbers, starting from 1, the requests take longer and longer to complete, until we hit the default timeout we've set.
We can get all the products if we increase the timeout to stupid levels (10 minutes+) and the page size to e.g. 5000+. But isn't this defeating the purpose of the paging? What is the expected behaviour here?
It's as if, for every request, it's hitting a SQL DB and taking more and more records, without skipping ones not needed first?
Here's an example request, for page number 49, where it starts taking 2 minutes+:
URL decoded
https://********/V1/products?fields=items[id,sku,type_id]&searchCriteria[pageSize]=250&searchCriteria[currentPage]=49&searchCriteria[filter_groups][0][filters][0][field]=status&searchCriteria[filter_groups][0][filters][0][value]=1&searchCriteria[filter_groups][1][filters][0][field]=website_id&searchCriteria[filter_groups][1][filters][0][value]=3

A: ?searchCriteria[filterGroups][0][filters][0][field]=store_id&searchCriteria[filterGroups][0][filters][0][value]=1
Replace some of url with this


text:
Q: How secure are the default repositories of Fedora, CentOS, and Debian? UPDATE: this question has, thankfully, been thoroughly answered over on infosecurity:
https://security.stackexchange.com/a/139203/112311
I have struggled to find info on what kind of measures are in place, for the most popular distributions, before a package is added to a repository.
I understand that package integrity is verified from repository to user, but I am specifically wondering about when/how it is checked, from a security perspective, from developer to repository. Are there scripts run on new submissions ? Or machines that are frequently rolled back and used solely to test packages and what they do ?
Apple's App Store, for example, has accidentally hosted malware after developers used an unofficial source of xcode.


text:
Q: How to compare two column values incrementally and copy entire row if the cells in those columns meet a condition I am trying to compare two columns in one workbook and based on a certain condition copy the row where that condition is met to another workbook.
This is for a "database" I am working on. I have a Master sheet and then several versions of sub-masters that are catered specifically to certain individuals.
I have tried to some success by creating two different With statements and using a delete function on the sub-sheet but it is clunky and I'm not a fan of it. Please see the example code below.
Public Sub Workbook_Open()

Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim copyFrom As Range
Dim lRow As Long
Dim strSearch As String
Dim vrtSelectedItem As Variant

Set wb1 = Application.Workbooks.Open("C:\Users\myfolder\Desktop\Excel Master Test\ROLE BASED TRACKER DRAFT.xlsx")
Set ws1 = wb1.Worksheets("Master")

Set wb2 = ThisWorkbook
Set ws2 = wb2.Worksheets("Sheet1")

'~~> Specifies which resources info. you are retrieving
strSearch = "117"
ws2.Cells.Clear

'~~> Copying the header information and formatting.
ws1.Range("1:1").Copy
ws2.Range("1:1").PasteSpecial

With ws1

    '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    With .Range("L1:L" & lRow)
        .AutoFilter Field:=1, Criteria1:=strSearch
         Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
    End With

    .AutoFilterMode = False

End With

'~~> Destination File

With ws2
    If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
        lRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row + 1
    Else
        lRow = .Range("A" & Rows.Count).End(xlUp).Row
    End If
    copyFrom.Copy .Rows(lRow)
End With

With ws2
        '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    With .Range("AD1:AD" & lRow)
        .AutoFilter Field:=1, Criteria1:=strSearch
        .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    End With

    .AutoFilterMode = False

End With

With ws1

    '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    With .Range("AD1:AD" & lRow)
        .AutoFilter Field:=1, Criteria1:=strSearch
         Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
    End With

    .AutoFilterMode = False

End With

'~~> Destination File

With ws2
    If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
        lRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row + 1
    Else
        lRow = .Range("A" & Rows.Count).End(xlUp).Row
    End If
    copyFrom.Copy .Rows(lRow)
End With

With ws2.Sort
    .SetRange Range("A2:A12000")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

wb1.Save
wb1.Close
wb2.Save

End Sub

This is the code that I am trying to get work. I keep getting a Type Mismatch error on my cell comparison lines. '' If ws1.Range("AD1:AD" & lRow) <> ws1.Range("L1:L" & lRow) Then ''
Public Sub Workbook_Open()

Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim copyFrom As Range
Dim lRow As Long
Dim strSearch As String
Dim vrtSelectedItem As Variant

Set wb1 = Application.Workbooks.Open("C:\Users\myfolder\Desktop\Excel Master Test\ROLE BASED TRACKER DRAFT.xlsx")
Set ws1 = wb1.Worksheets("Master")

Set wb2 = ThisWorkbook
Set ws2 = wb2.Worksheets("Sheet1")

'~~> Specifies which resources info. you are retrieving
strSearch = "117"
ws2.Cells.Clear

'~~> Copying the header information and formatting.
ws1.Range("1:1").Copy
ws2.Range("1:1").PasteSpecial

With ws1

    '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    If ws1.Range("AD1:AD" & lRow) <> ws1.Range("L1:L" & lRow) Then

        With .Range("AD1:AD" & lRow)
            .AutoFilter Field:=1, Criteria1:=strSearch
            Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
        End With

        .AutoFilterMode = False

    End If

End With

'~~> Destination File

With ws2
    If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
        lRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row + 1
    Else
        lRow = .Range("A" & Rows.Count).End(xlUp).Row
    End If
    copyFrom.Copy .Rows(lRow)
End With

With ws1

    '~~> Remove any filters
    .AutoFilterMode = False

    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    If ws1.Range("AD1:AD" & lRow) = ws1.Range("L1:L" & lRow) Then

        With .Range("L1:L" & lRow)
            .AutoFilter Field:=1, Criteria1:=strSearch
            Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow
        End With

        .AutoFilterMode = False

    End If

End With

'~~> Destination File

With ws2
    If Application.WorksheetFunction.CountA(.Rows) <> 0 Then
        lRow = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByRows, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Row + 1
    Else
        lRow = .Range("A" & Rows.Count).End(xlUp).Row
    End If
    copyFrom.Copy .Rows(lRow)
End With

With ws2.Sort
    .SetRange Range("A2:A12000")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

wb1.Save
wb1.Close
' wb2.Save

End Sub

A: I just wanted to thank everyone who helped. I am going to just stick with my initial solution of filter, copy, paste, filter, delete, filter, copy, paste, sort.
See my first code block for what I am talking about. Cheers.


text:
Q: adding a new field into the existing table without giving a default value to it [Django] just out of curiosity is there any way to add a new field to the Django model without giving a default value?
Like I have a model and a new field needed but the field can't be null or blank and the default value is not acceptable

A: You can recreate completely the model and table if you are in development process (delete migrations of the app and recall makemigrations and migrate django command) but after this step, it is not possible without data loss
On the other hand, you can use a function to define the default value of a field of a model. This may help you to determine the default value at creation time?
def get_default_value():
    return "value"

message = CharField(default=get_default_value)

More informations: https://docs.djangoproject.com/en/dev/ref/models/fields/#default


text:
Q: APK no compatible con mis dispositivos Android Llevo cuatro actualizaciones de unas de mis apps modificando el AndroidManifest.xml para si logro que en la ficha salga "aplicación compatible con todos tus dispositivos" y no tengo éxito la ficha de la app.
Dispongo de los siguientes dispositivos

*

*EEpad TF101 (ICE_CREAM_SANDWICH)

*ACER LIQUID Z200 (KITKAT)

*MOTO G (Lollipop)

Update
He bajado una versión SDKmin, eliminado support-screen y android:supportsRtl
Defino la API para dispositivos API 14+
En todos consigo instarlo mediante AndroidStudio pero en la ficha de google play, me sale que no es compatible con ningún dispositivo.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pro.caminsderonda.app.caminsderonda"
    android:installLocation="auto">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:name="pro.caminsderonda.app.caminsderonda.MyApplication"
        android:allowBackup="true"
        android:fullBackupContent="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

        <activity
            android:name="pro.caminsderonda.app.caminsderonda.SplashActivity"
            android:configChanges="keyboardHidden|orientation|screenSize"
            android:launchMode="singleInstance"
            android:theme="@style/AppTheme.SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name="pro.caminsderonda.app.caminsderonda.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">

            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data
                    android:host="caminsderonda.wordpress.com"
                    android:pathPrefix="/"
                    android:scheme="https" />
            </intent-filter>
        </activity>

        <activity
            android:name="pro.caminsderonda.app.caminsderonda.DetailedActivity"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name="pro.caminsderonda.app.caminsderonda.SettingsActivity"
            android:label="@string/settings_activity_title" />
        <activity
            android:name="pro.caminsderonda.app.caminsderonda.AboutActivity"
            android:label="@string/about_title_activity"
            android:theme="@style/AppTheme.NoActionBar" />
    </application>

</manifest>

Y en el app.graddle
apply plugin: 'com.android.application'

android {

    compileSdkVersion 23
    buildToolsVersion '23.0.2'
    defaultConfig {
        applicationId 'app.caminsderonda.pro'
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 214
        versionName '2.1.4'
        signingConfig signingConfigs.config
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
   compile fileTree(dir: 'libs', include: ['*.jar'])
   testCompile 'junit:junit:4.12'
   compile 'com.android.support:appcompat-v7:23.4.0'
   compile 'com.android.support:design:23.4.0'
   compile 'com.android.support:recyclerview-v7:23.4.0'
   compile 'com.android.support:cardview-v7:23.4.0'
   compile 'eu.the4thfloor.volley:com.android.volley:2015.05.28'
   compile 'com.android.support:palette-v7:23.4.0'
   compile 'com.github.bumptech.glide:glide:3.6.1'
   compile 'com.android.support:support-v4:23.4.0'
}

Dentro de la consola en el apartado compatibilidad del dispositivo
Compatibles:  10685
Tengo check verde a todos mis dispositivos que tengo, pero aún así en la ficha playstore la que ve el usuario, me sale "Esta aplicación no es compatible con ninguno de tus dispositivos" los tengo asociados todos a la misma cuenta.
Seria de agradecer los que dispongáis de un MotoG si podéis visitar la ficha de la app desde desktop con vuestra cuenta asociada, así poder ver si os muestra si es compatible con vuestro dispositivo
Dejadme un comentario aquí de cómo se os notifica la compatibilidad.
UPDATE / SOLUCIONADO
Por fin ya he encontrado porque me informa que mis dispositivos no son compatibles.
Si la app es de pago, como Google no deja que el mismo developer pueda comprarla, aparece ese mensaje.
Mi última prueba ha sido sacar una nueva app de pago, y después ponerla gratis
Mientras está de pago: Esta aplicación no es compatible con ninguno de tus dispositivos.
Cuando la he puesto GRATIS: Esta aplicación es compatible con todos tus dispositivos.
Gracias a todos, por las respuestas, he marcado como correcta la que más dispositivos compatibles me ha ofrecido.

A: Primeramente podemos descartar que es por el  minSdkVersion  ya que lo tienes definido como 15  (4.0.3 and up)
pero veo que tienes
android:supportsRtl="true" soportado por api 17 en adelante (Android 4.2, 4.2.2)
Si se soporta en todas las densidades y tamaños trata eliminando :
<supports-screens
        android:anyDensity="true"
        android:smallScreens="true"
        android:normalScreens="true"
        android:largeScreens="true"
        android:resizeable="true"
        android:xlargeScreens="true">
    </supports-screens>

En mi caso, no agrego supports-screens ya que es inherente que la aplicación es para cualquier densidad de pantalla.
En el caso de incluir en tu AndroidManifest.xml elementos que usen <uses-feature>, que sirve para filtrar elementos que no reunen caracteristicas de hardware o software, se pueden marcar como "no requeridos", no los incluí al inicio de mi respuesta ya que no tienes este tipo de elementos en tu manifest.xml, pero lo agrego para documentar esta respuesta.
Por ejemplo si definieras el uso de Bluetooth y Camara en tu aplicación, para ciertos dispositivos que no contaran con estas caracteristicas, serian filtrados y no podrias encontrarlos en la playstore:
<uses-feature android:name="android.hardware.bluetooth" />
<uses-feature android:name="android.hardware.camera" />

pero puedes definirlos como "no requeridos" para que los dispositivos que no cuenten con estas caracteristicas, puedan usar tu aplicación:
    <uses-feature android:name="android.hardware.bluetooth"
 android:required="false"/>
    <uses-feature android:name="android.hardware.camera"
android:required="false"/>

para más información;
https://developer.android.com/guide/topics/manifest/uses-feature-element.html
Update:
Revisando con más detenimiento tu AndroidManifest.xml y basándonos en la lista de permisos que implican requerimientos de alguna característica de Hardware
Para ACCESS_WIFI_STATE agrega:
  <uses-feature android:name="android.hardware.wifi" android:required="false" />

Esto quiere decir que los dispositivos que no soporten Wifi no serán filtrados por tu aplicación.

A: Algunos dispositivos no soportan algunas características. Como puede ser una cámara frontal, acceso Wifi u otros. Por esta razón trata siempre de incluir a tus permisos un requiered=false a no ser que sea 100% necesario para que te aplicación funcione.
<uses-permission
 android:name="android.permission.INTERNET"
 android:required="false" />
<uses-permission
 android:name="android.permission.ACCESS_WIFI_STATE"
 android:required="false" />
<uses-permission
 android:name="android.permission.ACCESS_NETWORK_STATE"
 android:required="false" />
<uses-permission
 android:name="android.permission.WRITE_EXTERNAL_STORAGE"
 android:required="false" />
<uses-permission
 android:name="android.permission.READ_EXTERNAL_STORAGE"
 android:required="false" />

Por otro lado, revisa que los números de los SDK de tus archivos proguard-android.txt y proguard-rules.pro coinciden con los de tu gradle. Esto debería ser automático, pero habiendo venido de Phonegap, quiza estos no se han actualizado correctamente.
Espero que te ayude,
un saludo.


text:
Q: Using Facebook social plugin "like" button in Yahoo Site Builder How do I get the iframe code to work on my website built using Yahoo's Site Builder?  It will not accept the Java code in either HTML or the other format without erasing my background.

A: There is actually a very easy way to do so. It's as simple as copy some html and paste. I use Yahoo Sitebuilder frequently and this stumped me for a bit as well but I did find the answer.
When you go onto this next site, and I'll link it.
You can either sign on with your Facebook
account or register a new account with them. The
registration is really simple because it's really just
a 3 question form and you'll be on your way.

*

*Go to ADDTHIS.com and register.

*Once you have completed the registration,
create the buttons that you want to add and
implement them as HTML on your site.
should take you less than 2 minutes to add the like button as well as share buttons for other networks like G+.


text:
Q: Template property of type ControlTemplate accepts both 'DataTemplate & ControlTemplate' in style? Why are we able to assign either of DataTemplate or ControlTemplate to the Template property which is of type ControlTemplate in the below markup:-
<Style TargetType="ListBox">
    <Setter Property="Template">
        <Setter.Value>
            <!--
            Visual Studio Intellisense shows
            both ControlTemplate and
            DataTemplate here.
            -->
        </Setter.Value>
    </Setter>
</Style>

A: I think the answer is just that the Intellisense isn't smart enough (actually for me VS2010 it shows any XAML as valid, not just ControlTemplate and DataTemplate).  The documentation on ListBox  shows that in fact only ControlTemplate is valid.  And this is confirmed if you declare the template as a direct child of ListBox, instead of as a Style:
<ListBox>
    <ListBox.Template>
        <!-- Intellisense lists only ControlTemplate here -->
    </ListBox.Template>
</ListBox>


text:
Q: Is it okay to use functions as object proprty name? Here is code sample:
var eventStack = {};
function addEvent (fn) {
  eventStack[fn] = fn;
}
function removeEvent (fn) {
  delete eventStack[fn];
}
addEvent(alert);
addEvent(console.log);
addEvent(addEvent);

it works whatever function I define myself, but doesn't work for console.log. Instead it's replaced with _firebugignore.
I think there is some magic with toString property
EDIT hmng, I just run my code again, and It worked fine for console.log, previous time both key and value were replaced buy "_firebuignore", I suppose its higgs bugson

A: Yes, there is some magic with Function.prototype.toString: It's implementation-dependent, it only needs to return a representation of the function which is FunctionDeclaration-syntax-like. And of course it can't return a JS function for all those environment-builtin functions (like console.log).
However, I don't think it is a good idea to identify a function by its string representation at all. It can easily happen that two different functions end up in the same string (examples: two identical function expressions, identical function declarations in different scopes - or closures, builtin-functions (Array.prototype.toString.toString() == Function.prototype.toString.toString()).
Instead, use an Array for your eventStack and check for a function's existance by indexOf().

A: Property names can only be strings.  Other types are coerced to string values as necessary. When you iterate over properties with for ... in you get strings.


text:
Q: How to detect the python package name inside the script I am trying to install pip libraries inside a python script so I would issue the command:
os.system('python -m pip install requests > null 2>&1')

However this script will be run by different users on different hosts and on some hosts, python package is installed as python2 or python3 (same for pip) rather that just python. This makes the command above not work since it doesn't detect the name python.
So is there any way to detect the python package name on the client hosts so the installation can work?
(I know that it's better to use the subprocess library to install pip packages but I am using os.system for a specific reason).

A: You can use sys.executable to get full path to python:
>>> import sys
>>> sys.executable
'/home/***/.pyenv/versions/3.8.1/bin/python3.8'

Then use that path to run python
os.system('{} -m pip install requests > null 2>&1'.format(sys.executable))


text:
Q: Realloc Invalid Pointer in C This is a homework assignment so I don't want to post any code, but I'm pretty stumped with the bug that I have.
Currently I have a array that has been malloced and am copying the pointer to the array. Now, I can memcpy and memmove with this array and that works fine.
However, when I do a realloc with it an invalid pointer error comes up - and I have absolutely no idea why.
Can anyone help?

A: realloc() only works if the pointer you pass it was one returned earlier from malloc(), calloc() or realloc() (or is NULL, in which case it works exactly like malloc()).
You can not call it on arrays.  If you have a struct like this:
struct foo {
    char a;
    int x[5];
    double z;
};

then you cannot use realloc() to increase the size of x.  You must instead switch to using entirely dynamic allocation: the struct member changes to a pointer:
struct foo {
    char a;
    int *x;
    double z;
};

...and when you create an instance of the struct, you call malloc() for the initial allocation:
struct foo f;

f.x = malloc(5 * sizeof f.x[0]);

Now you can call realloc() on f.x, but the cost is that you must also call free() on f.x when the struct is no longer needed.

A: When realloc or free result in an invalid pointer error or segfault, and you are sure that you are passing a valid pointer obtained from malloc, then a good possibility is that you corrupted your memory: You wrote to the area where malloc stores the book keeping of the memory blocks. In your case this is a memcpy or memmove call.
You can use the valgrind memory error detector to help you find these kind of errors.

A: you said 'I copy the pointer to this array into another variable'.  The problem is as soon as you do a realloc, the original pointer is no longer valid.  I dont see the reason to copy the pointer to a variable?


text:
Q: Best way to spoof geo ip information in xDB I am looking to spoof the geo ip information in my local sitecore 8 instance so I can create events widget based on which city the end user is in.
From my research I found you can either use the ForwardedRequestHttpHeader in the header to pass the IP or my own class to override the IP via startTracking pipeline. Both these method allow me to write the IP address into the Interaction collection in my xDB.
My question is how do I resolve the spoofed IP to get rest of the details in Interaction collection document such as city, state, country and postcode?
Please note: I currently do not have access to the sitecore geolocation service. So really need a way to mock all the geo location based data.

A: Not sure if it helps, but 8.1's Experience Explorer allows you to (natively) spoof locations. If you expand out the ribbon and goto the Experience Tab and click "Other" you'll see "Explore":

Once you click that, the UI will change over and expose two expandable tabs (on left and right). On the left slide-out, you can manage location by going to the "Visitor Information" section and opening the "GEO IP" tab.

A: What I needed to was to spoof the IP address but also create a custom geo ip lookup provider by overriding the method GetInformationByIp(string ip) in
LookupProviderBase.


text:
Q: How to check is the given  is already fully downloaded or not? First when I run ipfs --offline block stat <ipfs_hash> and if the hash does not locally exist I get following message: Error: blockservice: key not found.

*

*Afterwards I run following: ipfs object stat <ipfs_hash> and after getting a valid output

*I run ipfs --offline block stat <ipfs_hash> again , now it always return valid information (hence does not give an error) even the hash is not downloaded.  So assuming if  ipfs --offline block stat <ipfs_hash> gives and Error message is not correlated that the given hash is locally downloaded.
How can I resolve this in order to detect if the asked hashed is fully downloaded or not?

I can do something like ipfs refs local | grep <hash> , but I don't want to keep fetch all the hashes and it will be slower when there is hundreds of hashes exist.
Related: https://discuss.ipfs.io/t/how-to-check-is-the-given-ipfs-hash-and-its-linked-hashes-already-downloaded-or-not/7588

A: ipfs files stat --with-local --size <path> returns the downloaded percentage of the requested ipfs hash. If its 100.00% than we can verify that its fully downloaded into local ipfs repo.

ipfs files stat <path> - Display file status.

--with-local  bool   - Compute the amount of the dag that is local, and if possible the total size.
--size        bool   - Print only size. Implies '--format=<cumulsize>'. Conflicts with other format options. ```

$ hash="QmPHTrNR9yQYRU4Me4nSG5giZVxb4zTtEe1aZshgByFCFS"
$ ipfs files stat --with-local --size /ipfs/$hash
407624015
Local: 408 MB of 408 MB (100.00%)


text:
Q: MYSQL food ordering portal database design I'm trying to create a database for a restaurant ordering portal, I've created the tables excluding the payment table. I'm a bit stuck on whether its the correct structure.  If i could get any feedback it would be greatly appreciated! so the database should allow the following:

*

*allow the customer to order

*restaurant can update/add to menu

*restaurant can confirm/deny an order

(i havent added Pkeys or Fkeys yet)
CREATE TABLE Customer (
customerID INT(11) NOT NULL,
Fname VARCHAR(100) NOT NULL,
Lname VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL,
phone INT(14) NOT NULL,
address VARCHAR(255) NOT NULL,
postcode VARCHAR(20) NOT NULL

CREATE TABLE CusOrder (
orderID INT(11) NOT NULL,
prodname VARCHAR(55) NOT NULL,
quantity INT(11) NOT NULL,
price FLOAT(10 , 2 ) NOT NULL,
totalprice FLOAT(10 , 2 ) NOT NULL,
menuID INT(11) NOT NULL,
deliveryfee FLOAT(10 , 2 ) NOT NULL,
customerID INT(11) NOT NULL

CREATE TABLE resturantMenu (
menuID INT(11) NOT NULL,
deliveryfee FLOAT(10 , 2 ) NOT NULL,
productName VARCHAR(255) NOT NULL,
productPrice FLOAT(10 , 2 ) NOT NULL

CREATE TABLE resturantLogin (
resturantUserID INT(11) NOT NULL,
menuID INT(11) NOT NULL,
username VARCHAR(255) NOT NULL,
pass VARCHAR(255) NOT NULL,
restDetails VARCHAR(255) NOT NULL,
restPhone INT(14) NOT NULL,
restAddress VARCHAR(255) NOT NULL,
restPostcode VARCHAR(20) NOT NULL

CREATE TABLE orderConfirm (
orderID INT(11) NOT NULL,
resturantUserID INT(11) NOT NULL,
status ENUM('yes','no') NOT NULL

not afraid of criticism so please fire away :)

A: First: don't code, draw.  It's much easier to make mistakes in diagrams than it is to try and visualize relations, keys, etc. in code.  At this point in design column types are irrelevant.  Focus on keys and relations.
This may be a good starting point*:

Here we have customers who can place orders for restaurants.  Those orders cannot contain items not offered by that restaurant.  Those orders can include the same item at different prices (buy 1, get 1 50% off, etc).  Those orders can include fees, including delivery fees which can be looked up from a schedule.
Questions not answered by this diagram:

*

*How do we determine if a OrderLine is a menu item or a charge and enforce that?

*How is the status of an Order defined?

*What exactly encompasses OrderLineCharge?

*Should the order request a menu item/quantity which is then becomes an OrderLine?

*When an MenuItem is requested but can't be fulfilled, what happens?

*How are price changes stored?

*Should we track types of cuisine or categories of menu items?

*How is delivery tracked?

*How are payments tracked?

*How do we track quantity discounts ($2 each, 3 for $5, etc)?

*Should it be 'OrderId' or 'OrderNumber'

That is a lot of questions we won't solve with lines of code or table definitions, at least not yet.
The next steps I'd recommend are:

*

*Familiarize yourself with ERDs, specifically IDEF1X which are easily read and understood

*Start thinking about business rules and how they might shape your data model - what problems can you solve through constraints/relations?  Which problems will require the transactions to contain rules?

*I'm leaving a lot out because this isn't something that can be answered in one step - I don't know if this is a homework assignment, hobby project, or actual work.


text:
Q: Ok to return const references/pointers to std::vectors across dll boundaries? I have business logic in a separate dll, and to be able to export a class from this dll for use by for example GUI classes, I have been told not to pass any std template objects like std::vector across the dll interface boundary. However, I am allowed to pass references and pointers to template type objects.
When would it be ok to pass a reference or a pointer to a std::vector (filled with pointers if that makes a difference) to code outside of the business logic/across the dll boundary (as a return value from getters). Example:
const std::vector<int*>& getNumbers();
const std::vector<int*>* getNumbers();

Can I always to this? What are the implications of the two alternatives compared to just passing by value?
Or should I avoid passing the std::vector altogether and what would be the alternatives in that case?
EDIT: I know passing of objects across dll boundaries is problematic and you have to know which compiler is used etc. I am wondering if returning const references and pointers can be a workaround in anyway, since I was told that it is, and if this is good practice.

A: Any reason that justifies "not to pass any std template objects like std::vector across the dll interface boundary" will apply equally to passing pointers and references to std::vector.
When the code across the boundary dereferences the pointer, it will run into the same issue.
So, no.


text:
Q: Public static variables and Android activity life cycle management According to the documentation the Android OS can kill the activity at the rear of the backstack.
So, say for example I have an app and open the Main Activity (let's call it Activity A). In this public activity class I declare and initialize a public static variable (let's call it "foo"). In Activity A's onCreate() method I then change the value of "foo." From Activity A the user starts another activity within my app called Activity B. Variable "foo" is used in Activity B. Activity B is then paused after the user navigates to some other activities in other apps. Eventually, after a memory shortage occurs, Activity A then Activity B can be killed. After the user navigates back to my app it restarts (actually "recreates") activity B.
What happens:

*

*Will variable "foo" at this point have the value that was set to it when Activity A's onCreate() method ran?

*Variable "foo" does not exist ?

*Variable "foo" exists and but is now the initialized value and not the value set in Activity A's onCreate() method ?

A: The answer is (3). If you need to keep values, persist them in shared preferences when each activity pauses and restore them when it resumes. Alternatively, you can also maintain an "initialized" static flag and re-initialize the static variables from any activity's onCreate() method if it is false.

A: If the process is killed then all static variables will be reinitialized to their default values.
So whatever value you have set in Activity A will not persist

A: Good explanation can be viewed here from 2:50
http://www.infoq.com/presentations/Android-Design
Here are some instructions for those who want to test this issue manually:
Create android v.4 emulator, then go to settings -> developer settings -> disable background tasks.
Then create sample android project with 2 activities,
declare static variable in activity A, initialize it in onCreate() method.
Place a button in activity A that starts activity B.
In Activity B's onCreate() method print the value of A.staticVar to logcat.
Launch the project - activity A appears. Hit the button - activity B appears, value of static variable is printed to logcat. Press the home button and launch any other program - your sample project process will be killed (because you have disabled background processes).
Now long-press on home button - you will see the list of recently launched programs. Select your sample project - OS will try to recover your project's activities back-stack and recreate last running activity B. But at this step program will crash with NullPointerException because A.staticVar will be null, and we are trying to print it to logcat.


text:
Q: java gui builder custom jlabel How do I add a custom JLabel in Netbeans' gui builder?

A: If you're just looking to see how to create JLabel's dynamically, you're close, although the snippet of code you posted in a comment has several errors in it.  Here's a similar example to your code:
import javax.swing.*;

public class Jpl extends JPanel {
    public static final String[] LABEL_TEXT = {"Monday", "Tuesday",
        "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

    public Jpl() {
        for (int i = 0; i < LABEL_TEXT.length; i++) {
            JLabel lbl = new JLabel();
            lbl.setText(LABEL_TEXT[i]);
            add(lbl);
        }
    }

    private static void createAndShowUI() {
        JFrame frame = new JFrame("Jpl");
        frame.getContentPane().add(new Jpl());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                createAndShowUI();
            }
        });
    }
}

If on the other hand, you're trying to create your own class that extends from JLabel that you can put in the NetBeans GUI-builder palette, then things will be a bit more difficult.
edit: but not impossible.  Custom components can be added via NetBeans Palette Manager.  For more on this, please check this link:  Creating GUIs with NetBeans Check the section on Custom Components


text:
Q: cant get media query to work I created a website that is mostly responsive, but it needed a little help when viewed on smaller screens.  I tried to add an @media query to the css page, but it doesn't seem to be making any difference.
I only added different style rules in my main css page, and did not add anything to my html.  I am confused on how media queries work exactly, so maybe that's my problem?
Here is my css
/*Alt styles for smaller screens*/
@media only screen and (max-width: 780px) {

     div.price-area1 {
          width: 100%;
          text-align: center;
     }

     div.price-area2 {
          width: 100%;
          text-align: center;
     }

     div.price-area3 {
          width: 100%;
     }

     input.submit {
          width: 60%;
          margin-left: 20%;
     }

     nav {
          width: 100%;
     }

     nav ul li {
          position: relative;
          float: left;
          width: 50%;
          font-family: 'Poiret One', cursive;
          margin-bottom: 15px;
          text-align: center;
          font-size: 24px;
     }
}

A: The easiest way to understand media queries is to read about it here and here:
With that said, you may want to use a framework such as bootstrap which is a great way to start a site. Otherwise you can use this template for media queries:
/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen and (min-width : 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen and (min-width : 1824px) {
  /* Styles */
}

/* iPhone 4 ----------- */
@media only screen and (-webkit-min-device-pixel-ratio:1.5), only screen and (min-device-pixel-ratio:1.5) {
  /* Styles */
}

This is a good starting point if you want to do it all yourself.


text:
Q: Chaining apollo retryLink and errorLink Should Apollo retryLink come before or after the errorLink? Some examples show it as before https://medium.com/@joanvila/productionizing-apollo-links-4cdc11d278eb#3249 while some show it after https://www.apollographql.com/docs/react/api/link/apollo-link-rest/#link-order.

A: It depends how you want your errorLink logic to work, from the docs

Additive composition involves combining a set of links into a serially executed chain

and the Error Link

is called after the GraphQL operation completes and execution is moving back up your link chain

so if you place the retryLink before the errorLink
ApolloLink.from([retryLink, errorLink])

the errorLink will also be executed with the retries once the respective result is traveling back up the chain, in other words (if you are using the default docs example), there should be a console log on every attempt and attempts.max console logs in total.
In case the order is flipped the errorLink will be called after the retryLink is complete and the result traveled all the way back up, so there should be 1 console log from the errorLink call.


text:
Q: Basis of Lie Algebra $\mathfrak{su}(3)$ With the matrices below, apparently $\{u_k = -\frac i2 \lambda_k| k=1,2,\cdots,8\}$ forms a basis of $\mathfrak{su}(3)$

How could that be true? $-\frac i2 \lambda_1$ shouldn't even be an element of $\mathfrak{su}(3)$, it isn't hermitian.

A: The problem is explained here as follows: the $8$-dimensional real Lie algebra $\mathfrak{su}(3)$ has a basis $\lambda_1,\ldots ,\lambda_8$ as above, consisiting of Hermitian matrices. However, the Lie bracket of this subspace of $3\times 3$ matrices is not given by the commutator $AB-BA$, because the commutator of two Hermitian matrices is not Hermitian again in general. Of course, we could insist on a different Lie bracket given by $[A,B]=i(AB-BA)$. However, a more popular solution is to pass to anti-Hermitian matrices, which gives an isomorphic Lie algebra, but this time with the more natural Lie bracket $[A,B]=AB-BA$. For a similar discussion on MSE, see here.


text:
Q: Cancel a Future and still retrieve its return value I have a recorder class that polls for values from a data source every n milliseconds. The whole this is supposed to run asynchronously and return a collection containing the recorded data.
My Idea was to have an ExecutorService with a single thread and a Callable that does the data polling. The callable is supposed to be interrupted, so the caller does not have to wait for any Thread.sleep calls to finish. To interrupt he Callable i call Future.cancel(true) on the Future returned from the ExecutorService:
class Recorder {
    private DataSource source;
    private ExecutorService executor;
    private Future<List<MyData>> dataFuture;

    private class FixedPollRateCallable {
        private DataSource source;
        private long pollrate;

        public FixedPollrateCallable(DataSource source, long pollrate) {
            this.source = source;
            this.pollrate = pollrate;
        }

        public List<MyData> call() throws Exception {
            List<MyData> dataList = new ArrayList<>();
            while(!Thread.currentThread().isInterrupted()) {
                dataList.add(source.getData());
                try {
                    Thread.sleep(pollrate);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            return dataList;
        }
    }

    public Recorder(DataSource source) {
        this.source = source;
        this.executor = Executors.newSingleThreadExecutor();
    }

    public void startRecording(long pollrate) {
        if(dataFuture != null && !dataFuture.isDone())
            throw new RecordingException();

        dataFuture = executor.submit(new FixedPollRateCallable(source, pollrate);
    }

    public void stopRecording() {
        dataFuture.cancel(true);
    }

    public List<MyData> getRecordedData() throws InterruptedException, ExecutionException {
        return dataFuture.get();
    }
}

But when calling the whole thing like this:
recorder.startRecording();
recorder.stopRecording();
recorder.getRecordedData();

I get a java.util.concurrent.CancellationException on the recorder.getRecordedData() call.
I guess that besides interrupting the Thread, cancel(true) also sets a cancellation flag, so calls to Future.get() will always fail.
Is there any way around that, or do you know about a better alternative that allows me to interrupt a Thread, breaking out of Thread.sleep() and still being able to return a value?

A: Well, you ask for something that conceptually does not make sense:
Lets quote the javadoc for get():
Throws: CancellationException - if the computation was cancelled
And for cancel() it says:
After this method returns, subsequent calls to isDone() will always return true. Subsequent calls to isCancelled() will always return true if this method returned true.
In other words: you probably need some other kind of mechanism here. For example, you could change your Runable to push the already collected information instead of returning it.
In other words: instead of using a Future to get all data at some point; why don't you simply send all data to a "safe sink" directly upon arrival? Your approach is to poll; but obviously: polling and interrupting do not go hand in hand!
Edit: right now you create your Recorder like this:
 public Recorder(DataSource source)

so you built to receive "data" from source. An easy solution could be to have
 public Recorder(DataSource source, List<MyData> sink)

as well.
And instead of keeping a local dataList in your Runable ... you simply append to the sink provided to the recorder.
Me using the word "safe" simply refers to the fact that need to pay attention when multiple threads start updating the same list for example.


text:
Q: Nodejs application using "node postgres" having a "Connection terminated unexpectedly" every 60min in GKE I have multiple applications that run using Node.js and pg (node-postgres).
The issue i have is that every app is getting the error "Connection terminated unexpectedly" every hour. Here is the error :
> node ./dist/app.js

App Started
events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: Connection terminated unexpectedly
    at Connection.con.once (/app/node_modules/pg/lib/client.js:255:9)
    at Object.onceWrapper (events.js:286:20)
    at Connection.emit (events.js:198:13)
    at Socket.<anonymous> (/app/node_modules/pg/lib/connection.js:139:10)
    at Socket.emit (events.js:203:15)
    at endReadableNT (_stream_readable.js:1145:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
    at connectedErrorHandler (/app/node_modules/pg/lib/client.js:202:10)
    at Connection.con.once (/app/node_modules/pg/lib/client.js:272:9)
    at Object.onceWrapper (events.js:286:20)
    [... lines matching original stack trace ...]
    at process._tickCallback (internal/process/next_tick.js:63:19)

Here is how i connect my Client to the database :
Database.ts:
import { Client, QueryResult } from 'pg';

export default class DatabaseModule {

    private client: Client;

    constructor() {
        this.client = new Client({
            connectionString: process.env.DATABASE_URL
        });
    }

    public init(): Promise<any> {
        return this.client.connect();
    }
}

app.ts:
Promise.all([
    express.init(),
    database.init()
])
.then(() => {
    console.log("App Started");
    [load routes...];
})
.catch((error) => {
    console.error(error);
    process.exit(1);
});

All works fine on local but not on production.
On production we are running every app as micro services in Google Kubernetes Engine. Is there any config in K8s that may cause this connection loss every hour ? (even if the Client is idle or not idle, this error happens)
NAME                                                    READY   STATUS    RESTARTS   AGE
my-service-57c9f99767-wnm47                             2/2     Running   96         4d

As you can see, my app has 96 restarts: 4 days * 24 hours = 96 => error every hour that crashs the pod.
We are using a postgreSQL server hosted by Google Cloud SQL, and every app in K8s has an access to it with a local address.
EDIT:
I just found this in the Google Cloud SQL documentation :
WebSockets are always available to your application without any additional setup. Once a WebSockets connection is established, it will time out after one hour.
So the error was generated from the usage of pg.Client with a persistent connection to the SQL server. I will try to use pg.Pool().
Here is the explanation of why i should use pool instead of client : https://stackoverflow.com/a/48751665/12052533

A: I found the problem :
In the Google Cloud SQL documentation : WebSockets are always available to your application without any additional setup. Once a WebSockets connection is established, it will time out after one hour.
The error was generated by the usage of pg.Client() because i had a persistent connection into my database which is a bad practice. A client shall connect to the database then end its connection after it finished executing a query.
I will use pg.Pool() as it will generate clients and it is better for multiple requests.
After the generation of a client i juste have to release all my clients.
I removed the database.init() and modified the database.query() function like the following :
     public query(command: string, args?: Array<any>): Promise<QueryResult> {
        if (args === undefined)
            args = [];
        return this.pool.connect()
            .then((client: Client) => {
                return this.queryClient(client, command, args)
            })
            .then((result: QueryResult) => {
                return result;
            })
            .catch((error) => {
                throw error;
            });
    }

     private queryClient(client: Client, command: string, args?: Array<any>): Promise<QueryResult> {
        return client.query(command, args)
            .then((result: QueryResult) => {
                client.release();
                return result;
            }).catch((error) => {
                client.release();
                throw error;
            })
    }

A: What I am seeing wrong in your code is, you didnt closed the connection after making client.connect().
Whenver we connects a client or pool, It means all our request is going throw that connection, but if you are not going to close it after usage, it will keep on pilling up, as after sometime, your database connection is going to crash !
So best practice according to me for 1-2 queries use pool.query() as it open and automatically closes the connection, we do not have to do it manually.
or whenver use have lots of sql query in single api use  const client = pool.connect(), and then client.query(),  close the connection by client.release();


text:
Q: How can I process a python dictionary with callables? I would like to create a python directory whose values are to be evaluated separately.
So, for example, in the following non-working example I define
a = {'key1': 'value1', 'key2': 42, 'key3': foo(20)}

for which e.g.
def foo(max):
    """Returns random float between 0 and max."""
    return max*random.random()

and after processing of the dict I want to have e.g.
a_processes = {'key1': 'value1', 'key2': 42, 'key3': 12.238746374}

The example does not work since the value of key key3 is immediately  evaluated, and foo(20) is no callable. The way it could work would be to use something like
a = {'key1': 'value1', 'key2': 42, 'key3': foo}

but here foo will miss its arguments. One way to handle this would be to define the dict in the following way
a = {'key1': 'value1', 'key2': 42, 'key3': [foo, 20]}

with the following processing scheme
a_processed = dict([k,process(v)] for k,v in a.items())

in which process is a meaningful function checking if its argument is a list, or if the first element is a callable which gets called with the remaining arguments.
My question is about a better way/idea to implement my basic idea?

A: Use the functools.partial() to create a callable that'll apply a set of arguments to another callable:
from functools import partial

a = {'key1': 'value1', 'key2': 42, 'key3': partial(foo, 20)}

Now the key3 value is a callable object; a['key3']() will in turn call foo(20) and return the result.
You'd still need to 'process' this dictionary (testing with the callable() function:
{k: v() if callable(v) else v for k, v in a.iteritems()}

of course. If you are using Python 3, use a.items() instead.
A functools.partial setup let's you add additional arguments as needed (provided foo() supports them):
a['key3']('additional', arguments='accepted')

You could even create a dictionary subclass that does this automatically when accessing a key:
def CallablesDict(dict):
    def __getitem__(self, key):
        value = super(CallablesDict, self).__getitem__(key)
        return value() if callable(value) else value

then define a as:
a = CallablesDict({'key1': 'value1', 'key2': 42, 'key3': partial(foo, 20)})

print a['key3']  # calls foo(20)

A: I often use an argument-free lambda here, just because I like the syntax:
>>> def foo(x):
...     return x*100
...
>>> a = {'key1': 'value1', 'key2': 42, 'key3': lambda: foo(20)}
>>> a
{'key3': <function <lambda> at 0x96ae80c>, 'key2': 42, 'key1': 'value1'}
>>> {k: v() if callable(v) else v for k,v in a.iteritems()}
{'key3': 2000, 'key2': 42, 'key1': 'value1'}


text:
Q: Change drop-shadow with Javascript without jQuery I want to add the style -webkit-filter: drop-shadow(5px 5px 5px #222); in JavaScript without jQuery.
I want create a shadow for png transparent image duration with CSS transform.
This code is not working correctly:

var scscsc = document.getElementById('scscsc');
scscsc.setAttribute("style", "-webkit-filter: drop-shadow(5px 5px 5px #222);");
scscsc.style.transform = "rotate(216deg)";
body {
  margin: 0px;
  padding: 0px;
  text-align: center;
}
img {
  position: absolute;
  top: 0;
  left: 0;
}
<img src="http://sirati.info/tmp/ss.png" id="scscsc">

A: Uzbekjon's answer will only work if that is the only CSS property you are using. It's preferable to set inline CSS using the style property of the element like so:
var elt = document.getElementById("#your-element-id");

elt.style.setProperty("-webkit-filter", "drop-shadow(5px 5px 5px #222)");

Edit: here is a working JSfiddle demonstrating this works
https://jsfiddle.net/w4n024b4/

A: Try this:
var elt = document.getElementById("#your-element-id");

elt.setAttribute("style", "-webkit-filter: drop-shadow(5px 5px 5px #222);");


text:
Q: Zend Framework 1.12 - Zend Command Line PHP deprecated I use  local server - "WebServ", directory : "D:\Program Files\WebServ\php".
My directory to Zend library: "D:\Library\ZendFramework".
I add path to bin folder of zend and path to php.ini file
Variable Path - "D:\Program Files\WebServ\php;**C:\Program Files\Java\jdk1.8.0_05\bin\;D:\Library\Android SDK\sdk\tools\;D:\Program Files\TortoiseSVN\bin;**D:\Library\ZendFramework\bin"
Now when I insert into comand line (in Windows):
zf show version
I have output:
C:\Users\Mati>zf show version
PHP Deprecated:  Directive 'register_globals' is deprecated in PHP 5.3 and greater in Unknown on line 0

Deprecated: Directive 'register_globals' is deprecated in PHP 5.3 and greater in Unknown on line 0
PHP Warning:  require_once(Zend/Config/Ini.php): failed to open stream: No such file or directory in
 D:\Library\ZendFramework\library\Zend\Tool\Framework\Client\Config.php on line 90

Warning: require_once(Zend/Config/Ini.php): failed to open stream: No such file or directory in D:\Library\ZendFramework\library\Zend\Tool\Framework\Client\Config.php on line 90
PHP Fatal error:  require_once(): Failed opening required 'Zend/Config/Ini.php' (include_path='.;c:\
php\includes;D:\Library\ZendFramework\library;D:\Biblioteki\ZendFramework\extras\library') in D:\Library\ZendFramework\library\Zend\Tool\Framework\Client\Config.php on line 90

Fatal error: require_once(): Failed opening required 'Zend/Config/Ini.php' (include_path='.;c:\php\includes;D:\Library\ZendFramework\library;D:\Biblioteki\ZendFramework\extras\library') in D:\Library\ZendFramework\library\Zend\Tool\Framework\Client\Config.php on line 90

A: You have two problems here: one is that your server php configuration uses flag register_globals which is deprecated. Not sure if you need it but better to turn it off for security reasons. You can turn it off in your php.ini
Second error is php can't find file. I'm not a Win user, so I can't really help you but I would check is it ok to have spaces in include_path and also try path withou "**" in it. And ofcource just to be 100% proof make sure that file is there.


text:
Q: Writing a program to create variables as it needs them in C I am writing a program in C to read in text from a FASTA file and for every name (ex. >COTV-SPAn232-096) I want my program to recognize the '>' and then use the following text before the \n to be used as the name for the variable.
The problem with hard coding the variables is that this program needs to be as dynamic as possible as it may be reading in an arbitrary number of different data sets. For example my testing set has 15 different sequences that look something like this:

COTV-SPAn232-096
  MKILNSYNDFIISFINFILFPTIQNVSISKLNILGYILSFIRIISISMDFDILKFSNIIQDYGLIFPDDIKKIQNEKFLVLERGLSGKLYAIHIYDFMARFDNETIFGIAKFLYRNNTKILDVLFINKDLFDKTDILYPKSTITLSSYSDEYIDYTYKTIKLIFLNLFNSFRFSKIDSKLSYLYLPLRKDINNVIL

The plan is read in the name of the sequence, set that name as the variable for a dynamic array and use malloc/realloc to handle storing the actual sequence for a later comparison of all the different sequences. I can handle everything except the variable variable names.
Briefly looking around for an answer to this, it seems as though it cannot be done in C though can be in python and some other languages. I am really hoping that is not the actual case though in the event that it is Does anyone have alternative suggestions for handling this problem? And yes this is bioinformatics and I probably should be using python, perl, java, or some other language but I would rather continue with this problem in C to become further versed in C.
Thanks in advance for any answers that I may receive!

A: This isn't possible in C, but there is never a reason for creating variables with dynamic names (indeed, even once you created such variables in C, how would you use them?)
Instead, use a hash table- that's a data structure that maps from keys to values. In your case, you would want it to map from strings (your sequence names) to strings (your sequences).
Examples of C libraries for hash tables abound online: this StackOverflow question provides a few.

A: The bad news is that it cannot be done in C, because C variables are a compile-time concept. Variables serve as "labels" for memory regions containing the data; once the compiler is done, the names of most variables are thrown away. They may be written to a separate file for the debugger, but that's a convenience for humans.
The good news is that you do not need a new variable to be named a new name. All you need is a second variable containing a name. A pair of variables - one for the name and one for the value is all you need.

A:
The plan is read in the name of the sequence, set that name as the variable for a dynamic array and use malloc/realloc to handle storing the actual sequence for a later comparison of all the different sequences. I can handle everything except the variable variable names.

Instead of naming the variable with the sequence header/name, create a struct that holds the sequence header/name and the sequence, e.g.:
typedef struct {
    char *header;
    char *sequence;
} fasta_t;

Then create a list of fasta_t pointers ("pointer to pointers"):
fasta_t **fasta_elements = NULL;

Use malloc() to allocate space for N elements of type fasta_t *, e.g.:
fasta_elements = malloc(N * sizeof(fasta_t *));

It's a good idea to check if you actually got the memory you asked for:
if (!fasta_elements) {
    /* i.e., if fasta_elements is still NULL */
    fprintf(stderr, "ERROR: Could not allocate space for FASTA element list!\n");
    return EXIT_FAILURE;
}

(You should get into the habit of doing this with every pointer you malloc(), in my opinion.)
Now that space has been allocated, read in N elements (use realloc() if we need to make the list bigger, but let's assume N elements for now). Within a loop, allocate space for an individual fasta_t pointer, as well as space for header and sequence char *s within the fasta_t pointer:
#define MAX_HEADER_LENGTH 256
#define MAX_SEQUENCE_LENGTH 4096

/* ... */

size_t idx;
char current_header[MAX_HEADER_LENGTH] = {0};
char current_sequence[MAX_SEQUENCE_LENGTH] = {0};

for (idx = 0U; idx < N; idx++)
{
    /* set up space for the fasta_t struct members (the header and sequence pointers) */
    fasta_elements[idx] = malloc(sizeof(fasta_t));

    /* parse current_header and current_sequence out of FASTA input */
    /* ... */

    /* validate input -- does current_header start with a '>' character, for instance? */
    /* data in bioinformatics is messy -- validate input where you can */

    /* set up space for the header and sequence pointers */
    /* sizeof(char) is redundant in C, because sizeof(char) is always 1, but I'm putting it here for completeness */
    fasta_elements[idx]->header = malloc((strlen(current_header) + 1) * sizeof(char));
    fasta_elements[idx]->sequence = malloc((strlen(current_sequence) + 1) * sizeof(char));

    /* copy each string to the list pointer, for which we just allocated space */
    strncpy(fasta_elements[idx]->header, current_header, strlen(current_header) + 1);
    strncpy(fasta_elements[idx]->sequence, current_sequence, strlen(current_sequence) + 1);
}

To print out the i+1'th element's header, for example:
fprintf(stdout, "%s\n", fasta_elements[i]->header);

(Remember that indexing is 0-based in C — the 10th element has index 9, for instance.)
When finished, be sure to free() individual pointers within a fasta_t * pointer, the fasta_t * pointer itself, and then the fasta_t ** pointer to pointers:
for (idx = 0U; idx < N; idx++)
{
    free(fasta_elements[i]->header), fasta_elements[i]->header = NULL;
    free(fasta_elements[i]->sequence), fasta_elements[i]->sequence = NULL;
    free(fasta_elements[i]), fasta_elements[i] = NULL;
}
free(fasta_elements), fasta_elements = NULL;

For convenience, once you get the hang of dealing with structs and memory management, you'll want to write wrapper functions that set up, access, edit and break down a fasta_t * element, as well as wrapper functions that do the same for a list of fasta_t * elements.