text:
Q: Papyrus 2.0.1 installation fail on eclipse neon (Release 4.6.1) Eclipse for PHP Developers
Version: Neon.1a Release (4.6.1)
Build id: 20161007-1200
http://download.eclipse.org/modeling/mdt/papyrus/updates/releases/neon

Papyrus version: 2.0.1
I am currently using above eclipse version on windows 2012 R2 64bit environment and when I am trying to install Papyrus 2.0.1 plugin using above URI via Install new software wizard. This only download until 26% and not continue to complete. (Internet connection is working properly I have 2MBps connection and other eclipse updates working fine). Kindly advice.

A: I re-installed Eclipse Neon (executed eclipse-installer/eclipse-inst.exe from wherever I had previously had the eclipse-inst-win64.exe unpack everything) and selected to provision a Papyrus project during the install phase.
Prior to that, the Install New Software would report errors about not finding various packages (log message: "No repository found containing: osgi.bundle,org.eclipse.wst.common.core,1.2.0.v200908252030")
Various attempts at modifying the Available Sites (appending "/" to those entries missing them was suggested for a previous Eclipse release) ended up killing the Available Sites list, so I started over. After restart, Eclipse ran some updates and now seems to work, though I haven't actually made any drawings yet.


text:
Q: JavaFX Canvas: Draw a shape exclusively within another shape I'm currently developing a game in Java, and I've been trying to figure out how to draw a shape (e.g. a circle) to the canvas, on top of a different shape (e.g. a square), but to only draw the parts of the circle which are intersecting the square, similar to a clipping mask between layers in Photoshop.
I've tried using GraphicsContext.clearRect() to clear the areas where the bottom shape is not, but that removes the background.
The code below produces this result:

However, this is the result I desire:

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;

public class CircleWithinSquareTest extends Application {
    @Override
    public void start(Stage stage) throws Exception {
        int width = 200;
        int height = 200;
        Canvas canvas = new Canvas(width, height);
        GraphicsContext gc = canvas.getGraphicsContext2D();

        AnimationTimer timer = new AnimationTimer() {
            final int bgCellSize = 8;
            final int x = 100;
            final int y = 100;
            double angle = 0;

            @Override
            public void handle(long now) {
                /* Draw checkered background */
                gc.setFill(Color.WHITE);
                gc.fillRect(0, 0, width, height);
                gc.setFill(Color.LIGHTGRAY);
                boolean odd = false;
                for (int y = 0; y < height; y += bgCellSize) {
                    odd = !odd;
                    for (int x = odd ? 0 : bgCellSize; x < width; x += bgCellSize * 2) {
                        gc.fillRect(x, y, bgCellSize, bgCellSize);
                    }
                }
                /* Draw square */
                gc.setFill(Color.BLUE);
                gc.fillRect(x, y, 50, 50);
                /* Draw circle */
                gc.save();
                angle += 5;
                if (angle >= 360) {
                    angle = 0;
                }
                Rotate r = new Rotate(angle, x, y);
                gc.setTransform(r.getMxx(), r.getMyx(), r.getMxy(), r.getMyy(), r.getTx(), r.getTy());
                gc.setFill(Color.RED);
                gc.fillOval(x, y, 30, 30);
                gc.restore();
            }
        };
        timer.start();

        Group root = new Group(canvas);
        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }
}

A: You can use clipping, add next code before setTransform:
gc.beginPath();
gc.rect(x, y, 50, 50);
gc.closePath();
gc.clip();

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parallelizing Simpson's Method in C using pthreads and OpenMp I am fairly new to the whole multiprocessing and parallelizing world. I am currently working on an algorithm to implement Simpson's Method and Simpson 3/8. I have already implemented the algorithm in C in its serial form.
I need some help to parallelize both of this algorithms using, OpenMp and Pthreads. Any recommendation is welcome and appreciated.
//Simpson.c
#include <stdio.h>
#include <stdlib.h>

double function(double x) //función a la cual se le aplicará el método
{
  return 0.5*x;
}

int main(int argc, char*argv[])
{
  double resultado = 0.0; //resultado de la integral tras aplicar el método de simpson
  double a = 0.0;  //límite inferior de la integral
  double b = 0.0;  //límite superior de la integral
  int n = 0; //cantidad de particiones entre los intervalos, tiene que ser un número par
  int i = 0; //variable para poder iterar sobre las diferentes particiones
  double h = 0.0; //variable para guardar el incremento que habrá entre cada valor de "x"
  double calc = 0.0; //variable intermedia para ir acumulando el resultado de evaluar las diferentes "x" en la función

  //variables para almacenar los diferentes valores de "x", es decir los límites inferiores y superiores y el valor intermedio de cada partición
  double x0 = 0.0;
  double x1 = 0.0;
  double x2 = 0.0;

  printf("Introduce el límite inferior: ");
  scanf("%lf", &a);
  printf("Introduce el límite superior: ");
  scanf("%lf", &b);
  printf("Introduce la cantidad de particiones (número par): ");
  scanf("%d", &n);

  h = (b-a)/n; //se calcula el incremento para poder iterar sobre todas las particiones

      //Para el cálculo de la integral se utilizan xj, x(j+1) y x(j+2) en el subintervalo [xj, x(j+2)] para cada i = 1, 3, 5, ..., n

  for (i=0; i<=n; i+=2)
  {
    x0 = a + h*i; //límite inferior
    calc += function(x0); //se evalua la x en la función

    x1 = a + h*(i+1); //valor intermedio
    calc += 4*function(x1);

    x2 = a + h*(i+2); //límite superior
    calc += function(x2);

    calc *= ((x2-x0)/6) ; //se vuelve a calcular el incremento entre nuestros límites, y se divide entre 6

    resultado += calc; //variable para ir acumulando los cálculos intermedios de cada "x"
  }

  printf("La aproximación a la integral es: %f \n", resultado);

}

#include<stdio.h>
#include<math.h>

// función a integrar
#define f(x) (0.5*x)

int main()
{
  float b; //Limite superior
  float a; //Limite inferior
  float resultado=0.0;
  float dx;
  float k;
  int i;
  int N;  //numero de intervalos o iteraciones

 // Entradas
 printf("Dame el limite inferior: ");
 scanf("%f", &a);
 printf("Dame el limite superior: ");
 scanf("%f", &b);
 printf("Número de iteraciones/intervalos (número par): ");
 scanf("%d", &N);

  //Calculando delta de x
  dx = (b - a)/N;

  //Sumas de la integracion
  resultado = f(a) + f(b); //primera suma

  for(i=1; i<= N-1; i++)
  {
    k = a + i*dx; //Suma del intervalo

    if(i%3 == 0)
    {
      resultado = resultado + 2 * f(k);
    }
    else
    {
      resultado = resultado + 3 * f(k);
    }
  }

  resultado = resultado * dx*3/8;

  printf("\nEl valor de la integral es: %f \n", resultado);
  printf("\n");

  return 0;
}

A: My first recommendation is to start by reading a lot about the shared-memory paradigm and its problems. Then read about Pthreads and OpenMP, and only then look at concrete OpenMP and Pthread parallelizations, and how they deal with some of the issues of the shared-memory paradigm. If you have to learn both Pthreads and OpenMP, in my opinion, if I were you I would start by looking into Pthread first and only then looking into OpenMP. The latter helps with some of the cumbersome details, and pitfalls, of coding with the former.
I will try to give you a very general (not super detailed) formula on how to approach a parallelization of a code, and I will be using as an example your second code and OpenMP.
If you opt to parallelize an algorithm, first you need to look at the part of the code that is worth parallelization (i.e., the overhead of the parallelization is overshadowed by the speedups that it brings). For this profiling is fundamental, however, for smaller codes like yours it is pretty straightforward to figure it out, it will be typically loops, for instance:
for(i=1; i<= N-1; i++)
  {
    k = a + i*dx; //Suma del intervalo

    if(i%3 == 0)
    {
      resultado = resultado + 2 * f(k);
    }
    else
    {
      resultado = resultado + 3 * f(k);
    }
  }

To parallelize this code, which constructor should I use tasks ? parallel for ? you can look at the great answers to this topic on this SO thread. In your code, it is pretty clear that we should use parallel for (i.e., #pragma omp parallel for). Consequently, we are telling to OpenMP to divide the iterations of that loop among the threads.
Now you should think about if the variables used inside the parallel region should be private or shared among threads. For that openMP offers constructors like private, firstprivate, lastprivate and shared. Another great SO thread about the subject can be found here. To evaluate this you really need to understand the shared memory paradigm and how OpenMP handles it.
Then look at potential race conditions, interdependencies between variables and so on. OpenMP offers constructors like critical, atomic operations, reductions among others to solve those issues (other great SO threads atomic vs critical and reduction vs atomic). TL;DR : You should opt for the solution that gives you the best performance without compromising correctness.
In your case reduction of the variable "resultado" is clearly the best option:
 #pragma omp parallel reduction ( +: resultado)
 for(i=1; i<= N-1; i++)
  {
    k = a + i*dx; //Suma del intervalo

    ...
  }

After you guarantee the correctness of your code you can look at load unbalancing problems (i.e., the difference among the work performed by each thread). To deal with this issue openMP offers parallel for scheduling strategies like dynamic and guided (another SO thread) and the possibility of tuning the chunk size of those distributions.
In your code, threads will execute the same amount of parallel work, so no need to use a dynamic or guided schedule, you can opt for the static one instead. The benefit of the static over the others is that it does not introduce the overhead of having to coordinate the distributions of tasks among threads at-runtime.
There is much more stuff to look into to extract the maximum performance out of the architecture that your code is running on. But for now, I think it is a good enough start.


text:
Q: How to avoid "this.fireAuth.auth.createUserWithEmailAndPassword is not a function" when using akita-ng-fire I've just followed most of the akita-ng-fire example + doc to setup the auth in my ionic project.
I've installed @angular/fire(6.0.2), akita-ng-fire(1.5.13), firebase(7.19.1), angular lib(10.0.0), ionic libs(5.0.0).
Here is my model:
export interface Profile {
  displayName: string;
  photoURL: string;
  organizationIds: string[];
}

export function createProfile(profile: Partial<Profile>): Profile {
  return {
    displayName: '',
    photoURL: '',
    organizationIds: [],
    ...profile,
  };
}

Here is my query:
import { Injectable } from '@angular/core';
import { Query } from '@datorama/akita';
import { AuthStore, AuthState } from './auth.store';

@Injectable({ providedIn: 'root' })
export class AuthQuery extends Query<AuthState> {
  profile$ = this.select('profile');
  userId$ = this.select((state) => state.profile.id);
  roles$ = this.select('roles');
  isLoggedIn$ = this.select((state) => !!state.profile); // check section "roles" below

  constructor(protected store: AuthStore) {
    super(store);
  }
}

Here is my store:
import { Injectable } from '@angular/core';
import {  Profile } from './auth.model';
import {  Store, StoreConfig } from '@datorama/akita';
import { FireAuthState, RoleState } from 'akita-ng-fire';

export interface AuthState extends FireAuthState<Profile>, RoleState {}

const initialState: AuthState = {
  uid: null,
  profile: null,
  roles: {},
  loading: false,
  emailVerified: false,
};

@Injectable({ providedIn: 'root' })
@StoreConfig({ name: 'auth' })
export class AuthStore extends Store<AuthState> {
  constructor() {
    super(initialState);
  }
}

And here is my service:
import { Injectable } from '@angular/core';
import { AuthStore, AuthState } from './auth.store';
import { CollectionConfig, FireAuthService } from 'akita-ng-fire';
import { createProfile } from './auth.model';

@Injectable({ providedIn: 'root' })
@CollectionConfig({ path: 'users' })
export class AuthService extends FireAuthService<AuthState> {
  formatFromFirestore = createProfile;

  constructor(store: AuthStore) {
    super(store);
  }

  onCreate() {
    console.log('Logged from onCreate hook');
  }

  onDelete() {
    console.log('Logged from onDelete hook');
  }

  onUpdate() {
    console.log('Logged from onUpdate hook');
  }

  onSignup() {
    console.log('Logged from onSignup hook');
  }

  onSignin() {
    console.log('Logged from onSignin hook');
  }

  onSignout() {
    console.log('You have been signed out. Logged from onSignout hook');
  }
}

I've set the environment's firebase + initialized firebase in my app.module.
But, when in my app, I'm trying to make a call to the service:
  async doLogin() {
    await this.authService.signup('aaa@bbb.com', 'xxxyyyzzz');
    await this.authService.signin('aaa@bbb.com', 'xxxyyyzzz');
  }

I get this error in chrome dev tools:
[WDS] Live Reloading enabled. core.js:4197 ERROR Error: Uncaught (in promise): TypeError: this.fireAuth.auth.createUserWithEmailAndPassword is not a function TypeError: this.fireAuth.auth.createUserWithEmailAndPassword is not a function
    at AuthService.<anonymous> (akita-ng-fire.js:1181)
    at Generator.next (<anonymous>)
    at tslib.es6.js:74
    at new ZoneAwarePromise (zone-evergreen.js:960)
    at __awaiter (tslib.es6.js:70)
    at AuthService.signup (akita-ng-fire.js:1179)
    at AppComponent.<anonymous> (app.component.ts:80)
    at Generator.next (<anonymous>)
    at tslib.es6.js:74
    at new ZoneAwarePromise (zone-evergreen.js:960)
    at resolvePromise (zone-evergreen.js:798)
    at zone-evergreen.js:705
    at rejected (tslib.es6.js:72)
    at ZoneDelegate.invoke (zone-evergreen.js:364)
    at Object.onInvoke (core.js:27436)
    at ZoneDelegate.invoke (zone-evergreen.js:363)
    at Zone.run (zone-evergreen.js:123)
    at zone-evergreen.js:857
    at ZoneDelegate.invokeTask (zone-evergreen.js:399)
    at Object.onInvokeTask (core.js:27424)

What could I've missed? What to do to initialize auth? I'm looking everywhere, but I can't find what I've missed.
I've dumped the this.authService before calling it, I'm seing a fireAuth property, but no auth below. Is there some kind of incompatibility?


text:
Q: Script awk to make an HTML file I have one CSV file of suicides between 1985 and 2016, and I wanted to make an HTML from one output that I have generated using awk. With this command I counted the total amount of suicides in every country, and also I included GDBpc. The code I used and the output that I obtained with that code is the following:
tail -n +2 suicidios_final.csv | awk -F, 'BEGIN {print "Country" " " "Year " " "GDPpc" " " "Suicides"}1 {a[$1 " " $2 " " $11]+=$5} END{for (i in a) print i, a[i]}' > suicides1.txt

(head -n 1 suicides1.txt && tail -n +2 suicides1.txt | sort) > suicides.txt

cat suicides.txt

Country Year GDPpc Suicides
Albania 1987 796 73
Albania 1988 769 63
Albania 1989 833 68
Albania 1992 251 47
Albania 1993 437 73
Albania 1994 697 50
Albania 1995 835 88
Albania 1996 1127 89
Albania 1997 793 170
Albania 1998 899 154
Albania 1999 1127 139
Albania 2000 1299 54
Albania 2001 1451 119
Albania 2002 1573 133
Albania 2003 2021 124
Albania 2004 2544 146
Albania 2005 2931 0
Albania 2006 3235 0
Albania 2007 3863 124
Albania 2008 4672 160
Albania 2009 4387 0
Albania 2010 4359 96
Antigua and Barbuda 1985 3850 0
Antigua and Barbuda 1986 4740 0
Antigua and Barbuda 1987 5595 0
Antigua and Barbuda 1988 6693 0
Antigua and Barbuda 1989 7407 0
Antigua and Barbuda 1990 7744 1
Antigua and Barbuda 1991 7976 0
Antigua and Barbuda 1992 8087 0
Antigua and Barbuda 1993 8453 1
Antigua and Barbuda 1994 9062 0
Antigua and Barbuda 1995 8636 0
Antigua and Barbuda 1998 10078 0
Antigua and Barbuda 1999 10378 0
Antigua and Barbuda 2000 11021 2
Antigua and Barbuda 2001 10468 2
Antigua and Barbuda 2002 10499 0
Antigua and Barbuda 2003 10878 1

I have the output in one .txt folder and I would like to make an HTML with it. The script that Im using to do this is
#!/bin/bash

awk 'BEGIN {
    split("80,80,150,150,", widths, ",")
    print ""
    print "
"
}
NR == 1{
    print "
"
    tag = "th"
}
NR != 1{
    print "
"
    tag = "td"
}
{
    for(i=1; i<=NF; ++i) print "<" tag " width=\"" widths[i] "\">" $i "</" tag ">"
    print "
"
}
END { print "
"}' suicides.txt > table.html

But with this script I create one HTML like this:
Country     Year    GDPpc   Suicides
=====================================
Albania     1987    796     73
Albania     1988    769     63
Albania     1989    833     68
Albania     1992    251     47
Albania     1993    437     73
Albania     1994    697     50
Albania     1995    835     88
Albania     1996    1127    89
Albania     1997    793     170
Albania     1998    899     154
Albania     1999    1127    139
Albania     2000    1299    54
Albania     2001    1451    119
Albania     2002    1573    133
Albania     2003    2021    124
Albania     2004    2544    146
Albania     2005    2931    0
Albania     2006    3235    0
Albania     2007    3863    124
Albania     2008    4672    160
Albania     2009    4387    0
Albania     2010    4359    96
Antigua     and     Barbuda     1985    3850    0
Antigua     and     Barbuda     1986    4740    0
Antigua     and     Barbuda     1987    5595    0
Antigua     and     Barbuda     1988    6693    0
Antigua     and     Barbuda     1989    7407    0
Antigua     and     Barbuda     1990    7744    1
Antigua     and     Barbuda     1991    7976    0
Antigua     and     Barbuda     1992    8087    0
Antigua     and     Barbuda     1993    8453    1
Antigua     and     Barbuda     1994    9062    0
Antigua     and     Barbuda     1995    8636    0
Antigua     and     Barbuda     1998    10078   0
Antigua     and     Barbuda     1999    10378   0
Antigua     and     Barbuda     2000    11021   2
Antigua     and     Barbuda     2001    10468   2
Antigua     and     Barbuda     2002    10499   0
Antigua     and     Barbuda     2003    10878   1
Antigua     and     Barbuda     2004    11535   2
Antigua     and     Barbuda     2005    12649   0
Antigua     and     Barbuda     2006    14114   0
Antigua     and     Barbuda     2007    15775   1

As you can see, the countries that have spaces in names, for example, "Antigua and Barbuda", are separated by columns in the HTML, and I would like to have them in the first column, related with the countries.
Someone know what could be happend and how could I solve it?
Thanks a lot!

A: The issue you have is that you have not used commas in the suicide.txt file.
If you use commas, then you can use commas as the field separator when generating the HTML and the spaces in names won't cause an issue.


text:
Q: How to set del or access environment vars / ArcPy Error "No Free Units (LUNGET)" This concerns the same error as Debugging No Free Units (LUNGET) from RasterToASCII_conversion() in ArcPy?.
Would anyone know how or where ArcPy is setting these directory paths below?  After exactly 12 iterations of TopoToRaster it stops with the Error "No Free Units (LUNGET)".   The below is output to the terminal, whether it completes successfully or throws this error.
*** Open files ***

Type Unit Acc Mem Count File
---- ---- --- --- ----- ----

 AF   43  rw   n   1    d:\usr\appdata\local\temp\sha1635
 AF   44  rw   n   1    d:\usr\appdata\local\temp\sha1643
 AF   45  rw   n   1    d:\usr\appdata\local\temp\sha1615
 AF   46  rw   n   1    d:\usr\appdata\local\temp\sha1621
 AF   47  rw   n   1    d:\usr\appdata\local\temp\sha1627

For each separate iteration I create and set a new scratch workspace with arcpy.env.scratchWorkspace and default workspace with arcpy.env.workspace and set arcpy.env.overwriteOutput = 1.  But I am not setting these paths below and I don't know how to change them in the environment settings, or capture their paths to delete their contents.
OS is Windows 10 and I am using ArcPy in VSCode via ArcGIS Pro v2.8.


text:
Q: Set values of $x \in \mathbb{R}$ in a way that given series is convergent. Problem
We have series defined as:
$$ \sum_{n=1}^{\infty}\frac{1}{n}x^{n} $$
Define $x$ in a way that the series is convergent when $x \in \mathbb{R}$
Attempt to solve
I would start off simply with some trial and error.
$x=0 \quad \text{everything is 0}$
$x=1  \quad 1+\frac{1}{2}+\frac{1}{3}+\frac{1}{4}\dots \quad \text{converges} \rightarrow 2$
$x=2 \quad 2+2+\frac{8}{3}+4\dots \quad \text{diverges}\rightarrow \infty$
$x=3 \quad 3+\frac{9}{2}+9+\frac{81}{4}\dots \quad \text{diverges}\rightarrow \infty$
If we try to insert negative x values we can note that there is $x^n$ which means every $x\in(2,4,6,8,\dots)$ will give positive value and every $x\in(1,3,5,7,9,\dots)$ will give negative value. Doesn't seem it would be convergent. Mayby divergent but there isn't enough proof of this.
I would say this series is convergent when $ 0 < x < 1 $
There is possibly more definitive way to find out all $x\in \mathbb{R}$ values that the series will converge. If someone can help with this that would be highly appreciated.
(Also i am not implying this would be considered as the correct solution)

A: Hint
Read the following Wikipedia articles:

*

*Cauchy-Hadamard theorem

*Harmonic series

*Alternating series test

A: Guide:
For the series, $\sum_{n=1}^\infty a_n$, compute the limit
$L = \lim_{n \to \infty}|\frac{a_{n+1}}{a_n}|$, according to ratio test:

*

*if $L<1$, the series converges absolutely.

*if $L>1$, the series diverges,

*if $L=1$ or undefined, the test is not conclusive.
Also reading on Harmonic series might help you with the boundary case.


text:
Q: Posting a comment to Reddit API with NodeJs Request module So I'm building a pretty silly bot for a fellow Redditor. And it needs to log in, then post a comment. The Reddit documentation is fairly sparse, IMHO, so I'm hoping that someone can show me where I'm going wrong.
As I understand it, I need to post to https://ssl.reddit.com/api/login, retrieve a cookie and then send that cookie, along with the provided modhash to https://api.reddit.com/api/comment. But I keep getting a 403 statusCode when I follow these steps. I'm sure there's something silly that I'm missing, but I can't seem to tell what it is.
Relevant code:
var request = require('request')
  , modhash;

request.defaults({jar:true});

function login () {
  var options = {
      url     : 'https://ssl.reddit.com/api/login?api_type=json&user=USERNAME&passwd=PASSWORD&rem=true',
      headers : {
        'User-Agent' : 'fooBot/0.1 by USERNAME'
      },
      method  : 'POST'
  };

  request(options, function (err, res, body) {
    if (err) {
      console.log(err.json.errors);
      return;
    } else {
      var parsedBody = JSON.parse(body);
      modhash = body.json.data.modhash;
    }
  });
}

function postComment () {
  var parentId = 't1_cf9k3wa'
    , options = {
        url : 'https://api.reddit.com/api/comment?api_type=json&text=foobar&thing_id=' + parentId,
        headers : {
            'User-Agent' : 'fooBot/0.1 by USERNAME',
            'X-Modhash'  : modhash
          },
        methods : 'POST'
      };
  request(options, function (err, res, body) {
    if (err) {
      console.log(err);
      return;
    } else {
      // this blows up
    }
  });
}

A: So I've solved the problem, though not to my satisfaction. A working version of what I posted this weekend is below. There were a number of things that I was doing wrong.

*

*As noted by gotnull above, I had fat-fingered method as methods.

*For whatever reason request's cookie jar was not working for me. I had to handle the cookie manually as illustrated by the code.

*api.reddit.com doesn't handle https so I had to send the request to post a comment to https://en.reddit.com/
I'm still unhappy with the way that this works, because it limits the length of my message by having it in the URI. From what I understand I need to have the message in the POSTDATA but I haven't been able to coax request into doing that for me.
My initial problem is solved, but I'll need to open a second question for this when I re-visit the bot.
var request  = require('request')
  , argv     = require('yargs').argv
  , modhash
  , cookie;

function login () {
  var options = {
      url     : 'https://ssl.reddit.com/api/login?api_type=json&user=' + argv.user + '&passwd=' + argv.pass + '&rem=True',
      headers : {
        'User-Agent' : 'fooBot/0.1 by USERNAME',
      },
      method  : 'POST'
  };

  request(options, function (err, res, body) {
    if (err) {
      console.log('LOGIN ERROR:');
      console.log(err.json.errors);
      return;
    } else {
      var parsedBody = JSON.parse(body);
      modhash = parsedBody.json.data.modhash;
      cookie  = parsedBody.json.data.cookie;
    }
  });
}

function postComment (parentId) {
  var text     = 'message message message.'
    , options  = {
        url      : 'https://en.reddit.com/api/comment?api_type=json&text=' + encodeURIComponent(text) + '&thing_id=' + parentId,
        headers  : {
            'User-Agent' : 'fooBot/0.1 by USERNAME',
            'X-Modhash'  : modhash,
            'Cookie'     : 'reddit_session=' + encodeURIComponent(cookie)
          },
        method : 'POST'      };

  request(options, function (err, res, body) {
    if (err) {
      console.log('COMMENT POST ERROR:');
      console.log(err.stack);
      return;
    } else {
      console.log('// ------ //');
      console.log(body);
      console.log('// ------ //');
    }
  });
}


text:
Q: Template function with iterators but fixed type ProcessIndex( int index );

template< typename Iterator >
void ProcessIndexes( Iterator start, Iterator end )
{
    while( start!=end )
    {
        ProcessIndex(*start++);
    }
}

How can I enforce that this function can only ever be called with a specific, fixed iterator-value-type, e.g. int (but any container-type) ? In this case, ProcessIndex() takes an int as input, thus, compilation fails for non-primitive types and generates a warning for e.g. float. However, I would like the declaration to enforce int such that the compilation fails for all but int.
Haven't found the "solution" here or elsewhere, despite good efforts, is it trivial (?).

A: Starting from C++20 you can use new concepts and requires keyword to check that the iterator points on int type:
#include <vector>

void ProcessIndex( int ) {}

template< typename Iterator >
void ProcessIndecies( Iterator start, Iterator end )
    requires( std::same_as<std::decay_t<decltype(*start)>, int> )
{
    while( start!=end )
    {
        ProcessIndex(*start++);
    }
}

int main() {
    std::vector<int> vi;
    ProcessIndecies(vi.begin(), vi.end()); //ok

    std::vector<float> vf;
    //ProcessIndecies(vf.begin(), vf.end()); //fails
}

Demo: https://gcc.godbolt.org/z/hba1qh8bz

A: With C++11 you can do this using enable_if, is_same and decay as shown below:
#include<iostream>
#include <type_traits>
#include <vector>

void ProcessIndex( int index )
{
    //do something here
    std::cout<<"Inside ProcessIndex with: "<< index <<std::endl;
}

template< typename Iterator >
auto ProcessIndexes( Iterator start, Iterator end ) -> typename std::enable_if<std::is_same<typename std::decay<decltype(*start)>::type, int>::value>::type
{
    std::cout<<"Inside ProcessIndexes"<<std::endl;
    while( start!=end )
    {
        ProcessIndex(*start++);
    }
}

int main(){
    std::vector<int> vec{1,2,3};
    ProcessIndexes(vec.begin(), vec.end()); //WORKS

    std::vector<float> vec2;
    //ProcessIndexes(vec2.begin(), vec2.end()); //this won't work
}


text:
Q: Webrick crashing with Segmentation Fault on first page load I am trying to run a Ruby on Rails application on my development environment (Ubuntu 14.04). rails s does not report errors and Webrick seems to start properly:
$ rails s
=> Booting WEBrick
=> Rails 3.2.13 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2015-04-30 08:52:32] INFO  WEBrick 1.3.1
[2015-04-30 08:52:32] INFO  ruby 1.9.3 (2014-11-13) [x86_64-linux]
[2015-04-30 08:52:32] INFO  WEBrick::HTTPServer#start: pid=15523 port=3000

However, once I try to access the application through a web browser Webrick crashes with the following error:
/home/desousa/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/webrick/server.rb:98: [BUG] Segmentation fault
ruby 1.9.3p551 (2014-11-13 revision 48407) [x86_64-linux]

-- Control frame information -----------------------------------------------
c:0016 p:---- s:0060 b:0060 l:000059 d:000059 CFUNC  :select
c:0015 p:0106 s:0053 b:0053 l:000043 d:000052 BLOCK  /home/desousa/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/webrick/server.rb:98
c:0014 p:0007 s:0047 b:0047 l:000046 d:000046 METHOD /home/desousa/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/webrick/server.rb:22
c:0013 p:0063 s:0044 b:0044 l:000043 d:000043 METHOD /home/desousa/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/webrick/server.rb:89
c:0012 p:0118 s:0039 b:0039 l:000038 d:000038 METHOD /home/desousa/.rvm/gems/ruby-1.9.3-p551/gems/rack-1.4.5/lib/rack/handler/webrick.rb:13
c:0011 p:0294 s:0034 b:0034 l:002200 d:002200 METHOD /home/desousa/.rvm/gems/ruby-1.9.3-p551/gems/rack-1.4.5/lib/rack/server.rb:268
c:0010 p:0231 s:0028 b:0028 l:0011a0 d:0011a0 METHOD /home/desousa/.rvm/gems/ruby-1.9.3-p551/gems/railties-3.2.13/lib/rails/commands/server.rb:70
c:0009 p:0063 s:0024 b:0024 l:000015 d:000023 BLOCK  /home/desousa/.rvm/gems/ruby-1.9.3-p551/gems/railties-3.2.13/lib/rails/commands.rb:55
c:0008 p:---- s:0021 b:0021 l:000020 d:000020 FINISH
c:0007 p:---- s:0019 b:0019 l:000018 d:000018 CFUNC  :tap
c:0006 p:0702 s:0016 b:0016 l:000015 d:000015 TOP    /home/desousa/.rvm/gems/ruby-1.9.3-p551/gems/railties-3.2.13/lib/rails/commands.rb:50
c:0005 p:---- s:0012 b:0012 l:000011 d:000011 FINISH
c:0004 p:---- s:0010 b:0010 l:000009 d:000009 CFUNC  :require
c:0003 p:0061 s:0006 b:0006 l:0016e8 d:001838 EVAL   script/rails:6
c:0002 p:---- s:0004 b:0004 l:000003 d:000003 FINISH
c:0001 p:0000 s:0002 b:0002 l:0016e8 d:0016e8 TOP

-- Ruby level backtrace information ----------------------------------------
script/rails:6:in `<main>'
script/rails:6:in `require'
/home/desousa/.rvm/gems/ruby-1.9.3-p551/gems/railties-3.2.13/lib/rails/commands.rb:50:in `<top (required)>'
/home/desousa/.rvm/gems/ruby-1.9.3-p551/gems/railties-3.2.13/lib/rails/commands.rb:50:in `tap'
/home/desousa/.rvm/gems/ruby-1.9.3-p551/gems/railties-3.2.13/lib/rails/commands.rb:55:in `block in <top (required)>'
/home/desousa/.rvm/gems/ruby-1.9.3-p551/gems/railties-3.2.13/lib/rails/commands/server.rb:70:in `start'
/home/desousa/.rvm/gems/ruby-1.9.3-p551/gems/rack-1.4.5/lib/rack/server.rb:268:in `start'
/home/desousa/.rvm/gems/ruby-1.9.3-p551/gems/rack-1.4.5/lib/rack/handler/webrick.rb:13:in `run'
/home/desousa/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/webrick/server.rb:89:in `start'
/home/desousa/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/webrick/server.rb:22:in `start'
/home/desousa/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/webrick/server.rb:98:in `block in start'
/home/desousa/.rvm/rubies/ruby-1.9.3-p551/lib/ruby/1.9.1/webrick/server.rb:98:in `select'

-- C level backtrace information -------------------------------------------
SEGV received in SEGV handler
Aborted (core dumped)

The software versions I am using in this project:
$ ruby -v
ruby 1.9.3p551 (2014-11-13 revision 48407) [x86_64-linux]

$ rails -v
Rails 3.2.13

What could be the cause of this? Or can I do to understand the cause?

A: I had some touble with Webrick too that caused a segementation fault. I only had this on one specific ubuntu box but I didn't have the same error on other ubuntu boxes with the exact same setup. Lately I solved it using thin. To do this add this to your Gemfile:
gem 'thin'

Then run
bundle install
rails server


text:
Q: OnClick action gives error in recycler grid layout This is My MainActivity Code.In this we get error in setOnItemClickListener as null pointer exception and it stops my app.give me some suggestions where am i wrong. I am trying to achieve custom grid with image on top and title next to it.
public class MainActivity extends AppCompatActivity  {

//RecyclerView recyclerView;
private static final String TAG = "MainActivity";

    private final String android_version_names[] = {
            "Donut",
            "Eclair",
            "Froyo",
            "Gingerbread",
            "Honeycomb",
            "Ice Cream Sandwich",
            "Jelly Bean",
            "KitKat",
            "Lollipop",
            "Marshmallow"
    };

    private final String android_image_urls[] = {
            "https://api.learn2crack.com/android/images/donut.png",
            "https://api.learn2crack.com/android/images/eclair.png",
            "https://api.learn2crack.com/android/images/froyo.png",
            "https://api.learn2crack.com/android/images/ginger.png",
            "https://api.learn2crack.com/android/images/honey.png",
            "https://api.learn2crack.com/android/images/icecream.png",
            "https://api.learn2crack.com/android/images/jellybean.png",
            "https://api.learn2crack.com/android/images/kitkat.png",
            "https://api.learn2crack.com/android/images/lollipop.png",
            "https://api.learn2crack.com/android/images/marshmallow.png"
    };

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initViews();

}

private void initViews(){
    RecyclerView recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
    recyclerView.setLayoutManager(layoutManager);

    ArrayList<AndroidVersion> androidVersions = prepareData();
    DataAdapter adapter = new DataAdapter(getApplicationContext(),androidVersions);
    recyclerView.setAdapter(adapter);

    DataAdapter mAdapter = null ;

    mAdapter.setOnItemClickListener(new DataAdapter.ClickListener() {
        @Override
        public void onItemClick(int position, View v) {

            Log.d(TAG, "onItemClick position: " + position);
        }

    });

}
private ArrayList<AndroidVersion> prepareData(){

    ArrayList<AndroidVersion> android_version = new ArrayList<>();
    for(int i=0;i<android_version_names.length;i++){
    AndroidVersion androidVersion = new AndroidVersion();
    androidVersion.setAndroid_version_name(android_version_names[i]);
    androidVersion.setAndroid_image_url(android_image_urls[i]);
    android_version.add(androidVersion);
    }
    return android_version;
    }

    }

This Is My Adapter Code.
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<AndroidVersion> android;
private Context context;
private static ClickListener clickListener;

public DataAdapter(Context context,ArrayList<AndroidVersion> android) {
    this.android = android;
    this.context = context;
}

@Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout, viewGroup, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {

    viewHolder.tv_android.setText(android.get(i).getAndroid_version_name());
    Picasso.with(context).load(android.get(i).getAndroid_image_url()).resize(240, 120).into(viewHolder.img_android);
}

@Override
public int getItemCount() {
    return android.size();
}

public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
    private TextView tv_android;
    private ImageView img_android;
    public ViewHolder(View view) {
        super(view);
        view.setOnClickListener(this);

        tv_android = (TextView)view.findViewById(R.id.tv_android);
        img_android = (ImageView) view.findViewById(R.id.img_android);
    }
    @Override
    public void onClick(View v) {
        clickListener.onItemClick(getAdapterPosition(), v);
    }
}
public void setOnItemClickListener(ClickListener clickListener) {
    DataAdapter.clickListener = clickListener;
}

public interface ClickListener {
    void onItemClick(int position, View v);

}

}

A: you are setting mAdapter = null before setting setOnItemClickListener, remove it
DataAdapter mAdapter = null ; //remove this line

adapter.setOnItemClickListener(new DataAdapter.ClickListener() {
    @Override
    public void onItemClick(int position, View v) {

        Log.d(TAG, "onItemClick position: " + position);
    }

});

you are calling wrong adapter, your actual variable is adapter and you are calling it with mAdapter, that also by setting its value to ull

A: Try this
DataAdapter adapter = new DataAdapter(getApplicationContext(),androidVersions);
recyclerView.setAdapter(adapter);

adapter.setOnItemClickListener(new DataAdapter.ClickListener() {
    @Override
    public void onItemClick(int position, View v) {

        Log.d(TAG, "onItemClick position: " + position);
    }

});


text:
Q: How to draw a circle within OxyPlot AngleAxis and MagnitudeAxis? My plot model class is
public class MyViewModel
{
    public PlotModel model { get; private set; }

    public MyViewModel()
    {
        model = new PlotModel();
        AngleAxis a = new AngleAxis();
        a.Minimum = 0;
        a.Maximum = 360;
        MagnitudeAxis m = new MagnitudeAxis();
        m.Minimum = 0;
        m.Maximum = 1000;
        model.Axes.Add(a);
        model.Axes.Add(m);
    }
}

And I want to draw just a simple circle of 500 radius.
So in my MainWindow class I put
public partial class MainWindow : Window
{
    MyViewModel _myModel = new MyViewModel();

    public MainWindow()
    {
        InitializeComponent();

        oxpMyView.Model = _myModel.model;

        FunctionSeries f = new FunctionSeries((x) => 500, 0, 360, 0.1);
        oxpMyView.Model.Series.Add(f);
    }

But instead of circle, I see just a single line like this

What am I doing wrong and how do I draw circle properly within polar plot?

A: hope you've already gotten solution. Otherwise, here is my solution:
You could use two functions constructor: (x)=>500 and (y)=>y


text:
Q: Real-time camera self-calibration OpenCV I'm developing an augmented reality application - a virtual try-on, using OpenCV + OpenGL + QtCreator - and I'm stuck now at calibrating the camera. I found a lot of resources about the calibration process in OpenCV using the chessboard pattern, but I need to implement some sort of self-calibration, so that's not helpful. I know it can be done, but didn't really find anything useful.
 I found this research http://www.eidelen.ch/thesis/MscThesisV1.0.pdf in which a self-calibration process is described (chapter 4), but I'm not sure if that's the way to go. What I want to achieve can be seen at http://www.ray-ban.com/usa/virtual-mirror. I just want to know how do they calibrate.

A: For camera calibration you need to know a set of real coordinates in the world.  The chessboard gives you that since you know the size and shape of the squares, so you can correlate pixel locations with measurements in the real world.
You'll see that in Schneider's thesis he uses a 3D tracking unit (Figure 3.1) to give him the real-world coordinates of the points.  One he has those, it's a similar problem to the chessboard.
In the virtual mirror example, I don't know but I'd guess that they are using a face detection system, and thus do not need a calibrated image.  Something like: http://www.vision.caltech.edu/html-files/EE148-2005-Spring/pprs/viola04ijcv.pdf
For your system that might make more sense.  Lots of people do face detection in OpenCV, so there's plenty around on that.  You might start here: http://docs.opencv.org/trunk/modules/contrib/doc/facerec/facerec_tutorial.html

A: Camera self-calibration methods exist. They all use an assumption or another like rigidity. Take a look at this paper.
There is a summary here.


text:
Q: i'm getting "error: Deployment in version "v1" cannot be handled as a Deployment: unable to parse quantity's suffix"" when deploying heartbeat on k8s Hello everyone i'm trying to deploy Heartbeat on kubernetes to monitor kubernetes components.
i got the yaml file from official elastic documentation. yaml file
this is the full configuration file:
  apiVersion: apps/v1
  kind: Deployment
  metadata:
    name: heartbeat
    namespace: kube-system
    labels:
      k8s-app: heartbeat
  spec:
    selector:
      matchLabels:
        k8s-app: heartbeat
    template:
      metadata:
        labels:
          k8s-app: heartbeat
      spec:
        serviceAccountName: heartbeat
        hostNetwork: true
        dnsPolicy: ClusterFirstWithHostNet
        containers:
        - name: heartbeat
          image: docker.elastic.co/beats/heartbeat:7.17.6
          args: [
            "-c", "/etc/heartbeat.yml",
            "-e",
          ]
          env:

          - name: NODE_NAME
            valueFrom:
              fieldRef:
                fieldPath: spec.nodeName
          securityContext:
            runAsUser: 0
          resources:
            limits:
              memory: 1536mi
            requests:
          # for synthetics, 2 full cores is a good starting point for
         relatively consistent perform of a single concurrent check
        # For lightweight checks as low as 100m is fine
              cpu: 2000m
        # A high value like this is encouraged for browser based
        monitors.
        # Lightweight checks use substantially less, even 128Mi is fine
        for those.
              memory: 1536Mi
          volumeMounts:
          - name: config
            mountPath: /etc/heartbeat.yml
            readOnly: true
            subPath: heartbeat.yml
          - name: data
            mountPath: /usr/share/heartbeat/data
        volumes:
        - name: config
          configMap:
            defaultMode: 0600
            name: heartbeat-deployment-config
        - name: data
          hostPath:
            path: /var/lib/heartbeat-data
            type: DirectoryOrCreate

now it's giving me this error "error when creating "heartbeat-kubernetes.yaml": Deployment in version "v1" cannot be handled as a Deployment: unable to parse quantity's suffix".
when applying the yamlfile i get that `
configmap/heartbeat-deployment-config unchanged
clusterrolebinding.rbac.authorization.k8s.io/heartbeat unchanged
rolebinding.rbac.authorization.k8s.io/heartbeat unchanged
rolebinding.rbac.authorization.k8s.io/heartbeat-kubeadm-config
unchanged
clusterrole.rbac.authorization.k8s.io/heartbeat unchanged
role.rbac.authorization.k8s.io/heartbeat unchanged
role.rbac.authorization.k8s.io/heartbeat-kubeadm-config unchanged
serviceaccount/heartbeat unchanged`

eveything is good except the deployment part.
any help would be appreciated and thank you.

A: Hey I think there is a mistake in indentation in your yaml file. Can you check if this works for you?
data:
  heartbeat.yml:  |-
    heartbeat.autodiscover:
     # Autodiscover pods
      providers:
      - type: kubernetes
        resource: pod
        scope: cluster
        node: ${NODE_NAME}
        hints.enabled: true
      providers:
      - type: kubernetes
        resource: service
        scope: cluster
        node: ${NODE_NAME}
        hints.enabled: true
      providers:
      - type: kubernetes
        resource: node
        node: ${NODE_NAME}
        scope: cluster
        templates:
          # Example, check SSH port of all cluster nodes:
          - condition: ~
            config:
              - hosts:
                  - ${data.host}:22
                name: ${data.kubernetes.node.name}
                schedule: '@every 10s'
                timeout: 5s
                type: tcp

    processors:
      - add_cloud_metadata

    output.elasticsearch:
      hosts: ['https://10.112.100.121:30883']
      username: "elastic"
      password: "***********"
      ssl.verification_mode: none`

Yes your deployment has issues. I have made few changes but its failing for me due to an error but just check if this works for you
  apiVersion: apps/v1
  kind: Deployment
  metadata:
    name: heartbeat
    namespace: kube-system
    labels:
      k8s-app: heartbeat
  spec:
    selector:
      matchLabels:
        k8s-app: heartbeat
    template:
      metadata:
        labels:
          k8s-app: heartbeat
      spec:
        serviceAccountName: heartbeat
        hostNetwork: true
        dnsPolicy: ClusterFirstWithHostNet
        containers:
        - name: heartbeat
          image: docker.elastic.co/beats/heartbeat:7.17.6
          args: [
            "-c", "/etc/heartbeat.yml",
            "-e",
          ]
          env:

          - name: NODE_NAME
            valueFrom:
              fieldRef:
                fieldPath: spec.nodeName
          securityContext:
            runAsUser: 0
          resources:
            limits:
              memory: "1300Mi"
              cpu: "3000m"
            requests:
              cpu: "2000m"
              memory: "700Mi"
          volumeMounts:
          - name: config
            mountPath: /etc/heartbeat.yml
            readOnly: true
            subPath: heartbeat.yml
          - name: data
            mountPath: /usr/share/heartbeat/data
        volumes:
        - name: config
          configMap:
            defaultMode: 0600
            name: heartbeat-deployment-config
        - name: data
          hostPath:
            path: /var/lib/heartbeat-data
            type: DirectoryOrCreate

Can you test if this works for you ?


text:
Q: how to layoutInDisplayCutoutMode Never on android api 27? this code perfect working for api level 28. How to do this on android api 27?
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
      window.attributes.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER
}

I tried this but it's not working
<style name="PlayerTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">#000000</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowLayoutInDisplayCutoutMode" tools:targetApi="27">
            never
        </item>
    </style>


text:
Q: when to use await key word? do I need it in this case? i have a onClick method on a buttom. when this button is pressed, i get a displayalert message.
getTokenQ has a value. my question why its going inside catch block?
    private async void Button_Clicked(object sender, EventArgs e)
    {
        try
        {
            var getTokenQ = await SecureStorage.GetAsync("Save_Security_Question");

            if ((String.IsNullOrWhiteSpace(getTokenQ) == false))
            {
            }
            else
            {
            }
        }
        catch (Exception ex)
        {
            await DisplayAlert("Message", "Some thing went wrong. Please try different method", "ok");
        }
    }

A: no you don't need to do that, you can use .Result if you don't want to execute your code asynchronously , this code is perfectly fine :
private void Button_Clicked(object sender, EventArgs e)
    {
        try
        {
            var getTokenQ = SecureStorage.GetAsync("Save_Security_Question").Result;

            if ((String.IsNullOrWhiteSpace(getTokenQ) == false))
            {
            }
            else
            {
            }
        }
        catch (Exception ex)
        {
            DisplayAlert("Message", "Some thing went wrong. Please try different method", "ok");
        }
    }

Why in catch ! Because it's a message to display only if an exception is thrown.


text:
Q: how to find the current date in XSLT 1.0 I am finding trouble in retrieving the current date in my XSLT code. I am using version 1.0  and MSXSL.exe application to trigger my xslt code.
I tried using the following line of code to implement this functionality, however its not working. Looks like the version 1.0 doesn't support the current date function. Could you please provide a solution which will work for xslt 1.0.
               <xsl:value of select="current-date()"/>

A: There is no current-date() function in XSLT 1.0.
If your processor supports it, you can use the date-time() EXSLT extension function. Otherwise
you will have to pass the date as a parameter to the stylesheet during runtime, or get it from a web service.

A: With MSXML you can use extension functions done in JScript or VBScript, see http://www.exslt.org/date/functions/date-time/index.html for details and an implementation http://www.exslt.org/date/functions/date-time/date.msxsl.xsl which should work with MSXML.


text:
Q: How can I configure my nginx server to accept different subdomains and also port? I have a server running on Ubuntu/Nginx. I have subdomains running from different internal ports. I want to expose one application to the public but not associate it with any domain/server name.
Below is my configuration file:
server {
    server_name app.example.com www.app.example.com;
    access_log /home/hub-app/logs/app.example.com.access.log;

    location / {
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:8082;
        proxy_redirect off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_cache_bypass $http_upgrade;
        proxy_http_version 1.1;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    listen 443 ssl;
    ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

}

server {
    server_name example.com www.example.com;
    access_log /home/hub-public/logs/example.com.access.log;

    location / {
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:8081;
        proxy_redirect off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_cache_bypass $http_upgrade;
        proxy_http_version 1.1;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    listen 443 ssl;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

}

The above works well and points to the specified domains ie example.com and app.example.com. Now I want to add another virtual server to run at MY_PUBLIC_IP:8080. The port 8080 should not be accessible on the other domains i.e. example.com:8080/app.example.com:8080 should not be available.


text:
Q: Create click-through overlay instruction view A really simple question here.
How do you create a view like this?

It has to overlay the first time user runs this part of the app and be removed forever once the user taps on it. I understand it should be a UIImageView, but how do you make it active and then remove it from the view forever?

A: You can add your subview just after your app launch in the didFinishLaunchingWithOptions method of your app delegate by using the addSubView method of the UIView class. Here are some code snippets of how you could proceed:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    UIImageView *imageView = [[UIImageView alloc]
    initWithImage:[UIImage imageNamed:@"yourimage.png"]];
    [self.window addSubview:imageView];

     UITapGestureRecognizer * recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
     recognizer.delegate = self;
    [imageView addGestureRecognizer:recognizer];
    imageView.userInteractionEnabled =  YES;
    self.imageView = imageView;
}

- (void) handleTap:(UITapGestureRecognizer *)recognize
{
     [self.imageView removeFromSuperView];
}

Note that you will need a property to reference your imageView in the handleTap method.

A: UIView has all the methods you need, e.g.

*

*Call [myView addSubview:imgView] to add the image view to the current view (myView)

*Call [imgView removeFromSuperview] when finish (i.e. in respond to tap or after a timer)

Make sure userInteractionEnabled property of imgView to NO so that touches are passed to myView.

A: My thoughts would be set an NSUserDefault variable and check it on applicationDidFinishLaunchingWithOptions or somewhere else in your app that makes sense. You could just push a separate view when your variable is true vs. false.


text:
Q: JPA: Querying a OneToOne relationship with an abstract class I have two classes which have a unidirectional OneToOne relationship:
@Entity
@Table(name = "TypeA")
public class TypeA implements A
{
    ...
}

@Entity
@Table(name = "OTHER")
public class Other
{
    @OneToOne
    private A a;

    .....
}

When I save these classes everything works fine. Now I want to retrieve the Other based on an existing A. I created a CriteriaQuery which basically says "SELECT * FROM OTHERE WHERE a = :a". But when I set an object of type A into the query it will fail. Looking into the database I can see that the OTHER.A field is actually a varchar with the value "typeA:123" (where 123 is the ID of the A-object). Unfortunately I can't use a bidirectional mapping here.
    final CriteriaBuilder cb = em.getCriteriaBuilder();
    final CriteriaQuery<Other> cq = criteriaBuilder.createQuery(Other.class);
    final Root<Other> root = cq.from(Other.class);
    cq.where(cb.equal(root.get(Other_.a), myActualAObject));
    final TypedQuery<Other> tq = em.createQuery(cq);
    final Other other = tq.getSingleResult();

Any ideas how to perform the query mentioned above?
Thanks in advance.
Cheers
Philipp

A: A is an interface, not an entity, so I don't think a standard OneToOne mapping will work without using provider specific code - JPA only allows mapping to JPA objects, not interfaces.  For this to work, you need to specify the target type in the mapping so it knows 'a' can only be TypeA entity instances.  Or you can just change the type from A to TypeA.
EclipseLink has a variable OneToOne mapping concept used to map interfaces here:
http://eclipse.org/eclipselink/documentation/2.4/jpa/extensions/a_variableonetoone.htm
I'm not sure what other providers have that is equivalent.


text:
Q: React Js - Recomendación sobre el desarrollo de un e-commerce Principalmente, destacar que esto no es una pregunta sobre un problema a resolver como tal; sino una pregunta sobre recomendación.
En esencia estoy desarrollando un ecommerce en React Js, he llevando tiempo en el mismo, lo que me ha permitido darme cuenta que lo estoy creando de una forma muy limitada. El ecommerce cuenta con panel de administración para agregar los productos; en sí, en un inicio lo estuve creando para un producto específico que llevaba ciertas características (tallas, colores); el usuario puede seleccionar la talla, el color e ingresar una cantidad y al presionar agregar al carrito, se efectúan ciertas validaciones para la disponibilidad en stock, de lo solicitado. Después de un tiempo tomé en cuenta que no solo existirán productos con esas especificaciones, sino que solo tengan por ejemplo talla, o solo color; así que tuve que cambiar el panel de administración y la forma en la que se almacenan los datos del producto.
Dado el caso, la forma en que se pintarán los elementos en pantalla será distinto, dependiendo de qué opciones tenga el producto (para que el usuario elija).
De momento, tengo los siguiente; 3 estados uno para la cantidad, color y talla; pero como mencioné previamente no todos los productos tendrán las mismas opciones, por lo que tener esos estados para un producto que no los requiera, sería innecesario y agregar todas las opciones no sería una buena  opción. Lo que necesito es que, por favor, me den su recomendación ara cambiar esto, por algo versátil, que no dependa de las opciones.
const PurchaseSection = ({product}) => {
    // Contexts
    const { setShowAlertMsg, setMsg } = useContext(AlertMsgContext)
const { productsToBuy, setProductsToBuy } = useContext(ProductsToBuyContext)

    const [color, setColor] = useState('')
    const [qty, setQty] = useState(1)
    const [size, setSize] = useState('')

    const [msgQty, setMsgQty] = useState('')

    const [showPopup, setShowPopup] = useState(false)
    const [purchaseSpecs, setPurchaseSpecs] = useState({})

    return (
        <>
            {showPopup && <PurchasePopup product={purchaseSpecs} setShowPopup={setShowPopup} />}
            <FirstContainer>

                    Price: ${product.price}

            </FirstContainer>

            <ElementsContainer>
                <InfoSpecsContainer>
                    <InfoContainer>

{product.product_name}

{product.description}

                    </InfoContainer>
                    <SpecsContainer>

                            {product && product.options &&
                                <Row>
                                    {product.options.map((option) => {
                                        if (option.option === 'color') {
                                             return (
                                                option.values.map((value, id) => {
                                                    if (value.total === 0) {
                                                        return (

                                                                <Button disabled={true} >
                                                                    {value.color}
                                                                </Button>

                                                        )
                                                    } else {
                                                        return (

                                                                {color === value.value ?
                                                                    <Button type={'selected'}>
                                                                        {value.value}
                                                                    </Button>
                                                                :
                                                                    <Button onClick={() => {
                                                                        setColor(value.value)
                                                                        validate(value.value)
                                                                    }}>
                                                                        {value.value}
                                                                    </Button>
                                                                }

                                                        )
                                                    }
                                                })
                                            )
                                        }
                                    })}
                                </Row>
                            }
                            {product && product.options &&
                                <Row>

                                        <select onChange={(e) => setSize(e.target.value)}>
                                            <option value="Selecciona">Selecciona</option>
                                            {product.options.map(option => {
                                                if (option.option === 'size') {
                                                    return (
                                                        option.values.map((value, id) => {
                                                            return (
                                                                <option
                                                                    key={id}
                                                                    value={value.value}
                                                                >{value.value}</option>
                                                            )
                                                        })
                                                    )
                                                }
                                            })}
                                        </select>

                                </Row>
                            }
                            <Row>

                                    <ReactKeyboardEventHandler
                                        handleKeys={['enter']}
                                        onKeyEvent={() => addTocart()}
                                    >
                                        <input
                                            name="qty"
                                            value={qty}
                                            onChange={handleChange}
                                            type="number"
                                        />
                                    </ReactKeyboardEventHandler>

                            </Row>
                            <Row>
                                {msgQty !== '' && {msgQty}}
                            </Row>

                    </SpecsContainer>
                </InfoSpecsContainer>

                <ButtonsContainer>
                    <button>Regresar</button>
                    <button onClick={() => addTocart()}>Agregar al carrito</button>
                </ButtonsContainer>

            </ElementsContainer>
        </>
    )
}

export {PurchaseSection}


text:
Q: Homeomorphism from the coset space $G/G_x$ to the orbit $xG$ I'm currently working through a set of notes on fiber bundles and I'm struggling to prove something mentioned in my notes.
Question
Let $G$ be a topological group and $X$ be a Hausdorff, paracompact topological space with right $G-$action. That is, there exists a continuous map, $\mu: X \times G \to X : (x, g) \mapsto xg$ that satisfies the group action axioms.
For $x \in X$, let $xG = \{xg : g \in G \}$ and $G_x = \{ g \in G : xg = x\}$. Finally, consider the set $ G \big / G_x = \{G_xg : g \in G \}$, with quotient topology defined by the projection $p: G \to G \big / G_x : g \mapsto G_xg$. I want to prove the claim that $G \big / G_x $ is homeomorphic to $xG \subset X$.
My attempts
Consider the map $ \phi: G \big / G_x \to xG : G_xg \mapsto xg$. I was able to prove that this map is well-defined, bijective and continuous. So in order for it to be a homeomorphism, it remains to prove that it is an open map.
Now, if $G \big / G_x $ were compact, then the claim would be proved because continuous bijective functions from a compact space to a Hausdorff space are homeomorphisms. However, I do not know if $G \big / G_x $ is in fact compact and I could not think of a way to prove/disprove this fact. So, I tried a different method.
Suppose $U \subset G \big / G_x $ is an open set. Then, $p^{-1}(U) = \{ g : G_xg \in U \}$ is open in $G$ and $\phi(U) = \{ xg : G_xg \in U \} = \{xg : g \in p^{-1}(U) \} $. If the map $g \to xg$ is open, then $\phi(U)$ is open and the theorem has been proved. However, I also do not know how to prove this.
Summary
More specifically, I am asking the following questions.
Let $G$ be a topological group and $X$ be a Hausdorff, paracompact topological space with right $G-$action that is both continuous and proper.

*

*Is $G \big / G_x $ necessarily compact? If so, how could I go about proving this?

*Is the map $g \to xg$ is open? If so, how can I prove this?

*If 1 and 2 are false, how do I prove $G \big / G_x \simeq xG$?

Note: Thanks to Moishe Kohan's comment, I included the condition that the G-action be proper.

A: Instead of the paracompactness of $X$ I will assume that $X$ is 1st countable (e.g. metrizable). I will keep the Hausdorff assumption for $X$. I will also assume that $G$ is metrizable (equivalently, is Hausdorff and 1st countable). I am quite sure, all these assumptions will suffice for the purpose of discussion of fiber bundles in the notes that you are reading.
Lemma. Suppose that $G\times X\to X$ is a proper action. Then for every $x\in X$, the orbit map $o_x: G\to Gx$ descends to a homeomorphism $\phi: G/G_x\to Gx$ (where the orbit $Gx$ is equipped with the subspace topology induced from $X$).
Proof. You already know that $\phi$ is bijective (clear) and continuous. Hence, we just need to verify that its inverse $\psi: Gx\to G/G_x$ is continuous. Since $X$ is assumed to be 1st countable, it suffices to prove that for every sequence $g_n\in G$, if $g_nx$ converges to $y=gx\in Gx$, then the sequence $[g_n]\in G/G_x$ converges to $[g]\in G/G_x$. First, observe that the subset
$$
K=\{y\}\cup \{g_nx: n\in {\mathbb N}\}
$$
is compact. Hence, its preimage in $G$ (under $o_x$) is a compact $C$ (by properness of the action). Clearly, $g_n\in C$ for each $n$. After extraction, we can assume that $g_n$ converges to some $h\in C$ (here I am using the assumption that $G$ is metrizable). By the continuity of the orbit map, $o_x(h)=y$, hence, $[h]=[g]$ in $G/G_x$. This proves continuity of $\psi$. qed
See also my answer here  for a proof which assumes only that $Gx$ is closed (instead of properness of the action) but makes further assumptions: $G$ is locally compact and $X$ is completely metrizable.


text:
Q: TextFormField not resetting its Initial Value I'm somewhat new to Flutter so I don't know if this is the "correct" way of updating data collected from a server. In my case, what I'm doing is (my app code is quite long, I think the description below will suffice):

*

*Let the user create a custom form for a given date.

*Have him upload the data to a server (more specifically, Firebase).

*If he clicks on a date, the form should be updated to the most recent one saved on Firebase.

*

*To do this, I'm deleting all of the TextFormField widgets (they are held in a Map which I reset with widgetsMap = {}, which is also what I do for the form data itself) and rebuilding them with the data retrieved from Firebase.

*The TextFormField should have an initial value based on what was retrieved from Firebase. To achieve this, I've tried to use a controller and an initialValue, but neither have worked.

*

*The problem is that, if I want to update the initial value of a field a second time, the previous one will remain. For example, if date 1 has an initial value of Hello and date 2 has an initial value of World; when I click on date 2 coming from date 1, although the TextFormField widgets (there might even be a different number of them) will be built correctly, the initial value shown will still be Hello.

So what is happening? Shouldn't the initialValue of a widget be wiped out once the widget and the data have been reset? Do those objects still exist in the background somewhere even after I have reset them with = {} (I thought that, since dart is a garbage-collected language, these objects would be deleted once the references to them disappear...)?

A: Add Key to TextFormField. You can use Key(initialValue). For example:
TextFormField(
  key: Key(widget.initialValue),
  initialValue: widget.initialValue),
  ...
)

Although you reset your own map of TextFormFields, if you put new TextFormFields in same position in the widget tree, the Flutter framework will reuse the previous state. Setting the Key will tell Flutter that this is a different widget.


text:
Q: Facesbook games feed does not show multiple images I've created a simple open graph story "Assemble a puzzle".
When I assemble first puzzle Game Feed shows it as excepted (see below)
But when I've completed second and more images then small app icons displayed instead.
Screenshoyt: http://photoshare.ru/data/14/14132/1/6oaprl-68d.jpg
Why it happens? Some image size limitation or other reason?
Thanks,
Yury

A: That's the beauty of open graph, it groups the activities of the app together to avoid the unnecessary flooding of the posts on wall.
User always have the option to click on the options and see the individual stories. This makes sense, right?


text:
Q: Odd math error in Java I'm writing a program to demonstrate Miller-Rabin probability testing in Java. The code is pretty much done...
import java.util.Random;
import java.util.Scanner;

/**
 * Program to demonstrate Miller-Rabin primality testing
 *
 * @author Nick Gilbert
 */
public class MillerRabin
{
    public static void main(String[] args)
    {
        //Setting up for algorithm
        Scanner in = new Scanner(System.in);
        Random rn = new Random();
        int n = 0, k = 0, m = 0, a = 0;
        double b = 0;
        boolean probablyPrime = false;

        //Asking user for an odd n
        do
        {
            System.out.print("Enter an odd number to test for primality: ");
            n = in.nextInt();
        }
        while(n % 2 == 0);

        //Calculating k and m
        m = n - 1;
        while(m % 2 == 0)
        {
            m /= 2;
            k++;
        }

        //Generating random a
        //a = rn.nextInt(n-1);

        //Outputting numbers that will be used in algorithm
        System.out.println("k = " + k);
        System.out.println("m = " + m);
        System.out.println();
        a = 86;
        System.out.println("A = " + a);

        //Running the algorithm
        //b_{0}
        b = Math.pow(a, m) % n;
        System.out.println("b0 = " + b);
        if(Math.abs(b) == Math.abs(1 % n)) //Dealing with +/- case via absolute value
        {
            probablyPrime = true;
        }
        else
        {
            //b_{1-(k-1)}
            for(int i = 1; i < k; i++) //Going to k-1
            {
                b = Math.pow(b, 2) % n;
                System.out.println("b" + i + " = " + b);
                if(Math.abs(b) == Math.abs(1 % n)) //Dealing with +/- case via absolute value
                {
                    probablyPrime = true;
                    break;
                }
            }
        }

        //Printing result
        if(probablyPrime)
        {
            System.out.println("Probably Prime");
        }
        else
        {
            System.out.println("Definitely Composite");
        }

    }
}

I've hard-coded 86 as my a value to demonstrate my problem. Where it calculates b for the first time by raising a to the m and taking the modulus n the math is incorrect. Instead of giving a b0 of 86 which is the correct answer to 86^19 % 153 it gives me b0 equals 107. I've checked my values in the debugger and they are right. I've also checked the value of a^m and it gives me 86^19 so the problem occurs with the modulus part. Unfortunately I don't know what is throwing the math off.

A: double precision in Java (and any IEEE system) has only 15-16 digits of accuracy.  If you use a number which is larger than this you will get a representation error.
Most likely what you need to do is use BigInteger which not only handles arbitrary precision but has a method optimised for power & modulus.
// 86^19 % 153
BigInteger result = BigInteger.valueOf(86).modPow(BigInteger.valueOf(19), BigInteger.valueOf(153));
System.out.println(result);

prints
86

A: Here, Math.pow returns a double, so taking modulus of a double wouldn't help(Never take a Mod on double, No one is responsible for what you get).
and note that, (89^19) is roughly 2^122, so an unsigned long(2^64-1) wouldn't hold these number. and double has a precision 2^53(never use double to mod, number theory is on integers).Try a smaller value or use the BigInteger class.

A: The primitive data types have set sizes which can limit their accuracy.
Java has the BigInteger class which may work for your scenario.


text:
Q: Visual Studio 2013 won't build .Net 4.0 project I've got a really frustrating error in Visual Studio 2013. For some projects I need .Net 4.5 so I've installed that framework. Now I get problems with any project targetting .Net 4.0 - a dialog tells me 'The project is targetting ".NETFramework,Version=v4.0" which is not installed on this machine.'
I've tried going to the Microsoft website to download the targetting pack for this version, but it tells me that .Net v4.0 itself is not installed so the targetting pack refuses to install as well. Repairing VS 2010 and/or VS 2013 does nothing to fix the problem.
What can I do? I can't change the project to target v4.5 but my machine now seems to reject lower versions!

A: It's hard to answer, because the problem is very strange. But there can be hints to solution:

*

*4.5 is an update to 4.0 you can .NET Framework 3.5 and 4.5 side by side, but not 4.0 and 4.5. Do not waste your time on installing them in different order.

*VS2013 uses a different MSBuild, which is a part of VS2013. Previously it was a part of .NET Framework. Look at your csproj files and try to change MSBuild from 11 to 12  (the new path is %ProgramFiles%\MSBuild\12.0\bin)

A: You can try the following step to repair your Visual Studio

Control Panel\Programs\Programs and Features > Select your Visual Studio > Change > Repair

Or you also can try

Control Panel\Programs\Programs and Features > .NET 4.5 > Repair

Hopefully this help


text:
Q: Получение данных из компонента TGrid в Embarcardero RAD Studio XE5 Имеется компонент TGrid с одной колонкой TPopupColumn. Необходимо получить данные из n-ой ячейки в данной колонке. В C++ Builder 6 получение данных осуществлялось через Grid->Cells[row][col], сейчас не могу понять как.
С уважением, maxspb.


text:
Q: Linearized equations rearranged into series of first order differential equations for state-space form I am trying to follow this tutorial: http://ctms.engin.umich.edu/CTMS/index.php?example=InvertedPendulum&section=SystemModeling
I am stuck to understand how to make a state-space representation from these transfer functions
$$ \frac{\Phi(s)}{U(s)} = \frac{\frac{ml}{q}s}{s^3+\frac{b(I+ml^2)}{q}s^2-\frac{(M+m)mgl}{q}s-\frac{bmgl}{q}} \\ \frac{X(s)}{U(s)} = \frac{\frac{(I+ml^2)s^2-gml}{q}}{s^4+\frac{b(I+ml^2)}{q}s^3-\frac{(M+m)mgl}{q}s^2-\frac{bmgl}{q}s} $$
The text gives a hint "The linearized equations of motion from above can also be represented in state-space form if they are rearranged into a series of first order differential equations. Since the equations are linear, they can then be put into the standard matrix form shown below."
But I do not understand this hint, I tried to research on to reduce the order like on http://tutorial.math.lamar.edu/Classes/DE/ReductionofOrder.aspx but maybe you can give me more input to my brain.
Solution:
$$  \begin{bmatrix} \dot x \\ \ddot x \\ \dot \phi \\ \ddot \phi \end{bmatrix}
= \begin{bmatrix} 0 & 1 & 0 & 0 \\ 0 & \frac{-(I+ml^2)b}{I(M+m)+Mml²} & \frac{m^2gl^2}{I(M+m)+Mml^2} & 0 \\ 0 & 0 & 0 & 1 \\ 0 & \frac{-mlb}{I(M+m)+Mml^2} & \frac{mgl(M+m)}{I(M+m)+Mml^2} & 0 \end{bmatrix} \begin{bmatrix} x \\ \dot x \\ \phi \\ \dot \phi \end{bmatrix} + \begin{bmatrix} 0 \\ \frac{I+ml^2}{I(M+m)+Mml²}  \\ 0 \\ \frac{ml}{I(M+m)+Mml^2} \end{bmatrix} u  $$
$$ y = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \end{bmatrix} \begin{bmatrix} x \\ \dot x \\ \phi \\ \dot \phi \end{bmatrix} + \begin{bmatrix} 0 \\ 0 \end{bmatrix} u $$

A: There's a step that seems to be suppressed here, which is mapping your system back to the time domain from the Laplace-frequency domain. In this case the denominator represents the "left side" of your ODE in a standard way. Specifically an $s^k$ term corresponds to a $y^{(k)}$ term and their coefficients match up. The numerators, when they are polynomial, correspond to initial conditions: the coefficient on $s^{(k)}$ in the numerator is the initial condition for $y^{(k)}$. So for example, $Y=\frac{2s-1}{3s^2-2s+4}$ means $3y''-2y'+4y=0,y(0)=-1,y'(0)=2$.
Then there is a standard way to change variables to convert an nth order equation to a first order system: you just choose your variables to be $y,y',y'',\dots,y^{(n-1)}$. Then your nth order equation "lives" in the equation defining $(y^{(n-1)})'$, which you get by solving for $y^{(n)}$.
What I don't understand is why you wind up dividing by $U$ rather than adding it to the numerator on the other side, which is what would happen if your equation were just "left side of ODE = $u$". But that might be lack of familiarity with control theory specifically.

A: The second approach does not start from the transfer functions but restarts fresh from the original linearized equations. Write them in matrix form as
$$
\begin{bmatrix}I+ml^2&-ml\\-ml&M+m\end{bmatrix}
\begin{bmatrix}\ddot ϕ\\\ddot x\end{bmatrix}
+
\begin{bmatrix}0&0\\0&b\end{bmatrix}
\begin{bmatrix}\dot ϕ\\\dot x\end{bmatrix}
+
\begin{bmatrix}-mgl&0\\0&0\end{bmatrix}
\begin{bmatrix}ϕ\\ x\end{bmatrix}
=
\begin{bmatrix}0\\ u\end{bmatrix}
$$
and then as usual transform into a first order system by forming a phase space vector
$$
\begin{bmatrix}I+ml^2&-ml&0&0\\-ml&M+m&0&0\\0&0&1&0\\0&0&0&1\end{bmatrix}
\begin{bmatrix}\ddot ϕ\\\ddot x\\\dot ϕ\\\dot x\end{bmatrix}
+
\begin{bmatrix}0&0&-mgl&0\\0&b&0&0\\-1&0&0&0\\0&-1&0&0\\\end{bmatrix}
\begin{bmatrix}\dot ϕ\\\dot x\\ϕ\\ x\end{bmatrix}
=
\begin{bmatrix}0\\ u\\0\\0\end{bmatrix}
$$
Now multiply with the inverse of the first matrix to get an explicit first order system.


text:
Q: "var reloj" no recibe los estilos CSS Cuando hago click en el botón de enviar mensaje, aparece la hora actualizada a la que ha sigo enviado el mensaje. Lo que no puedo es dar estilos a "var reloj" en "function sendMessage". Alguna solución? Gracias!!
Éste es mi código:

var actualizarHora = function() {
  fecha = new Date(),
    horas = fecha.getHours(),
    minutos = fecha.getMinutes(),
    segundos = fecha.getSeconds(),
    dia = fecha.getDate(),
    mes = fecha.getMonth(),
    year = fecha.getFullYear(),

    phoras = document.getElementById("horas").innerHTML = horas,
    pminutos = document.getElementById("minutos").innerHTML = minutos,
    psegundos = document.getElementById("segundos").innerHTML = segundos,
    pdia = document.getElementById("dia").innerHTML = dia,
    pmes = document.getElementById("mes").innerHTML = mesesDelAño[mes],
    pyear = document.getElementById("year").innerHTML = year,

    pdia.innerHTML = dia,

    pmes.innerHTML = mesesDelAño[mes],

    pyear.innerHTML = year;

  if (phoras < 10) {
    phoras = "0" + phoras
  };
  if (pminutos < 10) {
    pminutos = "0" + pminutos
  };
  if (psegundos < 10) {
    psegundos = "0" + psegundos
  };

  phoras.innerHTML = horas;
  pminutos.innerHTML = minutos;
  psegundos.innerHTML = segundos;

};

actualizarHora();
var intervalo = setInterval(actualizarHora, 1000);

}())

function sendMessage() {

  var reloj = (" " + phoras + ":" + pminutos + ":" + psegundos + " | " + pdia + " de " + pmes + " del " + pyear);
}
.tiempo {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
  background-color: #21c921;
}

:

:

 |

 de

 del


text:
Q: A class from external jar throws exception while loading Resource Hi I am working on a Maven project having dependency on a external jar which has a class ConfigLoader having following loader() method.
public class ConfigLoader {
   public void initialize() {
      loader();
   }
   private static void loader() {
      URL configURL = ConfigLoader.getClass().getResource("runtimeConfiguration.xml");
      //some other method calls to which configURL is an argument.
   }
   //other methods of ConfigLoader class
}

and the directory structure is like this -
src
|...main
|.......java
|.......resources
|................dev
|................prod

both dev and prod have a file named runtimeConfiguration.xml
and the code which uses this class is
public class Application {
   private Application application;
   public static void main(String []args){
      application = new Application();
      application.invokeConfigLoader();
      //additional code
   }
   private void invokeConfigLoader() {
      configLoader.initialize();
   }
}

The error I get is
could not find: runtimeConfiguration.xml
and the exception is thrown at the getResource() line in the class from jar.

I have tried adding the dev folder to classpath but still the same error. I want to run this code from linux terminal, and the command I am giving from trunk directory (where all my exernal jars and resource folder sits after maven build) is -
java -cp /resources/dev/*:configuration-loader.jar

I am using intelliJ 2017.2 and also tried to add the resources/dev folder as module dependency, but I keep on getting the same error. The resources folder is added as a library via project structure settings. I tried to search a lot but have not found any question with this issue. Kindly help me out as I am new to this environment based development.
Thanks!

A: ConfigLoader.getClass().getResource("runtimeConfiguration.xml"); will try to get runtimeConfiguration.xml from the same package a the ConfigLoader is defined and not from the root of classpath. Try appending / to runtimeConfiguration.xml.
This should work ConfigLoader.getClass().getResource("/runtimeConfiguration.xml"); or ConfigLoader.getClass().getResource("/dev/runtimeConfiguration.xml"); depending how you are adding resources to your classpath.
See javadoc for more.


text:
Q: No suitable driver found for jdcb This is my first time doing sql work in Java, all I was doing was making a simple program where I open and close the connection
package exercises;

import java.sql.*;

public class JdbcEx1 {
    static Connection conn = null;
    static String dbURL = "jdbc:oracle:thin:@127.0.0.1:1521:XE";
    static String user = "labs";
    static String password = "labs";

    public JdbcEx1() {}

    public static void main (String args[]) throws SQLException {

        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e){
            System.err.println(e.getMessage());
        }

        try {
            conn = DriverManager.getConnection(dbURL, user, password);
            conn.clearWarnings();
            System.out.println("Connection opened! for driver ==>Oracle 11XE");
        } catch (SQLException e) {
            System.err.println(e.getMessage());
        } finally {
            if(!conn.isClosed()) {
                conn.close();
                System.out.println("Connection Close! Oracle");
            }
        }

    }
}

Whenever I try to run it I get the following error:
oracle.jdbc.driver.OracleDriver
No suitable driver found for jdbc:oracle:thin:@127.0.0.1:1521:XE
I really don't have much of a clue as to whats going on, I've tried running through it with the debugger multiple times but that just confused me even more

A: The path of the ojdbc6.jar file that you points out:
C:\Program Files\Java\jre1.8.0_60\lib\ext ,
must be specified into the environment variable CLASSPATH.

You need to have the ojdbc6.jar in your classpath environment variable
  in order to have JDBC 4.0 standard support.


text:
Q: Android and Arduino both receiving strange values via Bluetooth I am using BluetoothChat code on the Android side to send an ON/OFF signal (I am sending 110, 119 or other cases as defined below) to the Arduino UNO using the chat box, but when I display the received value, it shows strange values in the Arduino Serial monitor, that is, 255, 254, 250 or 245 and replies with strange values on the Android side too.
but suprisingly only single condition among 110, 119, etc gets true when i send these commands from android and no other instruction/LED gets properly executed/turned ON/off.
Can any one help me figure out the problem? Below is my arduino code.
int data;
String message;

void setup ()
{
Serial.begin (57600);

pinMode (6, OUTPUT);
pinMode (7, OUTPUT);
pinMode (8, OUTPUT);
pinMode (9, OUTPUT);
pinMode (10, OUTPUT);

digitalWrite(6, LOW); // off LED 1 at pin6
digitalWrite(7, LOW); // off LED 2 at pin7
digitalWrite(8, LOW); // off LED 3 at pin8
digitalWrite(9, LOW); // off LED 4 at pin9
digitalWrite(10, LOW); // off LED 5 at pin10
}

void loop () {
int i=0;
if (Serial.available()>0)
{
int data= Serial.read();

Serial.println (" Received data: ");
Serial.println (data);

if (data==110) //q
{
digitalWrite(6, HIGH); // turn on LED 1 at pin6
message = "LED 1 On";
Serial.println (message);

}
if (data==102) // a
{
digitalWrite(6, LOW); // off LED 1 at pin6
message = "LED 1 Off";
Serial.println (message);
}

if (data==96) //c
{
digitalWrite(7, HIGH); //on LED 2
message = "LED 2 On";
Serial.println (message);
}

if (data==115) //d
{
digitalWrite(7, LOW); // off LED 2
message = "LED 2 Off";
Serial.println (message);
}

if (data==111) //e
{
digitalWrite(8, HIGH); //on LED 3
message = "LED 3 On";
Serial.println (message);
}

if (data==97)// f
{
digitalWrite(8, LOW); //sets the LED 3
message = "LED 3 Off";
Serial.println (message);
}

if (data==107) //g
{
digitalWrite(9, HIGH); //turn on LED 4
message = "LED 4 On";
Serial.println (message);
}

if (data==120)//h
{
digitalWrite(9, LOW); //sets the LED 4
message = "LED 4 Off";
Serial.println (message);
}

if (data==99) //i
{
digitalWrite(10, HIGH); //sets the LED 5
message = "L5 high";
Serial.println (message);
}

if (data==104) //j
{
digitalWrite(10, LOW); //sets the LED 5
message = "LED 5 Off";
Serial.println (message);
}

if (data==112) //y
{
digitalWrite(6, HIGH); // turn on ALL LEDs
digitalWrite(7, HIGH);
digitalWrite(8, HIGH);
digitalWrite(9, HIGH);
digitalWrite(10, HIGH);
message = "ALL LEDs ON";
Serial.println (message);
}

if (data==122)//z
{
digitalWrite(6, LOW); //Turn off all LEDs
digitalWrite(7, LOW);
digitalWrite(8, LOW);
digitalWrite(9, LOW);
digitalWrite(10, LOW);
Serial.println ("ALL LEDs OFF");
}

else
{
digitalWrite(13, HIGH); //sets the LED 5
delay(3000); //3sec
digitalWrite(13, LOW);
delay(3000);
Serial.println (" else case executed ");

} ////end of else

}
data=0;
}

A: Try char data = Serial.read();
And show Java code for Android.
See 100% work code for Bluetooth Arduino&Android

A: If you are using Arduino Uno, then you can't use the serial monitor to print values, if you are already using serial to communicate to Bluetooth, since it has only one serial port.
You have to use the Software serial library or use Arduino Mega, which has 4 serial ports.


text:
Q: Calculating cyclotron orbits in a lattice I have a naive question, is it possible to obtain the wavepacket dynamics that give rise to cyclotron orbits from a real space tight-binding Hamiltonian?
Consider a square lattice in the presence of a constant magnetic field that amounts to say that the hopping elements acquire a phase. Let $H = \sum_{<m,n>} H_{m,n}$ be the real space tight-binding Hamiltonian describing such a system.
The cyclotron orbits are actually the semi-classical approximation to the above dynamics that $ H$ captures. These orbits are the paths of the electron $\dot{\textbf{r}}(t) = \partial H/\partial \textbf{p}$. How can we obtain this information from the above $H$?
Numerically:
We can diagonalize $H$, to obtain eigenfunctions $\psi_{m,n}$ from this, we can obtain probability densities $|\psi_{m,n}|^{2}$.
To obtain wavepacket dynamics $\Psi(t)$ , we solve Schrodinger's equation: $i\partial\Psi(t) = H \Psi$. This equation can be solved for some initial conditions. The solution tells if we make an excitation in the system at a site $(m_0,n_0)$ (initial condition) then how it will propagate in the lattice. This was my attempt, link.
However, this does not give any information about the semi-classical information!

A: The state with sufficiently large angular momentum is correlated with the classical orbital movement. The question is how we can prepare this state? If we use Hamiltonian described on this page and plot all eigenvectors, then we have picture

States from 3 to 10 looks promising, and if we prepare initial state from some mixture of  its, then animated peripheral region of lattice looks as follows

It looks like rotation with period of $T=37$. I think that for the large lattice we can get something similar to cyclotron orbit.
Update 1. Eigenvalues of Hamiltonian described above are
{2.90519, -2.90519, -2.76278, -2.76278, 2.76278, 2.76278, -2.58201, \
2.58201, -2.58201, 2.58201, 2.52133, -2.52133, -2.39276, 2.39276, \
-2.34139, 2.34139, 2.25356, 2.25356, -2.25356, -2.25356, 2.13097, \
2.13097, -2.13097, -2.13097, -1.95441, 1.95441, -1.95441, 1.95441, \
-1.92521, 1.92521, -1.86377, 1.86377, -1.86377, 1.86377, -1.69775, \
1.69775, -1.61748, 1.61748, -1.58945, 1.58945, -1.58945, 1.58945, \
-1.58691, 1.58691, 1.57744, -1.57744, -1.36333, -1.36333, 1.36333, \
1.36333, 1.29892, -1.29892, -1.29892, 1.29892, 1.27992, -1.27992, \
-1.27992, 1.27992, -1.25195, 1.25195, 1.07599, -1.07599, 1.06731, \
1.06731, -1.06731, -1.06731, 1.04507, -1.04507, -1.04507, 1.04507, \
-1., 1., -1., -1., 1., 1., -0.863067, 0.863067, -0.839226, 0.839226, \
-0.74239, 0.74239, 0.74239, -0.74239, -0.692981, 0.692981, -0.491724, \
-0.491724, 0.491724, 0.491724, -0.35947, 0.35947, -0.229448, \
-0.229448, 0.229448, 0.229448}

We can combine eigenvectors with negative sign of eigenvalues, for example, {2, 3, 4, 7, 9} as initial condition. Then we have picture with illusive rotation


text:
Q: Calling C# code within Python3.6 with absolutely no knowledge of coding in C#, I wish to call a C# function within my python code. I know there's quite a lot of Q&As around the same problem, but for some strange reason, i'm unable to import a simple c# class library from a sample python module.
Here's below as to what i've done -

C# Class Library setup

I'm using the VS 2017 CE.
I create a new project TestClassLibrary under the type of ClassLibrary(.NET Standard)
The classes inside the project are as follows -
MyClass.cs
using System;
namespace TestClassLibrary
{
    public class MyClass
    {
        public string function()
        {
            return "Hello World!";
        }
    }
}

This was built successfully, generating the .dll file under the \bin\Debug\netstandard2.0 dir as TestClassLibrary.dll
Now, I switch over to python3.6 (running on a virtualenv, backed with pythonnet 2.3.0)
main.py
import sys
sys.path.append(r"<Ablsloute Path to \bin>\Debug\netstandard2.0")
import clr
clr.AddReference(r"TestClassLibrary")
from TestClassLibrary import MyClass

When i Run python main.py, the code fails with the error -
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    from TestClassLibrary import MyClass
ModuleNotFoundError: No module named 'TestClassLibrary'

Should the code be -
import sys
sys.path.append(r"C:\Users\DELL\source\repos\TestClassLibrary\TestClassLibrary\bin\Debug\netstandard2.0")
import clr
clr.AddReference("TestClassLibrary.dll")
from TestClassLibrary import MyClass

I get -
clr.AddReference("TestClassLibrary.dll")
System.IO.FileNotFoundException: Unable to find assembly 'TestClassLibrary.dll'.
   at Python.Runtime.CLRModule.AddReference(String name)

But when i ran the code below, the code runs as expected -
import clr
clr.AddReference(r"System.Windows.Forms")
from System.Windows.Forms import MessageBox
MessageBox.Show("Hello World!")

I've no idea of what i might be missing :(

A: This is really janky but how I like to do things that are personal projects.
Python lets you send stuff to the command line really easily. C# can be run from command line. You probably see where I'm going with this.
Try adding C sharp to PATH. import os to python. then use this line of code when you want to run the C# script:
os.system("csc nameofscript.cs")

perhaps I've misunderstood, but this is how I would make it work on my machine


text:
Q: How to subtract multiple grouped columns in SQL I want to perform aggregations in the following format for each date: result = A - (B+C)
I have the following query for that:
WITH
  net_revenue_calculator AS (
    SELECT(
     DATE_FORMAT(created, '%Y-%m-%d') AS "date",
    (SELECT
      SUM(IF(reporting_category = 'platform_earning', net, 0)) AS "gross_revenue"
    FROM balance_transactions
    WHERE
      reporting_category = 'platform_earning'
    )
    -
    (SELECT
    SUM(IF(reporting_category = 'network_cost', net, 0)) AS "network_fees"
    FROM balance_transactions
    WHERE
      reporting_category = 'network_cost'
    )
    -
     (SELECT
        SUM(IF(reporting_category = 'fee', net, 0)) AS "stripe_fees"
    FROM balance_transactions
    WHERE
            reporting_category = 'fee'
   )
   AS DIFFERENCE ,
   GROUP BY 1,
    ORDER BY 1 DESC
    )
 )

select * from net_revenue_calculator

This is failing and says: mismatched input 'AS'. Expecting: <expression>
How can I fix this?

A: I think you want conditional aggregation here:
SELECT
    created,
    SUM(IF(reporting_category = 'platform_earning', net, 0)) AS gross_revenue,
    SUM(IF(reporting_category = 'network_cost', net, 0)) AS network_fees,
    SUM(IF(reporting_category = 'fee', net, 0)) AS stripe_fees
FROM balance_transactions
WHERE
    reporting_category IN ('platform_earning', 'network_cost', 'fee')
GROUP BY
    created;

If you want the A - (B + C) version, then use:
SELECT
    created,
    SUM(IF(reporting_category = 'platform_earning', net, 0)) -
    SUM(IF(reporting_category = 'network_cost', net, 0)) -
    SUM(IF(reporting_category = 'fee', net, 0)) AS net_earnings
FROM balance_transactions
WHERE
    reporting_category IN ('platform_earning', 'network_cost', 'fee')
GROUP BY
    created;


text:
Q: Why do my variables attach to each other instead of adding together? The perimeter for my code always comes back like 2020 4040 and so on and I cannot seem to figure out why when the variables are both numbers. I know it is a pretty simple fix but I cannot figure it out. I tried parseInt but that did not work either. Can anyone help explain to me what I need to add or change to get my perimeter to come up say 40 using say 10 and 10 for the width and height.

    <meta charset="utf-8" />

Click the button to calculate the area and perimeter of a rectangle.

    <button onclick="myFunction()">Try it out!</button>

A: prompt always returns a string. You have to convert it to a number before doing a +. Otherwise, it just concatenates.
You can do something like
var width = parseFloat(prompt("Please enter a width", " "));

A: This is because
var height = prompt("Please enter a height", " ");

gets a string value for 20, instead of Number value for 20, as I assume you wanted.
This might be what you are looking for: How do I convert a string into an integer in JavaScript?

A: if you are positive it always come back as a number.  Force it to become a number by multiple it by 1.  see https://jsfiddle.net/ktaacx92/
var width = prompt("Please enter a width", " ") * 1;
var height = prompt("Please enter a height", " ") * 1;

but i recommend a quick form.

A: Put the plus sign (+) in front of prompt() calls.  This will cast the input as a number.  (code pen: http://codepen.io/anon/pen/jrryBP).
JS:
function myFunction() {
  var width = +prompt("Please enter a width", " ");
  var height = +prompt("Please enter a height", " ");
  var area = width * height;
  var perimeter = (width + height) * 2;
  if (width != null && height != null) {
    alert("The area is " + area + " and the perimeter is " + perimeter + ".");
  }
}

A: Add parseInt around your prompt will parse the prompt string to an int. The math will then work correctly. (using + with strings will concatenate the strings and not add them as you desire).

    <meta charset="utf-8" />

Click the button to calculate the area and perimeter of a rectangle.

    <button onclick="myFunction()">Try it out!</button>


text:
Q: Invalid namespace prefix for xpath I have the following xml document:
<?xml version="1.0" encoding="UTF-8"?>
<ns0:WasteTask xmlns:ns0="http://lcc/dm/waste/v1.0">
    <ns0:Identifiers>
        <ns0:Identifier>
            <ns1:Name xmlns:ns1="http://lcc/dm/common/v1.0">id</ns1:Name>
            <ns1:Value xmlns:ns1="http://lcc/dm/common/v1.0">242498</ns1:Value>
        </ns0:Identifier>
        <ns0:Identifier>
            <ns1:Name xmlns:ns1="http://lcc/dm/common/v1.0">ServiceCode</ns1:Name>
            <ns1:Value xmlns:ns1="http://lcc/dm/common/v1.0">SR00239776</ns1:Value>
        </ns0:Identifier>
        <ns0:Identifier>
            <ns1:Name xmlns:ns1="http://lcc/dm/common/v1.0">ExternalReference</ns1:Name>
            <ns1:Value xmlns:ns1="http://lcc/dm/common/v1.0">9024896</ns1:Value>
        </ns0:Identifier>
    </ns0:Identifiers>
</ns0:WasteTask>

I would like to select the Value node that has a sibling Name node containing "ExternalReference" i.e. select "9024896"
I've been using xml spy to run xpath. I hoped "//ns1:Value" would get me the Value nodes but it gives the error "Invalid namespace prefix".
The xpath works ok if I manually add the ns1 prefix declaration to the root node but I don't have the option of this in the actual application.
Is there another way to get the result I need with xpath? I have tried "/*/*[local-name()='Value']" but that returned no results.

A: With an XPath 2.0 engine (which I think XML Spy supports) you can do //*:Value to select any element with local name Value.


text:
Q: PDF (Prawn) : Generate tables without Prawnto For some permission restriction, I can't install prawnto gem to my server. I used the method of http://blog.idyllic-software.com/blog/bid/204082/Creating-PDF-using-Prawn-in-Ruby-on-Rails to generate PDF for my object.
But, I used the method pdf.table to generate table, and this method is not accessible since I've remove prawnto.
Is there any method accessible to easily generate tables just with prawn gem ?
My application is on Rails 2.3.16, and prawn version 0.8.4.
Regards

A: Is there any reason to use prawn 0.8.4? If not then try to upgrade to latest prawn.
I am using prawn 0.12.0 and I can generate tables using pdf.table without prawnto gem.