text:
Q: How to formulate a likelihood ratio test for an exponential distribution?
Find the form of the likelihood ratio test of $H_0 : \lambda = \lambda_0$ against $\lambda\neq\lambda_0$ when $X_1,X_2,...,X_n$ is a random sample from $Ex(\lambda)$. Simplify it as much as possible.

I've started as follows, where $\lambda_1$ is some alternative parameter
$$
\frac{L_0}{L_1}=\frac{\prod f(x;\lambda_0)}{\prod f(x;\lambda_1)}
$$
I think the p.d.f. for an exponential is $\lambda e^{-\lambda x}$ so
$$
\frac{L_0}{L_1}=\frac{\prod \lambda_0 e^{-\lambda_0 x_i}}{\prod \lambda_1 e^{-\lambda_1 x_i}}
$$
$$
=(\frac{\lambda_0}{\lambda_1})^n\frac{\prod e^{-\lambda_0 x_i}}{\prod e^{-\lambda_1 x_i}}
$$
Which I think can be simplified like this by taking logs
$$
=n log(\frac{\lambda_0}{\lambda_1})\frac{e^{-\sum\lambda_0 x_i}}{e^{-\sum\lambda_1 x_i}}
$$
Not sure about this but, I think that becomes
$$
=n log(\frac{\lambda_0}{\lambda_1}) e^{-\sum x_i ({\lambda_0}-{\lambda_1})}
$$
Am I right so far? Not sure where to go from here. I think the critical region is where the above is less than some constant.


text:
Q: If else in Mysql, how to declare constants in mySQL SET @Name1 = 'YES';
If @Name1 ='YES' select 2 from dual else Select 3 from dual;
what is wrong in above statements

A: show this:
SET @Name1 := "YES";
SELECT IF(@Name1 = "YES", 2,3) AS VAL;

You can also do the init in 1 statement like this:
SELECT IF(@Name1 = "YES", 2,3) AS VAL, field1, field2
FROM yourTable
CROSS JOIN(SET @Name1 := "YES") AS init
WHERE ......;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Como criar e acessar uma variável global com PHP e codeigniter Bom dia pessoal, estou com uma duvida estou usando o seguinte para gerar alertas de sucesso ou erros no meu sistema.
if ($this->model->inserir($data)) {
    $msg = "
 Cliente salvo com sucesso
";
    $this->session->set_flashdata('mensagem', $msg);
    redirect('clientes');
} else {
    $msg = "
 Erro ao inserir cliente
";
    $this->session->set_flashdata('mensagem', $msg);
}

Vejam que eu possuo vários controllers e dentro desses controllers vários métodos se eu for colocar isso em cada método sera muito trabalhoso.
Gostaria de saber se tenho como criar a variável $msg de froma global para ser acessada por qualquer controller/método e onde eu crio ela.

A: Pelo que entendi, não se trata de criar outra "variável global", e sim de uma função que leia a SESSION, que já é global. Sempre que vc precisar criar uma função (ou método) que deve ser acessado de forma "global", use um HELPER, um HOOK ou uma biblioteca.
Minha sugestão: crie um HELPER que vai ler a SESSION mensagem e retornar um alert formatado de acordo com o comando do método.
Crie applications/helpers/session_helper.php:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

if( ! function_exists('session_alert')){
    function session_alert(){
        if(isset($_SESSION['mensagem'])){
            echo '
';
            echo '<button type="button" class="close" data-dismiss="alert"';
            echo 'aria-label="Close">×';
            echo '</button>Aviso! '.$_SESSION['mensagem'][1];
            echo '
';
        }
        unset($_SESSION['mensagem']);
    }
}

Carregue o HELPER com autoload: $autoload['helper'] = array('session_helper');
Seu controller vai criar os avisos da mesma forma, só que passando um array com dados da mensagem para a $_SESSION['mensagem']:
if ($this->model->inserir($data)) {
    $this->session->set_flashdata('mensagem', ['success','Cliente salvo com sucesso']);
    redirect('clientes');
} else {
    $this->session->set_flashdata('mensagem', ['danger','Erro ao inserir cliente']);
}

Como vc pode ver, a função session_alert() só vai mostrar o alert quando houver dados na $_SESSION['mensagem']. Assim, vc pode chamar essa função na  VIEW usando <?= session_alert(); ?> em qualquer VIEW do sistema.
Por exemplo, sua VIEW "clientes" pode ter algo assim:

  <?= session_alert(); ?>

A: Utiliza o $GLOBALS da seguinte forma:
$GLOBALS['msg'] = $msg;

E dentro de cada função tu pode chamar assim:
global $GLOBALS;
$msgGlobal = $GLOBALS['msg'];

Eu sugiro utilizar assim pois não sei o número nem de classes e funções que tu tem.


text:
Q: Can a parser fail silently? May ANTLR generated parsers fail silently? That
is, can they omit diagnosing when not recognising?
Using a very small grammar for a demonstration and using defaults only for ANTLR, these are the contrasting observations:
When sending input to the usual test rig for the grammar below, I am
noticing two things:

*

*the parsers recognize valid input (actions show that), o.K.;

*however, the recognisers seem to "accept" certain invalid(?) inputs, meaning there is no
diagnosis. V3 and v4 parsers behave similarly. The issue—if there is
an issue—appears when there are characters ('1') missing
at the front of an input for stat, provided that prior to this input another input of
just a NEWLINE had been sent.
This is the v4 grammar:
grammar Simp;

prog : stat+ ;
stat : '1' '+' '1' NEWLINE
     | NEWLINE
     ;

NEWLINE : [\r]?[\n] ;

The v3 grammar is the same, mutatis mutandis.
Some runs using v4; class TestSimp4 is the usual test rig as in the book(s),
see below:
% printf "1+1\n" |java -classpath "antlr-4.11.1-complete.jar:." TestSimp4
% printf "+1\n" |java -classpath "antlr-4.11.1-complete.jar:." TestSimp4
line 1:0 extraneous input '+' expecting {'1', NEWLINE}
line 1:2 mismatched input '\n' expecting '+'
% printf "\n+1\n" |java -classpath "antlr-4.11.1-complete.jar:." TestSimp4
%

The first two invocations' results I had expected. I had expected the last invocation to visibly fail, though. Correct?
Looking at the generated SimpParser.java, the silent exit seems
consequential, as outlined below. But should it be that way? I am thinking that ANTLR just
stops before recognising invalid input here, but it shouldn't just stop.
Question: Is this silent failure rather to be expected? Have I
overlooked something like a greedyness setting for grammar tokens with a
+ suffix?
Some code analysis.
Referring to the loop that calls stat() (in the
prog() procedure):

The v3 parser sets a counter variable to >= 1 on sucessfully matching
the initial NEWLINE. The effect is that EarlyExitException is then
not being thrown on later inputs, it just breaks the loop.

The v4 parser similarly calls _input.LA(1) and then just terminates
the loop whenever that call's result cannot be at the start of stat.
(So no recovery?)

The test rig:
class TestSimp4 {
  public static void main(String[] args) throws Exception {
    final CharStream subject   = CharStreams.fromStream(System.in);
    final TokenSource tknzr    = new SimpLexer(subject);
    final CommonTokenStream ts = new CommonTokenStream(tknzr);
    final SimpParser parser    = new SimpParser(ts);
    parser.prog();
  }
}

So another paraphrase of my question would be: "How does one
create ANTLR parsers such that they will always say YES or NO?"

A: Your 3rd test input, \n+1\n, does not produce an error because you're telling it to recognize the production/rule stat once or more. And prog successfully matches the input \n and then stops. If you want the entire input (token stream) to be consumed, "anchor" your prog rule with the EOF token:
prog : stat+ EOF;


text:
Q: Why do X applications show a question mark as TTY in ps's result? $ ps -ef | head -n 1 && ps -ef | grep calc
UID          PID    PPID  C STIME TTY          TIME CMD
user1     524014    5382  0 10:21 ?        00:00:01 gnome-calculator
user1     532125  510665  0 10:36 pts/4    00:00:00 grep calc

I thought that only daemons would have ? as TTY, but obviously Gnome Calculator is not a daemon. I know it's running on TTY2, which is the TTY used by my Gnome session. So why does the ps result show ? in the TTY column ?
[EDIT]
I get the idea that Gnome Calculator is not directly attached to a TTY, because it has been launched through a graphical shell (Gnome Shell). I thought that by going up the process tree I'd get a process attached to TTY2, but that's never the case :
$ ps -f | head -n 1 && ps -ef | grep calc
UID          PID    PPID  C STIME TTY          TIME CMD
user1     524014    5382  0 10:21 ?        00:00:01 gnome-calculator
user1     578611  552619  0 11:58 pts/5    00:00:00 grep calc

$ ps -f -p 5382
UID          PID    PPID  C STIME TTY          TIME CMD
user1       5382    5131  4 juin10 ?       00:42:26 /usr/bin/gnome-shell

$ ps -f -p 5131
UID          PID    PPID  C STIME TTY          TIME CMD
user1       5131       1  0 juin10 ?       00:00:00 /lib/systemd/systemd --user

$ echo $DISPLAY
:1

No process up the chain is attached to TTY2. But obviously Gnome Calculator is currently displayed on TTY2. Is there a command to find out on which TTY a given process is currently displayed ? (or maybe on which $DISPLAY) ?

A: ps will display a question mark for any thread not immediately attached to a tty. (a terminal from which the process can be controlled)
That is of course the case for kernel threads and misc other daemons.
But this is also necessarily the case for X-clients.
Did you launch gnome-calculator directly from a standard tty ? No of course ! would you find a tty under which typing Ctrl-C would just kill it ? No again !
You certainly launched it from your graphical interface that is to say, logically some X-client. => No tty attached.
However, if you have been launching your X-server from some tty using startx, you'll notice that the X-server iitself is indeed attached to that tty.

EDIT following comments :
I cannot tell for you but as far as I am concerned, looking at :
1 S acoswt    1817     1  0  80   0 -  1036 -      07:02 tty4     00:00:00 dbus-launch --exit-with-session startplasma-x11

my desktop environment (KDE-Plasma) is launched by… the dbus… daemon. I suspect you get something similar with gnome. Therefore… again… no controlling terminal as such.

A: There are two parts to this question.
The first, why does ps show "?" is reasonably simple. The procps library looks at the 7th field on the process' stat file and tries to parse that into a TTY name.
$ ps -o pid,tty,cmd -C gnome-calculator
    PID TT       CMD
  74426 ?        gnome-calculator
$ cut -f 1-9 -d' ' /proc/74426/stat
74426 (gnome-calculato) S 2325 2325 2325 0 -1 4194304

See the zero after 2325 and -1? That's the TTY device ID which the kernel is basically saying "don't know" or "not applicable".
Start it on the command line in gnome-terminal and you do get a TTY because it now has a controlling terminal.
$ ps -o pid,tty,cmd -C gnome-calculator
    PID TT       CMD
  75446 pts/2    gnome-calculator
$ cut -f 1-9 -d' ' /proc/75446/stat
75446 (gnome-calculato) S 72016 75446 72016 34818 75721 4194304

The 34818 is the device ID, with some odd bit masking and shifting you get that becoming the major ID of 136 and minor of 2 which are the IDs of /dev/pts/2
Secondly, the reason why the first calculator doesn't have a TTY device ID is based on how X works because the computer your display was on could be different to the computer the calculator program was running.
So while your X server runs on TTY2 your calculator program is not running from that TTY. If you hunt around looking for your session process (probably gnome-session) you'll find that is running on tty2.


text:
Q: Is there a way to run a python script and still be able to use my Ubuntu server? I have a server I lease from Digital Ocean. I access it using Putty. I want to run my python script in the background so that I can still do other things on the machine. What is a terminal command I can use to have it run in the background so that I can still use the machine?
Random information you might need:
-Using Ubuntu 14.04
-Python3.4 script
-My favorite dessert is cheesecake (buy me cheesecake)
Thanks for the help!

A: It's more of a unix/linux question than python, but you can do it in a couple of different ways:
% python myprogram.py &

The "&" says to run it in the background.
If you forgot, and just ran it, then you can type "^z" (control-Z) to suspend your program, then type:
% bg

To start it running again in the background.  And, just for fun, "fg" would put it back in the foreground.  You can have many processes running in the background - if you're doing more than one, you can use "%n" to explicitly say which one (i.e. "bg" and "bg %1" would both work, if you only had one background job), and for more fun, if you have multiple jobs running in the background:
% jobs

Will list them for you.


text:
Q: Visual Studio 2015: Solutionexplorer -> Any Project ->Properties --> Rightclick missing the "add item" option || Diffrent context menu? When I rightlick on Properties in the Solutionexplorer there are 2 Items missing in that List.
One of them is the "add item" option
EDIT: Actually the conext menus are totally diffrent - WAT

A friend of mine has the missing options

I am currently using

*

*Visualstudio 2015 Enterprise

*Version 14.0.25431.01

*Update3

Anyone know the option where I activate them?
This is why I am trying to do it this way.


text:
Q: How can you print the prime numbers from 0 to 100 in python I am writing a small program to find all prime number from a range from 0 to whatever number the user want. How should I fix my code?
I tried to swap the loop position and the algorithm but it didn't work
g=int(input("type"))
def check_prime(g):
    if(g<2):
        return False
    for x in range(2, g+1):
        v=int(math.sqrt(x))
        if(x%v==0):
            return False
        return True

if check_prime(g):
 print(x)

I expect when the user input g they will get all the prime numbers from 0 to g and also the program will tell them how many prime numbers found

A: It's pretty simple, this code below will return you both the count of primes and their values.
g=int(input("type"))

def check_prime(g):
  count = 0
  primes = []
  for number in range(g+1): #considering 'g' is inclusive
    primes.append(number)
    count += 1
    if(number < 2 or number%2 == 0):
        primes = primes[:-1]
        count -= 1
        continue
    for x in range(3, number, 2):
      if (number % x) == 0:
        primes = primes[:-1]
        count -= 1
        break

  return count, primes

print (check_prime(g))


text:
Q: Dart - initializing final class members depedent on each other I like to use final members in my classes whenever it makes sense, but I ran into a problem trying to do something relatively simple:
import 'dart:ui';

class Foo {
  final PictureRecorder recorder;
  final Canvas canvas;
  final int margin;

  Foo({
    this.margin = 10,
  })  : recorder = PictureRecorder(),
        canvas = Canvas(recorder) { // this line errors out
  }
}

The error I'm getting from the compiler is:
 The instance member 'recorder' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression
Is there another way of doing what I want without making the canvas field non-final?
I know I can make the class look similar "from the outside" using a non-final private field and a custom getter, but it feels like an unnecessary workaround.

A: Try using late keyword for the canvas.
late final Canvas canvas;

And the constructor should be updated like this :
Foo({
    this.margin = 10,
  }) : recorder = PictureRecorder() {
    canvas = Canvas(recorder);
  }

Check this post to get more info: https://dev.to/pktintali/late-variables-in-dart-dart-learning-series-1-2opf

A: You can make use of a factory constructor which calls your real (hidden) constructor like this:
class Foo {
  final PictureRecorder recorder;
  final Canvas canvas;
  final int margin;

  factory Foo({
    int margin = 10,
  }) {
    final recorder = PictureRecorder();
    final canvas = Canvas(recorder);

    return Foo._(
      recorder: recorder,
      canvas: canvas,
      margin: margin,
    );
  }

  Foo._({
    required this.recorder,
    required this.canvas,
    required this.margin,
  });
}

Since we have yet to create any object when running inside the factory body, we are allowed to do anything as long as we return an object compatible with the type which the factory constructor is part of.
So we can create all necessary values and then forward them to our real constructor and prevent the use of any late variables.

A: You can do this
class Foo {
  final PictureRecorder recorder;
  late final Canvas canvas;
  final int margin;

  Foo({
    this.margin = 10,
  }) : recorder = PictureRecorder() {
    canvas = Canvas(recorder);
  }
}

A: Here's the workaround I have in mind, but I'd rather do without:
import 'dart:ui';

class Foo {
  final PictureRecorder recorder;
  Canvas? _canvas;
  final int margin;

  Canvas get canvas => _canvas!;

  PatternVisualizer({
    this.margin = 10,
  }) : recorder = PictureRecorder() {
    _canvas = Canvas(recorder);
  }
}


text:
Q: Emacs erlang buffer I use GNU/Emacs for Erlang programming. I compile my code by issuing C-c C-k. When I call compile, Emacs opens a new buffer (Erlang). It's half the size of the original window. How can I control the size of this buffer?
Thank you.

A: You could try:
(setq compilation-window-height 15)

A: I'm not sure how Erlang mode does the window splitting. Generally speaking though, the main frame is split into 2 windows vertically using split-window-vertically which takes a SIZE argument to control the size of the window (check the documentation for further details). You can see if your erlang compilation command uses this and try wrapping/advising it.


text:
Q: PostgreSQL like not returning matching instances How does the PostrgeSQL like function work? I'm using token inputs to limit input from user with only existing values.
I have the following values in the DB:
  `Yellow, White, Orange...`

My Code
 @colors = Color.where("name like ?", "%#{params[:q]}%")

If I type in w for example White is not proposed. I have to type in second letter to see White proposed. Because Db values all start by Capital letter I suspect a difference with SQLite.
I found this post which mentions ILIKE but was wondering if there is some common code that work both with Postgres and SQLite.

A: The SQLite LIKE operator is case insensitive per default.
In PostgreSQL ILIKE is the case insensitive version of LIKE. There are also operators:
~~   .. LIKE
~~*  .. ILIKE
!~~  .. NOT LIKE
!~~* .. NOT ILIKE

These three expressions are all effectively the same in PostgreSQL:
name ilike '%w%'
name ~~*   '%w%'
lower(name) like lower('%w%')

The last line mostly works in both SQLite and PostgreSQL. I added links to the respective manual pages.
A limitation applies: SQLite only understands lower / upper case of ASCII characters, while PostgreSQL understands other UTF-8 characters, too.

A: The case-sensitivity of LIKE depends on the database you use. Some databases ignore case when using LIKE, some don't, some look at various configuration options. One way around this is to normalize the case yourself by converting to upper or lower case:
@colors = Color.where("lower(name) like ?", "%#{params[:q].downcase}%")


text:
Q: Scanner only picking up certain input I am making a Blackjack program using a Card and Deck class. Everything works except for one method in the main Class. Before every round of Blackjack, the player is asked if he would like to keep the same bet amount, change the bet, or exit the program (sentinel value of 0). The getBet() method is called at least twice(it could be called more than twice if this problem didn't stop the program). However, unlike the first time the method is called, the method only recognizes and acts on input of the sentinel. If you try and change the number or press enter, the player gets stuck in an endless loop on the console screen.
Why does the getBet() method, when called a second time, not return any input unless 0 is the value entered? All 3 classes are provided below. I would have provided a Minimal, Complete, and Verifiable example, but, I thought the reader might prefer to run my actual code and, since the getBet() method seemed free of errors, I couldn't narrow down what the problem was.
CARD CLASS
import java.util.Random;

public class Card
{
    private String suit, valueString;
    private int value, valueNum, suitNum;
    private final String[] SUITS = {"Clubs", "Diamonds", "Hearts", "Spades"};
    private final int[] VALUES = {2,3,4,5,6,7,8,9,10};
    private static int tot = 0;
    private static boolean[][] duplicateCheck = new boolean[4][13];//to see if suit/value pair has been used yet
    Random rand = new Random();

    public Card()
    {
        suit = createSuit();
        value = createValue();
        valueString = createValueString();

        tot += value;
    }
    private String createSuit()
    {
        String suit;

        do
        {
            suitNum = rand.nextInt((3 - 0) + 1) + 0;
            suit = SUITS[suitNum];
            valueNum = rand.nextInt((12 - 0) + 1) + 0;
        }
        while(duplicateCheck[suitNum][valueNum]);

        duplicateCheck[suitNum][valueNum] = true;

        return suit;
    }
    private int createValue()
    {
        int value;

        if(valueNum >= 9 && valueNum <= 11)
            value = 10;
        else if(valueNum == 12)
        {
            if(tot + 11 > 21)
                value = 1;
            else
                value = 11;
        }
        else
            value = VALUES[valueNum];

        return value;
    }
    private String createValueString()
    {
        String valueString;

        if(valueNum >= 9 && valueNum <= 11)
        {
            switch(valueNum)
            {
                case 9:
                    valueString = "Jack";
                    break;
                case 10:
                    valueString = "King";
                    break;
                case 11:
                    valueString = "Queen";
                    break;
                default:
                    valueString = Integer.toString(valueNum);//not really needed
                    break;
            }
        }
        else if(valueNum == 12)
            valueString = "Ace";
        else
            valueString = Integer.toString(VALUES[valueNum]);

        return valueString;
    }
    public String getSuit()
    {
        return suit;
    }
    public int getValue()
    {
        return value;
    }
    public String getValueString()
    {
        return valueString;
    }
    @Override
    public String toString()
    {
        String str;

        str = valueString + " (" + suit + ")";

        return str;
    }
}

DECK CLASS
import java.util.ArrayList;

public class Deck
{
    ArrayList <Card> deck = new ArrayList<>();
    private static int drawCard = 0;

    public Deck()//creates shufffled deck (each card is made at random)
    {
        for(int x = 0; x < 52; x++)
        {
            deck.add(new Card());
        }
    }
    public Card draw()
    {
        Card drawn;

        drawn = deck.get(drawCard);
        drawCard++;

        return drawn;
    }
}

MAIN CLASS AND METHOD
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Scanner;

public class Blackjack
{
    public static void main(String[] args)
    {
        Deck newDeck;
        Card c = null;
        String name;
        int bal = 1000, currentBet = 25;
        char move = 'h';//hit by default
        int[] handValues = new int[2];
        ArrayList<Card> dealer = new ArrayList<>();
        ArrayList<Card> player = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("#,###");

        name = getName();
        System.out.println(name + " has $" + df.format(bal));
        currentBet = getBet(currentBet);

        while(currentBet != 0 && bal > 0)//determines when program ends
        {
            newDeck = new Deck();

            //player 2 cards, dealer 1 card
            firstDeal(c, newDeck, player, dealer, name, handValues, currentBet);
            System.out.println();
            move = nextMove();

            //loop: player hits until bust, stand, or hits 21
            while(handValues[0] != 21 && handValues[0] < 21 && move != 's')
            {
                System.out.println("\nBet: $" + df.format(currentBet));
                dealerStand(dealer, handValues);
                playerHit(c, newDeck, player, name, handValues);
                if(handValues[0] != 21 && handValues[0] < 21 && move != 's')
                    move = nextMove();
            }

            if(move == 's')//player stands
            {
                //loop: dealer hits until bust or stand
                while(handValues[1] < 17)
                {
                    System.out.println("\nBet: $" + df.format(currentBet));
                    dealerHit(c, newDeck, dealer, handValues);
                    playerStand(name, player, handValues);
                }

                if(handValues[1] >= 17 && handValues[1] <= 20 &&
                        handValues[1] > handValues[0])//dealer wins
                {
                    System.out.println("Dealer wins\n");
                    bal -= currentBet;
                }
                if(handValues[1] >= 17 && handValues[1] <= 20 &&
                        handValues[1] < handValues[0])//player wins
                {
                    System.out.println(name + " wins\n");
                    bal += currentBet;
                }
                if(handValues[1] > 21)//dealer bust, player wins
                {
                    System.out.println("Dealer bust\n");
                    bal += currentBet;
                }
                if(handValues[0] == handValues[1])//push
                    System.out.println("The game is a push\n");
            }
            else if(handValues[0] > 21)//player busts
            {
                System.out.println(name + " bust\n");
                bal -= currentBet;
            }
            else if(handValues[0] == 21)//player wins
            {
                System.out.println(name + " wins\n");
                bal += currentBet;
            }
            else if(handValues[0] == handValues[1])//both tie at 21
                System.out.println("The game is a push\n");

            System.out.println(name + " has $" + df.format(bal));
            currentBet = getBet(currentBet);//does stuff with 0, but not enter or new num
        }
    }
    public static String getName()
    {
        Scanner input = new Scanner(System.in);
        String name;

        System.out.print("Name? ");
        name = input.nextLine();

        return name;
    }
    public static int getBet(int currentBet)
    {
        Scanner input = new Scanner(System.in);
        String temp;

        System.out.print("Bet? (0 to quit, Enter to stay at $" + currentBet + ", or a new number to change bet) ");
        temp = input.nextLine();

        if(!temp.isEmpty())
            currentBet = Integer.parseInt(temp);

        return currentBet;
    }
    public static char nextMove()
    {
        Scanner input = new Scanner(System.in);
        String moveStr;
        char move;

        System.out.print("Move? (\"h\" for hit/\"s\" for stand) ");
        moveStr = input.nextLine();
        /*while(moveStr.charAt(0) != 'h' || moveStr.charAt(0) != 's')
        {
            System.out.println("Invalid choice. Enter either \"h\" or \"s\".");     //input validation
            moveStr = input.nextLine();
        }*/
        move = moveStr.charAt(0);

        return move;
    }
    public static int[] firstDeal(Card c, Deck newDeck, ArrayList player,
            ArrayList dealer, String name, int[] handValues, int currentBet)
    {
        DecimalFormat df = new DecimalFormat("#,###");
        System.out.println("\nBet: $" + df.format(currentBet));

        //dealer 1 card
        c = newDeck.draw();
        dealer.add(c);
        System.out.print("Dealer's hand: ");
        for(int cardNum = 0; cardNum < dealer.size(); cardNum++)
            System.out.print(dealer.get(cardNum) + "  ");
        System.out.println();
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[1] >= 11)
                handValues[1] += 1;
            else
                handValues[1] += 11;
        }
        else
            handValues[1] += c.getValue();
        System.out.print("Value: " + handValues[1] + "\n");

        //player 2 cards
        c = newDeck.draw();
        player.add(c);
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[0] >= 11)
                handValues[0] += 1;
            else
                handValues[0] += 11;
        }
        else
            handValues[0] += c.getValue();
        c = newDeck.draw();
        player.add(c);
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[0] >= 11)
                handValues[0] += 1;
            else
                handValues[0] += 11;
        }
        else
            handValues[0] += c.getValue();
        System.out.print(name + "'s hand: ");
        for(int cardNum = 0; cardNum < player.size(); cardNum++)
            System.out.print(player.get(cardNum) + "  ");
        System.out.println();
        System.out.print("Value: " + handValues[0] + "\n");

        return handValues;
    }
    public static int playerHit(Card c, Deck newDeck, ArrayList player,
            String name, int[] handValues)
    {
        c = newDeck.draw();
        player.add(c);
        System.out.print(name + "'s hand: ");
        for(int cardNum = 0; cardNum < player.size(); cardNum++)
            System.out.print(player.get(cardNum) + "  ");
        System.out.println();
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[0] >= 11)
                handValues[0] += 1;
            else
                handValues[0] += 11;
        }
        else
            handValues[0] += c.getValue();
        System.out.println("Value: " + handValues[0] + "\n");

        return handValues[0];
    }
    public static void playerStand(String name, ArrayList player,
            int[] handValues)
    {
        System.out.println(name + "'s hand: ");
        for(int cardNum = 0; cardNum < player.size(); cardNum++)
            System.out.print(player.get(cardNum) + "  ");
        System.out.println();
        System.out.println("Value: " + handValues[0] + "\n");
    }
    public static int[] dealerHit(Card c, Deck newDeck, ArrayList dealer,
            int[] handValues)
    {
        c = newDeck.draw();
        dealer.add(c);
        System.out.print("Dealer's hand: ");
        for(int cardNum = 0; cardNum < dealer.size(); cardNum++)
            System.out.print(dealer.get(cardNum) + "  ");
        System.out.println();
        if(c.getValueString().equals("Ace"))
        {
            if(handValues[1] >= 11)
                handValues[1] += 1;
            else
                handValues[1] += 11;
        }
        else
            handValues[1] += c.getValue();
        System.out.println("Value: " + handValues[1]);

        return handValues;
    }
    public static int[] dealerStand(ArrayList dealer, int[] handValues)
    {
        System.out.print("Dealers's hand: ");
        for(int cardNum = 0; cardNum < dealer.size(); cardNum++)
            System.out.print(dealer.get(cardNum) + "  ");
        System.out.println();
        System.out.println("Value: " + handValues[1]);

        return handValues;
    }
}

A: The problem is not with the Scanner!
I plugged this code into a debugger, and it gets stuck in an infinite loop in the Card.createSuit() function. The duplicateCheck dictionary gets filled with true so it can never pick the next suit.
Note: duplicateCheck is declared as static, so it will maintain its instance between "deals". duplicateCheck should probably not be inside the Card class, but in the Deck class instead, and NOT static. That way, each Deck instance will have a reference to which cards have been used. You can still call new Card() to generate a random card, but check the suit and value of the new Card instance inside the Deck instance.
Another note: this will still be a very busy deck generator since you are always generating a random card each time, which may be already part of the deck. I would recommend maybe having some Lists (or Sets) of "available" cards, and each time you want a card, you pick a random index in that List to get the card value/suit. Then remove that item from the List so that it is not available for the next card selection. I will leave that all up to you though. Have fun!


text:
Q: R - sjp.glm "Error: Unknown parameters: family" I'm getting the following error when I try to plot predicted probabilities of a glm model using the sjPlot package in R:
Error: Unknown parameters: family

I'm somewhat new to R and have been unable to successfully troubleshoot this issue.  Here is code:
options(warn=1)
library(sjPlot)

df = data.frame(x = c(10, 20, 30, 40, 50, 60, 70, 80),
            y = c(1, 1, 0, 1, 1, 0, 0, 0))

m1 = glm(data = df, y ~ x, family = binomial)
sjp.glm(fit = m1, type = "prob")

And when I run it...
> sjp.glm(fit = m1, type = "y.pc", show.se = TRUE)
Error: Unknown parameters: family

Since they both refer to "family", I would think the error is connected to this warning I get when I load the sjPlot library, but I don't know enough about R yet to understand it...
> options(warn=1)
> library(sjPlot)
Note: the specification for S3 class "family" in package 'MatrixModels' seems
equivalent to one from package 'lme4': not turning on duplicate class
definitions for this class.
Warning: replacing previous import by 'grid::unit' when loading 'sjPlot'

Any help is much appreciated...

A: It is a bug that occured when implementing support for more family types than just binomial. This bug should be fixed in the current GitHub version.
Edit: it might also be to the ggplot update - which package versions of sjPlot and ggplot are you using? Perhaps updating packages might already help.


text:
Q: Overwide Webpage, Images Stretching? Could anybody tell me why the following page has a horizontal scroll bar? I have tried to set the limits of any image or div to be 100% of the width of the page, but I still get the scroll bar.
Thanks so much.
http://onmywifesback.tumblr.com

A: Your CSS contains the following styling for the body { width: 100%; }. By default a browser adds some margin, Chrome 8px, around the <body> tag. This makes the total larger than 100%, thus it will show a scrollbar.
You can safely remove the width: 100% from the <body> or add body { margin: 0; }
As a tip on how to solve these issues yourself, try opening Chrome's DevTools and simply start removing elements until the problem disappears. The element you've removed last is most likely the culprit.

A: Remove width:100% in css. That should fix it

A: I have just been to the website (Safari / IE11 / Chrome, Opera & Firefox) and could not replicate your problem on my screen with a resolution of 1920 x 1080
I then checked it on my iPad Air and that never produced a scroll bar either, so it is difficult to give a precise answer, it may be the Browser you are using is an older version of IE that will need telling what to do in your .css
<link rel="stylesheet" media="all" href="[name].css" />
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->


text:
Q: Is there an AngularJS ORM I came a across the following article while considering adding bacon.js and AngularJS:
https://github.com/ProLoser/AngularJS-ORM
But I could not find any other resources that would encourage (or discourage) the use of bacon.js in angularJs.
So I'm looking for some other resources on the subject? Does anyone have use the concept proposed by Dean Sofer? Does it work the magic promise?
Has anyone use the concept used in the video?

A: Sure this link can help you https://github.com/lauripiispanen/angular-bacon. Also I have my work with angularjs and bacon together https://github.com/xgrommx/angular-bacon-bridge.


text:
Q: SwiftUI mysterious space on top of the VStack I have this code
    NavigationView{
      VStack{
        GeometryReader{ geometry in
            VStack{
                Text("a")
            }
            .frame(width:geometry.size.width)
            .background(Color.orange)
            Spacer()
        }
      }
      .modifier(NavBarModifier(font: self.fontUI,text: "Profile"))
    }
    .navigationViewStyle(StackNavigationViewStyle())

I want the
GeometryReader to appear at top of the VStack, however what I get is:
Where the blue line is the top of the VStack and orange is the GeometryReader. I tried adding Spacer() after the GeometryReader, but it didn't work. How can I remove that spacing?
struct NavBarModifier: ViewModifier{
    var font: UIFont
    var text: String
    func body(content: Content) -> some View {
        return content
        .zIndex(0)
        .animation(.spring())
        .padding(.top,80)
        .navigationBarTitle(Text(self.text),displayMode: .inline)
        .navigationBarHidden(false)
        .foregroundColor(.orange)
        .background(NavigationConfigurator { nc in
                       nc.navigationBar.barTintColor = UIColor(red: 243/255, green: 107/255, blue: 21/255, alpha: 1)
                       nc.navigationBar.titleTextAttributes = [
                        .foregroundColor : UIColor.white,
                        .font : self.font,
                        .kern: 1.2
                       ]
        }
        .padding([.top, .leading, .trailing]))
    }
}

A: Just remove redundant padding in NavBarModifier
func body(content: Content) -> some View {
    return content
    .zIndex(0)
    .animation(.spring())
//    .padding(.top,80)        // << this one !!

A: You need to add the Spacer after the GeometryReader for it to layout in the top of the VStack and also add .edgesIgnoringSafeArea(.top) for it to ignore that white space (the safe area) and make it align at the top of the VStack.
VStack {
    GeometryReader{ geometry in
        VStack {
            Text("s")
        }
        .frame(width:geometry.size.width)
        .background(Color.orange)

        Spacer()
    }
    .edgesIgnoringSafeArea(.top)

    Spacer()
}


text:
Q: Disable header for a specific page in wordpress how can i disable header for this specific page. Is there any php function that disables the header for a specific page? In wordpress
Here is the link: https://techmax.ro/elementor-14408/

A: You can hide by CSS and using WP is_page function. check the below code.
function hide_header_on_some_pages(){
    if( is_page( 'yourpagename' ) ){
        ?>
        <style type="text/css">
            .site-header {
                display: none;
            }
        </style>
        <?php
    }
}
add_action( 'wp_head', 'hide_header_on_some_pages', 10, 1 );

A: Put this condition where the code is done to get the menu.
if(! is_page( 'your-page-slug' ) ){
      wp_nav_menu( array( 'theme_location' => 'your menu name', 'container_class' => 'my_extra_menu_class' ) );
}
Using this there is no extra dom element on this page.


text:
Q: Validate Azure Resource Group option disappears from menu in VS2017
*

*Create Azure Resource Group (from Function App dedicated template) project in VS2017 Enterprise Version 15.6.7

*Create new dev-azuredeploy-parameters.json file

*Add resources, params, etc. to azuredeploy.json file

*Right-click project, select "Validate". ARM template is validated.

*Close solution, close VS, open VS, open solution

*Make changes to azuredeploy.json

*Right-click project to validate

Expected behavior: Validate option is available
Actual behavior: Validate option is missing

A: Appears to be in bug in VS2017.
Workaround: Unload the project, reload the project. The Validate menu option should now be visible.


text:
Q: I want to control 2 instances of a backtesting software simultaneously Im using soft4fx, to backtest currency and indices. Ive renamed the back test software so i can run 2 instances in 2 separate mt4 instances(crashes if you don't do this) any how I want to  have a controller that will allow me to simultaneously scroll the candles backwards and forwards in both instances. Anyone have any idea about how I could begin to go about developing something like this. My coding skills are basic, but I have perseverance. Can this be done perhaps using quantmod  ect in R??
many thanks


text:
Q: selected option laravel livewire I have a dropdown and in edit page I want to show old input. I use this code but it still shows "please select". Where is the problem?
<select wire:model.defer="form.department" id="form.department" class="tf-input">
    <option value="null" selected disabled>{{ __('Please select') }}</option>
    @foreach($this->departments as $department)
        <option {{ $form->department_id == $department->id ? 'selected' : '' }} value="{{ $department->id }}" >{{ $department->name }}</option>
    @endforeach
</select>

A: Livewire does not listen to selected attributes in HTML when you are using wire:model, because it will overwrite it with the value from the component. Therefor, remove it entirely.
<select wire:model.defer="form.department" id="form.department" class="tf-input">
    <option value="null" disabled>{{ __('Please select') }}</option>
    @foreach ($this->departments as $department)
        <option value="{{ $department->id }}" wire:key="department-{{ $department->id }}">{{ $department->name }}</option>
    @endforeach
</select>

As you can see, I removed the parts that adds selected, but I also added a wire:key to the options - this is because the elements are rendered in a loop, and will help Livewire keep track of all elements on a page.
To set a value that is bound through wire:model, you need to set the value in the component. So in the mount() method, you can do
$this->form['department'] = $department->id;


text:
Q: User session management using Javascript I have one session timer in my application which checks if the user is idle for a specific time. Below is my code.
var sessionTimeout;
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
// I have some more dom events here

function logout() {
    alert("You are now logged out.")
    //location.href = 'logout.php'
}
function resetTimer() {
    clearTimeout(sessionTimeout);
    sessionTimeout = setTimeout(logout, 30000)
}

If the user opens two tabs simultaneously and keeps the one tab idle and other not, he will be logged out after the timeout period because the timer will run in the other tab which is not in focus. Is there any way to handle this? I think Javascript can't access the data in the other tabs. So is there any global timeouts specific to the browser which applies to all tabs so that the session will be active if any tab is not idle? Can anyone suggest solutions?

A: You can use BroadcastChannel to communicate between the tabs and get this done. Refer https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel
A possible solution pseudo code can look like
var sessionTimeout;
var bc = new BroadcastChannel('session_channel');
window.onload = resetTimer;
// DOM Events
document.onmousemove = resetTimer;
document.onkeypress = resetTimer;
bc.onmessage = resetTimer;
// I have some more dom events here

function logout() {
   alert("You are now logged out.")
   //location.href = 'logout.php'
}
function resetTimer() {
   bc.postMessage('activity');
   clearTimeout(sessionTimeout);
   sessionTimeout = setTimeout(logout, 30000)
}

So every time there is activity in the tab, it will notify all the other tabs, so they update the timer as well.
But do keep in mind that broadcastChannel is not supported in older browsers, so look at the support table and if needed implement fallback using localStorage to share the activity state


text:
Q: join two collections with group by and sum in Mongodb i have this two collection and i want to join, after this I want to sum the value of TotalPrice  each orderdate :
some line of my two collections
the first collection date :
{"Id_Date":1,"OrderDate":"2018-01-03"},
{"Id_Date":2,"OrderDate":"2018-01-05"},
{"Id_Date":3,"OrderDate":"2018-01-09"},
{"Id_Date":4,"OrderDate":"2018-01-10"},
{"Id_Date":5,"OrderDate":"2018-01-11"},
{"Id_Date":6,"OrderDate":"2018-01-12"},
{"Id_Date":7,"OrderDate":"2018-01-18"},
{"Id_Date":8,"OrderDate":"2018-01-21"},
{"Id_Date":9,"OrderDate":"2018-01-22"},
{"Id_Date":10,"OrderDate":"2018-02-02"},

the second collection order_fact :
{"orderid":"c3e15faf-e338-4ed5-9bbb-bbcd15295fd7","Id_Cust":"10995116278711","Id_Date":"91","TotalPrice":1933.53,"Orderline":[{"productId":"4165","asin":"B005G2G2SQ","title":"ESEE-6 Plain Black Blade With Grey Removable Lined Micarta Handles 1095 Carbon Steel 57-Rc","price":140.05,"brand":"Fila_(company)"},{"productId":"5916","asin":"B001CJ2LQ4","title":"Aimpoint M4s 2 Minute of Angle QRP2 CompM4 Sight with Mount","price":804.95,"brand":"Atletica"},{"productId":"7779","asin":"B003DO5L3G","title":"Lee Precision Load Master 223 Remington Reloading Rifle Kit (Red)","price":249.26,"brand":"BURRDA"},{"productId":"2722","asin":"B0017U1MJU","title":"Casio Mens PAW1500-1V Pathfinder Multi-Band Solar Atomic Ultimate Watch","price":190.27,"brand":"Reebok"},{"productId":"52","asin":"B007SYGLZO","title":"Armasight Spark CORE Multi-Purpose Night Vision Monocular","price":549.0,"brand":"Signia_(sportswear)"}],"Livreur":{"Id_livreur":"91bcee9f-8896-4e18-a24c-a8e86b97b3a1","Nom":"Tyson Anderson","gender":"Male","phone":"7-458-665-3444"}},
{"orderid":"35b26e6d-e450-4edc-9071-306cea10a083","Id_Cust":"10995116278711","Id_Date":"249","TotalPrice":1540.91,"Orderline":[{"productId":"1978","asin":"B001CZBMRC","title":"Benchmade Osborne Design Rift Knife","price":178.5,"brand":"CCM_(ice_hockey)"},{"productId":"857","asin":"B004IIKA2I","title":"Barnett Quad 400 Crossbow Package (Quiver 3 - 22-Inch Arrows and 4x32mm Scope)","price":354.99,"brand":"Fischer_(company)"},{"productId":"8362","asin":"B00635GTTW","title":"Schwinn IC2 Indoor Cycling Exercise Bike","price":422.49,"brand":"Admiral_Sportswear"},{"productId":"216","asin":"B000GKN45C","title":"Swagman XTC-4 Cross-Country 4-Bike Hitch Mount Rack (2-Inch Receiver Hitch)","price":349.99,"brand":"Elfin_Sports_Cars"},{"productId":"7766","asin":"B000KKEPJ2","title":"Lyman Reloading Press T-Mag Turret Press","price":234.94,"brand":"BURRDA"}],"Livreur":{"Id_livreur":"48d64c09-7a63-4fca-815a-a96921a82ee7","Nom":"Abdul Coll","gender":"Male","phone":"1-273-204-4721"}},
{"orderid":"ffaec62e-9875-42af-8789-0a97eabe77e4","Id_Cust":"10995116278711","Id_Date":"67","TotalPrice":1058.41,"Orderline":[{"productId":"2675","asin":"B00BPRM2O4","title":"Large Exercise Mat Large Workout Mat With A Unique Fabric Finish That Provides Excellent Traction And Floor Protection. Can Be Used In Conjunction With The Square36 YOGA Mat. The Square36 CARDIO Mat - The BIG Exercise Mat- Step Into the Square.","price":159.99,"brand":"Reebok"},{"productId":"1380","asin":"B000EQCVQ6","title":"Eureka! Apex 2XT Two-Person Tent","price":175.16,"brand":"Topper_(sports)"},{"productId":"9665","asin":"B004H4VSI8","title":"IRONMAN HIGH CAPACITY GRAVITY 3000 INVERSION TABLE","price":239.8,"brand":"Wilson_Sporting_Goods"},{"productId":"7603","asin":"B0017SC9H6","title":"Zero Tolerance Combat Folding Knife","price":199.0,"brand":"Tramontana_(sports_car)"},{"productId":"887","asin":"B00BCLL8C0","title":"SportRack SR7018 Vista XL Rear Opening Cargo Box 18-Cubic Feet","price":284.46,"brand":"Fischer_(company)"}],"Livreur":{"Id_livreur":"7548ac7b-5bf7-4c5a-a80d-5390b73b9b90","Nom":"Henry Wilde","gender":"Male","phone":"3-624-033-5243"}},
{"orderid":"125e7887-c41d-4a5a-aa6b-d2a3679d58e7","Id_Cust":"10995116278711","Id_Date":"477","TotalPrice":1624.98,"Orderline":[{"productId":"6250","asin":"B005DYQ9V2","title":"Invicta Men s 1463 Reserve Collection Chronograph Silver Dial Stainless Steel Watch","price":199.95,"brand":"Keuka_(brand)"},{"productId":"1138","asin":"B000AMRN12","title":"Stamina AeroPilates Reformer with Free-Form Cardio Rebounder","price":449.0,"brand":"Topper_(sports)"},{"productId":"7575","asin":"B005D7FXMA","title":"Cygolite Expilion 400 Usb Rechargeable Headlight with Quick Release Li-Ion Battery Stick and Wall Charger","price":113.99,"brand":"Derbi"},{"productId":"6529","asin":"B005Z2CYX4","title":"Zero Tolerance ZT0550 Hinderer Design Folding Knife","price":160.0,"brand":"CA_Sports"},{"productId":"7125","asin":"B007INYN6O","title":"Barnett Zombie 350 CRT Crossbow","price":702.04,"brand":"Elan_Snowboards"}],"Livreur":{"Id_livreur":"a1060a87-fdff-4acc-b728-c805b72b0740","Nom":"Percy Thornton","gender":"Male","phone":"5-744-522-0782"}},
{"orderid":"b259eafc-2f47-47dc-927b-5b6d6edbba1d","Id_Cust":"10995116278711","Id_Date":"617","TotalPrice":1484.76,"Orderline":[{"productId":"7667","asin":"B008W1TUAK","title":"MAGPUL ACS CARB STOCK MIL-SPEC BLACK","price":98.99,"brand":"POC_Sports"},{"productId":"6406","asin":"B001CJX50K","title":"Kinetic Rock n Roll Trainer w/Road Resistance Unit","price":389.99,"brand":"MYLAPS_Sports_Timing"},{"productId":"1883","asin":"B000O8Z7TW","title":"KNEX Education - Exploring Machines","price":126.79,"brand":"TRYMAX"},{"productId":"4158","asin":"B003AQKQAA","title":"Vortex Viper PST 6-24x50 Rifle PST-624S1-M","price":749.0,"brand":"Fila_(company)"},{"productId":"7578","asin":"B00D43A93I","title":"Under Armour Hammer 8600014-4808 Polarized Wrap Sunglasses","price":119.99,"brand":"Derbi"}],"Livreur":{"Id_livreur":"eb135eef-7ee2-4d90-b073-cbd4570935b3","Nom":"Violet Adler","gender":"Female","phone":"5-466-075-2676"}},
{"orderid":"b5755c1e-fc3f-4481-a175-edfc82290ea5","Id_Cust":"10995116278711","Id_Date":"208","TotalPrice":2487.71,"Orderline":[{"productId":"965","asin":"B000O3AVNY","title":"Advanced Elements AdvancedFrame Expedition Kayak","price":599.99,"brand":"Donnay_(sports)"},{"productId":"6888","asin":"B0029KL3S2","title":"Precor 240i Commercial Series StretchTrainer","price":704.2,"brand":"Elan_(company)"},{"productId":"6439","asin":"B004PJ1J4S","title":"Invicta Men s 6566 Subaqua Noma IV Collection Chronograph Black Polyurethane Watch","price":340.65,"brand":"MYLAPS_Sports_Timing"},{"productId":"9503","asin":"B0034PXYRY","title":"Eotech EXPS3-0 Holographic Weapon Site","price":606.92,"brand":"EA_Sports"},{"productId":"7740","asin":"B00271ERVI","title":"Crimson Trace Lasergrip for Ruger Lcr","price":235.95,"brand":"BURRDA"}],"Livreur":{"Id_livreur":"c75a672e-37cf-498e-8bf9-8dae7857165f","Nom":"Renee Eyres","gender":"Female","phone":"6-311-624-4031"}},
{"orderid":"8a129f4e-e736-4919-9a22-c98373f1df3b","Id_Cust":"10995116278711","Id_Date":"390","TotalPrice":1233.67,"Orderline":[{"productId":"1929","asin":"B004P4HH8U","title":"Barnett Ghost 350 CRT Crossbow Package (Quiver 3 - 20-Inch Arrows and Illuminated 3x32mm Scope)","price":509.99,"brand":"TRYMAX"},{"productId":"2940","asin":"B004IIZVQ8","title":"Barnett Wildcat C5 Crossbow Package (Quiver 3 - 20-Inch Arrows and Premium Red Dot Sight)","price":342.99,"brand":"Volkl"},{"productId":"3174","asin":"B006U0YZPA","title":"Bushnell X-8 6MP Trail Camera with Night Vision and Field Scan","price":136.94,"brand":"Daei_Sport"},{"productId":"6527","asin":"B003MA1SSI","title":"Sadlak Industries M14 National Match Spring Guide","price":40.75,"brand":"CA_Sports"},{"productId":"1759","asin":"B007L4ZGXE","title":"Zero Tolerance ZT0560 Hinderer Design Black Folding Knife","price":203.0,"brand":"Olympikus"}],"Livreur":{"Id_livreur":"2ccb39c1-5c1a-46d8-b394-fc887bd4cecd","Nom":"Faith Flanders","gender":"Female","phone":"2-586-775-3278"}},
{"orderid":"bb671476-5f67-414a-9b84-77498b05f0bd","Id_Cust":"10995116278711","Id_Date":"205","TotalPrice":1601.81,"Orderline":[{"productId":"810","asin":"B009K28INA","title":"Schwinn 425 Elliptical Trainer (2013)","price":599.99,"brand":"Fischer_(company)"},{"productId":"6802","asin":"B000WY8ZHO","title":"Luminox Men s Navy Seal ColorMark Watch 3051","price":229.09,"brand":"Onda_(sportswear)"},{"productId":"3178","asin":"B007O5B0LC","title":"Weslo Cadence G 5.9 Treadmill","price":351.0,"brand":"Daei_Sport"},{"productId":"2126","asin":"B0025YCYK8","title":"Spyderco Temperence 2 Canvas Micarta Plain Edge Knife","price":207.72,"brand":"Li-Ning"},{"productId":"6736","asin":"B002QWB8HY","title":"CamelBak BFM 3L Backpack","price":214.01,"brand":"Onda_(sportswear)"}],"Livreur":{"Id_livreur":"629b2edd-8bd4-4d50-8e63-33f4904ffd2c","Nom":"Stephanie Garcia","gender":"Female","phone":"6-618-288-6820"}},
{"orderid":"d3016947-f478-4782-941d-37132482a10a","Id_Cust":"10995116278711","Id_Date":"694","TotalPrice":1534.78,"Orderline":[{"productId":"3029","asin":"B00AJK9CW8","title":"Seiko Men s SRP307 Classic Automatic Dive Watch","price":192.87,"brand":"Kettler"},{"productId":"2964","asin":"B004V956P0","title":"Crosman Optimus Break Barrel Air Rifle (.177)","price":91.98,"brand":"Volkl"},{"productId":"4115","asin":"B003UNZHNY","title":"Schwinn A10 Upright Exercise Bike (2011)","price":199.99,"brand":"Fila_(company)"},{"productId":"6853","asin":"B0081MPIBA","title":"ETEK4 - Planet Eclipse Etek 4 LT / AM Paintball Guns","price":499.95,"brand":"Elan_(company)"},{"productId":"893","asin":"B001AS697O","title":"Bowflex PR1000 Home Gym","price":549.99,"brand":"Fischer_(company)"}],"Livreur":{"Id_livreur":"787192a7-8417-44a9-a5bb-dd9060afd524","Nom":"Isla Denton","gender":"Female","phone":"1-260-416-8800"}},
{"orderid":"30dd4a79-4dac-4043-8fbc-e746e78aced3","Id_Cust":"10995116278711","Id_Date":"702","TotalPrice":1329.04,"Orderline":[{"productId":"2726","asin":"B005SSWKMK","title":"Casio Men s PRW2500T-7CR Pathfinder Triple Sensor Tough Solar Digital Multi-Function Titanium Pathfinder Casual Watch","price":266.12,"brand":"Reebok"},{"productId":"6563","asin":"B0014NDXGA","title":"Bushnell Tour V2 Standard Edition Golf Laser Rangefinder","price":290.06,"brand":"Onda_(sportswear)"},{"productId":"4856","asin":"B001QD48GC","title":"FreeForm Hideaway Home Gym","price":641.93,"brand":"ASICS"},{"productId":"7653","asin":"B007ZNUG9K","title":"Blackhawk Black TraverseTrack Bipod - 10 - BH71BP10BK","price":50.98,"brand":"POC_Sports"},{"productId":"4166","asin":"B00AJT98OQ","title":"Universal Brass Catcher","price":79.95,"brand":"Fila_(company)"}],"Livreur":{"Id_livreur":"5acb6f8a-fb71-4b32-b40d-fde782d70600","Nom":"Belinda Marshall","gender":"Female","phone":"6-671-643-4273"}},

How i can  sum of the total prices for each date ?

A: The below query will join both the tables and return the sum based on order date:
db.order_fact.aggregate([
  {
    "$lookup": {
      "from": "date",
      "localField": "Id_Date",
      "foreignField": "Id_Date",
      "as": "dateDetails"
    }
  },
  {
    "$unwind": "$dateDetails"
  },
  {
    "$group": {
      "_id": {
        "date": "$dateDetails.OrderDate"
      },
      "totalPrice": {
        "$sum": "$TotalPrice"
      }
    }
  }
])

A: As per MongoDB documentation  here  Changed in version 3.2: $sum is available in the $group and $project stages. In previous versions of MongoDB, $sum is available in the $group stage only.
When used in the $group stage, $sum has the following syntax and returns the collective sum of all the numeric values that result from applying a specified expression to each document in a group of documents that share the same group by key:
{ $sum: <expression> }

For Example Use in $group Stage
Consider a sales collection with the following documents:
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-01-01T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-02-03T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 5, "date" : ISODate("2014-02-03T09:05:00Z") }
{ "_id" : 4, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-02-15T08:00:00Z") }
{ "_id" : 5, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-02-15T09:05:00Z") }

Grouping the documents by the day and the year of the date field, the following operation uses the $sum accumulator to compute the total amount and the count for each group of documents.
db.sales.aggregate(
   [
     {
       $group:
         {
           _id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } },
           totalAmount: { $sum: { $multiply: [ "$price", "$quantity" ] } },
           count: { $sum: 1 }
         }
     }
   ]
)

The operation returns the following results:
{ "_id" : { "day" : 46, "year" : 2014 }, "totalAmount" : 150, "count" : 2 }
{ "_id" : { "day" : 34, "year" : 2014 }, "totalAmount" : 45, "count" : 2 }
{ "_id" : { "day" : 1, "year" : 2014 }, "totalAmount" : 20, "count" : 1 }

Using $sum on a non-existent field returns a value of 0. The following operation attempts to $sum on qty:
db.sales.aggregate(
   [
     {
       $group:
         {
           _id: { day: { $dayOfYear: "$date"}, year: { $year: "$date" } },
           totalAmount: { $sum: "$quantity" },
           count: { $sum: 1 }
         }
     }
   ]
)

The operation returns:
{ "_id" : { "day" : 46, "year" : 2014 }, "totalAmount" : 0, "count" : 2 }
{ "_id" : { "day" : 34, "year" : 2014 }, "totalAmount" : 0, "count" : 2 }
{ "_id" : { "day" : 1, "year" : 2014 }, "totalAmount" : 0, "count" : 1 }

When used in the $project stage, $sum returns the sum of the specified expression or list of expressions for each document and has one of two syntaxes:

*

*$sum has one specified expression as its operand:
{ $sum:  }

*$sum has a list of specified expressions as its operand:
{ $sum: [ ,  ... ]  }
For Example Use in $project Stage
A collection students contains the following documents:
{ "_id": 1, "quizzes": [ 10, 6, 7 ], "labs": [ 5, 8 ], "final": 80, "midterm": 75 }
{ "_id": 2, "quizzes": [ 9, 10 ], "labs": [ 8, 8 ], "final": 95, "midterm": 80 }
{ "_id": 3, "quizzes": [ 4, 5, 5 ], "labs": [ 6, 5 ], "final": 78, "midterm": 70 }

The following example uses the $sum in the $project stage to calculate the total quiz scores, the total lab scores, and the total of the final and the midterm:
db.students.aggregate([
   {
     $project: {
       quizTotal: { $sum: "$quizzes"},
       labTotal: { $sum: "$labs" },
       examTotal: { $sum: [ "$final", "$midterm" ] }
     }
   }
])

The operation results in the following documents:
{ "_id" : 1, "quizTotal" : 23, "labTotal" : 13, "examTotal" : 155 }
{ "_id" : 2, "quizTotal" : 19, "labTotal" : 16, "examTotal" : 175 }
{ "_id" : 3, "quizTotal" : 14, "labTotal" : 11, "examTotal" : 148 }

For Further you ref here


text:
Q: iOS MagicalRecord--Can I change the MR/CD setup scheme after the fact? I've got a little app using Core Data via MagicalRecord that is working fine, in its rudimentary fashion, thanks largely to the help I've found here.
Now, I've discovered that I need to add a new attribute on an entity in my data model. And, belatedly, I've also discovered that I should have used the MagicalRecord method "setupCoreDataStackWithAutoMigratingSqliteStoreNamed" instead of the plain Jane "setupCoreDataStackWithStoreNamed:"
I understand that the automigrating option will take care of the lightweight migration (my first) automatically.
Before I get myself into real trouble, can I simply change that one line of code in the AppDelegate from:
[MagicalRecord setupCoreDataStackWithStoreNamed:@"MyDatabase.sqlite"];

to:
[MagicalRecord setupCoreDataStackWithAutoMigratingSqliteStoreNamed:@"MyDatabase.sqlite"];

Be gentle with me--in all the tuts and research I've done, the issue was never addressed up front, I mean, making sure all possible attributes have been thought of and included when creating the data model and before deciding on which MR option to use. I'm sure this gotcha would have been obvious to a more experienced programmer, but it wasn't to me. :)
Thanks!

A: Yes, that should be just fine. All the auto migrating method does is set some configuration options to the stack setup. The rest of the initialization is identical to the basic setup.
However, if you're using your app in development, I would also recommend just deleting the old version of the store and starting over. This is commonly how I work in development when I am rapidly updating or modifying the core data model for an app.


text:
Q: [Vue warn]: Failed to resolve component: app at  Laravel 8 & Vue 3 I have the following problem which repeats a lot to me when using Vue 3 and Laravel somewhere. I'm just getting started and have a virtually clean app and can still see this issue exist. Namely, Vuejs 3 from Laravel 8 do not work for me.
I get an error in the console:

[Vue warn]: Failed to resolve component: app
at  app.js:13797

app.js
require('./bootstrap');

import { createApp } from 'vue';

import App from './App.vue';
const app = createApp({App});
app.mount("#app");

App.vue
<template>

{{ greeting }}

</template>

webpack.mix.js
const mix = require('laravel-mix');
const tailwindcss = require('tailwindcss');

mix.js('resources/js/app.js', 'public/js')
    .vue()
    .sass('resources/sass/app.scss', 'public/css', {}, [tailwindcss('./tailwind.config.js')])
    .version();

welcome.blade.php
<!doctype html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    <title>Document</title>

<app>

</app>

Please help me with this.
:)

A: It should be createApp(App), not {App}, which is a shorthand for {App: App}.


text:
Q: C3.js - Show/hide points independently for a data series I am creating a line chart for a data series using C3.js.
I am struggling in trying to show the "points" only for one of the series.
Basically, first I am creating a multiple series line chart with some reference data, and then I am loading (with char.load) a new particular data line in which I want to show points, only for that particular line while the other reference lines remain with hidden points.
Is that possible via C3.js? If so, could you instruct me to do so, thanks!
Also, any method to do so using D3.js while using C3.js is welcome.
This is the official example in which all points are hidden for a data series, just for reference:
http://c3js.org/samples/point_show.html

A: c3.js provides comprehensive class attributes on all its elements so you can customize them with CSS.  For example to hide the points on the 2nd series add this CSS:
#chart .c3-circles-data2 {
  display: none;
}

Example here.

A: Here's an example of using the show and hide methods of a chart object to selectively display lines:
<!DOCTYPE html>

    <title>show hide</title>
    <meta charset="utf-8" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/c3/0.4.10/c3.min.css" rel="stylesheet" />

        <input type="checkbox" id="cb1" onclick="cbclick(1)" checked="true">y1</input>
        <input type="checkbox" id="cb2" onclick="cbclick(2)" checked="true">y2</input>

A: There are a code for this purpose in the C3.js library:
point: {
  show: false,
}

You can check this at here


text:
Q: Fixing the OpenLayers MBTiles Example I've been trying to implement the OpenLayers Example for reading MBTiles:  http://projects.bryanmcbride.com/ol_mbtiles/
Right off, the link to the necessary mbtiles.php script was broken, but I found what I believe to be a copy of it, here:  https://gist.github.com/1818011
After exporting my MBTiles file from TileMill, I saw in the SQLite that the mbtiles.php file's SQL query was using the wrong columns and tables for pulling the appropriate tile images.
The original query:
$sql = "SELECT * FROM tiles WHERE zoom_level = $zoom AND tile_column = $column AND tile_row = $row";

What it should be based off what TileMill Exported:
$sql = "SELECT images.tile_data FROM map, images WHERE map.zoom_level = $zoom AND map.tile_column = $column AND map.tile_row = $row AND map.tile_id = images.tile_id";

Once I did that and stopped doing bindColumns on SQLite columns I wasn't using, I could pull the tile images from my MBTiles file using the php script.
That's where I get stuck.  I followed the Javascript code from the OpenLayers example linked to above, but the TMS layer keeps calling for tile rows and columns that don't exist.
Here's the relevant bits of my JS code.  What I'm not showing is my creation of an OSM base layer.  I think the problem lies in the math used to calculate the x and y values in mbtilesURL():
function load_mbtiles(){
            var mbtilesLayer = new OpenLayers.Layer.TMS("MBTiles Overlay", "mbtiles.php", {
                getURL: mbtilesURL,
                isBaseLayer: false
            });

            map.addLayer(mbtilesLayer);
        }

        function mbtilesURL (bounds) {
            var db = "filename.mbtiles";
            var res = this.map.getResolution();
            var x = Math.round ((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
            var y = Math.round ((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
            var z = this.map.getZoom();

            return this.url+"?db="+db+"&z="+z+"&x="+x+"&y="+((1 << z) - y - 1);

        }

Can anyone think of why this function would be calling the completely wrong tiles?

A: It ends up that it was all a projection problem.  When I created the map object, I just needed to specify the projections, and then my MBTiles layer was positioned correctly.
var options = {
  projection: "EPSG:900913",
  displayProjection: new OpenLayers.Projection("EPSG:4326")
};

map = new OpenLayers.Map('map', options);

var layer = new OpenLayers.Layer.WMS(
  "OpenLayers WMS",
  "http://vmap0.tiles.osgeo.org/wms/vmap0",
  {layers: 'basic'}
);

map.addLayer(layer);

A: I have updated and GitHubbed my PHP-MBTiles-Server script, with updated examples showing how to use it in both OpenLayers and Leaflet.
I have tested again and you absolutely can query the "tiles" view from a TileMill export.


text:
Q: What is the name of the icon that comes up (red with white horizontal line) when update fails? Trying to get the name of the icon that appears in the left side of the upper right set of icons in the Ubuntu top panel or toolbar, when an update has failed? Red circle with a white horizontal line through the center.

A:
This icon is dialog-error.svg. You can find the 64x64 file in the following folder:
/usr/share/icons/Humanity/status/64/dialog-error.svg

For a quick preview, open a terminal and type:
eog /usr/share/icons/Humanity/status/64/dialog-error.svg


text:
Q: Measure a power supply voltage with floating ground I'd like to measure the output voltage on a power supply with a ADC and a micro-controller. The ADC is powered from a different source and the grounds of the power supplies are not connected. How can safely I measure the differential output voltage of the power supply? I'm sorry if this is a standard question, but I can't find a simple solution.
Edit in response to the comments:
The voltages I want to measure range between 0 and 14V. Precision is not important (a few percent). Frequency of measurements is low (about 1Hz). No high frequency components present.

A: If your grounds are guaranteed to be close, and the voltages are within the common mode range, a simple differential amplifier may be enough.
Otherwise, depending on the accuracy you need, your best bet is probably to use a linear opto-coupler circuit.

In your case the left side would be powered from the thing you are testing and the Vin would be some division of that voltage. However if the source goes below the supply requirements of U1, that will not work.

A: I came up with the most hackish solution possible: Using an ESP8266 to stream the data wirelessly. It works.


text:
Q: How to paste HTML to clipboard with GTK+ How do I paste HTML to the clipboard so that it is recognized as HTML in applications such as Open Office and MS Word? It is possible when using gtkhtml or gecko if you've already rendered it, but I need a straight GTK+ solution.

A: You call gtk_clipboard_set_with_data or gtk_clipboard_set_with_owner, passing a GtkTargetEntry with "text/html" as the value for the target field.
It's good practice to also provide "UTF8_STRING" and "STRING" targets for applications that don't support HTML.
Here's an example of some code that does this: GEdit HTML clipboard plugin.


text:
Q: ejabberd connection using Smack in android giving connection timed out error Hello we have downloaded the ejabberd from this. domain is localhost and we have set the xmppDomain as my computer's ip address. I have used the following code for connection
    public static final String XMPP_DOMAIN = "localhost";
    public static final String XMPP_HOST = "10.0.2.2";//kept for emaulator
    //public static final String XMPP_HOST = "192.168.1.152"; //ip of my pc
    public static final int XMPP_PORT = 5222;
    public static final String XMPP_RESOURCE = "xmppdemo";
    public static final boolean XMPP_DEBUG = true;

      private void initialiseConnection() throws IOException, InterruptedException, XMPPException, SmackException {
        InetAddress addr = InetAddress.getByName(Constants.XMPP_HOST);
        DomainBareJid serviceName = JidCreate.domainBareFrom(Constants.XMPP_DOMAIN);

        XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration
                .builder();
        config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
        config.setXmppDomain(serviceName);
        config.setHostAddress(addr);
        config.setPort(Constants.XMPP_PORT);
        config.setDebuggerEnabled(Constants.XMPP_DEBUG);
        config.setResource(Constants.XMPP_RESOURCE);
        connection = new XMPPTCPConnection(config.build());
        connection.addConnectionListener(mConnectionListener);
        connection.addAsyncStanzaListener(mStanzaListener, new StanzaFilter() {
            @Override
            public boolean accept(Stanza stanza) {
                //You can also return only presence packets, since we are only filtering presences
                return true;
            }
        });

        Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
        roster = Roster.getInstanceFor(connection);
        roster.addRosterListener(mRoasterListener);

    }

     public void connect() {

        @SuppressLint("StaticFieldLeak") AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected synchronized Boolean doInBackground(Void... arg0) {
                //There is no point in reconnecting an already established connection. So abort, if we do
                if (connection.isConnected())
                    return false;

                //We are currently in "connection" phase, so no requests should be made while we are connecting.
                isconnecting = true;

                if (isToasted)
                    new Handler(Looper.getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(service, "connecting....", Toast.LENGTH_LONG).show();
                        }
                    });

                if (debug) Log.d(TAG, "connecting....");

                try {
                    connection.connect();

                    /**
                     * Set delivery receipt for every Message, so that we can confirm if message
                     * has been received on other end.
                     *
                     * @NOTE: This feature is not yet implemented in this example. Maybe, I'll add it later on.
                     * Feel free to pull request to add one.
                     *
                     * Read more about this: http://xmpp.org/extensions/xep-0184.html
                     **/

                    DeliveryReceiptManager dm = DeliveryReceiptManager.getInstanceFor(connection);
                    dm.setAutoReceiptMode(DeliveryReceiptManager.AutoReceiptMode.always);
                    dm.addReceiptReceivedListener(new ReceiptReceivedListener() {
                        @Override
                        public void onReceiptReceived(Jid fromJid, Jid toJid, String receiptId, Stanza receipt) {

                        }

//                        @Override
//                        public void onReceiptReceived(final String fromid,
//                                                      final String toid, final String msgid,
//                                                      final Stanza packet) {
//
//                        }
                    });
                    connected = true;

                } catch (IOException e) {
                    service.onConnectionClosed();
                    if (isToasted)
                        new Handler(Looper.getMainLooper())
                                .post(new Runnable() {

                                    @Override
                                    public void run() {
                                        Toast.makeText(service, "IOException: ", Toast.LENGTH_SHORT).show();
                                    }
                                });
                    if (debug) Log.e(TAG, "IOException: " + e.getMessage());
                } catch (SmackException e) {
                    service.onConnectionClosed();
                    if (isToasted)
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(service, "SMACKException: ", Toast.LENGTH_SHORT).show();
                            }
                        });
                    if (debug) Log.e(TAG, "SMACKException: " + e.getMessage());
                } catch (XMPPException e) {
                    service.onConnectionClosed();
                    if (isToasted)
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(service, "XMPPException: ", Toast.LENGTH_SHORT).show();
                            }
                        });
                    if (debug) Log.e(TAG, "XMPPException: " + e.getMessage());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //Our "connection" phase is now complete. We can tell others to make requests from now on.
                return isconnecting = false;
            }
        };
        connectionThread.execute();
    }
     //Signup to server
    public void Signup(SignupModel signupModel) {
        XMPPError.Condition condition = null;
        boolean errors = false;
        String errorMessage = "";

        String mUsername = signupModel.getUsername();
        String mPassword = signupModel.getPassword();

        boolean isPasswordValid = signupModel.checkPassword();
        boolean areFieldsValid = signupModel.validateFields();

        if (!isPasswordValid) {
            errors = true;
            errorMessage = Constants.SIGNUP_ERR_INVALIDPASS;
        }

        if (!areFieldsValid) {
            errors = true;
            errorMessage = Constants.SIGNUP_ERR_FIELDERR;
        }

        if (errors) {
            service.onSignupFailed(errorMessage);
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!connected && !isconnecting) connect();
            }
        }).start();

        try {
//            final AccountManager accountManager = AccountManager.getInstance(connection);
//
//
//            accountManager.createAccount(Localpart.from(mUsername), mPassword);

            AccountManager accountManager = AccountManager.getInstance(connection);
            accountManager.sensitiveOperationOverInsecureConnection(true);
            accountManager.createAccount(Localpart.from(mUsername), mPassword);

        } catch (XMPPException | SmackException e) {

            e.printStackTrace();
            if (debug) Log.e(TAG, "Username: " + mUsername + ",Password: " + mPassword);

            if (e instanceof XMPPException.XMPPErrorException) {
                condition = ((XMPPException.XMPPErrorException) e).getXMPPError().getCondition();
            }

            if (condition == null) {
                condition = XMPPError.Condition.internal_server_error;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (XmppStringprepException e) {
            e.printStackTrace();
        }

        if (condition == null) {
            service.onSignupSuccess();
        } else {
            switch (condition) {
                case conflict:
                    errorMessage = Constants.SIGNUP_ERR_CONFLICT;
                    break;
                case internal_server_error:
                    errorMessage = Constants.SIGNUP_ERR_SERVER_ERR;
                    break;
                default:
                    errorMessage = condition.toString();
                    break;

            }

            service.onSignupFailed(errorMessage);
        }
    }

    //Login to server
    public void login() {
        try {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    if (!connected && !isconnecting) connect();
                }
            }).start();

            if (debug) Log.i(TAG, "User " + userId + userPassword);

            connection.login(userId, userPassword);

            if (debug) Log.i(TAG, "Yey! We're logged in to the Xmpp server!");

            service.onLoggedIn();
        } catch (XMPPException | SmackException | IOException e) {

            service.onLoginFailed();
            if (debug) e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

When I run this code I an receiving the following exception (when tried to run from emulator)
SMACKException: The following addresses failed: '10.0.2.2:5222' failed because: /10.0.2.2 exception: java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 5222) from /192.168.232.2 (port 34922) after 30000ms

when tried to run from my device I kept HOST_NAME as my pc's ip address, but then I am receiving the following error
E/XMPPHandler: SMACKException: The following addresses failed: '192.168.1.152:5222' failed because: /192.168.1.152 exception: java.net.SocketTimeoutException: connect timed out

When I installed ejabberd on my pc then I received the following Access Control List page
.. Should I have to change something?? Or missing something?

A: I had this problem too. I don't know why, but ejabberd server on windows does not works properly. I tried installing server on linux and mac, and it's working correctly. But on windows version always gets SocketTimeoutException.

A: I had similar problem. I have openfire serevr installed in windows 10.
My code was
DomainBareJid xmppServiceDomain = JidCreate.domainBareFrom("desktop-urvfr83");
            //DomainBareJid xmppServiceDomain = JidCreate.domainBareFrom("192.168.1.3");
            InetAddress addr = InetAddress.getByName("192.168.1.3");

            XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
                    .setUsernameAndPassword("alir", "111111")
                    .setHostAddress(addr)
                    .setResource("phonn")
                    .setXmppDomain(xmppServiceDomain)
                    .setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
                    .setPort(5222)
                    .build();

but it could not connect. When I disabled the firewall it worked correctly and connected.


text:
Q: Is there a media query for the viewport size of a zoomed area? ( iPhone ) Say you have a 1200px x 1000px webpage that you are developing.  When one of your test users pinches in on the webpage, say 50% of the original size, the viewport would be 600px x 500px.
Are there any media queries that will fire once the user zooms 50%, 600px x 500px in this case?

A: These two articles cover the viewport topics better than anything else I've seen:
http://www.quirksmode.org/mobile/viewports.html
http://www.quirksmode.org/mobile/viewports2.html


text:
Q: TWebBrowser control slow performance only in Delphi Can someone explain me why TWebBrowser control is working so slow on all XE editions of Delphi including XE5 and possibly XE6? To test this you need to create a new Delphi project and put TWebBrowser control in it. On form show event, navigate to this website:
http://ie.microsoft.com/testdrive/Performance/setImmediateSorting/Default.html
Please test this on Windows 7 or later. When navigation is complete, run setImmediate test and watch the results. It will take huge amount of time to complete the test. It will take about a minute to finish this.
When you open true Internet Explorer browser and do the same thing - test will be completed instantly (~200 miliseconds).
Some additional wierd informations:
When you recreate this procedure on old versions of Delphi (Delphi 7 to be precise) the web-control works as fast as it should be working and test is completed instantly. But the HTML5 speed test will still works slow (alternative test on this page).
Another weird thing is, the same slow behavior can be seen on C++ Builder but not in Visual Studio products. Is Microsoft deliberately slowing down the TWebBorwser in Embarcadero products?? I can't belive this.
I was trying to overcome this problem with diffrent methods such as:

*

*Trying different feature options in registry such as:
FEATURE_GPU_RENDERING,
FEATURE_BROWSER_EMULATION (11001),
FEATURE_ALIGNED_TIMERS (undocumented option),
FEATURE_ALLOW_HIGHFREQ_TIMER (undocumented option),

*Setting timerBeginPeriod(1) - no effect.
Please, if someone have any clue how to fix this issue - share this information with me.
UPDATE1
I made standalone test app if anyone cares. It can be downloaded here: http://mp.org.pl/download/ietest.zip It contains source and exe app with htm file. HTM file contains some js procedure that works 10 times faster in standalone IE than in TWebBrowser control. It uses setImmediate as a test (the same procedure used in test described above). But it can be easier for testing this way.

A: I can also see the behavior described (in your original post and in the comments).  I have a few thoughts, but not necessarily an answer.
One should expect some difference in performance between the WebBrowser control and IE, in part because your Delphi app will need to build in support for certain features/APIs that IE supports out of the box.
For example, the WebBrowser control fires notifications related to tabbed browsing (old, but relevant), but it does not intrinsically handle those notifications or update the UI.  You have to respond to the notifications and draw the tabs yourself.  By default, IE is hardware accelerated and uses certain Windows APIs that may not be directly supported by Delphi's VCL (for resource/performance) reasons.  (Hardware acceleration could account for some of the performance differences you've noticed.)
(And, for the record, I don't believe a list of differences between IE and the WebBrowser control was ever documented.  I certainly don't remember seeing one in the portfolio.)
Also, the default values for various feature controls vary between IE and applications hosting the WebBrowser control.  Part of the reason for this stems from the idea that IE needs to highlight performance over compatibility whereas applications generally need to emphasize compatibility over performance.  You may wish to review the feature control reference to see if there are other FCKs you need to enable for your app.
Second, your loops are very tight, perhaps too tight.  You've got one request piling on earlier requests and you're not really leaving much room for processing, even with setImmediate.  (IIRC, we're not really supposed to use anything smaller than 250ms for setInterval without risking performance hits from the sheer number of requests.)  The remarks in the setImmdiate ref. page provide some guidance, as does this article on requestAnimationFrame.
One reason why dragging the window appears to improve performance may due to the priority of window drag repaint requests.  They may be forcing your loops to hold long enough (or even break) to allow other events to process.  Hard to say without with tracing the system with a debugger.
Have you ever had to add application.processMessages() to your Delphi apps in order to allow the system a chance to handle the work you've already assigned?  A similar need may be coming into play given the nature of your test.
Performance testing and timing is a tricky thing.  You need to make sure the test isn't imposing so much overhead that it interferes with the actual work you're trying to perform.
Finally, there were some questions about the document mode of the page as it's loaded into your project.  When I first started messing around with your sample, I couldn't get project4 to load slowtest.html in anything other than IE5 quirks mode (notoriously slow).  Here's what eventually started working for me:
<!DOCTYPE html>
<!-- saved from url=(0023)http://www.contoso.com/ -->
<html>
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <script type="text/javascript">
  ...

(Note, I deleted your initial doctype declaration and rewrite it to resolve a syntax error that was being reported by the F12 tools debugger.)
A few style key points here:

*

*I used a mark of the web to load the page in the Internet zone.  I find this makes it easier to load the page in edge mode, as pages in the intranet zone are loaded in compatibility view by default (unless you map the zones differently).

*The x-ua-compatible header needs to be one of the first in the head block.  It can follow title, but not much else.

*Stylistically, elements need to be specified in lower case these days.  There's a possibility that not following the current conventions forces the parser to fall back to an earlier rendering that supports the conventions.
Once I was able to control the documentMode at runtime, I found results I expected: older document modes ran more slowly.  I also found that using requestAnimationFrame instead of setImmediate led to even better performance, but also surfaced the timing issue almost immediately.
In the end, this may be a case where the test highlights a problem, but not necessarily one you're trying to solve.  (Insert Inigo meme here.)  I get that you're trying to resolve a bottleneck.  Are you sure you've found the correct bottleneck?
You may not be able to replicate the same performance of the native browser, but perhaps you can refactor the code to perform adequately without the extra overhead?  Is there anything that might be better handled with a worker or some other implementation technique?
Hope this helps...


text:
Q: My twitter reply doesnt appear after original status I,ve made a bot to reply followers whenever they call me with key words. however the reply only appears on my account. The person who got replied doesnt see the reply or gets notified
import tweepy
import random
import time

CONSUMER_KEY = 'xxxxx'
CONSUMER_SECRET = 'xxxxx'
ACCESS_KEY = 'xx-xx'
ACCESS_SECRET = 'xxxx'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

max_tweets = 20

list_delirio = ['coisa escrita', 'yes']

list_isso = ['ok', 'nope']

list_acabou = ['bye', 'see you']

delirio = random.choice(list_delirio)
isso = random.choice(list_isso)
acabou = random.choice(list_acabou)

def get_id():
    with open('ultimoid.txt', 'r') as f:
        ultimoid = f.read()
    return ultimoid

def salva_id(novo_ultimo_id):
    with open('ultimoid.txt', 'w') as f:
        f.write(str(novo_ultimo_id))

def responde():
    ultimoid = get_id()
    ids_pegos = []
    time.sleep(20)
    try:
        for tweet in tweepy.Cursor(api.mentions_timeline, since_id=ultimoid).items(max_tweets):
            ids_pegos.append(tweet.id)
            user_name = tweet.user.screen_name
            status = api.get_status(tweet.id)
            if 'frota' in status.text.lower():
                api.update_status('@' + user_name + '\n hello...', in_reply_to_status_id=tweet.id, auto_populate_reply_metadata=True)
            elif 'hello' in status.text.lower():
                api.update_status('@' + user_name + '\n wtf!', in_reply_to_status_id=tweet.id, auto_populate_reply_metadata=True)
            elif 'delírio' in status.text.lower():
                api.update_status('@' + user_name + '\n' + delirio, in_reply_to_status_id=tweet.id, auto_populate_reply_metadata=True)
            elif 'é isso?' in status.text.lower():
                api.update_status('@' + user_name + '\n' + isso, in_reply_to_status_id=tweet.id, auto_populate_reply_metadata=True)
                time.sleep(6)
            else:
                api.update_status('@' + user_name + '\n' + acabou, in_reply_to_status_id=tweet.id, auto_populate_reply_metadata=True)
                time.sleep(6)
        salva_id(max(ids_pegos))
    except Exception:
        time.sleep(30)
        pass

if __name__ == '__main__':
    while True:
        responde()
        time.sleep(30)

I'm trying to understand whats the problem. I've already put

in_reply_to_status_id=tweet.id, auto_populate_reply_metadata=True

as documentation says, but still not working

A: I've found solution:
the line status = api.get_status(tweet.id) shouldn't be there. So every status.text.lower() should be tweet.text.lower()
But the most important, the code must work with strings instead of intergers on Id's, so every tweet.id stay

tweet.id_str

that consequently changes salva_id(max(ids_pegos)) to salva_id(ids_pegos[0])


text:
Q: Assuming seems not working and "Solve::svars: Equations may not give solutions for all "solve" variables." issue I am trying to solve these equations
    Assuming[{x1 ∈ Reals && x1 > 0 && x1 < 1},
 Solve[{(a3 - r2)^2 + (b3 + r2 - 1)^2 ==
    r2^2, (a6 - r2)^2 + (b6 + r2 - 1)^2 == r2^2,
   b5 == k1*(a5 - 1) + 1, b3 == k1*(a3 - 1) + 1,
   b2 == k1*(a2 - 1) + 1, b6 == k2*(a6 - a1) + b1,
   b4 == k2*(a4 - a1) + b1, (a2 - 1/2)^2 + (b2)^2 ==
    1/4, (a1 - 1/2)^2 + (b1)^2 == 1/4, (a4 - x1)^2 + (b4 - y1)^2 ==
    r1^2, x1 + r1 == 1, (a5 - x1)^2 + (b5 - y1)^2 ==
    r1^2, (y1 - b4)*k2 == -(x1 - a4), (b1)*k2 == -(a1 - 1/2), (b2)*
     k1 == -(a2 - 1/2), (1 - r2 - b3)*k1 == -(r2 - a3), (1 - r2 - b6)*
     k2 == -(r2 - a6), (b5 - y1)*k1 == -(a5 - x1)}, {x1, y1, r1, r2,
   k1, k2, a1, a2, a3, a4, a5, a6, b1, b2, b3, b4, b5, b6}]]

And it does output a valid solution

x1 -> 5/6, y1 -> 2/3, r1 -> 1/6, r2 -> 1/4, k1 -> 3/4, k2 -> -(4/3),
a1 -> 9/10, a2 -> 1/5, a3 -> 2/5, a4 -> 7/10, a5 -> 11/15, a6 -> 9/20,
b1 -> 3/10, b2 -> 2/5, b3 -> 11/20, b4 -> 17/30, b5 -> 4/5, b6 -> 9/10

But it also outputs a bunch of other invalid/undesired "solutions". I was trying to limit the output by using Assuming, apparently it does not work though.
Also, the console outputs

Solve::svars: Equations may not give solutions for all "solve" variables.

However, I clearly gave 18 variables with 18 equations. Why so?
My mma is 9.0.0.0. on mac.

A: Using v 9.0 on a Mac
$Version

"9.0 for Mac OS X x86 (64-bit) (November 20, 2012)"

eqns = {(a3 - r2)^2 + (b3 + r2 - 1)^2 == r2^2, (a6 - r2)^2 + (b6 + r2 - 1)^2 == r2^2, b5 == k1*(a5 - 1) + 1, b3 == k1*(a3 - 1) + 1, b2 == k1*(a2 - 1) + 1, b6 == k2*(a6 - a1) + b1, b4 == k2*(a4 - a1) + b1, (a2 - 1/2)^2 + (b2)^2 == 1/4, (a1 - 1/2)^2 + (b1)^2 == 1/4, (a4 - x1)^2 + (b4 - y1)^2 == r1^2, x1 + r1 == 1, (a5 - x1)^2 + (b5 - y1)^2 == r1^2, (y1 - b4)*k2 == -(x1 - a4), (b1)*k2 == -(a1 - 1/2), (b2)*k1 == -(a2 - 1/2), (1 - r2 - b3)*k1 == -(r2 - a3), (1 - r2 - b6)*k2 == -(r2 - a6), (b5 - y1)*k1 == -(a5 - x1)};

sol = Solve[eqns, {x1, y1, r1, r2, k1, k2, a1, a2, a3, a4, a5, a6, b1, b2, b3, b4, b5, b6}];

Solve::svars: Equations may not give solutions for all "solve" variables. >>

Length[sol]

20

Assuming that you are looking for real solutions:
solr = Select[sol, FreeQ[N[#], Complex[_, _]] &];

Length[solr]

12

Some solutions are dependent on y1. Removing those,
solr2 = Select[solr, Length[#] == 18 &]

{{x1 -> 1/2, y1 -> 0, r1 -> 1/2, r2 -> 1/4, k1 -> 3/4, k2 -> -(4/3),
     a1 -> 9/10, a2 -> 1/5, a3 -> 2/5, a4 -> 9/10, a5 -> 1/5, a6 -> 9/20,
     b1 -> 3/10, b2 -> 2/5, b3 -> 11/20, b4 -> 3/10, b5 -> 2/5,
     b6 -> 9/10}, {x1 -> 2, y1 -> 1/2, r1 -> -1, r2 -> 1/4, k1 -> 3/4,
     k2 -> -(4/3), a1 -> 9/10, a2 -> 1/5, a3 -> 2/5, a4 -> 6/5, a5 -> 7/5,
     a6 -> 9/20, b1 -> 3/10, b2 -> 2/5, b3 -> 11/20, b4 -> -(1/10), b5 -> 13/10,
      b6 -> 9/10}, {x1 -> 5/6, y1 -> 2/3, r1 -> 1/6, r2 -> 1/4, k1 -> 3/4,
     k2 -> -(4/3), a1 -> 9/10, a2 -> 1/5, a3 -> 2/5, a4 -> 7/10, a5 -> 11/15,
     a6 -> 9/20, b1 -> 3/10, b2 -> 2/5, b3 -> 11/20, b4 -> 17/30, b5 -> 4/5,
     b6 -> 9/10}, {x1 -> 2/3, y1 -> 7/6, r1 -> 1/3, r2 -> 1/4, k1 -> 3/4,
     k2 -> -(4/3), a1 -> 9/10, a2 -> 1/5, a3 -> 2/5, a4 -> 2/5, a5 -> 13/15,
     a6 -> 9/20, b1 -> 3/10, b2 -> 2/5, b3 -> 11/20, b4 -> 29/30, b5 -> 9/10,
     b6 -> 9/10}, {x1 -> 1/2, y1 -> 0, r1 -> 1/2, r2 -> 1/4, k1 -> 3/4, k2 -> 0,
      a1 -> 1/2, a2 -> 1/5, a3 -> 2/5, a4 -> 1/2, a5 -> 1/5, a6 -> 1/4,
     b1 -> 1/2, b2 -> 2/5, b3 -> 11/20, b4 -> 1/2, b5 -> 2/5,
     b6 -> 1/2}, {x1 -> 5/6, y1 -> 2/3, r1 -> 1/6, r2 -> 1/4, k1 -> 3/4,
     k2 -> 0, a1 -> 1/2, a2 -> 1/5, a3 -> 2/5, a4 -> 5/6, a5 -> 11/15,
     a6 -> 1/4, b1 -> 1/2, b2 -> 2/5, b3 -> 11/20, b4 -> 1/2, b5 -> 4/5,
     b6 -> 1/2}, {x1 -> 4/3, y1 -> 5/6, r1 -> -(1/3), r2 -> 1/4, k1 -> 3/4,
     k2 -> 0, a1 -> 1/2, a2 -> 1/5, a3 -> 2/5, a4 -> 4/3, a5 -> 17/15,
     a6 -> 1/4, b1 -> 1/2, b2 -> 2/5, b3 -> 11/20, b4 -> 1/2, b5 -> 11/10,
     b6 -> 1/2}, {x1 -> 0, y1 -> 3/2, r1 -> 1, r2 -> 1/4, k1 -> 3/4, k2 -> 0,
     a1 -> 1/2, a2 -> 1/5, a3 -> 2/5, a4 -> 0, a5 -> 3/5, a6 -> 1/4, b1 -> 1/2,
     b2 -> 2/5, b3 -> 11/20, b4 -> 1/2, b5 -> 7/10, b6 -> 1/2}}

Length[solr2]

8

Verifying
And @@@ (eqns /. solr2)

{True, True, True, True, True, True, True, True}


text:
Q: Unable to consume REST API in SAPUI5 I am trying to develop a weather app which consumes 3rd party services (API link here ) for which the code is given in this link. When I run the app, it shows ther table with no data. It also shows as error in my View1.Controller file which I have provided below.
View1.controller.js
        sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/ui/model/json/JSONModel"
    ], function(Controller) {
        "use strict";

        return Controller.extend("WeatherAPI.controller.View1", {

    onInit: function() {
                this._loadForecast();
            },

            _formatDate: function(date) {
                var d = new Date(date),
                    month = '' + (d.getMonth() + 1),
                    day = '' + d.getDate(),
                    year = d.getFullYear();

                if (month.length < 2) {
                    month = '0' + month;
                }
                if (day.length < 2){
                    day = '0' + day;
                }
                return [year, month, day].join('-');
            },

            _mapResults: function(results) {
                var oModel = this.getView().getModel();
                oModel.setProperty("/city", results.city.name);
                oModel.setProperty("/country", results.city.country);

                var aForecastResults = [];
                for (var i = 0; i < results.list.length; i++) {
                    var oTemp = results.list[i].temp;
                    var date = this._formatDate(results.list[i].dt * 1000);
                    aForecastResults.push({
                        date: date,
                        temp: oTemp.day,
                        units: "Celsius",
                        humidity: results.list[i].humidity
                    });
                }

                oModel.setProperty("/items", aForecastResults);
            },

            _loadForecast: function() {
                var oView = this.getView();
                var oParams = {
                    q: "London",  // Get the weather in london
                    units: "metric",
                    appid: "fa2a1fb5db6debe044492728ca66a8f8",  // replace with your API key
                    cnt: 16,  // get weather for the next 16 days
                    mode: "json"  // get it in JSON format
                };
                var sUrl = "/OpenWeather/data/2.5/forecast/daily";
                oView.setBusy(true);

                var self = this;

                $.get(sUrl, oParams)
                    .done(function(results) {
                        oView.setBusy(false);
                        self._mapResults(results);
                    })
                    .fail(function(err) {
                        oView.setBusy(false);
                        if (err !== undefined) {
                            var oErrorResponse = $.parseJSON(err.responseText); /*error : Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>) */
                            sap.m.MessageToast.show(oErrorResponse.message, {
                                duration: 6000
                            });
                        } else {
                            sap.m.MessageToast.show("Unknown error!");
                        }
                    });
            }
        });
    });

model.js
        sap.ui.define([
        "sap/ui/model/json/JSONModel",
        "sap/ui/Device"
    ], function(JSONModel, Device) {
        "use strict";

        return {

            createDeviceModel: function() {
                var oModel = new JSONModel(Device);
                oModel.setDefaultBindingMode("OneWay");
                return oModel;
            },

            createAPIModel: function() {
                var oModel = new JSONModel();
                oModel.setData({
                    city: "",
                    country: "",
                    cols: [{
                        name: "Date"
                    }, {
                        name: "Day Temperature"
                    }, {
                        name: "Units"
                    },{
                        name: "humidity"
                    }],
                    items: []
                });
                return oModel;
            }

        };
    });

neo-app.json
 {
  "path": "/OpenWeather",
  "target": {
    "type": "destination",
    "name": "OpenWeather",
    "entryPath": "/"
  },
  "description": "Open weather API"}

Please help. Thanks.

A: If you app is calling an API outside your domain, you will run into CORS issues. Maybe this is the case. Your network developer window will help you to figure this out.