How to perform animation listview scroll or limit the speed of scroll

Question: How can I bring the item in front off the screen on stop scrolling automatically with animation.Currently it works with following code but it perform very fast with scroll.
So my requirement is to perform this with animation so user can see sliding of listview.
Below is my code,but I did not get expected result.
listview.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == SCROLL_STATE_IDLE) {
                    View child = layout.getChildAt(0);    // first visible child
                    Rect r = new Rect(0, 0, child.getWidth(), child.getHeight());     // set this initially, as required by the docs
                    double height = child.getHeight() * 1.0;
                    layout.getChildVisibleRect(child, r, null);
                    if (Math.abs(r.height()) != height)
                    {
                        //only smooth scroll when not scroll to correct position
                        if (Math.abs(r.height()) < height / 2.0)
                        {
                            listview.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    listview.smoothScrollBy(listview.getFirstVisiblePosition(), 10000);
                                }
                            }, 500);
                        } else if (Math.abs(r.height()) > height / 2.0)
                        {
                            listview.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    listview.smoothScrollBy(listview.getFirstVisiblePosition(), 10000);
                                }
                            }, 500);
                        } else
                        {

                            listview.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    listview.smoothScrollBy(listview.getFirstVisiblePosition(),10000);
                                }
                            },500);

                        }

                    }
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });

Comment: check this answer (http://stackoverflow.com/questions/5590001/android-listview-slow-down-scroll-speed)
Comment: did not work at all.
Answer: Old question but just for reference, this worked for me:
    if (condition) {
        // add stuff to begining of ListView and scroll up
        arrayList.add(0, stuff);
        listView.post(new Runnable() {
            @Override
            public void run() {
                listView.smoothScrollToPosition(0);
            }
        });
    } else {
        // add stuff to end of ListView and scroll down
        arrayList.add(index, stuff);
        listView.post(new Runnable() {
            @Override
            public void run() {
                listView.smoothScrollToPosition(adapter.getCount() - 1);
            }
        });
    }

Basically just smoothScrollToPosition instead of smoothScrollBy.


Android Scoped Storage Testing

Question: I am trying to test scoped storage in my app and I need to be able to toggle scoped storage on and off for testing.  According to the development documentation:

To enable scoped storage in your app, regardless of your app's target SDK version and manifest flag values, enable the following app compatibility flags:

DEFAULT_SCOPED_STORAGE (enabled for all apps by default)
FORCE_ENABLE_SCOPED_STORAGE (disabled for all apps by default)

Important: When toggling this change off for app testing, you must also disable FORCE_ENABLE_SCOPED_STORAGE (if it is not already disabled) to restore the legacy storage behavior.

I am able to toggle FORCE_ENABLE_SCOPED_STORAGE in the phone's Developer Settings, but the DEFAULT_SCOPED_STORAGE item is disabled and cannot be toggled.  How do I toggle it? Both switches must be set to the off position to disable scoped storage for testing.
Answer: I dont know those flags and they come quite unhandy as you have to recompile your app.
Better read answer at Accessing external storage in Android API 29
Then the user of your app can toggle it on/off.
Comment: The Android documentation encourages developers to make use of those flags for development.  They are hidden pretty well deep in the developer settings and it is not something the average android user will ever access.
Answer: I have not had too much luck toggling the compatibility flags in the developer screen. However, another way toggle the forced scoped storage is to change between targetSdkVersion 29 and targetSdkVersion 30

Android Scoped Storage Testing


Proof that exist $y \in \mathbb R$ for which $f(y)=f(y+2019)$

Question:
Proof that exist $y \in \mathbb R$ for which $f(y)=f(y+2019)$ if you know that $f: \mathbb R \rightarrow \mathbb R$ is continuous, $f(19)=0,01$ and $f(x)<0$ for every $x \in \mathbb R$ such that $|x|\ge100$.

Thanks for knowledge witch I have in this task I know that this function have the highest value because if this function is continuos and $f(x)<0$ for every $x \in \mathbb R$ such that $|x|\ge100$ so $f(x)>0$ for every $x \in \mathbb R$ such that $|x|<100$ from the Bolzano–Weierstrass theorem in interval $[-100,100]$ I have the highest value. Unfortunately I don't know what to do to go $f(y)=f(y+2019)$.
Comment: @copper.hat: It is the standard notation for $0.01$ in [about half the world](https://en.wikipedia.org/wiki/Decimal_separator#Arabic_numerals).
Comment: No wonder there are so many problems in the world.
Comment: I'm afraid I can't understand this at all. Please try to re-word it to be more clear.
Comment: What does 0,01 mean?
Comment: @copper.hat: what, because they don't use the same decimal separator as you?
Comment: @TonyK: I only use whole numbers. Lighten up.
Comment: @copper.hat: and Roman numerals, right?
Comment: Yes, $0,01$ means $0.01$. I know that in promming it is used $0.01$ but I didn't know that in some countries people don't know what is $0,01$ so I'm sorry
Answer: Hint: You're searching for a zero of the function $g(y) := f(y + 2019) - f(y)$.  What properties of this function $g$ can you deduce?  In particular, what can you say about $g(19)$, and what can you say about $g(-2000)$?
Comment: By a similar argument, you should be able to show $g(-2000) > 0$.  So now, you know $g(-2000) > 0$ and $g(19) < 0$, and you want to show there is some $y$ such that $g(y) = 0$...
Comment: @Daniel Schepler $g(19)=f(2038)-f(19)$ and $g(-2000)=f(19)-f(-2000)$ so I have $g(19)+g(-2000)=f(2038)-f(-2000)>0$ but I don't know what can I do with it
Comment: @MP3129 OK, let's focus on $g(19)$: you know the value of $f(19)$, right?  What can you say about $f(2038)$?
Comment: @Daniel Schepler $f(2038)<0$, $-f(19)=-0.01$ so $g(19)<0$
Comment: Unfortunately Istill do not know how to do it. @TonyK maybe you have some tips?
Comment: OK, I see your point now. +1.


Array.prototype.values() is undefined - using Babel to transpile ES6 in NodeJS environment

Question: My setup is:
$ babel --version
6.3.15 (babel-core 6.3.15)
$ node --version
v5.1.0

Using Webstorm 11 IDE in case that is important too.
I am using Babel(js) to transpile the following ES6, and have set up some logging to verify:
Array.from([ 'a', 'b' ].keys());
Array.from([ 'a', 'b' ].values());  // TypeError: ["a","b"].values is not a function
Array.from([ 'a', 'b' ].entries());

Can verify this v.quickly:
Array.prototype.values === undefined) // true

Note that keys, and entries both exist.
Any ideas what the likely cause is? (Have I missed a special options flag or something on Babel to switch on support of this feature?). Thanks for any help, and shall continue to check documentation etc in meantime.
Comment: You have to manually require the polyfill https://babeljs.io/docs/usage/polyfill/
Comment: Just in case of another missing feature, you should take a look at https://kangax.github.io/compat-table/es6 ;)
Comment: Thanks Paolo, taking a look now. you may wish to put your comment into a one line answer so i can credit you if it works.
Comment: Excellent, thank you, this is the solution. Mocha tests all passing now - mystery solved. Cheers!
Comment: @juliobetta - thanks, I had that link open, but didn't fully understand the meaning of "Babel + Core JS". Great suggestion all the same.
Answer: Providing an answer for completeness. BabelJS requires an extra polyfill package to extend it with some extra ES6+ features - such as the one in this question.
npm install babel-polyfill --save

Then insert the following require statement towards the top of the affected module to obtain required (generator) behaviour:
require("babel-polyfill");

This should be all you need, just importing the module adds required polyfill
Answer: I know, you accepted the answer, but I'd highly recommend to use core-js standard library for node.js.
With this library you'll forget seeing any problems on JS features support.
It includes polyfills for ECMAScript 5, ECMAScript 6: promises, symbols, collections, iterators, typed arrays, ECMAScript 7+ proposals, setImmediate, etc. Some additional features such as dictionaries or extended partial application.
It's easy to install dependency and to use it:
npm i core-js --save

Then within your project, use it this way, to include all the features it support:
// Without global namespace pollution
var core = require('core-js/library');

Or like this, if you want to include only specific features (in your case you was missing Array.prototype.values()):
require('core-js/fn/array/values');

This lib is a "must-have" to me for every project, after I discovered it for myself. Package description can be found at official page: https://www.npmjs.com/package/core-js
Comment: As arcseldon already said, babel-polyfill uses core-js itself and it loads all the additional runtimes needed (such as regenerator).
Comment: thanks for this answer. I have upvoted it on basis it looks like a good option. I realise that babel leans on this library internally, so for now I shall leave the accepted answer as-is. If more voters choose this answer then I'd be happy to assign this as a correct answer.


How do people come up with divisibility tests?

Question: For example, the test for divisibility by $2$ is quite obvious. But I am quite intrigued by the others, particularly $3$, $7$ and $11$. Also I have come across tests for numbers as far as $50$. How do people even think of these? And consequently, how do they prove it?
Comment: I'm [not a big fan](http://math.stackexchange.com/questions/1186424/what-is-the-point-of-the-common-divisibility-trick-for-7) of the divisibility "rule" for $7$. I think other than $2, 3,5,9,11$, there aren't many primes with useful divisibility rules ...
Comment: This might help: http://www.savory.de/maths1.htm
Comment: @SteveKass He provided that link in his question. This is in interesting question. I wonder if these rules are used in the search for very large prime numbers (it would seem to be vastly more efficient).
Comment: The $11$ one is super lovely. Note that $11 \equiv -1 \pmod {10}$. Now think about how you can tell if a polynomial has $-1$ as a zero: If you think about plugging in $x = -1$ into $a_nx^n + a_{n - 1}x^{n - 1} + \ldots + a_1x + a_0$, you wind up with the alternating sum $a_0 - a_1 + \ldots \pm  a_{n - 1} \mp a_n$: And that's the divisibility rule for $11$, but with the digits!
Comment: @pjs36 That is lovely. But what is the intuition behind trying to find a polynomial with $-1$ as a zero after stating that $11\equiv -1(\mod 10)$?
Comment: @ZubinMukerjee What about GIMPS? The current highest prime is $2^{74207281}-1$ I imagine it saves a lot of time to use clever rules like these.
Comment: @Klik Do mathematicians use computer programs to find large primes? If so I imagine that neat tricks would save alot of time in their algorithms...
Comment: @Klik Yes, I'm sure a ton of clever tricks go into verifying that something like that is prime. But I am more talking about how divisibility rules are taught in grade school as useful for mental arithmetic or whatever. I personally think $2,3,5,9,11$ are the only ones worth learning for that purpose.
Comment: @TheOddbodNumber Yes, it is all done by computer. For the GIMPS project they check the numbers that follow the Mersenne Primes which is a number found by $2^{n}-1$ which is sometimes a prime number (hence why they have to check it)
Comment: @TheOddbodNumber The base $10$ representation of a number is the value of some polynomial in $x$ at $x=10$. For example:

$$2016 = 2x^3 + x + 6$$

So $2016$ is the value of that cubic polynomial at $x=10$. In the case of modulo $11$, we can replace $x=10$ with $x=-1$, which gives us the divisibility trick.
Comment: Indeed, note that I mixed up my modulus there, I meant to say $10 \equiv -1 \pmod{11}$
Comment: See http://math.stackexchange.com/questions/328562/divisibility-criteria-for-7-11-13-17-19
Comment: See also [here](http://math.stackexchange.com/q/1961065/11619).
Answer: There are various methods for developing divisibility criteria. Here is a fairly general one:
Let's develop a divisibility criterion for example with $13$. Take any integer $n$ with digits $a_k,a_{k-1},...,a_2,a_1,a_0$ and write its decimal expansion:
$$n = (a_k \times 10^k) + (a_{k-1} \times 10^{k-1}) + .... + (a_2 \times 10^2) + (a_1 \times 10^1) + a_0$$
Notice the following congruences:
$$10^0 \equiv 1 \ \ mod 13 \\
10^1 \equiv 10 \ \ mod 13 \equiv (-3) \ \ mod 13 \\
10^2 \equiv 9 \ \ mod 13 \equiv (-4) \ \ mod 13  \\
10^3 \equiv 12 \ mod 13 \equiv (-1) \ \ mod 13  \\
10^4 \equiv 3 \ \ mod 13   \\
10^5 \equiv 4 \ \ mod 13  \\
10^6 \equiv 1 \ \ mod 13   \\
\vdots
$$
this means we get the $6$-step cycle:
$$1,-3,-4,-1,\ 3,\ 4,\ 1,-3,...$$
thus:
$${\small
n\equiv\big(a_0+a_1\times(-3)+a_2\times (-4)+a_3\times(-1)+a_4\times 3+a_5 \times 4+a_6\times 1+a_7\times(-3)+...\big)\ \ mod 13}$$
Setting
$${\small
m = a_0 + a_1 \times (-3) + a_2 \times (-4) + a_3 \times (-1) + a_4 \times 3 + a_5 \times 4 + a_6 \times 1 + a_7 \times (-3) + ...}$$
it is clear that:
$$n\equiv m \ \ mod 13$$
and that:
$$m<n$$
and thus it is easier to check if $m$ is divisible by $13$.
Notice that
$$m\mid 13 \Leftrightarrow n\mid 13$$
Repeat as many times as necessary.
The above method works for any integer, however it is not the only applicable method. There other criteria as well (for any integer) that can be developed either through systematic or heuristic methods.
Answer: There's also the casting out rule.  If $x$ is divisible by $n$ then $x - a*n*10^k$ is divisible by $n$.  So one common trick is to multiply $n$ by something to get a number with last digit of 1 or maybe 9 and remove the last digit and cast acordingly.
Example:  23.
23*3 = 69.  = 70 - 1.  So $23|x \iff 23|(x + 70a - a)/10$.
So the rule is:  take off the last digit.  multiply it by 7.  Add.  repeat.
So for example:  23*1234 = 28382.
Take off the last digit.  2838.  Multiply 2*7 = 14. Add 2838 + 14 = 2852.  Repeat.

2*7 = 12. 285+14 = 299.  29. 9*7 = 63. 29+63 = 92.  9.  2*7 = 14.  9+14 = 23.  It is divisible by 23.

Let's make one up for 37.  37*3 = 111.  Oh!  This is really good!  If the last digit is a just subtract aaa and divide by 10.
Example: 8658.  Subtract 888.  8658 - 888 = 777.  Subtract 777. 777-777= 0.  It's divisible by 37.
Let's make one for 43.  43*3 = 129 or 43*7 = 301.  Truncate the last digit and subract 30 times it.  Or truncate the last digit and add 13 times it.
43*9876 =424668
Truncate the 8: 42466.  8*30=240; subtract 240.  42226.  Truncate the 6: 4222.  6*30 = 180; subtract 180. 4042.  Truncate 2, subtract 60. 404 - 60 = 344. Truncate the 4: 34 and subtract 120: -86.  Take absolute power. 86 subtract 43 and get 43.  The test passes.
And so on.
=====
But to be honest, other than the 3, 9 and 11 test I hate these tests and prefer to cast directly.
Ex.  Is 748354062 divisible by 57?
$748,354,062 - 570,000,000 \equiv 178,354,062 - 57,000,000 \equiv 131,354,062 - 57,000,000 \equiv 74,354,062 - 57,000,000 \equiv 17,354,062 -11,400,000 \equiv 5,954,062 - 5,700,000 \equiv 254,062 - 114,062 \equiv 140,062 - 114,000 \equiv 26,062 - 11,400 = 14,962 - 11,400 \equiv 3,562 - 570 \equiv 2,992 - 2,280 \equiv 712 - 570 \equiv 142 - 114 \equiv 28 \mod 57$.
So not only is it not divisible by 53, I know the remainder is 28.  (I like to do this as I ride my bicycle and pass street addresses.)
Comment: For what it's worth I hate these rules and never use them.


Problema com rota no Laravel; minha página não acessa os arquivos do bootstrap que estão na página de layout

Question: gostaria de uma forcinha, estou iniciando com o laravel 6 e estou com o seguinte problema;
Possuo uma página de layout dentro da pasta "views>layouts" que se chama "admin.blade.php":

Nela estão os meus arquivos do bootstrap e jQuery e etc. Página "admin.blade.php":
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="css/bootstrap.min.css">

    <title> @yield('title') </title>

        @yield('content')

Aqui estão as minhas rotas:

//Admin
Route::get('/admin', 'AdminController@index');
Route::get('/admin/usuarios', 'UsuariosController@index');

As rotas direcionam para a controller que direciona para os devidos arquivos.
Quando eu acesso a página index do módulo admin dentro de "views>admin>index.blade.php" estendendo a página de layout:

@extends('layouts.admin')

@section('title')
    Index
@endsection

@section('content')

@endsection

Nos recursos do Google Chrome o diretório de busca dos arquivos do bootstrap é:

Dessa forma eu consigo acessar os arquivos do bootstrap e tudo ocorre bem, porém quando eu tento acessar a index de usuarios do módulo admin, no seguinte diretório "views>admin>usuarios>index.blade.php", estendendo da mesma forma a página de layout admin, o diretório de busca dos arquivos do bootstrap fica sendo:

Com esse "admin" no meio da Request Url, desse modo eu não consigo mais acessar os arquivos do bootstrap e a página perde a estilização.
Gostaria de saber o porque desse problema e como resolver.
Desde já abraços! ;)
Answer: Tenta chamar os arquivos do bootstrap e jquery utilizando um helper do laravel chamado asset:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="{{ asset('css/app.css') }}">

    <title> @yield('title') </title>

        @yield('content')


Why does NSDateFormatter return nil?

Question: Why is lDateFormatted nil on iPhone simulator 3.1.2 after executing this piece of code?
NSString *lDateString = @"Wed, 17 Feb 2010 16:02:01";
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy hh:mm:ss"];
NSDate *lDateFormatted = [dateFormatter dateFromString: lDateString ];

Any ideas appreciated,
Thanks
Answer: You probably want to be using HH for hours, that's 0-23 / military style
Also, you may need to put single ticks around your comma like ','
Reference: the UTS doc and date formatting guide.
Comment: In this case the ticks didn't seem to be necessary, but I put them in anyway. Thanks!
Answer: The DateFormatter format is correct, but you've probably set the wrong locale. Try this one (working sample code of one of my projects):

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  NSLocale *enUS = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
  [formatter setLocale:enUS];
  [enUS release];
  [formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss"];
  ...
  [formatter release]
Comment: Beware: if current device is set to military time (24 hr format), if you force the "en_US" locale in the NSDateFormatter, you may end up with a nil date object.

Why does NSDateFormatter return nil?


How to programmatically check a view to test if it has any results?

Question: What's the most lightweight way to test if a view has any results in it or not? I have a system which creates links to various views, but if the view has no results I want the link to be greyed out. I can only think to load the whole view and execute it, but hopefully there is an easier solution?
I should also note that these views contain contextual filters, if it makes any difference.
Answer: Your options:

Trim down the "view" to return only 1 row of possible results.
Attack the problem from the other side. Use a Rule or a Hook to track the condition of your event (eg, "is there new content of type X") in a site variable and check that value instead of your View.

... etc ...
Answer: This is the best solution I have found so far:
<?php
$view = views_get_view_result($name, $display, $args);
$result = count($view);
if ($result) {
//do something here
}
?>

Source: https://www.drupal.org/node/446798#comment-6439726


$|\sin(nx)| ≤ n|\sin x|$ Proof by induction

Question:
Using induction, prove $|\sin(nx)| \le n|\sin x|$ for $n\in \mathbb{N}$.

How I can show that with induction?
Normally , When I make a induction I know for $n$, and I prove for $n+1$. But I can't write $n+1$ in this question. If I write $n+1$, formula change like this: $|\sin((n+1)x)| \le (n+1)|\sin x|$ for $n+1$, This new formula doesn't include $n$.
What should I do in such cases?
Comment: Indeed a duplicate, but I suggest to try it yourself. Write $\sin((n+1)x)=\sin(nx+x)$ and use the formula $\sin(x+y)=\sin(x)\cos(y)+\sin(y)\cos(x)$.
Answer: For induction step we can use that
$$|\sin ((n+1)x)|=|\sin(nx+x)|=|\sin(nx)\cos x+\sin x\cos(nx)|$$
$$\le |\sin(nx)\cos x|+|\sin x\cos(nx)|\le n|\sin x|+|\sin x|=(n+1)|\sin x|$$


Como fazer Thread de um método da classe

Question: Estou precisando realizar um processo em paralelo utilizando o php, instalei a extensão pthreads e observei alguns exemplos mas não vi como eu poderia implementa-lo.
Classe:
<?php

class Negociacao{
    /*
        Retorna código de rastreio das condições do usuário.
    */
    public function SolicitarOpcoesPagamento($cpfOuCnpj, $telefone, $email, $nrParcelas, $dataPagamento){
        $codigo =  md5($cpfOuCnpj);
        //ConsultarOpcoesPagamento($codigo); <- aqui dou start na thread
        return $codigo;
    }

    /*
        Retorna status e array de condições do usuário.
    */
    public function ConsultarOpcoesPagamento($codigo){
        return array("status" => "pendente","opcoes"=> array());
    }

}

Servidor Soap:
<?php

$options = array("uri" => "http://localhost/soap/");

$server = new SoapServer(null, $options);

require_once "negociacao.php";

$server->setObject(new Negociacao());

$server->handle();

?>

Cliente Soap:
<?php
$options = array(
    'uri' => 'http://localhost/soap/server.php',
    'location' => 'http://localhost/soap/server.php'
);

$client = new SoapClient(null, $options);

var_dump($client->solicitarOpcoesPagamento(025111151544));

?>

Objetivo:
Quando o cliente chamar a função SolicitarOpcoesPagamento eu devo retornar um id de rastreamento imediatamente, porém antes de retornar esse id eu preciso executar dentro dessa função em paralelo a função ConsultarOpcoesPagamento, que vai ir em outro webservice, montar as opções e inserir no meu banco de dados. Quando o cliente quiser ele vai consultar a função ConsultarOpcoesPagamento que já estará com os dados.
Comment: Nesse caso você precisa criar duas threads e sincronizar as duas correto?
Comment: **Relacionado:** https://pt.stackoverflow.com/a/207984/3635, talvez a parte que lhe seja interessante seja aonde falei: **Aonde Thread seria interessante**, ainda sim recomendo que leia tudo para entender alguns detalhes.
Comment: Vc precisa retornar imediatamente ou consultar primeiro?
Comment: Eu preciso retornar o código de rastreamento  e executar a função ConsultarOpcoesPagamento em paralelo
Comment: Não estou conseguindo visualizar a utilização de threads para isso. Unica forma que eu estou conseguindo enxergar é se você chamasse `SolicitarOpcoesPagamento()` e `ConsultarOpcoesPagamento()` separadamente e independente uma da outra. Mas como você disse, isso não ocorre.
Comment: @GuilhermeNascimento obrigado pela recomendação!
Answer: Não sei se entendi bem seu problema, mas se entendi, acredito que você não precisará criar uma thread apenas para isso. O que você pode fazer é entregar a resposta HTTP da solicitação ao cliente e continuar com o seu código. No exemplo abaixo eu adaptei um pouco o seu código apenas para testes.
class Negociacao {

    public function SolicitarOpcoesPagamento($data){
        $codigo =  md5($data);
        return $codigo;
    }

    public function ConsultarOpcoesPagamento($codigo){
        file_put_contents(
            "output.json",
            json_encode(
                array(
                    "status" => "pendente",
                    "opcoes"=> array(
                        "codigo" => $codigo
                    )
                )
            )
        );
    }

}

Ou seja, o método ConsultarOpcoesPagamento criará um código único a partir de um dado qualquer e o método ConsultarOpcoesPagamento gerará um JSON básico contendo a informação gerada pelo método anterior. No seu caso, esse método iria trabalhar com o banco de dados, conforme a sua necessidade real. Para finalizar a requisição e enviar a resposta ao cliente, pode fazer algo como:
<?php

ignore_user_abort(true);
set_time_limit(0);

ob_start();

$neg = new Negociacao();
$codigo = $neg->SolicitarOpcoesPagamento("Foo");

echo "Seu código de acesso é: ", $codigo;

header('Connection: close');
header('Content-Length: '.ob_get_length());

ob_end_flush();
ob_flush();
flush();

// Seu código continuará aqui...

Neste caso, ao abrir a página PHP, o cliente obterá a seguinte mensagem:
Seu código de acesso é: 1356c67d7ad1638d816bfb822dd2c25d

Mas o código continuará sendo executado. Para simular um processo mais demorado, irei utilizar a função sleep e após invocar o método ConsultarOpcoesPagamento:
<?php

ignore_user_abort(true);
set_time_limit(0);

ob_start();

$neg = new Negociacao();
$codigo = $neg->SolicitarOpcoesPagamento("Foo");

echo "Seu código de acesso é: ", $codigo;

header('Connection: close');
header('Content-Length: '.ob_get_length());

ob_end_flush();
ob_flush();
flush();

// Seu código continuará aqui...

sleep(5);

$neg->ConsultarOpcoesPagamento($codigo);

Assim, 5 segundos após você obter a resposta no navegador, o arquivo output.json será criado com o conteúdo:
{"status":"pendente","opcoes":{"codigo":"1356c67d7ad1638d816bfb822dd2c25d"}}

Comment: Bem que este detalhe poderia estar explícito na pergunta...
Comment: Com a sua resposta consegui chegar a esta solução: https://gist.github.com/Gabrielr47/23fd7e402ad9e56812f5ec7816d2f40c  acredito que é isso mesmo, só vou aguardar para ver se existe alguma solução melhor senão irei concluir.
Comment: Desta forma ai da certo, mas ai vem um problema, se eu estiver servindo essa classe usando o SoapServer ele só vai aceitar return $data, se você fizer um echo ele vai emitir "Uncaught SoapFault exception: [Client] looks like we got no XML document in"
Comment: Você esta certo, eu sempre tento criar seguindo https://pt.stackoverflow.com/help/mcve vou editar para ficar completo, obrigado.
Answer: Talvez sua pergunta não seja sobre threads em sí, porém esta pergunta será acessada por pessoas que buscam soluções sobre threads em php.
Antes de tudo, é importante entender a definição do que é uma threads:

Na ciência da computação,Thread é um pequeno programa que trabalha
  como um subsistema, sendo uma forma de um processo se autodividir em
  duas ou mais tarefas.

Este é um procedimento bem complexo para se realizar com PHP,  já que paralelismo não é usualmente o foco dos programadores PHP, porém não é impossível de se fazer. E ainda existem várias abordagens, algumas mais simples e seguras outras nem tanto. Veja abaixo alguns métodos para realizar ou simular threads no php.
Método 1: Criar uma chamada ao seu próprio servidor
A primeira abordagem, mais simples é a definida nessa resposta: https://pt.stackoverflow.com/a/217559/7130
Porém este método não é uma execução é assíncrona e seria menos performática do que chamar um método diretamente dentro do mesmo processo.
Método 2:  Cronjobs
Outra abordagem, também bem simples é a do cron ou cronjob, no windows agendador de tarefas.
A técnica consiste em cria uma rotina que é lida de tempos em tempos atrás de alguma "tarefa" que está agendada, você pode armazenar essa lista de tarefas à serem executadas pelo script em um banco de dados ou arquivo com os parâmetros.
Não é muito performática também, porém é mais simples e fácil de implementar, basta que você tenha acesso a um recurso de agendamento de tarefa.
Método 3:  PHP Process Control (PCNTL )
Bom, todos os métodos acima não podem ser executados deforma assíncrona de verdade, separando o processo do php em 2. Talvez esteja seja a única forma de fazer uma thread de um método de uma classe.
Precisando criar uma solução que fizesse exatamente isso, aonde fosse possível  inicializar uma rotina/método que ficasse em execução em background enquanto eu já desse o retorno para o usuário e depois apenas verificasse o progresso e o log dessa tarefa.
O resultado foi a elaboração de uma classe abstrata à ser estendida por sub-classes com as tarefas específicas, no exemplo abaixo no link do gist eu faço a exclusão de arquivos em forma assíncrona e gravo logs durante o processo
Veja parte do método abaixo:
/**
     * Executa a tarefa com os parâmetros pré-definidos.
     * @param mixed $parameters
     */
    final public function run($parameters) {
        try {
            //Não tenho certeza se há necessidade,
            //porém essas funções adicionam um controle para que o
            //processo continue à ser execudado mesmo que o usuário abandone a tela.
            ignore_user_abort(true);
            set_time_limit(0);
            // Inicializo o signal Handler
            pcntl_signal(SIGCHLD, SIG_IGN);
            $pid = pcntl_fork(); //Cria um novo processo, se criado com sucesso, o código executado daqui para baixo será executado em outra thread.
            if ($pid == -1) {//Se o retorno for -1 significa que não foi possível.
                throw new \RuntimeException("Could not start a fork process.");
            } else if ($pid) {
                //Se o valor for diferente de zero Significa que ainda está rodando no pai
//                pcntl_waitpid($pid, $exitcode, WNOHANG); // prevents zombie processes
//                 $this->log("Thread Still the same");
                return;
            } else {
                ignore_user_abort();
                $sid = posix_setsid();
                self::$shmId = shm_attach((int) (ftok(self::$file, 'A') . self::$line), self::SHARED_MEMORY_SIZE);
                $this->var_key_fork_pid = $this->alocatesharedMemory($sid, 112105100); //112105100
                shm_put_var(self::$shmId, $this->var_key_status, 'RUNNING');
//                $this->log("SubTask" . $sid);
//                $this->log("SubPid" . $this->var_key_fork_pid);
//                $this->log("Substatus" . $this->var_key_status);
                $this->onPreExecute($parameters);
//                $this->log("SessionDelay: " . session_id());
                try {
                    $result = $this->doInBackground($parameters);
                } catch (\Exception $e) {
                    $this->log("[ErrExec:" . $e->getCode() . "] " . $e->getMessage());
                    $this->cancel($e->getMessage());
                }
                $this->onPostExecute($result);
                //Ao finalizar, emitir o sinal de finalizado e apagar a memória compartilhada alocada.
                if (@shm_has_var(self::$shmId, $this->var_key_fork_pid)) {
                    shm_put_var(self::$shmId, $this->var_key_fork_pid, null);
                    shm_put_var(self::$shmId, $this->var_key_status, 'FINISHED');
                    shm_remove(self::$shmId);
                    gc_collect_cycles();
                    posix_kill(getmypid(), SIGKILL);
                }
            }
        } catch (\Exception $e) {
            $msg = "[Err:" . $e->getCode() . "] " . $e->getMessage();
            $this->log($msg);
            self::onError($msg,$e);
        }
    }

Explicação:
A separação da thread acontece na linha aonde eu uso a seguinte função:
$pid = pcntl_fork(); essa função poderá retornar -1 se falhar ao criar a ramificação do processo (fork). O valor diferente de 0 é o bloco que continuará executando no processo principal o outro valor é o id do processo "filho" ou fork, esse bloco será executado num processo completamente separado.
Para fazer a comunicação entre os 2 eu utilizo a memória compartilhada, já que são 2 processos separados e ambos não tem acesso às mesmas variáveis(nem mesmo por $_SESSION).
Sendo assim dentro do seu exemplo poderia ficar algo assim:
if($pid == 0){ //Se estiver na thread principal
 SolicitarOpcoesPagamento();
}else if($pid != -1){ //Se tiver no fork
 ConsultarOpcoesPagamento();
}

Exemplo Completo: https://gist.github.com/LeonanCarvalho/62c6fe0b62db8a478f502f84c5734c83
Neste meu exemplo você precisaria modelar uma classe para cada tarefa, essas classes devem herdar da classe abstrata e implementa alguns métodos.
Ele consiste em usar as funções do pcntl, que é a extensão oficial do php para controle de processo, principalmente a função pcntl_fork para criar uma separação do processo principal.
Também foi necessário utilizar algumas extensões auxiliares como a POSIX e "Semaphore, Shared Memory and IPC".
Resultado do exemplo acima:

Um problema conhecido por mim é que não é possível usar instâncias do PDO em modo singleton entre 2 processos, você precisa no processo ramificado ("fork") destruir a instancias singleton do PDO e então criar uma nova conexão PDO.
Este método está em uso a 1 ano, ele é responsável por fazer importação de arquivos para dentro do sistema, ao invés de ocupar a conexão com o servidor eu apenas recebo os dados e depois processo ele em background no servidor, liberando a conexão do usuário para que ele continue à trabalhar no sistema.
Método 4:  Pthreads
Embora já exista no php 5.6, recomendo fortmente utilizá-lo apenas no PHP7, ele foi completamente refatorado no PHP7 e está mais seguro de ser utilizado. Isso exigirá uma versão ZTS (Zend Thread Safety) do PHP 7.x instalada, juntamente com o pthreads v3 instalado. Até o momento não encontrei link para baixar essa versão pronta, mas você ainda pode compilá-la https://www.sitepoint.com/install-php-extensions-source/#installing-a-third-party-extension ( Link em inglês).
A documentação oficial é: http://php.net/manual/en/book.pthreads.php
Porém os bons exemplos estão aqui: https://www.sitepoint.com/parallel-programming-pthreads-php-fundamentals/ (link em inglês)
No caso específico da pergunta, não sei se esses 2 últimos método atenderiam, não há como você ter certeza que o ConsultarOpcoesPagamento terminará em paralelo com o ConsultarOpcoesPagamento, mas ficaria algo assim:
class OpcoesPagamento extends Threaded
{
    public $codigo;
    public $opcoes;

    public function Solicitar($cpfOuCnpj, $telefone, $email, $nrParcelas, $dataPagamento)
    {
        /** **/
        $this->codigo = md5($cpfOuCnpj);
    }

    public function Consultar()
    {
        $this->opcoes = array("status" => "pendente","opcoes"=> array());
    }
}
$OpcoesPagamento = new OpcoesPagamento;

$thread = new class($OpcoesPagamento) extends Thread {
    private $task;

    public function __construct(Threaded $task)
    {
        $this->task = $task;
    }

    public function run()
    {
        $this->task->Solicitar();
        $this->task->Consultar();
    }
};
$thread->start() && $thread->join();

var_dump($task->codigo);
var_dump($task->opcoes);

Outro projeto relevante que possa ser de interesse é este com bastante exemplos: https://github.com/krakjoe/pthreads, também requere PHP7. Não encontrei versão compatível com linux.
Resumindo, há várias formas de se realizar uma Thread em um método da classe, uns simulando e outros com componentes específicos, asíncronos ou síncronos. Qual você usar deve usar deve estar baseado nos seus requisitos e na sua infra estrutura, já que precisam de um conhecimento um pouco avançado para se implementar alguma dessas técnicas.
Comment: Essa resposta visa explorar o tema, "Como fazer thread de um método da classe" em php, dentro do tema abordado, apresentei 4 métodos de execução de paralelismo,a outra pergunta responde algo fora do contexto de thread em php, (devido ao teor específico do problema do autor em que o caso apresentado não é necessário fazer thread).
Comment: por isso falei significativo. O quanto é focado na PCNTL, o quanto é bloat?
Comment: Pelo que vi, o foco seria na função `run` e no método abstrato, correto? O resto pode por uma elipse `[...]` para indicar que tem mais coisa por debaixo dos panos
Comment: Olha a resposta do Anderson nessa mesma pergunta, ele se focou em postar o código essencial e deixar os excessos de lado/subentendido, já que não eram necessários
Comment: Obrigado pela orientação, farei a edição assim que possível.
Comment: @LeonanCarvalho, obrigado pelo excesso, o google me direcionou aqui por causa dele era tudo que eu precisava.
Comment: Não use formatação de título para dar ênfase. Também é recomendável por o código significativo na resposta também, não apenas num link referenciado
Comment: Posso por 500 linhas de código na resposta? como vou separar os scripts? Snippet so é possível com js, html e css.
Comment: @Everson os métodos onError, onDestroy, onCancelled são "eventos", vc deve implementar o que fazer nesses eventos dentro da classe filha, que é a que faz o processamento.


Alternative for DBMS_METADATA.GET_DLL in Oracle 8i

Question: In our project we have one database running on oracle 8i (i know this version is ancient but ...)
I want to check the DDL statement for one PUBLIC database link i tried :
select dbms_metadata.get_ddl('DB_LINK', 'LINKNAME', 'PUBLIC') from dual;

select dbms_metadata.get_ddl('DB_LINK', 'LINKNAME', 'PUBLIC') from dual;
                     *
ERROR at line 1:
ORA-00904: invalid column name

As per my knowledge it seems like oracle 8i does not support dbms_metadata. Please correct me if i am wrong.
Table dba_db_links gave me bit information but missing SID of target database.
Is there any way to get DDL statement on Oracle 8i apart from exporting the database/schema ?
Comment: Seriously... *8i*? That's previous century! Upvoting, since I would also like to know what people used to do in 8i days, because as far as I can say, you will get all the details from your **source control**.
Comment: Hopefully your question does not mean "What was the password used for this DB-Link?". The password you will not get in any case.
Comment: @LalitKumarB : Will check for source control. If you have any link regarding this can u please share ?
Comment: @WernfriedDomscheit : Nope , it doesnt mean for password.
Comment: @NagendraNigade Source/version control is maintained by every team. So if you have it, then check for the database source code.
Comment: PS: if you need password for db link then use google. There is some x$_.. view where you will find it in plain text.
Answer: You can query the data dictionary:
SELECT 'CREATE PUBLIC DATABASE LINK "'||DB_LINK||'" CONNECT TO '||USERNAME||' IDENTIFIED BY "<PWD>" USING '''||HOST||''';' AS cmd
FROM DBA_DB_LINKS
WHERE owner = 'PUBLIC'
    AND DB_LINK = 'LINKNAME';

If you miss information try to select table sys.link$ instead.
Comment: Yeah...i missed the column `host` in `dba_db_links`. Done.
Answer: You can use exp/imp tools. Export that database (or schema) using exp rows=now and then import it back into the database using imp show=yes.
This will not make any changes in the database, but all DDLs will be put into the logfile.
Comment: Yes , This will be very helpful for tables.


Polyphonic tie on lilypond

Question: I am writing down the lovely Old Castle from Mussorgsky. And from the beginning there is a tie linking polyphonic voices. What I want to achieve is this:

but what I get is

Even if I put a tie, nothing happens. My code looks like:
\language "italiano"
\header {
  title = "Il Vecchio Castello from Pictures at an Exhibition"
  composer = "Modest Mussorgsky"
 }
upper = \relative do' {
  \clef treble
  \key si \major %enter preformatted text here
  \time 6/8
  R3 R3 R3
 }

lower = \relative do {
  \clef bass
  \key si \major
  \time 6/8
  <sold red'>2.~<<{red'4 red8 red^. red^. red^.} \\ {sold,4. sold} >> <<{red'8.[( mi16) red8^.] fad^.( mi^. red^.)} \\ {sold,4. sold} >>  }

 \score {
 \new PianoStaff <<
  \new Staff = "upper" \upper
   \new Staff = "lower" \lower
>>
\layout { }
\midi {  \tempo 4 = 120 }
}

Any hint on how to tie?
Answer: I recommend starting the polyphonic construction immediately in the first measure. This will cause the opening G♯ to be stem down, so a quick \once \stemUp will move the stem up to match the notation you're looking for.
I also changed your R3 to R2. to accurately reflect the meter.
\version "2.20.0"
\language "italiano"

upper = \relative do' {
  \clef treble
  \key si \major %enter preformatted text here
  \time 6/8
  R2. R R
 }

lower = \relative do {
  \clef bass
  \key si \major
  \time 6/8
  <<
    {
      red2.~ |
      red4 red8 red-. red-. red-. |
      red8.[( mi16) red8^.] fad^.( mi^. red^.)
    }
    \\
    {
      \once \stemUp sold,2.~ |
      sold4. sold |
      sold sold |
    }
  >>
}

\score {
  \new PianoStaff <<
    \new Staff = "upper" \upper
    \new Staff = "lower" \lower
  >>
  \layout { }
}

Comment: Indeed @Richard, I figured out that extending the polyphonic constructions solves, but your solutions is really more elegant. Thank you! Also thank you for the R2. hint, I received lilypond warnings for this with no clue on how to solve it!
Comment: Oh and I missed the steam up, thank you again!
Answer: A suggestion to change your code practice:
Instead of this:
music = {
  ...
  <<{ ... }\\{ ... }>>
  ...
  <<{ ... }\\{ ... }>>
  ...
}
\score {
  \new Staff { \music }
}

Try doing this:
music_upper = {
  \oneVoice
  ...
  \voiceOne ... \oneVoice
  ...
  \voiceOne ... \oneVoice
  ...
}
music_lower = {
  \voiceTwo
  s
  ...
  s
  ...
  s
}
music = <<{ \music_upper }\\{ \music_lower }>>
\score {
  \new Staff { \music }
}

That is, instead of using <<{}\\{}>> multiple times within
one context, use it once, and use the combination of \voiceOne,
\voiceTwo, and \oneVoice to change voice directions.
The rationale:
According to the bug thread here,
there's apparently a common misconception about using the <<{}\\{}>> construct.
I didn't realize it until I'd typeset several hundred short pieces, but each
time <<{}\\{}>> is invoked, two additional Voice contexts are
created. That means that if you make use of that construct several times,
you might end up with the compiled equivalent of a \score {} with
dozens upon dozens of \new Voice {} contexts.
In my case, this caused a huge slow-down, and led to compile failures. The
proposed solution was to use fewer contexts and make use of \voiceOne, \voiceTwo,
and \oneVoice. Using \voice... will automatically control certain
aspects of the notation, such as stem direction and articulation direction. (\oneVoice neutralizes these.)
Think of the differences this way:
RH = \relative c'' {
  red
  <<{ yellow }\\{ blue }>> red
  red
  <<{ green }\\{ cyan }>>
  red
}

and this:
RH_upper = \relative c'' {
  red
  \voiceOne red \oneVoice red
  red
  \voiceOne red \oneVoice
  red
}
RH_lower = \relative c'' {
  s
  blue s
  s
  blue
  s
}
RH = <<{ \RH_upper }\\{ \RH_lower }>>

Five voices in five measures in the first example; two voices in the second example. It can feel a bit more cumbersome to begin with, but I think it helps in the long run, especially if you are going to typeset pieces longer than a few measures.
Using this method specifically, how to make a polyphonic tie:
RH_upper = \relative c' {
  \oneVoice
  R2. R
}
RH_lower = \relative c' {
  s2. s
}
LH_upper = \relative c {
  \oneVoice
  <gis dis'>2.^~
  \voiceOne dis'4 dis8 dis dis dis
}
LH_lower = \relative c {
  \voiceTwo
  \once \hideNotes
  <gis dis'>2.~
  gis4. gis
}
pianoRH = <<{ \RH_upper }\\{ \RH_lower }>>
pianoLH = <<{ \LH_upper }\\{ \LH_lower }>>

Incidentally, you will notice that certain notation elements, such as the . on the first note, are correctly moved above the staff line. They will not be in the other method unless you manually correct them.
Comment: Hello Neal, indeed your suggestion looks cumbersome and I dont fully understand it. Still your suggestion is interesting as, in this piece Mussorgsky wrote for the F key almost entirely two voices and for the G key two voices in several places.So my notation and code starts to look really cumbersome as well. I am going to study your example ( switching to onevoice is what was blocking me)

Polyphonic tie on lilypond


Chrome Extension: Javascript works in browser, but not as extension

Question: http://jsbin.com/ejofazU/1/
Works find in the browser, but when I make it a popup chrome extension, the javascript doesn't work, and don't know why. Source is still the same, I attached content scripts in the manifest thinking that would help, but still can't seem to get this to work.
Any help is much appreciated.
Manifest
{
   "name": "Resistor Color Calculator",
   "description": "Just a basic resistor color calculator.",
   "version": "1.1.0",
   "permissions": [
     "tabs", "http://*/*", "https://*/*"
   ],
   "icons": {
     "128": "src/128x128.png",
     "256": "src/logo.png",
     "48": "src/48x48.png"
   },
   "browser_action": {
     "default_title": "Resistor Calculator",
     "default_icon": "src/48x48.png",
     "default_popup": "popup.html"
   },
   "content_scripts": [
     {
      "matches": ["http://*/*"],
      "js": ["jquery.js"]
     }
   ],
   "manifest_version": 2
}

Popup
<!DOCTYPE html>

<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0">

          =  answer Ω

      <input type="text" name="problem" />
      <input type="text" name="hideresult" />

            <select id="colors">
               <option value=" ">1st Band</option>
               <option style="background:black; color:white;" value="0">Black</option>
               <option style="background:brown; color:white;" value="1">Brown</option>
               <option style="background:red; color:white;" value="2">Red</option>
               <option style="background:orange; color:white;" value="3">Orange</option>
               <option style="background:yellow; color:black;" value="4">Yellow</option>
               <option style="background:green; color:white;" value="5">Green</option>
               <option style="background:blue; color:white;" value="6">Blue</option>
               <option style="background:violet; color:black;" value="7">Violet</option>
               <option style="background:grey; color:white;" value="8">Grey</option>
               <option style="background:white; color:black;" value="9">White</option>
            </select>

            <select id="digits">
               <option  value=" ">2nd Band</option>
               <option style="background:black; color:white;" value="0">Black</option>
               <option style="background:brown; color:white;" value="1">Brown</option>
               <option style="background:red; color:white;" value="2">Red</option>
               <option style="background:orange; color:white;" value="3">Orange</option>
               <option style="background:yellow; color:black;" value="4">Yellow</option>
               <option style="background:green; color:white;" value="5">Green</option>
               <option style="background:blue; color:white;" value="6">Blue</option>
               <option style="background:violet; color:black;" value="7">Violet</option>
               <option style="background:grey; color:white;" value="8">Grey</option>
               <option style="background:white; color:black;" value="9">White</option>
            </select>

            <select id="multi">
               <option value=" ">3rd Band</option>
               <option style="background:black; color:white;" value="*1">x1</option>
               <option style="background:brown; color:white;" value="*10">x10</option>
               <option style="background:red; color:white;" value="*100">x100</option>
               <option style="background:orange; color:white;" value="*1000">x1,000</option>
               <option style="background:yellow; color:black;" value="*10000">x10,000</option>
               <option style="background:green; color:white;" value="*100000">x100,000</option>
               <option style="background:blue; color:white;" value="*1000000">x1,000,000</option>
               <option style="background:violet; color:black;" value="*10000000">x10,000,000</option>
               <option style="background:grey; color:white;" value="*100000000">x100,000,000</option>
               <option style="background:white; color:black;" value="*1000000000">x1,000,000,000</option>
               <option style="background:white; color:black;" value="/10">÷10</option>
               <option style="background:white; color:black;" value="/100">÷100</option>
            </select>

            <select id="toller">
               <option value=" ">4th Band</option>
               <option style="background:Black; color:white;" value="± 1%">Black</option>
               <option style="background:Brown; color:white;" value="± 2%">Brown</option>
               <option style="background:Gold; color:black;" value="± 5%">Gold</option>
               <option style="background:Silver; color:black;" value="± 10%">Silver</option>
               <option value="± 20%">None</option>
            </select>

         Color
         Digits
         Multiplier
         Tollerance

         Black
         0
         x1
         1%

         Brown
         1
         x10
         2%

         Red
         2
         x100

         Orange
         3
         x1,000

          Yellow
         4
         x10,000

         Green
         5
         x100,000

         Blue
         6
         x1,000,000

         Violet
         7
         x10,000,000

         Grey
         8
         x100,000,000

         White
         9
         x1,000,000,000

         Gold

         ÷10
         5%

         Silver

         ÷100
         10%

         None

         20%

Comment: "Doesn't work" is not really a great description if you are looking for people to help you.
Comment: Without other information and debugging efforts from you my money is on PEBKAC.
Answer: First of all, please, go and read about SSCCE.

According to the docs on changes regarding Manifest V2:

[...] inline event handlers [...] will not execute.
These will not work in manifest V2 extensions. Remove the inline event handlers, place them in your external JS file and use addEventListener() to register event handlers for them instead.

So, in your case, move any code inside script tags in a JS file and reference that file as the script's src. Also, replace any inline JS with equivalent code in the external JS file (e.g. adding event-listeners).


Criar JSON a partir de Select do banco

Question: Populei um banco mysql com dados neste formato:

 e queria retornar isso em json usando php, o problema é que eu tenho por exemplo varias linhas com o mesmo estado, e preciso retornar o json enste formato:
    {
  "Estados": {
    "Espirito Santo": {
      "Cidades": {
        "Cidade 1": {
          "Nome Unidade": {
            "Nome": "a",
            "Endereco": "b",
            "log": "222",
            "lat": "111"
          },
          "Nome Unidade2": {
            "Nome": "a",
            "Endereco": "b",
            "log": "222",
            "lat": "111"
          }
        }
      }
    }
  }
}

Ou seja, agrupar todos os estados repetidos, cidades tambem. não tenho ideia de como fazer, oque consegui até agora foi retirar o id e criar o array com os estados ( repetidos) assim:
$resultado = $this->sql->select("SELECT * FROM tb_unidades");
//print_r($resultado);
//print_r($resultado['0']['estado']);

$estados = array();
foreach ($resultado as &$row) {
    unset($row['id']);
    $estados[] = array($row['estado']);
}
$estados = array("Estados"=>$estados, "Ben"=>"37", "Joe"=>"43");
print_r(json_encode($estados));

EDIT:
Tentando a solução proposta obtive isto:

 $resultado = $this->sql->select("SELECT * FROM tb_unidades");

$estados = array();
$cidades = array();

foreach ($resultado as $row) {
    $cidades[$row["cidade"]][] = $row;
    $estados[$row["estado"]][] = $cidades;
}

$estadosp = array("Estados"=>$estados);
return json_encode($estadosp);

As cidades ficaram repetidas, e apareceu algumas de outros estados.
Answer: Olá.
Use o estado como sendo a chave do array.
$resultado = $this->sql->select("SELECT * FROM tb_unidades");

$estados = array();
foreach ($resultado as $row) {

    $estados[$row["estado"]][$row["cidade"]][] = $row;
}

Dá um print_r nesse array e veja como ele fica.
Comment: Veja o edit que fiz na resposta
Comment: Consegui criar os 2 array, de estados e de cidades sem repetir, ok, mas agora como coloco a cidade dentro do array estados?
Comment: Então, mas com apenas 1 array você consegue tudo isso.
Comment: confere meu edit, pelo que pensei, achei que as cidades iriram entrar como um novo array, mas na verdade misturou tudo
Comment: Oque é estranho pq quando printo apenas $cidades, me retorna corretamente
Comment: Exatamente isso, obrigado
Comment: deu certo? se for o caso, adiciona mais 1 chave para o bairro, acredito que vai ficar melhor.
Comment: Para minha aplicação não acho necessário, é um combo box de cidade e estado

Criar JSON a partir de Select do banco


Appropriate non-parametric post-hoc test for baseline comparisons?

Question: I want to evaluate several "classifiers" (machine-learning algorithms) with paired samples. I do not want to compare each algorithms' performance to every other (n x m comparison) but only compare the performance of each algorithm to one baseline (n x 1 comparison).
An often quoted paper in the field [1] uses the Friedman test for omnibus testing and suggests the following for post-hoc tests:

When all classifiers are compared with a control classifier, we can
  instead of the Nemenyi test use one of the general procedures for
  controlling the family-wise error in multiple hypothesis test-ing,
  such as the Bonferroni correction or similar procedures.

Can I thus use any test for the comparison of 2 groups with paired samples and apply a bonferroni (or less conservative) correction to the p-values? Is a Wilcoxon Signed-Rank test appropriate here?
[1] Demsar, J. (2006). Statistical Comparisons of Classifiers over Multiple Data Sets. Journal of Machine Learning Research, 7, 1–30.
Comment: Do you mean the *Friedman* test?
Answer: You can use Friedman test (or the correction named Iman-Davenport) to the the ranking of the methods. Then for the post-hoc procedure, for a 1xn comparison, you use a post-hoc with a control method.
Nemenyi is valid but not reccommended because it is a very conservative procedure and many of the obvious differences may not be detected. It's better to use procedures more powerful, such us holm or hochberg. The most powerful method are li and finner [1].
[1] S. García, A. Fernández, J. Luengo, F. Herrera, Advanced nonparametric tests for multiple comparisons in the design of experiments in computational intelligence and data mining: Experimental Analysis of Power. Information Sciences 180 (2010) 2044–2064. doi:10.1016/j.ins.2009.12.010
Comment: Thanks. Demsar suggests Nemenyi for n x m comparisons and Bonferroni/Hochberg/Holm for 1 x n testing against a control method. My question was: What is meant by "Bonferroni/Hochberg/Holm"? These are methods for adjusting p-values in multiple comparisons, but not statistical tests. So is it feasible to use Wilcoxon's signed-rank test for pairwise comparisons against the control method and then adjust the p-values?
Answer: I was looking for this same answer. And I think a found it: "In this case we are only interested, whether the treatments differ significantly from the control experiment."
They talk in this article about how is it possible to use a Dunn Test alteration (after Kruskal), allowing the poshoc comparison only with the control.
The function in R is dunn.test.control(x=weight, g=group,  p.adjust="bonferroni") and the article link is, named "The Pairwise Multiple Comparison of Mean Ranks Package (PMCMR)".


Necessary and sufficient conditions for $ax^2+bx+c$ to be factorizable...

Question:
What are necessary and sufficient conditions for $ax^2+bx+c$ to be factorizable involving just integer coefficients?

We already know that this expression is factorizable if $b^2-4ac$ is a perfect square,($ax^2+bx+c$ is factorizable if...)but in this case can we be sure that all the coefficients are just integers??
Comment: By [Gauss's lemma](https://en.wikipedia.org/wiki/Gauss's_lemma_%28polynomial%29), if you can factor a nonconstant polynomial (with integer coefficients) over the rationals, you can factor it over the integers.
Comment: $x^2 + \frac{4}{3} x + \frac{1}{3}$ does not have integer coefficients.
Comment: Assuming you mean factorizable over $\mathbb{Q}$, a necessary condition is given by Eisenstein's criterion.
Comment: @MathematicsStudent1122 No,I mean just factorizable over $\Bbb{Z}$
Comment: @RobertIsrael Thank you dear,I got it.
Comment: @RobertIsrael Is there any algorithm for converting a rational factorization of a polynomial into an integer factorization?
Comment: Put everything over a common denominator, and take out common integer factors of the numerators.  Denominators should cancel with the factors of the numerators.
Comment: @RobertIsrael What about this: $(x+\frac13)(x+1)=(\frac{3x+1}{3})(x+1)$?!!
Answer: Robert Israel's comment:

By Gauss's lemma, if you can factor a nonconstant polynomial (with integer coefficients) over the rationals, you can factor it over the integers.

And as you point out, it factors over the rationals just in case $b^2 - 4ac$ is a perfect square.
Therefore it factors over the integers just in case $b^2 - 4ac$ is a perfect square.
Comment: Yes,in fact my question had been already answered by Gauss's lemma! which I didn't know about.


Why is R giving a bad result of addition?

Question: I can't seem to do a comparison with a sum of numbers and get the right answer (lines alternate between my input and R output):

(.6 + .3 + .1) == 1
[1] FALSE
(.6 + .3 + .1)
[1] 1
1
[1] 1

I've tried with and without parenthesis, tried comparing to 1.0, tried using as.numeric, but can't get it to work.
Answer: You've fallen into the "Floating Point Trap." See the first chapter of the R Inferno:  http://www.burns-stat.com/pages/Tutor/R_inferno.pdf
You want to test floating point numbers with all.equal instead, like this:
> all.equal(.6+.3+.1, 1)
[1] TRUE

Comment: Thanks that helps!. BTW people should know that all.equal does NOT return FALSE when false. So to do the comparison you need to wrap isTRUE around all.equal. A long way to go just to compare 2 numbers.
Answer: It is floating point rounding.  You get
> round(.6 + .3 + .1, digits=16) == 1
[1] FALSE
> round(.6 + .3 + .1, digits=15) == 1
[1] TRUE
> (.6 + .3 + .1) - 1
[1] -1.11022302462516e-16


algortimo para ler idade anos, meses, e anos e converter o valor para a idade apenas em dias

Question: <code>#include <iostream>

using namespace std;

int main() {
 int idade;
 int anos;
 int meses;
 int dias;

cin >> anos >> meses >> dias;

 meses= anos*12;

 dias= meses*30;

 cout << ("sua idade em dias:");

}
</code>
No caso ele ta aparecendo pra eu digitar o valor em dias, mas ele que deveria responder e nao eu.
Answer: Você tem que acumular e ao final imprimir a quantidade de dias.
<code>#include <iostream>
using namespace std;

int main() {
    int anos, meses, dias;
    cin >> anos >> meses >> dias;
    cout << "Anos: " << anos << endl;
    cout << "Meses: " << meses << endl;
    cout << "Dias: " << dias << endl;
    meses += anos*12;
    dias += meses*30;
    cout << "Sua idade em dias: " << dias << endl;;
    return 0;
}
</code>


Find the control function

Question: Determine the general form of $u_0, u_1 ~\text{and} ~ u_2$ if a system of difference equations of the form
$$x_{n+1} = Ax_n  + Bu_n,$$
where:
$$A = \begin{pmatrix}
  3 & 2 & 2  \\
  -1 & 0 & -1 \\
   0 & 0 & 1
  \end{pmatrix}$$
and:
$$B = \begin{pmatrix}
  0 & 0  \\
  0 & 1 \\
  1 & 0
  \end{pmatrix}$$
is to be controlled for $x_0 = 0 ~ to ~ x_3 = [2, 1, 2]^T$ .
Comment: Thanks @Amzoti do you think you can haelp with the question. I have calculated the control martix $$
        \begin{matrix}
        0 & 0 & 2 & 2 & 6 & 6 \\
        0 & 1 & -1 & 0 & -3 & -2 \\
        1 & 0 & 1 & 0 & 1 & 0 \\
        \end{matrix}
$$
Comment: Later would be great thanks so much @Amzoti would really appreciate any help you could give me
Comment: Hi @Amzoti did you manage to get a chance to look at the question?
Comment: @Amzoti Yes I think I managed to solve it for myself by taking the Taylor series for cosh and sinh and substituting in. Thank you for your help on this one very much appreciated
Comment: Hi @Amzoti have you attempted this problem?
Answer: Edit: The controllability matrix is
$$
C=\begin{pmatrix}
B,AB,A^2B
\end{pmatrix}
=\begin{pmatrix}
0&0&2&2&6&6\\
0&1&-1&0&-3&-2\\
1&0&1&0&1&0
\end{pmatrix}.
$$
Clearly it has full rank. Thus the system is always controllable. In fact, if you take $u_0=0,\,u_1=(1,0)^T$ and $u_2=(1,2)^T$, you can get $x_3$ from $x_0$. For the general form of $u_0=(a,b)^T, u_1=(c,d)^T, u_2=(e,f)^T$, solve the system of linear equations $Cv=(2,1,2)^T$, where $v=(a,b,c,d,e,f)^T$.
Comment: Apologies @user1551 I realised I typed the B matrix wrong. I have edited it now. It should make more sense, Thanks for all your help
Comment: hi @user1551 thanks for this, could you expand on how you got went from the general form to the u values. Im can't quite make the link between your 3 equations for Cv=(2 1 2)^T and those
Comment: @Amzoti Im still struggling to see how to get from the controlability matrix to the solution? If you have the time I would be greatful if you could explain? Thank you so much, going round in circles here
Comment: @Jay As $x_0=0$, we have $x_1=Bu_0$ and in turn $x_2=ABu_0+Bu_1$ and $x_3=A^2Bu_0+ABu_1+Bu_2$, which is equivalent to $x_3=Cv$ if you stack up $u_0,u_1$ and $u_2$ together to form a $6$-vector $v$. That's why you need to solve $Cv=(2,1,2)^T$ for a general solution. I haven't solved it in my answer, as I thought you should know enough linear algebra to solve it.
Comment: @user1551 I think Im missing something. I have 6 unknowns (a,b,c,d,e,f) with only 3 equations? 2c+2d+6e+6f=2 , b-c-3e-2f=1 and a+c+e=2? SHould i be able to solve from this?
Comment: @Jay Yes, why not? You do remember elementary row operations, row echelon form, etc., don't you? Solving systems of linear equations is a standard topic in virtually every introductory textbook on linear algebra. If you have forgotten how to solve them, you may read your textbook again.
Comment: Can you confirm that I those equations are correct above?@User1551
Comment: @Jay Yes, they are.
Comment: @user1551 I have reduced the system to augmented echelon form to get   $$
        \begin{matrix}
        1 & 0 & 0 & -1 & -2  & -3 & 1 \\
        0 & 1 & 0 & 1 & 0  & 1 & 2 \\
        0 & 0 & 1 & 1 & 3  & 3 & 1 \\
        \end{matrix}
$$
so there are infinitely many solutions. however I still dont understand how you achieved the u_0 u_1 and u_2 you have given specific for x_3
Comment: @Jay Of course there are infinitely many solutions. (Weren't you asked to find the *general* solution for the $u_i$s?) Now you have reduced the system to a row echelon form, you can write down the solutions immediately.
Answer: @user1551 do you agree with  the general form of $ u_0 u_1 $and $ u_2 $ is
$ u_0 =(1-3r_3 +2r_2 +r_1, 2-r_1 -r_3)^T
u_1 = (1-3r_3 -3r_2 -r_1, r_1)^T
u_2=(r_2, r_3)^T $

Find the control function


ABAP 7.4 way of filling one itab from another?

Question: Consider, I have GT_KUNNR internal table like below:

KUNNR
TEXT

123
demo text

456
test inv

I have second GT_TEXT internal like below:

KUNNR
TEXT
EXPIRED

123
welcome
X

I am writing the code till now in ABAP as:
LOOP AT GT_KUNNR ASSIGNING FIELD-SYMBOL(<lfs_kunnr>).
  READ TABLE GT_TEXT ASSIGNING FIELD-SYMBOL(lfs_text>) WITH KEY kunnr = <lfs_kunnr>-kunnr BINARY SEARCH.
  IF sy-subrc EQ 0.
    <lfs_kunnr>-text = <lfs_text>-text.
  ENDIF.
ENDLOOP.

My question is, how to achieve above using ABAP 7.4 and upwards? My understanding is, constructor expression (VALUE,FOR,REDUCE..) creates a new type, which I don't need (basically, GT_KUNNR is being updated and can have huge records. So, creating new structure/type and then passing that again to GT_KUNNR will be a performance bottleneck). So, how to achieve that? Any efficient way?
Comment: It's a myth. I don't know why people think that any code needs to be re-written with some new "ABAP 7.4" syntax. The ABAP 7.4 syntax doesn't replace everything, that's just new syntax which may or may not be used. There is new syntax in every ABAP version. Field symbols have no specific replacement in 7.4, and not later (NB data references have been a possible alternative for a long time, but it's not more efficient). FYI, the constructor expressions don't "create a new type", they are just a new way to fill **variables**.
Comment: Hi @SandraRossi: Thanks for the guided direction and yes, you are right, I should have been asked in much better sense in terms of syntax. Will surely take this into consideration in coming future
Answer: If you want to do this with a constructor operator, then you can use the CORRESPONDING-operator with a lookup table.
But note that this requires that the linking condition between the two tables (kunnr = kunnr) uses a table key in the lookup table. That means that the lookup table (in this case gt_text) has to be a SORTED TABLE or a HASHED TABLE with kunnr as the keyfield, or that it at least has a SECONDARY KEY that matches the condition.
" Declarations:
TYPES:
  BEGIN OF kunnr_struct,
    kunnr TYPE kunnr,
    text TYPE string,
  END OF kunnr_struct,
  kunnr_tbl TYPE STANDARD TABLE OF kunnr_struct WITH DEFAULT KEY,
  BEGIN OF text_struct,
    kunnr TYPE kunnr,
    text TYPE string,
    expired TYPE abap_bool,
  END OF text_struct,
  text_tbl TYPE HASHED TABLE OF text_struct WITH UNIQUE KEY kunnr. " <- Important!

" Test data:
DATA(gt_kunnr) = VALUE kunnr_tbl(
   ( kunnr = '123' text = 'demo text'  )
   ( kunnr = '456' text = 'text inv')
).

DATA(gt_text) = VALUE text_tbl(
   ( kunnr = '123' text = 'welcome' expired = abap_true )
).

" The actual code you asked for:

gt_kunnr = CORRESPONDING kunnr_tbl(
    gt_kunnr FROM gt_text USING kunnr = kunnr ).

My understanding is, constructor expression (VALUE,FOR,REDUCE..) creates a new type, which I don't need (basically, GT_KUNNR is being updated and can have huge records.

This does not create a new type, but according to the documentation I linked above, it does indeed create an interim table with the results in memory. This is unlikely to be a performance problem (the runtime increase would probably be linear at worst), but it could double the memory being used, so it could become a memory problem with very large datasets.
If that is a concern for your use-case, then you can keep using your variant with a loop. If you don't want to use field-symbols, then you can do what many modern ABAP styleguides, like this one from SAP themselves, recommend to use references instead of field-symbols whenever possible. The code from the question using references would look like this:
LOOP AT gt_kunnr REFERENCE INTO DATA(lrs_kunnr).
  READ TABLE gt_text REFERENCE INTO DATA(lrs_text) WITH KEY kunnr = lrs_kunnr->kunnr BINARY SEARCH.
  IF sy-subrc EQ 0.
    lrs_kunnr->text = lrs_text->text.
  ENDIF.
ENDLOOP.

Comment: Hi @philipp : Thanks for this detailed beautiful answer. I tried with this REFERENCE INTO, and it did the job...Let me check the earlier CORRESPONDING one will revert back.


What is the purpose of these 2 pylons?

Question: In the following image, you can see 3 pylons. One of them is the goal line pylon, which can be helpful in determining whether or not the ball broke the plane of the end zone on plays close to the sideline. I did not put a red arrow next to this pylon.
I put red arrows next to the other 2 pylons, whose purpose I am not sure of.

There is a pylon very close to the goal line pylon. This pylon is larger than the goal line pylon. As you can see, on this particular play it is 3rd and goal, so this larger pylon cannot be any sort of first down marker. What is the purpose of this larger pylon?

There is a pylon at the corner of the back of the end zone. I don't know why there would need to be a pylon at that location, given that it is possible for a receiver to catch a ball flying past the end zone as long as both of his feet remain inbounds. What is the purpose of this pylon?
Answer: The functional purpose of pylons such as the back pylon (portrayed on the right of the still) is to denote the end zone (3.12.3) as inbound lines (1.2.2). These are important as they play a role in determining in and out of bounds (3.21.1, 3.21.2, 3.21.3) and scoring plays (11.2.1).
The pylon portrayed on the left of the still is the C360 pylon cam which provides video technologies on the field. The still is an ESPN Monday Night Football broadcast, which this article calls out as one of three broadcast channels to use C360 pylon cams this season (the others being Fox and CBS).
Comment: It is not clear to me which goal line pylon - the smaller one right on the goal line or the larger one just off the goal line - is the C360 goal line pylon.
Answer:
As you can see, on this particular play it is 3rd and goal, so this larger pylon cannot be any sort of first down marker. What is the purpose of this larger pylon?

As mentioned, it is a camera pylon.  For most plays, the pylon is placed at the first down location (line to gain) on top of a banner/arrow marking the line.

When the line to gain is the goal line, the first down marker is removed.   It looks like they place the pylon near the goal line, but away from the sideline.  That position doesn't indicate anything for gameplay, but is just another camera.
Comment: Although the smaller pylon that is right on the goal line also has a camera, making the larger pylon seemingly redundant.

What is the purpose of these 2 pylons?


Force transmission of TCP/IP data from one NIC to another on same PC

Question: We are preparing a product for EMC testing. The product runs Windows Embedded Standard 2009 (compare it with Windows XP) and has 2 NICs, say NIC1 and NIC2.
For the emission test, we need to send data from NIC1 to NIC2. If I assign both NICs an IP address in the same range, I can PING and send/receive data, but data is not transmitted over the crossed cable.
Is there a way (by changing the route table f.e.) to actually send the data from NIC1 to NIC2 over the crossed cable without adding extra hardware?
Comment: We can't answer the question, so we downvote it? At least leave a comment.
Comment: The saga of rogue down votes continues. All I can say is ignore the down votes. The only reason I can think of is that your question _may_ be out of scope for serverfault.
Answer: The simplest solution is probably to use a UDP broadcast.  That way, Windows will have to put the data on the wire, since it has no way of knowing that there are no other nodes on the network.
I'm not absolutely certain that Windows won't drop the incoming broadcast packets but it seems unlikely.  You might conceivably see two copies of each packet (one sent directly and one sent over the wire) but that seems unlikely too.
Comment: That's a great idea. Will try this today.
Answer: How about two virtual machines. VM 1 is bridged to the first interface while VM 2 is bridged to the second interface. Send traffic between the VMs that way. I don't know if this is easy in Windows, though.
Another option is to use IPv6 scope local, the addresses that begin with fe80:: (Just tested in Linux and it works there, but I don't have Windows to try with).
Comment: +1.  My guess would be that Windows is too smart for either of these approaches to work, but they're worth a try.
Comment: Had the VM idea too. As for this test I can't use it because there's a lot of other hardware that needs to be tested and this will not work from within a VM. I will still give it a try if the UDP broadcast method fails.
Comment: Opening a raw socket from a programming language with full capability socket bindings would be a direct approach if you are developing the testing tools.
Answer: You might look into iperf.  iperf is designed to test network speeds and performance by sending actual data.  It requires a client/server on both sides of the connection though, so depending on the environment, that may or may not help.
http://en.wikipedia.org/wiki/Iperf
http://sourceforge.net/projects/iperf/
Comment: I created my own program that listens to a port bound to NIC1 and connects to NIC1 with a socket bound to NIC2. I can send and receive, but the data stays in the machine and doesn't go over the crossed cable (I can even remove the cable, it keeps on working). So with iperf, I will have the same issue.
Comment: Ah, gotchya.  Not saying it's you WouterH, but I usually like comments with my down votes too :S looks like you experienced the same thing up there - here's an upvote for you to compensate ;)
Comment: Have you tried swapping the cables/ensuring the proper use of a crossover or straight cable?  Do your ping/ICMP requests come back?
Comment: No it wasn't my downvote, here is my compensating upvote :) Problem is that I can even remove the cable and ping still works. Even the client/ server program continues to work where server bound to IP of NIC1 and client to IP of NIC2
Comment: Haha, thanks - that's really bizarre.  I've seen some applications we use that indicate data flowing over the wire, even with no wire plugged in. I'm not sure what the mechanism is, but I'll let you know if I find anything.


How do I convert drupal_goto to 301?

Question: Right now I have a redirect in my code:
drupal_goto($path);

Per the documentation drupal_goto defaults to a 302 redirect. I want a 301.
However, when I put in:
drupal_goto($path, $http_response_code = 302);

It gives me an error:

Argument 2 passed to drupal_goto() must be of the type array, integer given,

But if I try something like:
drupal_goto($path, array $options = array(), $http_response_code = 302);

...I get this error:

Unexpected '$options'

How can I properly change drupal_goto into a 301 redirect?
Answer: Looks like you're mistaking the function definition for an implementation example.
The function definition describes the arguments to use, but it's not a literal example of how to call it.
So when you want to use the drupal_goto() function, instead of this:
drupal_goto($path, array $options = array(), $http_response_code = 302);

It should look more like this:
drupal_goto($path, array(), 301);

Answer: drupal_goto($path = '', array $options = array(), $http_response_code = 302)

Initialize $option as empty array something like this
$options = array();
$path = <your path>;
drupal_goto($path, $option, 301);

Comment: so I need both lines one after the other?
Comment: it should be like this

$options = array();
$path = ;
drupal_goto($path, $option, 301);

How do I convert drupal_goto to 301?


Techniques for MNAR without Imputation

Question: Oftentimes I see that people address missingness from the perspective of missing at random (MAR). However, there are cases where missing not at random (MNAR) in which one can sometimes be handled with stuff like imputation. However, I'm thinking of another case which is more complex but likely not uncommon.
Let's say participants are recruited from a study which had two years of recruiting participants. In the first year, a survey was administered with 20 questions. However, the second year required 30 questions because ceiling effects became very evident. Now if one was to run an analysis using these two years, there would be obvious issues because one year's participants did not get the full range of questions.
What would be the appropriate way of handling this data? Should one only use the 20 questions used for both years? Should the person running the analysis impute the data? What are ethical ways of handling this data? Given it would be substantial (at least 50% of the population wouldn't have answered 10 questions), I would think this would be important to address.
Comment: I think what to do will depend on the exact aims of the study, which you haven't specified. As a general comment, imputing all the missing questions for the first year is out of question in my view; I agree that a too substantial amount of data would be made up in this way without any possibility to check whether there may have been systematic differences between the two years regarding these questions.
Comment: MNAR is tricky. Say that you send a survey to a group of people because you want to study if they have a history of using illegal drugs. Some of the surveys don't go back, all of the surveys that were sent back said that they didn't use any illegal drugs in their life. Does it say that people use no illegal drugs? Or should you impute the "missing" surveys using the ones you got back (= people don't use drugs)? Or maybe treat the missing ones as acknowledging to using drugs (this is not a valid interpretation)?
Comment: Let's say there is a simple regression of vocabulary as a predictor and speaking ability in English as the outcome, with the speaking ability being the MNAR variable. We would want to know how well vocab predicts, but if speaking ability is purposely bounded one year at 20 points, it seems to be an issue. @ChristianHennig
Comment: @Tim i think the big issue here would be that its by-design from those making the questionnaire, which makes the MNAR much less ambiguous
Comment: Then as @ChristianHennig said, the answer depends on the detail of your study.
Comment: @ShawnHemelstrand Please add any relevant information to the question. I'd probably look at a few things: (a) looking at the original 20 questions, can any difference between the two years be detected? (b) Regression using only the 20 original questions, with thorough visualisation to see what the ceiling effects do (potentially more sophisticated techniques than standard regression can help), (c) Regression on all 30 questions using the second year only. You can then see whether all results allow more or less the same interpretation.
Comment: It may be illuminating to consider simple, "extreme" methods of responding to this situation before resorting to clever, potentially fragile statistical methods. For example, if the ceiling issue is sufficiently severe, maybe the first wave is just useless and effort would be better spent on acquiring more data, perhaps working on other projects while the next wave is prepared. Is there any reason to believe that the first wave might still be useful? A reason based in science and data, not publish-or-perish incentives?
Comment: I have actually already come up with a much better alternative than those listed for my specific case which doesn't require any drastic measures. However, the information here is certainly good to know for if this happens with different cases down the road.
Answer: I'll make an answer out of my comments.
(1) Do not impute the 10 missing questions for all participants of the first year. Note in particular that if the reason why the 10 additional questions were asked are ceiling effects, it means that it is clear that the original 20 questions are not enough to differentiate between the high scoring participants. But this means that there is no reliable way to predict how those participants in the first year would have responded to the additional 10 questions from the data. The 20 original questions do not give enough information, and if your aim is to run a regression with speaking ability ("MNAR variable") as response and some $x$-variable as predictor, you shouldn't use that $x$-variable for imputation either, as this would mean that you assume a specific regression connection that you want to find out about in the first place. In other words, you'd make up data in such a way that it would wrongly suggest that your overall regression is more precise than it actually is, as imputation would take for granted (without having data to check) that what holds in the second year for all questions extends to the first year (I believe that in this case even multiple imputation techniques would not give you a reliable indication of uncertainty, because they still need such assumptions for the actual imputation).
Instead, assuming that your aim is the regression mentioned in the comments, I'd try out a few things with particular focus on visualisation and understanding what goes on:
(2) Looking at the original 20 questions, can any difference between the two years be detected?
(3) Regression using only the 20 original questions, with thorough visualisation to see what the ceiling effects do (potentially more sophisticated techniques than standard regression can help, here's where the answer of @Björn comes in; that could probably even address analysing all data together, but this may rely on problematic assumptions. Another option to handle the ceiling problem would be ordinal regression, which however here may require lots of data due to the large number of parameters with 20 or 30 categories.
(4) Regression on all 30 questions using the second year only.
You can then see whether all results allow more or less the same interpretation.
PS: Note that "missing at random" (somewhat confusingly) does not mean that missingness occurs randomly, but rather that the randomness of the missing values themselves can be fully explained by observed information. Whether this is the case is generally unobservable (one would need to observe the missing values to check this), and may in principle hold for your data (involving the observation year as observable information). However I agree that it is safer to treat these data as at least potentially MNAR.
Comment: @ShawnHemelstrand I have added something in (3) and a PS after you accepted this.
Comment: Thanks. I think those are at least some reasonable suggestions.
Comment: Appreciate the extra info.
Answer: The particular situation you describe could potentially be handled using methods for censored data. I.e. data where you know don't know the exact value, but it's greater than some value ("right censoring"), smaller than some value ("left censoring") or in some interval ("interval censoring").
However, that only makes sense, if the same question gets asked with a truncated response scale (let's say 0 to 50) and without a truncated scale (let's say 0 to 100), and if (that's a big IF) the participants interpret the question the same way each time (i.e. in the same circumstances they would answer X on the truncated scale and X on the untruncated, just when X is >50, then they respond 50 on the truncated scale). In that circumstance, an answer of 50 on the truncated scale simply means $\geq to 50$. That's exactly the situation, for which methods for censored data (here right censored) were developed.
I would be a bit nervous about doing that, because I'd worry that people would treat/interpret the scale differently, in which case it becomes very difficult to say something across the two different questionnaires.
Generic methods for censored data of course only make sense when censoring occurs completely at random or in a way that can be explained by the observed data ("at random"; of course the things influencing censoring should be included in the analysis model to deal with it, otherwise you end up in the next scenario below). If you are in a situation where it occurs dependent on the value. What do I mean by that? Let's imagine you ask people their salary and people with a salary <100k USD/year always tell you their salary, people between 100 to 200k tell you their salary 50% of the time and 50% of the time tell you ">100k", but people with salaries >200k always tell you >100k, you have a "missing not at random" time of censoring that is really problematic (unless you have other information that can make you distinguish these groups). My initial thought was that a split in time for the new scale would not be that kind of situation.

Techniques for MNAR without Imputation


Collision of two particles: constant velocity, constant acceleration

Question: In the figure, particle $A$ moves along the line $y = 25~\text{m}$ with a constant velocity $v$ of magnitude $3.0~\text{m}/\text{s}$ and directed parallel to the $x$ axis. At the instant particle A passes the $y$-axis, particle $B$ leaves the origin with zero initial speed and constant acceleration $a$ of magnitude $0.44~\text{m}/\text{s}^2$. What angle $\theta$ between $a$ and the positive direction of the $y$-axis would result in a collision?
I did the problem but I'm not getting the right answer? How would this be solved and/or what am I doing wrong?
You don't have to read this part but to solve it,
Both have a same final displacement in the x direction so if you use an equation
$3t = 0.5 \cdot 0.44 \cdot t^2$ with $t = 13.64~\text{s}$.
Since it has the same $y$ point ($25$ m height) the angle can be found with $\arctan(13.64\cdot 3/25)$. Then you subtract that from $90$ to get the angle with reference to the $y$-axis.
What am I doing wrong here?
Comment: I don't think I have to include the picture of the figure (it didn't give an option to) but the A vector is a straight line at y = 25, and the B vector is like a line flowing at 60 degrees, going upwards towards the A vector, and then crossing it.
Answer: Mathematical Model
It is convenient to use vectors here. For particle $A$ we have:
$$
r_A(t) = r_A(0) + v_A t = (x_A(0), 25) + (3, 0) t = (x_A(0) + 3t, 25)
$$
where the text gives $x_A(0) = 0$.
For particle $B$ we have
$$
a_B(t) = a \\
v_B(t) = v_B(0) + a t = at \\
r_B(t) = r_B(0) + \frac{1}{2}a t^2
= \frac{1}{2}a t^2
= ((1/2)\lVert a \rVert \sin(\theta) t^2,(1/2)\lVert a \rVert \cos(\theta) t^2)
$$

The above image shows the trajectory of $A$ (green) and of $B$ (blue) and where the trajectories intersect at point $X$. Also the angle is given (named $\alpha$ instead of $\theta$).
You can fiddle with a live version here.
Calculating the Collision Point
For a collision we need $r_A(t) = r_B(t) = X$ for some $t$.
The intersection point $X$ is
$$
X = (\xi, 25)
$$
with $\tan(\theta) = \xi / 25 \iff \xi = 25 \tan(\theta)$.
$A$ arrives at $X$ if
$$
t = (25/3) \tan(\theta) \quad (1)
$$
$B$ arrives at $X$ if
$$
\frac{1}{2} \lVert a \rVert \sin(\theta) t^2 = 25 \tan(\theta) \quad (2) \\
\frac{1}{2} \lVert a \rVert \cos(\theta) t^2 = 25 \quad (3)
$$
Alas equation $(2)$ and $(3)$ are equivalent, division of both sides of $(2)$ by $\tan(\theta)$ gives $(3)$.
Inserting $(1)$ into $(3)$ gives
$$
\frac{1}{2} \lVert a \rVert \cos(\theta)
\left(\frac{25}{3}\right)^2 \tan^2(\theta) = 25 \iff \\
25 \lVert a \rVert \sin^2(\theta) = 18 \cos(\theta) \quad (4)
$$
To limit the solutions we should note that $\theta \in (0, \pi/2)$.
Algebraic Solution
Substituting (see Tangent half-angle formulas)
$$
t = \tan(\theta/2) \\
\sin(t) = \frac{2t}{1+t^2} \\
\cos(t) = \frac{1-t^2}{1+t^2} \\
$$
(note: this $t$ is not the time $t$ from further above, but just used for this intermediate calculation of $\theta$ from equation $(4)$) we get
$$
25 \lVert a \rVert \left(\frac{2t}{1+t^2} \right)^2
= 18 \frac{1-t^2}{1+t^2} \iff \\
25 \lVert a \rVert 4t^2 = 18(1-t^2)(1+t^2) = 18(1-t^4) \\
t^4 + \frac{50}{9} \lVert a \rVert t^2 - 1 = 0 \quad (5)
$$
Introducing $s = t^2$ we get
$$
s^2 + \frac{50}{9} \lVert a \rVert s - 1 = 0 \quad (6)
$$
which has the solutions
$$
s = \frac{\pm \sqrt{81+25^2 \lVert a \rVert^2}-25\lVert a \rVert}{9}
$$
we discard the negative solution and apply $25 \lVert a \rVert = 11$ and get
$$
s = \frac{\sqrt{202} - 11}{9} \\
t = \frac{\sqrt{\sqrt{202}-11}}{3} \\
\theta = 2 \arctan{\frac{\sqrt{\sqrt{202}-11}}{3}} \approx 1.0771 \approx 61.714^\circ
$$
Inserting in equation $(1)$ gives
$$
t \approx (25/3) \tan(1.0771) \approx 15.485 \, \text{s}
$$
Comment: The t I calculated above using the 3t = 1/2at^2, since the set distance is equal. So I have to solve for θ but I don't see how I would work to solve it, using tangent wouldn't work even though the tangent vector refers to the angle complementary to the angle of reference, so subtracting it from 90 should work, but for some reason it doesn't.
Comment: Simplifying that down you get cos θ/sin^2 θ = 50a / 36. Since a = 0.44 multiple 50 by that, divide by 36, and you get Is that correct? 0.611.
Comment: @Sal I guess I am done.
Answer: How can there be an angle between an acceleration and the $y$-axis? I suppose you mean there is an angle between the line along which particle $B$ moves and the $y$-axis.
In order for $B$ to collide with $A$, it has to move farther than $A$ does, because $B$ travels the entire hypotenuse of a right triangle
while $A$ travels just one leg of that triangle.
So your first equation for $t$ is wrong:
the time of collision, $0.5 \cdot 0.44 \cdot t^2 > 3t$;
the two are not equal.
The ratio of the distance traveled by $A$ to the distance
traveled by $B$ is just the sine of the angle $\theta$
(in fact it is practically the definition of $\sin(\theta)$).
The correct equation is
$$
3t = (0.5 \cdot 0.44 \cdot t^2) \sin(\theta).
$$
This is not enough information to solve the problem.
But you can also use the fact that the other leg of the right triangle
has length $25$, that is,
$$
25 = (0.5 \cdot 0.44 \cdot t^2) \cos(\theta).
$$
This gives you two equations in two unknowns. They are not the easiest
equations to solve simultaneously, but they are solvable.
Wolfram Alpha gives four solutions, only one of which has a
positive real value of $t$; in that solution, $t > 15$,
and the angle is about $62$ degrees.