How can I use Guzzle to send a POST request in JSON?

Question: Does anybody know the correct way to post JSON using Guzzle?
$request = $this->client->post(self::URL_REGISTER,array(
                'content-type' => 'application/json'
        ),array(json_encode($_POST)));

I get an internal server error response from the server. It works using Chrome Postman.
Comment: Request seems ok... have you checked the content of $_POST to be sure that you really get the values before encoding them ? : var_dump($_POST)
Comment: According to docs now, you can just use what @davykiash said, `'json' => $data`: https://stackoverflow.com/a/44154428/842768
Answer: For Guzzle 5, 6 and 7 you do it like this:
use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'] // or 'json' => [...]
]);

Docs
Comment: This is the right way to do ([official example here](http://docs.guzzlephp.org/en/latest/request-options.html#json))
Comment: It's recommended to use `RequestOptions` constants for the options array keys (`GuzzleHttp\RequestOptions::JSON` in this case) - it makes typos easier to detect as they suddenly become notices instead of just silent bugs waiting to cause trouble.
Comment: @MichalGallovic It is the same. The purpose to use the constant is to avoid typos. Using a constant that does not exists will raise an error, but sending a useless option (as `jsson` for example) won't raise any error, and you may take some time to find your typo.
Comment: I was looking around for an hour for this answer. Why is this not in the documentation (especially the quick setup guide)? Crazy!?!
Comment: @giovannipds GuzzleHttp\RequestOptions::JSON is an alias to 'json', either is fine.
Comment: According to [doc](http://docs.guzzlephp.org/en/latest/quickstart.html#sending-requests) magic methods can be used. So `post()` should work.
Comment: @ksadowski Can you share docs with this info ? In https://github.com/guzzle/guzzle/blob/master/src/RequestOptions.php#L140 RequestOptions::JSON is a constant with "json" - so it should be the same.
Comment: According to docs now, you can just use what @davykiash said, `'json' => $data`: https://stackoverflow.com/a/44154428/842768
Comment: @Tebe tried with Guzzle ^6.3 and it works with json string as well as constant.
Comment: just replaced library, much less hasssles , recommending this https://github.com/rmccue/Requests   . what e mess it should be  if sending simple post request take s a whole discussion
Comment: When using a client supplied by Google APIs the `'json' => $data` syntax did not work for me.
 But the `GuzzleHTTP\RequestOptions::JSON` syntax worked as expected.
Comment: how would we handle actual list values in json , in this case
Answer: The simple and basic way (guzzle6):
$client = new Client([
    'headers' => [ 'Content-Type' => 'application/json' ]
]);

$response = $client->post('http://api.com/CheckItOutNow',
    ['body' => json_encode(
        [
            'hello' => 'World'
        ]
    )]
);

To get the response status code and the content of the body I did this:
echo '
' . var_export($response->getStatusCode(), true) . '
';
echo '
' . var_export($response->getBody()->getContents(), true) . '
';

Comment: This is really one simple and easy way. Solved my problem about setting body and headers. Thanks very much
Comment: This answer works for me when the accepted answer doesn't.
Comment: I used a variation of this. I created the `Client` by itself and added the headers to the `$client->post()` call instead.
Answer: For Guzzle <= 4:
It's a raw post request so putting the JSON in the body solved the problem
$request = $this->client->post(
    $url,
    [
        'content-type' => 'application/json'
    ],
);
$request->setBody($data); #set body!
$response = $request->send();

Comment: This no longer works with GuzzleHttp. @Charlie has the right answer
Comment: If you want to set the content type header in Guzzle 6, you can do it like this: `$client->post($url, ['body' => $string, 'headers' => ['Content-type' => 'application/json']]);`
Comment: I think we just need to specify the version of Guzzle in the question.
Comment: I have tried this with Guzzle3 is not working even if it is the way mentionned in the doc : https://guzzle3.readthedocs.io/http-client/request.html?highlight=raw#raw-post-data  , it's been 2 days I am trying to solve this pb but in vain
Comment: According to docs now, you can just use what @davykiash said, `'json' => $data`: https://stackoverflow.com/a/44154428/842768
Answer: This worked for me (using Guzzle 6)
$client = new Client();
$result = $client->post('http://api.example.com', [
            'json' => [
                'value_1' => 'number1',
                'Value_group' =>
                             array("value_2" => "number2",
                                    "value_3" => "number3")
                    ]
                ]);

echo($result->getBody()->getContents());

Answer: $client = new \GuzzleHttp\Client();

$body['grant_type'] = "client_credentials";
$body['client_id'] = $this->client_id;
$body['client_secret'] = $this->client_secret;

$res = $client->post($url, [ 'body' => json_encode($body) ]);

$code = $res->getStatusCode();
$result = $res->json();

Comment: Does this also set the correct header? I think `['json' => $body]` is the better way here, as mentioned by Michael's answer.
Comment: `$res->json();` only works in Guzzle 5.3. It's been removed in v6.
Comment: David is correct. This is because of PSR-7 implementation. Use `json_decode()` instead.
Comment: this will not work when you have to send headers, f.e. authorization tokens for git. you have to instantiate a Request object and use the send or request function
Answer: You can either using hardcoded json attribute as key, or you can conveniently using GuzzleHttp\RequestOptions::JSON constant.
Here is the example of using hardcoded json string.
use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    'json' => ['foo' => 'bar']
]);

See Docs.
Answer: $client = new \GuzzleHttp\Client(['base_uri' => 'http://example.com/api']);

$response = $client->post('/save', [
    'json' => [
        'name' => 'John Doe'
    ]
]);

return $response->getBody();

Answer: This works for me with Guzzle 6.2 :
$gClient =  new \GuzzleHttp\Client(['base_uri' => 'www.foo.bar']);
$res = $gClient->post('ws/endpoint',
                            array(
                                'headers'=>array('Content-Type'=>'application/json'),
                                'json'=>array('someData'=>'xxxxx','moreData'=>'zzzzzzz')
                                )
                    );

According to the documentation guzzle do the json_encode
Answer: Solution for $client->request('POST',...
For those who are using $client->request this is how you create a JSON request:
$client = new Client();
$res = $client->request('POST', "https://some-url.com/api", [
    'json' => [
        'paramaterName' => "parameterValue",
        'paramaterName2' => "parameterValue2",
    ]
    'headers' => [
    'Content-Type' => 'application/json',
    ]
]);

Guzzle JSON Request Reference
Answer: Php Version: 5.6
Symfony version: 2.3
Guzzle: 5.0
I had an experience recently about sending json with Guzzle. I use Symfony 2.3 so my guzzle version can be a little older.
I will also show how to use debug mode and you can see the request before sending it,
When i made the request as shown below got the successfull response;
use GuzzleHttp\Client;

$headers = [
        'Authorization' => 'Bearer ' . $token,
        'Accept'        => 'application/json',
        "Content-Type"  => "application/json"
    ];

    $body = json_encode($requestBody);

    $client = new Client();

    $client->setDefaultOption('headers', $headers);
    $client->setDefaultOption('verify', false);
    $client->setDefaultOption('debug', true);

    $response = $client->post($endPoint, array('body'=> $body));

    dump($response->getBody()->getContents());

Answer: @user3379466 is correct, but here I rewrite in full:
-package that you need:

 "require": {
    "php"  : ">=5.3.9",
    "guzzlehttp/guzzle": "^3.8"
},

-php code (Digest is a type so pick different type if you need to, i have to include api server for authentication in this paragraph, some does not need to authenticate. If you use json you will need to replace any text 'xml' with 'json' and the data below should be a json string too):

$client = new Client('https://api.yourbaseapiserver.com/incidents.xml', array('version' => 'v1.3', 'request.options' => array('headers' => array('Accept' => 'application/vnd.yourbaseapiserver.v1.1+xml', 'Content-Type' => 'text/xml'), 'auth' => array('email@example.com', 'password', 'Digest'),)));

$url          = "https://api.yourbaseapiserver.com/incidents.xml";

$data = '<incident>
<name>Incident Title2a</name>
<priority>Medium</priority>
<requester><email>firstname.lastname@example.com</email></requester>
<description>description2a</description>
</incident>';

    $request = $client->post($url, array('content-type' => 'application/xml',));

    $request->setBody($data); #set body! this is body of request object and not a body field in the header section so don't be confused.

    $response = $request->send(); #you must do send() method!
    echo $response->getBody(); #you should see the response body from the server on success
    die;

--- Solution for * Guzzle 6 * ---
-package that you need:
 "require": {
    "php"  : ">=5.5.0",
    "guzzlehttp/guzzle": "~6.0"
},

$client = new Client([
                             // Base URI is used with relative requests
                             'base_uri' => 'https://api.compay.com/',
                             // You can set any number of default request options.
                             'timeout'  => 3.0,
                             'auth'     => array('email@example.com', 'dsfddfdfpassword', 'Digest'),
                             'headers' => array('Accept'        => 'application/vnd.comay.v1.1+xml',
                                                'Content-Type'  => 'text/xml'),
                         ]);

$url = "https://api.compay.com/cases.xml";
    $data string variable is defined same as above.

    // Provide the body as a string.
    $r = $client->request('POST', $url, [
        'body' => $data
    ]);

    echo $r->getBody();
    die;

Comment: Thank you. Could not find any guzzle3 solution anywhere else for legacy php5.3 projects, would like to see it line-break'd like your guzzle6 aswell since it would have saved me alot of time.
Answer: Simply use this it will work
   $auth = base64_encode('user:'.config('mailchimp.api_key'));
    //API URL
    $urll = "https://".config('mailchimp.data_center').".api.mailchimp.com/3.0/batches";
    //API authentication Header
    $headers = array(
        'Accept'     => 'application/json',
        'Authorization' => 'Basic '.$auth
    );
    $client = new Client();
    $req_Memeber = new Request('POST', $urll, $headers, $userlist);
    // promise
    $promise = $client->sendAsync($req_Memeber)->then(function ($res){
            echo "Synched";
        });
      $promise->wait();

Answer: I use the following code that works very reliably.
The JSON data is passed in the parameter $request, and the specific request type passed in the variable $searchType.
The code includes a trap to detect and report an unsuccessful or invalid call which will then return false.
If the call is sucessful then json_decode ($result->getBody(), $return=true) returns an array of the results.
    public function callAPI($request, $searchType) {
    $guzzleClient = new GuzzleHttp\Client(["base_uri" => "https://example.com"]);

    try {
        $result = $guzzleClient->post( $searchType, ["json" => $request]);
    } catch (Exception $e) {
        $error = $e->getMessage();
        $error .= '
'.print_r($request, $return=true).'
';
        $error .= 'No returnable data';
        Event::logError(__LINE__, __FILE__, $error);
        return false;
    }
    return json_decode($result->getBody(), $return=true);
}

Comment: that json option is super handy
Answer: The answer from @user3379466 can be made to work by setting $data as follows:
$data = "{'some_key' : 'some_value'}";

What our project needed was to insert a variable into an array inside the json string, which I did as follows (in case this helps anyone):
$data = "{\"collection\" : [$existing_variable]}";

So with $existing_variable being, say, 90210, you get:
echo $data;
//{"collection" : [90210]}

Also worth noting is that you might want to also set the 'Accept' => 'application/json' as well in case the endpoint you're hitting cares about that kind of thing.
Comment: Just a heads up... you can simplify your `$data` by using `json_encode`: `$data = json_encode(array('collection' => $existing_variable));`
Answer: Above answers did not worked for me somehow. But this works fine for me.
 $client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']);

 $request = $client->post($base_url, array('content-type' => 'application/json'), json_encode($appUrl['query']));


Inserindo Itens em uma collection Vb6

Question: Bom dia pessoal, .
A circunstancia é a seguinte. eu criei um Type e o mesmo tem seus atributos.
Gostaria de saber como eu faço para inserir dados em um collection(no Vb6).
POR EXEMPLO: criei o Type Pessoa q tem atributo de nome e sobrenome, agora preciso criar uma coleção desse type.
Answer: Uma coleção em VB6 / VBA é do tipo Colletion e aceita qualquer objeto de referencia, uma maneira de fazer isso é no Módulo ou na sua Classe ter uma propriedade que consuma sua coleção para esse tipo específico.
Por ex:
<code>Private Pessoas_ As New Colletion

Private Sub PopulaPessoas()
      Dim Pessoa1 As MeuTipoPessoa
      Dim Pessoa2 As MeuTipoPessoa
      Dim Pessoa3 As MeuTipoPessoa

      Pessoas_.Add(Pessoa1)
      Pessoas_.Add(Pessoa2)
      Pessoas_.Add(Pessoa3)
End Sub

Public Property Get Professores() As Colletion
    Dim oPessoa As MeuTipoPessoa
    Dim oColecaoRetorno As New Colletion

    For Each oPessoa In Pessoas_
        If (oPessoa.EhProfessor) Then
            oColecaoRetorno.Add(oPessoa)
        End If
    Next
    Set Professores = oColecaoRetorno
End Property
</code>

Inserindo Itens em uma collection Vb6


$T(n)=T(cn) + T((1-c)n)+1$ while $0<c<1$

Question: Question:
$T(n)=T(cn) + T((1-c)n)+1$
$0<c<1$ and $T(1)$ is constant.
My thoughts:
I'm trying to solve this recursion using Induction, but I think I got it all wrong.
My guess is that $T(n) = O(n)$
The induction assumption:
for every $k<n$ exists a constant $m$ that $T(k) < mn $
because $0<c<1$ we know that $cn<n$ and $(1-c)n<n$
Therefore $T(cn)<mn$ and $T((1-c)n)<mn$
I need to prove that $T(n)<mn$
so I said that $T(n) = T(cn) + T((1-c)n)+1 < mn +mn +1 = 2mn+1$
But now my constant has changed to $m'=2m$
which is a problem...
what can I do?
I hadn't studied any fancy sentences..
I can use induction, recursion trees or something simple...
any help would be highly appreciated! Thanks
Answer: If $T(n)=T(cn) + T((1-c)n)+1$ then let $S(n)={T(n)+1}$.
You have $S(n)=S(cn) + S((1-c)n)$ or equivalently $S(a+b)=S(a)+S(b)$, with the linear solution $S(n)=nS(1)$.
So $T(n)+1=n(T(1)+1)$, i.e. $$T(n)=nT(1)+n-1$$ which is indeed $O(n)$
Answer: By Archimedean principle, $\exists M\in \mathbb{Z}$ such that $(M-2m)n>1\Rightarrow T(n)<Mn$. So, $T(n)=O(n)$.

Let, for $k<n$, $T(n)<m_k n$ for some $m_k$. Then, since both $cn,\ (1-c)n$ are $<n$, $T(n)=T(cn)+T((1-c)n)+1<(m_1+m_2)n+1<m_3n$ for some $m_1,m_2,m_3$.
Comment: The thing is I can't change the constant in the middle of the proof. if I declared it to be m it should stay m until I finish the proof.
That's the whole problem...
Comment: You declared it $m\ \forall k<n$, so you can have some different constant for $n$, what's the problem in that?
Comment: Actually you can use different constants for different $k$.


For each dimension $k=0, 1, ..., 12$, find the number of distinct cyclic codes $C\subset \mathbb{Z}_{13}^{12}$ of dimension $k$.

Question:
For each dimension $k=0, 1, ..., 12$, find the number of distinct cyclic codes $C\subset \mathbb{Z}_{13}^{12}$ of dimension $k$.

Currently, I'm factoring $x^{12}-1$ over $\mathbb{Z}_{13}$ and got $x^{12}-1=(x-1)(x+1)(x-3)(x+3)(x-4)(x+4)(x-2)(x^5+2x^4+4x^3+5x^2+3x+6)$. However, since this factorization and computation are tedious, I'm not sure if this factorization is correct.
Also, after finding all factors of this polynomial, how should I proceed? If the above factorization is correct, this means that we can create a generator polynomial of degree k for all $k=0, 1, ..., 12$. This seems weird.
Comment: Maybe you should give some thought to the fact that $\mathbb Z_{13}$ is actually the finite field $\mathbb F_{13}$ whose nonzero elements are the _field integers_ $1,2,3,4,5,6,7,8,9,10,11,12$ and so $x^{12}-1$ factors into $\prod_{k=1}^{12}(x-k)$
Answer: (Answering since I can't comment yet.) What does Fermat's little theorem tell you about the roots of $ x^{12}-1$? When you are done factoring, it should be easy to count how many generator polynomials you have of any given degree... which is what you want to do.


Why memory and disk space utilization needs additional agent to be installed to get stats in GCP?

Question:
As you can see in the above picture, monitoring agent has to be installed to get memory utilization and disk space utilization, while CPU utilization and disk throughput do not need the agent.
Why is that? Cannot GCP gets memory utilization using the same method or tool that gets CPU utilization?
Answer: It's a matter of security and privacy. you can see the VM like a box. Google can see all the information outside of this box: Network throughput, disk throughput and CPU usage (number of cycle in fact).
But the content of the box is forbidden. You need to allow Google to look into the memory (what you use means check what you have write in it and thus get a read access to the memory. Potentially read more than only what is used and what is empty, and thus you need to autorize Google to do that). Same thing for the disk utilization.


Chamar método dentro de um getter

Question: É boa prática chamar um método qualquer dentro de um getter?
Exemplo:
public final class ScannerDeHtm {

    private static final String DIR_CEF = DefineDiretorio.getDiretorio() + "CEF";
    private static List<String> listaHtmFile;
    private static List<Jogo> listaJogos;

    private ScannerDeHtm() {}

    private static void scanHtmFile() throws IOException {

        List<String> listaSorteios;

        File arquivoHtm = new File(DIR_CEF + File.separator + "d_megasc.htm");

        try {
            Scanner scanner = new Scanner(arquivoHtm.toPath());

            // ...
        }
    }

    public static List<Jogo> getListaJogos() {

        try {
            scanHtmFile();       // é boa prática?
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (listaJogos != null) {
            return new ArrayList<>(listaJogos);
        }
        return new ArrayList<>();
    }
}

A outra forma seria inserir o método scanHtmFile() no construtor dessa classe, ou torná-lo público e chamar de forma estática quando for usar..
Mas continuo preferindo:
lista = ScannerDeHtm.getListaJogos();

a
ScannerDeHtm scan = new ScannerDeHtm();
lista = scan.getListaJogos();

E aí, o que acham?
Edit:
Vale salientar que essa Classe em questão só existe para retornar um List com os jogos e ela será muito utilizada nesse programa.
Comment: eu acho totalmente valido o que voce fez no metodo `getListaJogos()` ate por que se você quiser retornar algo diferente com base na lista de jogos, talvez um filtro, ou algo assim, você nao precisar rescrever o scan de HTML. Sem contar que eu acho mais organizado cada metodo fazendo um pedacinho do processo.
Answer: Métodos get tem um único propósito: devolver valores. Eles não podem ser responsáveis por nenhum processamento mais complexo do que apenas devolver um valor. Como o scanHtmFile é um método que inicializa um atributo da classe, o ideal seria colocá-lo no construtor que possui esse papel de inicializador dos atributos. Assim, o get seria chamado apenas para devolver o valor inicializado. Ficaria da seguinte forma:
public ScannerDeHtm() {
    try {
        listaJogos = scanHtmFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static List<Jogo> getListaJogos() {
    return listaJogos;
}

A respeito do atributo listaJogos ser estático ou não você precisa responder a seguinte pergunta: O atributo pertence à classe ou ao objeto?
Se o seu valor for igual para a classe, ele deverá ser estático, caso contrário ele não pode ser estático pois seu estado vai variar entre os objetos criados dessa classe.

Chamar método dentro de um getter


Access 2013 + Source Control (Team Foundation Server) workflow

Question: Since Access 2013 is not any longer offering direct source control compatibility: how is your workflow to integrate a source code control into MS Access, especially TFS?
Edit: workflow of access2013 -> ANY source code system appreciated
First thing I think of is exporting all objects into Text Files withe the builtin function SaveAsText which is available for almost every item in your database.
<code> Application.SaveAsText acModule, d.Name, sExportLocation & "Module_" & d.Name & ".txt"
</code>
I would load, save and maybe even check the plain files in with VBA functions. The question is: is there a better workflow for this task... I really doubt that this is the best way to integrate Access 2013 projects in Sorce control.
I heard of OASIS SVN but I think this is basically the same mechanism I would use.
Please tell me how you manage your access projects
Comment: Did you try TFS2013 MSSCCI Provider?
Comment: this would work for Access 2010 but not for 2013. Source Code Control is not available as an add-in for Access 2013.
https://support.office.com/en-za/article/Discontinued-features-and-modified-functionality-in-Access-2013-bc006fc3-5b48-499e-8c7d-9a2dfef68e2f
Comment: There is none...  Access isn't meant to be used as an application platform anymore I suspect... Tools like Lightswitch on top of SQL (localdb) have replaced it. https://msdn.microsoft.com/en-us/vstudio/lightswitch.aspx
Comment: Or keep using Access 2007 or 2010 in combination with the MSSCCI provider.
Comment: That is kind of sad. Microsoft encourages and even forces you to upgrade to the newest software product (for example if you are in the "partner benefits" program) but this seems to be a dead end if there`s no source code control support
Comment: Maybe you would like to take a look at [entAscc](http://www.entascc.com). It is an add-in for MS Access that aims to provide the same functionality as the Microsoft SCC Add-In, but works with Access 2013. It is still in private beta at the moment. Reputable SO users can certainly join the beta programm, if they email the address on the website.
(Disclosure: I am the owner of entAscc.)
Answer: I use OASIS-SVN here to export all objects in my access database file to be text files.
I then use git, souretree,  etc...
It has worked well for me and has a number of settings that are useful  (eg you can choose to export data, to export table links etc)
It is not ideal, but is manageable and better than nothing!
As you might expect, I use a git project and separate local directory for every access file.
Another option that is recently on the market can be found here  "entAscc" now known as Ivercy!
This looks very promising as the source control is integrated into the development environment.  I've not used it, but would like to!
Comment: What disturbs me is that OASIS SVN uses the same mechanism as I described above. Is there any way to automatically inform other developers about changes and is it possible to lock files (so different developers can`t alter the same module in access)?
Comment: After posting last night I found this: http://www.ivercy.com/  I've added it to my answer.  It looks pretty good.
Comment: OASIS-SVN does not support locking and informing, but ivercy.com does.
Comment: looks promising.. I´ll give it a try and if it does well I´ll accept your answer because there really seems to be nothing better out there
Comment: God!  You have to work so hard for an answer sometimes!  let me know how you get on.
Comment: PS.  Also check out these:   https://www.arrow-of-time.com/AXF.aspx        and    http://www.codevba.com/   I've used the latter.  The former looks AmAzing!
Comment: Couldn`t get ivercy working for TFS only for my (also installed) older sourcesafe.. anyway I think it depends on the scenario you have. Just include the two other options mentioned and I think we have a good overview of the source control addin alternatives on the current market
Comment: A agree.  Shame it didn't work.  Did you take a look at codeVBA?  it's nice (but a bit pricey)
Comment: not yet, will give it a try maybe next week though. Thx again!
Comment: @MarcWittmann: Ivercy works with TFS. Here is a getting started guide: http://www.ivercy.com/Support/docitem/getting-started-ivercy-team-foundation-server-ms-access . Our support will be pleased to assist you.
Comment: @HarveyFrench: AXF and CodeVBA look very interesting, but they both don't seem to have any integration of source code control. Am I missing something?


Assigning variance in regression

Question: Say we have a linear regression model $$y_t = \mathbf{x}_t'\boldsymbol{\beta} + \epsilon_t, \qquad \epsilon_t \sim \mathcal{N}(0, \sigma^2)$$
Assuming $\boldsymbol{\beta}$ is random and that $\mathbf{x}_t$ is given, the variance of $y_t$ is given by $$\mbox{var}(y_t) = \boldsymbol{x}_t'\mbox{cov}(\boldsymbol{\beta})\boldsymbol{x}_t + \sigma^2$$
how do we know how much of the variance is purely random (from $\sigma^2$) and how much of it is due to variance in the regression coefficients $\boldsymbol{\beta}$? For example, if we estimate the variance of $y_t$ by the empirical variance $\hat{\mbox{var}}(y_t) = (1/T)\sum_{t=1}^T(y_t - \bar{y})^2$, how do we know how much of that number came from $\sigma^2$ and how much of it came from the variance of $\boldsymbol{\beta}$?
Answer: The question does not make much sense in that

the variance of $y_t$ depends on $\mathbf{x}_t$, hence estimating it by $$(1/T)\sum_{t=1}^T(y_t - \bar{y})^2$$does not return the variance of $y_t$;
in most linear regression settings, there is only one observation of $Y_t$ for a given $\mathbf{x}_t$. It is therefore impossible to estimate the variance of $y_t$ directly from $y_t$;
despite the fact that the variance of $y_t$ decomposes as indicated when $\beta$ is random, the part $\sigma^2$ of this variance can be consistently estimated.

Assigning variance in regression


block_admin_display_form_submit not getting called

Question: I am having trouble saving my block regions(admin/structure/blocks).
Problem:
I am doing my thing on block admin page, saving blocks, moving them around and what not. but the changes i make are not being saved.
What i found: after some debugging efforts, i figure out that the function *block_admin_display_form_submit* is not called when the block form submits.
the site i am having problem is on a lamp server somewhere. i have another copy of this site on my local machine, which has no problem saving block regions.
any idea on how to fix this? thank you.
Answer: I'm having the same issue, I cannot call function block_admin_display_form_submit($form, &$form_state).
I've set a custom variable that should be updated if I change block region.
Everything works if I do it from the block edit page(admin/structure/block/manage/menu_block/ID/configure), but if I try to do it in the block admin display form (admin/structure/block), It will not work.
I've tried to increase max_input_vars with no success.
Have you solved it?
Comment: i fixed it by increasing max_input_vars.
Comment: I've managed to make it work. I was not calling the function in the proper way. Btw, I had already increased max_input_vars previously and I have tried to decrease it yet. I will let you know. Thanks
Comment: I can confirm it. It works without max_input_vars incresed. It's an Ubuntu server 12.04. In my php.ini I've got - ;max_input_vars=1000.


Passing reference of reference to function argument (book v1)

Question: In short, does passing reference A of another reference B to function parameter causing automatic dereference?
Here's the story...
When reading stack & heap - complex example, I am confused at the following explanation, please see img01 -> img02.
Since variable e is a reference to variable d, so the value of e is represented in -> 9 (i read it as: go to memory address of d), this is ok.
But why does the parameter f of baz get value of "data address referred by d", instead of the value of e? I thought the value of f should be -> 9 as well?
If f is what img02 says it is, then does it mean that "dereference" happened here automatically? Since e contains a reference to d, d contains a reference to some heap address, and the passing of e to f results in f has a reference to the heap address?
img01

img02
Comment: Maybe because f is declared as &i32 and the compiler is enable to silentlly cast &&i32 (type of e)  to &i32.
Comment: @JoëlHecht i think your comment makes sense, but this brings up another question; as far as i know, Box type is owned by d, and represented as "->(2^30) -2" in img02. So if f has the same value of "->(2^30) -2", than it looks like the same Box is owned by 2 variables?
Comment: [Please do not upload images of code/errors when asking a question.](//meta.stackoverflow.com/q/285551)
Answer: Yes, a dereference is done automatically. This is called Deref coercion.
This is the mechanism that allows for implicitly converting one reference to another. Some notable uses:

&&T -> &T
&&&&&&&&T -> &T
&Box<T> -> &T
&Vec<T> -> &[T]

See more explanation in the Rust book: Treating Smart Pointers Like Regular References with the Deref Trait or in the Rust reference: Type Coercions.
Comment: thanks @kmdreko, i think `&Box<32> -> &i32` explains the case of `e -> f` in my question.


How can I group text questions that are similar to each other?

Question: I have a dataset of 200k questions, and I would like to group them together by similarity/duplicates.
How can I use NLP/machine learning to group these questions with similar intents together?
Given a question and a list of questions, how can I find the question or questions that are similar or duplicates?
Are there any services that can do this?
Answer: Generally, you'd want to convert the questions into a abstract numerical format (such as a single high-dimensional vector, or 'bags of words/vectors'), from which it is then possible to calculate numerical pairwise similarities between questions.
For example: you could turn each question into a simple average of the word-vectors for its individual words. (Those word-vectors might come from your own training corpus, that matches the questions' usage domain exactly, or from some other outside source that's good enough.)
If the word-vectors are 300-dimensional, averaging all the words-vectors of a question together then gives you a 300-dimensional vector for the question. You can then use a typical measure of vector-similarity, such as "cosine similarity", to get a number from -1.0 to 1.0 for each pair of questions, with larger values indicating "more similar".
Such a simple approach is often a good baseline. Being smarter about dropping some words, or weighting words by their observed significance (eg by "TF/IDF" weighting) may improve it.
But there are other ways to get summary vectors that may work better than a simple average. One relatively straightforward algorithm, largely similar to the way word-vectors are created, is called "Paragraph Vectors", and is sometimes called in popular libraries (like Python gensim) "Doc2Vec". It's not quite a simple average of word-vectors, as much as creating a synthetic word-like token for a full text, which then is trained to be as good as possible at predicting the text's words. Again, once you have a (for example) 300-dimensional text-vector, calculating cosine-similarity can rank question similarities.
There's also an interesting algorithm called "Word Mover's Distance", which leaves the texts as variable-sized bags of each constituent word-vector, as if each word-vector was a pile-of-meaning. It then calculates the "effort" to move the piles from one text's shape-of-piles, to another text's – and less effort seems to correlate well with humans' sense of text similarity. (However, finding these minimal-shifts is a lot more computationally expensive than simple cosine-similarity – so this works best with short texts, or small corpuses, or when you can massively parallelize the computation.)
Once you have any of these numeric-similarity measures working, then you can also clustering algorithms to find groups of highly-related questions – and often once you have those groups, the most-common words in those groups (as opposed to others), or human editorial work, can name the groups.


laravel constructor redirect

Question: I have a method for checking if a user's role is an admin, if not, redirect them with return redirect('/')->send();. How can I check for user role and redirect the user without displaying the page and waiting for a redirect?
My Controller:
class AdminController extends Controller
{
    public function __construct()
    {
        if (Auth::check())
        {
            $user = Auth::user();
            if ($user->role != 'admin')
            {
                return redirect('/')->send();
            }
        }
        else
        {
            return redirect('/')->send();
        }
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return View('admin/index');
    }
}

Answer: Create your own Middleware. Here is an example. In my example, I have several usergroups in a separate model. You have to change the code for your needs.
Create the Middleware via terminal/console:
php artisan make:middleware UserGroupMiddleware

The created middleware class could be find in app/Http/Middleware/UserGroupMiddleware.php
You need the following code in your middleware:
namespace App\Http\Middleware;

use Closure;
use App\User;
use App\Usergroup;

class UserGroupMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $group)
    {
        if($request->user() !== NULL){
            $userGroupId = $request->user()->group;
            $userGroup = Usergroup::find($userGroupId);

            if($userGroup->slug === $group){
                return $next($request);
            }
        }
        // Redirect the user to the loginpage
        return redirect('/login');
    }
}

Now you have to register this middleware in app/Http/Kernel.php:
protected $routeMiddleware = [
    // other middlewares

    // Custom Middleware
    'group' => \App\Http\Middleware\UserGroupMiddleware::class
];

Finally you need to attach the middleware to your route:
Route::group(['middleware' => 'group:admin'], function(){
    // Routes for admins, e.g.
    Route::get('/dashboard', 'SomeController@dashboard');
});

// Or for a single route:
Route::get('/dashboard', ['middleware' => 'group:admin'], function(){
    return view('adminbereich.dashboard');
});

Remember, that you could pass in multiple middlewares with:
Route::get('/some/route', ['middleware' => ['group:admin', 'auth']], 'SomeController@methodXYZ');

Answer: import redirect by adding this to the above the class
use Illuminate\Support\Facades\Redirect;
And the make your redirect by using
return Redirect::to('login');

laravel constructor redirect


Send Html with ajax wrong Css structure

Question: i´am trying to send with ajax an html site, but on the server side, the structure of the css is damaged.
My getInfo function return a variable with a html text how looks like this

center<button style="margin-left: 109px; margin-top: -9px; position: absolute;">juhu</button>

this variable, i send with ajax to my php page:
$.ajax({
url:"createFile.php",
type:"post",
dataType:"text",
data:getInfo()
});

but on the server site(the php page) the value of the post variable is this:

center<button absolute;\"="" position:="" -9px;="" margin-top:="" 109px;="" style="\"margin-left:" xmlns="\"http://www.w3.org/1999/xhtml\"">juhu</button>

What is wrong?
Thanks
Answer: If I am not mistaken, this should work:
$.ajax({
url:"createFile.php",
type:"post",
dataType:"html",
processData:false,
data:getInfo()
});

Answer: The problem was the backslash´s. I thing jquery add a backslash on every " " ".
The solution was the "stripslashes" function on the php server-site.

Send Html with ajax wrong Css structure


How to detect highlighted  in a drop-down menue?

Question: I'm looking for a solution beside mouseover so the detection is also effective with arrow up/down button.
Comment: Just to clarify: are you asking about `` element or some custom implementation?
Comment: That's right. I probably need to edit the question to make that clear.
Comment: Would `onfocus` work?
Answer: you can use the change event - http://api.jquery.com/change/ which will be triggered when the selected value changes
<code>$("select").change(function (){});
</code>
Comment: Change only works when the selection is complete. I need to detect the state before that when user is just browsing the options with up and down key or hover.


What is an optimal way to model inheritance in a database with mostly static data?

Question: I'm modelling a role-playing game and need to create the database schema for equipment. The data will be mostly static.
This article discusses three ways to model inheritance in a database: Table per Class Hierarchy, Table per Subclass, and Table per Concrete Class. Of the three, which would you recommend?
I did a sample Entity Framework 4.2 code-first solution to see what it came up with and it used the "Table per Class Hierarchy" method.
Here are the (simplified) classes:
<code>public class Gear {
    public int GearID { get; set; }
    public string Name { get; set; }
}

public class Armor : Gear {
    public int Kinetic { get; set; }
    public int Energy { get; set; }
}

public class Weapon : Gear {
    public int Damage { get; set; }
    public int Range { get; set; }
}
</code>
Answer: everything has a tradeoff.  You need to pick the approach best for you.  The downside of per call hierarchy is that the table needs to have all the fields that are on any subclasses,  which could mean that some rows in the table are taking up more space than necessary because they don't have some fields.  Also, you need a way to discriminate between which type of class to hydrate when loading rows.
On the other hand, per class hierarchy is pretty simple to implement.  The other strategies become more attractive the more divergent the data between subclasses is.
Comment: I decided to go with table-per-subclass. I have too many different types of subclasses to make table-per-class-hierarchy attractive. I used [this guide](http://www.robbagby.com/entity-framework/entity-framework-modeling-table-per-type-inheritance/) as a starting point.
Answer: You could do name value pairings. Have a table of Gear that has id, name, Attribute1Name, and Attribute1Value. Have as many name/value columns as you need.
So if you were storing an Armor item Attribute1Name would be Kinetic and Attribute1Value would be the value of Kenetic. Attribute2Name would be Energy and Attribute2Value would be the value of Energy.


Use of Complex Numbers in Statistics

Question: I was asked recently if complex numbers were used in Statistics by a friend of mine who is an electrical engineer.  Besides statistical applications in other fields (e.g. quantum mechanics) and besides some  characteristic functions, I couldn't really identity many any off the top of my head.  I'm curious if anyone else can identity uses of complex numbers in statistics, outside of applications in other fields.
Comment: 1) Fourier transforms/spectral analysis in time series, 2) characteristic functions, 3) sometimes contour integration used in distribution theory, ... ?  https://www.quora.com/Does-complex-analysis-have-applications-in-statistics  ,    https://www.quora.com/Is-Complex-Analysis-relevant-to-Machine-Learning
Comment: The QM applications don't actually use complex numbers for the statistical calculations: all probability amplitudes must be *real* numbers (that's axiomatic).  Complex numbers are required to model interference of waves, but once that is taken care of, *only their amplitudes* are considered for statistical calculations.  This is the thrust of the requirement that all QM operators be Hermitean.
Comment: Thanks, @whuber.  My knowledge of quantum mechanics is about as vast as art history:  virtually 0. ;-)
Comment: Ah, yes! Of course regarding transforms/spectral in time series!  Thanks for this! and the other suggestions too!
Answer: There are two broad classes of use of complex numbers in statistics, one being when the underlying problem uses complex numbers (leading to complex random variables), and the other being when tools using complex numbers are used to describe statistical problems involving only real random variables.  (I will leave aside theories of probability that use complex probabilities - these are pretty crazy and I have never been able to see the use in them.)
Problems involving complex random variables: Complex numbers arise in statistics whenever you are dealing with an underlying problem where the random variables of interest are complex numbers themselves (i.e., complex random variables).  These applications tend to arise in the context of engineering and physics problems where complex numbers are used to describe some phenomena of interest, and we wish to add randomness to the description of that phenomena.  In particular, they often come up in the context of dealing with circular motion that is described by complex numbers, or in electrical circuits.  There is already a substantial statistical literature on this field, including results for complex versions of normal random variables, etc. (for an overview, see e.g., Eriksson et al 2009, Eriksson et al 2010).  (Note: Since your friend is an electrical engineer, it might be worth pointing him to various works published in IEEE that deal with complex random variables.  These are often used in electrical engineering work when the analyst wishes to add randomness to some aspect of an underlying electrical problem that uses complex numbers.)
Another common example of this kind of situation is whenever you have polynomials with randomly generated real coefficients, where the distribution of the coefficients is continuous.  In this case, even though the initial random variables are real, this gives rise to complex roots of the polynomial, so when you write the polynomial in its factorised form, this involves complex random variables (see e.g., Shepp and Vanderbei 1995, Ibragimov and Zeitouni 1997, Kabluchko and Zaporozhets 2014).  This is a simple example where random objects involving real numbers give rise to complex random variables.
Complex tools for dealing with real random variables: The most common set of statistical tools that deal with real random variables, but use complex numbers, are tools that are applications of the Fourier transform to various statistical problems.  This includes the characteristic function used to describe a distribution in Fourier-space,  frequency-space periodograms used for identifying signal frequencies in time-series analysis, and the various spectral densities in time-series analysis.  These are all examples where a standard mathematical tool using complex numbers is applied in a probability problem where the underlying random variables are real numbers.  These methods are often used in time-series analysis, but also crop up sometimes when dealing with tricky probability problems involving convolutions.  (In fact, the simplest proof of the central limit theorem uses the characteristic function of the normal distribution, so it involves the use of complex numbers.)
Comment: Thanks, @Ben.  Tha'ts great.  I'l going to leave the question open for a few days to see if I get some other responses too.  Otherwise, this is a perfectly good answer.  I'll come back in a couple of days to accept.
Comment: Another ide which might be mentioned is analytic function theory which crops up in math stat, for instance in unicity proofs, completeness. Maybe one van do with real analytic functions, but mostly complex is used.

Use of Complex Numbers in Statistics


Array fica vazio fora do escopo da função mesmo estando declarado no escopo global

Question: Estou iniciando no Javascript e no NodeJs e não estou conseguindo entender pq mesmo eu declarando um array no escopo global, quando tento acessá-lo fora das funções em que fiz o map o array vem vazio.
Eu li dois arquivos sem nenhum problema e consigo visualizar o conteúdo pelo console, mas só dentro da função, fora dela o array fica vazio, estou precisando usar os conteúdos deles para criar outro arquivo. O conteúdo dos arrays sigla e nome eu só consigo acessar dentro readFile:
var fs = require("fs");

let sigla = [];
let nome = [];

fs.readFile("Estados.json", "utf8", (err, data) => {
  let states = JSON.parse(data);
  sigla = states.map((state) => {
    const { ID, Sigla, Nome } = state;
    return {
      id: ID,
      sigla: Sigla,
      estadoNome: Nome,
    };
  });
  console.log(sigla);
});

fs.readFile("Cidades.json", "utf8", (err, data) => {
  let cities = JSON.parse(data);
  nome = cities.map((city) => {
    const { ID, Nome, Estado } = city;
    return {
      id: ID,
      cidadeNome: Nome,
      cidadeEstado: Estado,
    };
  });
  console.log(nome);
});

for (i = 0; i < sigla.length; i++) {
  //prettier-ignore
  fs.writeFile(sigla[i].sigla + ".json",JSON.stringify(cidadeNome),(err) => {}
  );
}

Answer: A função fs.readFile() lê o conteúdo de um arquivo de maneira assíncrona. Portanto, provavelmente você está tentando ler o conteúdo dos arrays antes de terminar de ler o arquivo.
Caso precise que a leitura do arquivo seja feita de maneira síncrona, você pode utilizar a função fs.readFileSync(). Os parâmetros são os mesmos, com exceçao do Callback, já que o seu código passará a ser síncrono.
Para mais detalhes sobre assincronismo, veja O que é o assincronismo? e Como programação assíncrona funciona em JavaScript?.


Creating Database

Question: I want to create a student database in a Drupal website.
There will be a page containing a form (name, id, age, phone)in the website, where data will be entered and stored.
Later on the stored student list can be retrieved or perform some operations on the database like sending sms to all the students.
Please note that students are not the site users, some other user will enter all the details of the students.
I am a newbie to Drupal.. Please guide me on how to do that...
Thanks
Comment: there is already an `user` table in Drupal which stores the user information. If you need you can add more fields (name, id etc.) to it.
Just create a user role student by visiting `http://yoursite/admin/people/permissions/roles`.
Comment: The students are not the user of the site.... my aim is just to store their information...and as far as I know user table has the details of users that login/use the site.... please correct me if  I am wrong
Comment: oh ok. I thought you needed users of type student. I suggest you edit your question to clearly mention that students will not be users and who will be the actual users. And yes users table contain login information of the users. Adding new fields would create new tables with respective names..
Comment: already edited .... :)
Answer: If you are requiring a front end to view the data stored I would highly recommend bui[lding a bunch of custom views. You can then go further and install Views Bulk Operations to allow actions to be performed on multiple rows (students). You have send mail as a default option but for sending a sms you will need to install the sms framework
As for the containers, Drupal 7 has fields which can be attached to user profiles, if they get pretty advanced you can use the Profile2 module which just gives you a little more control.
If you dont need the attachment to an actual user account you can create a content type "student" which will allow you to add custom fields in the same way you can with a profile.
Comment: Thanks for your answer.
but my doubt is that.... in my case students are not the site users, some other user will enter all the details of the students... so your approach is suitable in that case....
Comment: Yea i got a feeling that would be the case from your question which is not the typical case. Either way Drupal will support this well with a huge range of modules to extend your functionality.
Comment: so sir your suggested way is correct in my case also?... should I need to develop my custom module?
Comment: Might not need one, just use a content type and set up the fields / permission etc via the UI.
Answer: Make a content type for student. And using CCK add all the field i.e. name, age,etc..
For phone, CCK phone module will be helpful to you..
Answer: I think you should be using the default Drupal registration form, make the student entries users, even though you don't want them to sign in or anything like that. Put up some profile fields (I think this is the new Profile followup for D7, Profile 2) in which you could store some additional information and let them be filled on the registration form. Then afterward you could even export the users to CSV (Profile CSV). This way you could have some more flexible data to be used to for example SMS them.
Please make sure you configure a good default "Authenticated user" role, this role should not be assigned to any administrative functions. Or even better, create a new role "student" and be sure to assign the role to those new entries.
Using users is (I think) the right way to go, since you can afterwards (for unforeseen future proposes) even let the users login and share content which only students should be obliged to.

Creating Database


Java Countdown Timer

Question: Hi I am trying to create a countdown stopwatch timer for my gym.
Here is what I have for the actual displaying and decrementing of the time: (bear in mind I used my normal stopwatch one and just edited it briefly to decrement. It is still first pass and I still want to thread it all at some stage but for now this should work. )
            new Timer(1,new ActionListener(){
            public void actionPerformed(ActionEvent e){
                int seconds = (int)(System.currentTimeMillis()-watchStart)/1000;
                int days = seconds / 86400;
   //these are just initialization values for testing
                            int startHour, startMin, startSec;
                            startHour = 5;
                            startMin = 5;
                            startSec = 0;
                int hours = (seconds / 3600) - (days * 24);
                int min = (seconds / 60) - (days * 1440) - (hours * 60);
                int sec = seconds % 60;
                                    String s = String.format("%02d:%02d:%02d", startHour - hours, startMin - min, ((startSec == 0) ? startSec = 60 : startSec) - sec );

                displayTimeLabel.setText(s);
            }
    });

Now my issue is:
a) It is not decrementing the minute to start with (if it starts at say 5 minutes)
b) If I start it at 30 seconds it will go into negative until it reaches a full minute then decrements the minute. ( I think I will need a method like if == 0 then minute - 1? but I fear that will break the actual count?)
Thanks.
Edit: Full program:
    package countdown;

    import java.awt.*;
    import static java.awt.Frame.MAXIMIZED_BOTH;
    import javax.swing.Timer;
    import javax.swing.*;
    import java.awt.event.*;

    public class CountDown extends JFrame implements ActionListener{

    private int hour;
    private int minute;
    private int second;
// The component that shows the elapsed time.
private JLabel displayTimeLabel;

private long watchStart, watchEnd;

private Timer theChronometer;

// Keeps track of time when pausing the Timer.
private long pausedTime;

// Lets the program know if starting or resuming
private boolean paused = false;

// Button that changes from "Start" to "Resume" depending on pause status.
private JButton activateTimerButton;

// run the program
public static void main(String[] args) {

    CountDown count = new CountDown();
    count.setVisible(true);
    count.setLocationRelativeTo(null);
}

public CountDown(){

    // initialize
    super();
    setExtendedState(MAXIMIZED_BOTH);
    setLayout(new BorderLayout());

    setLayout(new GridLayout(2,1));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setTitle("CrossFit Slam");
    setBackground(Color.black);
    setForeground(Color.white);

    Font largeFontBOLD = new Font("Calibri", Font.BOLD,20);
    Font largeFontPLAIN = new Font("Calibri", Font.PLAIN,200);

    JPanel buttonPanel = new JPanel();
    buttonPanel.setLayout(new FlowLayout());

    activateTimerButton = new JButton("Start");// will display resume when the watch is paused
    JButton stopTimerButton = new JButton("Stop");
    JButton pauseTimerButton = new JButton("Pause");

    // register buttons to generate events when clicked
    activateTimerButton.addActionListener(this);
    stopTimerButton.addActionListener(this);
    pauseTimerButton.addActionListener(this);

    // the display for elapsed time
    displayTimeLabel = new JLabel("00:00:00");
    displayTimeLabel.setHorizontalAlignment(JLabel.CENTER);
    buttonPanel.setBackground(Color.black);
    buttonPanel.setForeground(Color.white);

    displayTimeLabel.setFont(largeFontPLAIN);
    displayTimeLabel.setForeground(Color.white);

    displayTimeLabel.setBackground(Color.black);

    activateTimerButton.setFont(largeFontBOLD);
    stopTimerButton.setFont(largeFontBOLD);
    pauseTimerButton.setFont(largeFontBOLD);

displayTimeLabel.setOpaque(true);

    buttonPanel.add(activateTimerButton);
    buttonPanel.add(stopTimerButton);
    buttonPanel.add(pauseTimerButton);

    add(displayTimeLabel);
    add(buttonPanel, BorderLayout.PAGE_END);

    theChronometer =
    new Timer(1,new ActionListener(){
            public void actionPerformed(ActionEvent e){
                int seconds = (int)(System.currentTimeMillis()-watchStart)/1000;
                int days = seconds / 86400;
                            int startHour, startMin, startSec;
                            startHour = 5;
                            startMin = 5;
                            startSec = 0;
                int hours = (seconds / 3600) - (days * 24);
                int min = (seconds / 60) - (days * 1440) - (hours * 60);
                int sec = seconds % 60;
                                    String s = String.format("%02d:%02d:%02d", startHour - hours, startMin - min, ((startSec == 0) ? startSec = 60 : startSec) - sec );

                displayTimeLabel.setText(s);
            }
    });
}

public void actionPerformed(ActionEvent e){

    if(e.getActionCommand().equals("Stop")){theChronometer.stop();}

    else if(e.getActionCommand().equals("Start") || e.getActionCommand().equals("Resume")){
        if(!paused){
           watchStart = System.currentTimeMillis();
           theChronometer.start();
        }
         else{
            watchStart = System.currentTimeMillis()+pausedTime;
            pausedTime = 0;
            theChronometer.start();
            paused = false;
            activateTimerButton.setText("Start");
         }
    }

    else if(e.getActionCommand().equals("Pause")){
        long now = System.currentTimeMillis();
        pausedTime -= (now - watchStart);
        theChronometer.stop();
        paused = true;
        activateTimerButton.setText("Resume");
    }
}

}
Comment: please post a [mcve](http://stackoverflow.com/help/mcve).
Comment: Apologies, will do so now.
Comment: Well when 1 second elapsed, you `min` is 0, so why would you expect it to be something else then 5 then? You need to do some smart rounding there. Or **use a library method**. Even the standard Java `Date` can do all this for you without errors, not to mention better ones...
Comment: What's the purpose of this code? To learn how to work with timestamps or make an easy stopwatch? In the latter case I can just post a three-line solution to the problem.
Comment: Well I would love to see that. I've never used the timer or date classes before. (May have used date but just to display the current date) Would like to see other methods too and see how I can incorporate it there. I've been googling but nothing I've found is fitting with how I want it to operate.
Answer: What you're trying to is easily achieved using standard libraries, in particular the Date class.
DateFormat f = new SimpleDateFormat("HH:mm:ss");
f.setTimeZone(TimeZone.getTimeZone("GMT"));
long startingTime = TimeUnit.HOURS.toMillis(5) + TimeUnit.MINUTES.toMillis(5);

public void actionPerformed(ActionEvent e) {
    long elapsed = System.currentTimeMillis() - startTimestamp;
    long displayTs = startingTime - elapsed;

    String out;
    if (displayTs >= 0) {
        out = f.format(new Date(displayTs));
    } else {
        out = "-" + f.format(new Date(-displayTs));
    }
    displayTimeLabel.setText(out);
}

All of this is in the standard Java libraries and the Javadoc on the methods/classes should provide insight on what's happening.
Comment: Thank you, I will try this out and let you know if I have any issues.
Comment: Whoops, forgot about timezones, sec.
Comment: @user2792920 You're likely to have problems with the hour field, as the format will be in your timezone, not GMT (forgot it's my default, hence worked for me). I added setting the timezone as well, should be fine now.
Comment: I am trying to workout where your "startTimestamp" is coming from? do you initialize it with the current time or did you mean something else?
Comment: @user2792920 That's you watchStart. It is, as you can imagine, the timestamp when the countdown started.
Comment: Got it, thanks a lot. Had to tweak it somewhat - in the if statement I had to make "out" accept displayTs as opposed to elapsed.
Comment: @user2792920 You are, of course, correct. The display should take the displayTs. Would you mind accepting the answer if it resolved your question? It would at least prevent others from wasting their time answering a problem already solved.

Java Countdown Timer


Help with Congruence, How is B Value Calculated

Question: Good afternoon,
I am trying to understand congruence, I could really use your help. First time I am using this.
I'm working with the congruence formula of ax ≡ b (mod n)
I'm following this YouTube explanation of Chinese Remainder Theorem | Sun Tzu's Theorem and she has the following congruence:
35x ≡ 1(mod 3)

She then reduces it to:
2x ≡ 4(mod 3)
 x ≡ 2(mod 3)

for 35x, I am assuming we need a number that will result in the modulus of 35 % 3 == 2
Easy enough.
How is she coming up w/ 4? 1 % 3 is 1 so my assumption for 35x won't work here.
...and for the final line of x ≡ 2(mod 3), is it because she divided both sides by 2?
Thanks for your help!
Comment: See twiddling (inverse reciprocity) in the linked dupes for this (and many other) methods.
Answer: I'm not quite sure where the $4$ came from. But as you said, you can reduce it to $$2x \equiv 1 \pmod 3.$$ In mod $3$, $2$ is the inverse of $2$, since if you multiply $2$ by $2$, you get 1, i.e. $2\times 2 \equiv 1 \pmod 3.$ So consider multiplying both sides of the equivalence by $2$. Then you get $$4x \equiv 2 \pmod 3.$$ But notice that $4x \equiv x \pmod 3,$ so you get that $$x \equiv 2 \pmod 3.$$
As another example, suppose you have that $$2x \equiv 1 \pmod 5.$$ Can you find the inverse of $2$ in mod 5, then solve the problem from here?
Actually, this notion of inverse is a little tricky. Consider the equation $$3x \equiv 1 \pmod 6.$$ This equation actually has no solutions, and the point here is that $3$ does not have an inverse mod $6$, so you can't multiply both sides of the congruence by a number to remove the $3$ on the left. In general, if you have a congruence $$ax \equiv b \pmod m,$$ you want to write $$x \equiv a^{-1} b \pmod m,$$ where $a^{-1}$ is the inverse of $a$. When $a$ and $m$ are relatively prime (meaning they have no factors in common), then $a$ will have an inverse mod $m$. In your question, you mentioned something about dividing both sides by 2. Division isn't really the right way to think about it; the right way to think about it is finding the inverse and multiplying both sides by it.
Comment: Please strive not to post more (dupe) answers to dupes of FAQs, cf. recent site policy announcement [here](https://math.meta.stackexchange.com/q/33508/242).
Comment: @BillDubuque I asked a simple question unrelated to anything before. Why the disrespect? This is not a duplicate question!
Answer: That is because $4 \equiv 1 \pmod{3}$. Take remainder of $4$ after dividing by $3$ and it is congruent to $1 \pmod{3}$. Since she has $2x \equiv 4 \pmod{3}$ and $\gcd(2,3) = 1$, you can apply the cancellation rule and cancel $2$ out to get $x \equiv 2 \pmod{3}$.
Comment: Please strive not to post more (dupe) answers to dupes of FAQs, cf. recent site policy announcement [here](https://math.meta.stackexchange.com/q/33508/242).


How do I properly install the MailChimp module?

Question: In order to install MailChimp in Drupal 8 I followed the instructions for the MailChimp Drupal module.

Instructions for 8.x-1.x
The 8.x-1.x release uses version 3.0 of the MailChimp API and bundles
  the library with the module. This is a temporary solution until the
  process for installing libraries via composer is finalized in Drupal
  8.

in admin/modules/install I added mailchimp 8.x-1.3
Checked that libraries is installed (Machine name: libraries; Version: 8.x-3.x-dev)
Enabled all four modules (mailchimp, mailchimp_campaign, mailchimp_lists, mailchimp_signup)

However, when trying to configure the module at admin/config/services/mailchimp the page could not be found.
How can I resolve this issue and where should I start looking?

PHP 7.1.6-nmm1
Drupal 8.4.0-dev
Answer: You should use Composer to fetch this module, as it has an external dependency noted in its composer.json file:
http://cgit.drupalcode.org/mailchimp/tree/composer.json
It seems to include an older version with the module, I'm not sure why, but the current version of Mailchimp API by Thinkshout looks to be 1.0.8. I don't see any installation notes. The module comes with 1.0.6... ?
Other than that, clear your caches and try to access the page again.


Erro com argumentos Foreach

Question: Criei uma estrutura com alguns loops contudo o php tá me retornando que os argumentos do foreach são inválidos... Eu não tenho certeza se essa estrutura é correta, então gostaria que alguém me informasse se isso é ou não correto:
for($x=1; x<=$n_cartelas_registradas; $x++) {
$contador[$x] = 0;
foreach($cartela[$x] as $n_cartela=>$numero){ //linha retornando erro
  for($a=0; $a<=$n_sort; $a++){
    if($numero == $sorteados_array[$a]){
     $contador[$x]++;
       }
    }
  }
}

Todas as variáveis usadas têm valores.
O array cartela tem a seguinte estrutura: $cartela[1] = array (n, q, e, r, t); e esses valores não são arrays. Ou seja, é bidimensional. Já o $sorteados_array é da seguinte forma: $sorteados_array[0] = x; ou seja; é um array unidimensional.
Então, os argumentos do foreach podem ser escritos dessa forma?
Se sim, onde pode estar o erro? Se não, como posso obter o resultado esperado de forma correta?
Obrigado.
Comment: N, q, e, r, t **não são** arrays mas é bidimensional? Não está nada claro.. Favor postar um var_dump de $cartela
Comment: Realmente precisaríamos ver o que tem na `$cartela`. Mas estrahei o seu loop de `1` até `$n_cartelas_registradas`. Não deveria ser de `0` a `$n_cartelas_registradas - 1`?
Comment: Pelo seu código estimo que esteja esquecendo de inicializar algum dos arrays dentro da variavel $cartela;
Poderia nos fornecer o código completo?
Comment: Errei na hora de escrever... Elas são arrays.
Answer: Faltou o cifrão na variável $x da condição.
for($x=1; x <= $n_cartelas_registradas; $x++)
----------^

Troque por:
for($x=1; $x <= $n_cartelas_registradas; $x++) {

Erro com argumentos Foreach


Dimension of a linear space in $\mathbb{P}^{n}$ (Schubert Calculus)

Question: I am reading about Schubert calculus and have come across this definition of a linear space:
A linear space $L$ in $\mathbb{P}^{n}$ is defined as the set of points $P = (p(0), p(1), \ldots, p(n))$ of $\mathbb{P}^{n}$ whose coordinates $p(j)$ satisfy a system of linear equations $\sum_{j=0}^{n} b_{\alpha j}p(j) = 0$, where $\alpha = 1, \ldots, (n-d)$. [Here, I get confused: ] We say that $L$ is $d$-dimensional if these $(n-d)$ equations are independent, that is if the $(n-d)\times (n+1)$ matrix of coefficients $[b_{\alpha j}]$ has a nonzero $(n-d) \times (n-d)$ minor.
I would have thought that this space is of dimension $(n+1)$. Maybe because each equation is zero and the $p(j)$ satisfy such an equation, in each combination there is an "extra" vector by dependence. Thus, this leaves $(d+1)$ independent vectors, but not $d$ (this may have to do with the fact that we are in $\mathbb{P}^{n}$).
Any help is appreciated.
Answer: Think of how $\mathbb P^n$ is defined:
$$\mathbb P^n = \mathbb K^{n+1}\setminus \{0\} /\sim, $$
where $\vec x \sim \vec y$ if they are proportional. Now the matrix $B$ is nondegenerate, so the linear map $B : \mathbb K^{n+1} \to \mathbb K^{n+1}$ has a $d+1$ dimensional Kernel $\tilde L$.
However, when you take quotient $\sim$, then $L = \tilde L\setminus\{0\} /\sim$ has one less dimension (The reason is the same as why $\mathbb P^n$ is $n$-dimensional instead of $n+1$-dimensional).
Note that you might think that it is an (established) abuse of languages to call that $L$ linear: $\mathbb P^n$ is not a vector space, after all.
Comment: This really cleared things up. Thank you.
Answer: The reason for the "off-by-one" error you are seeing is that in projective space, points are really given by equivalence classes of coordinates. Therefore the point
$$
(p_0,p_1,p_2,\ldots,p_n)
$$
is in the same equivalence class as
$$
(\lambda p_0,\lambda p_1,\lambda p_2,\ldots,\lambda p_n),
$$
for any $\lambda\not=0$.
Answer: I figure I'll add my two cents as well, even though the other answers are also good.  I agree that it is confusing that projective dimension is always one less than the vector space dimension.  You have to be careful to specify which you mean. However there is a good reason for this double usage of the term, using geometric intuition.
We can view a vector space and its subspaces geometrically; the zero vector is included in every subspace.  So one nonzero vector determines a line ($1$-dimensional), and two linearly independent vectors form a plane ($2$-dimensional).  Moving to a projective setting, one nonzero vector now determines only a point ($0$-dimensional) while two linearly independent vectors form a line ($1$-dimensional).  We need three linearly independent vectors to give a triangle/plane ($2$-dimensional) in this setting.  So really the dimension can be interpreted in a geometric way.
Of course when we deal with a projective space in analytic geometry, we have the complication that we need to keep track of both systems simultaneously: we are representing geometric objects in the projective setting with geometric objects in a vector space setting.  The same object has a different geometric dimension, depending on the point of view (i.e. a $(d+1)$-dimensional vector subspace corresponds to a $d$-dimensional projective subspace).
Comment: @Mike Not sure I really understand; $\ell$ is a "line" in the vector space, but not passing through the origin? I don't know that there is really a good way to interpret this in the projective space.  But yes, two good ways of thinking of the projective space are as the collection of lines through the origin (so you are just getting the collection of points in this way); or as the collection of *all* vector subspaces (so subspaces of different dimension are interpreted as different types of geometric objects in the projective space; points, lines, planes, etc.).
Comment: This was really helpful! Also, a sort-of-off-topic question: I've seen projective space defined as the set of lines through the origin of a vector space. This seems almost contrary to what I'd think of as projective space - but I'm thinking that if we had some line $\ell$ that crosses the $x$-axis at $x = k \neq 0$, then we have a point $(k, 0) \in \ell$ which is really part of the "point" $[1:0] \in \mathbb{P}^{2}$. Therefore the line sort of collapses into the origin and hence any line in $\mathbb{P}^{n}$ is aline through the origin. Is this correct? Thanks.


iOS6: do we have to set rootViewController in App delegate in order to support different orientations?

Question: The app was perfectly fine working in iOS5 in landscape orientation. However in iOS6, it started to use portrait orientation in all view controllers. The methods shouldAutorotateToInterfaceOrientation are not called anymore. I read the new stuff about changed rotation mechanism in iOS6 and I was able to fix that by adding a line in my AppDelegate:
<code>self.window.rootViewController = _viewController
</code>
_viewControler is the starting screen (Home-menu). All other view controllers implement shouldAutorotateToInterfaceOrientation method and returns YES for landscape orientations only. So, it's perfectly working solution for the app that needs to support only one orientation.
However, the problem is I need one view controller (lets call it phone-VC) to be presented in portrait orientation. Now, if I want this view controller would be rotated then I need to return YES in Home-menu controller that is assigned to rootViewControler in appDelegate. However, I can't do that because this rootViewController is starting window that need to presented in landscape only, otherwise the layout with graphics in this window will break. But if I don't return YES from its shouldAutorotateToInterfaceOrientation (Home-menu) then the same method is not called in my view phone-VC that needs to be presented in portrait.
Any ideas? Does the assignation of rootViewController is mandatory in AppDelegate?
UPDATE: the problem exists on device (at least on iPhone4).
Comment: Are you having the rotation problems on a really device or on the simulator? I've noticed that the simulator rotation is a different then on a real device.
Comment: Check this...

http://stackoverflow.com/questions/11544382/ios-6-screen-rotation-without-using-storyboard

http://stackoverflow.com/questions/12775265/ios-6-shouldautorotate-is-not-being-called
Answer: Yes, from iOS 6.0 onwards, you must have rootviewcontroller assigned to Windows.rootViewController. This controller will decide whether their children rotates or not. By default all orientations supported but you can restrict them by implementing shouldAutoRotate and supportedInterfaceOrientations delegate methods. I had an instance where I didn't have rootviewcontroller assigned to Windows in using MGSplitViewController which was adding viewcontroller as subview to window. I just needed to change it to make rootviewcontroller and all worked fine!
Check UIKit section on Apple documents - iOS 6.0 release notes.


bash, break loop if input value is contained in array

Question: I want to check if the user input value exists in the array, then stop checking inputs. I tried
var=( one two three )
while true; do
  read -p "Choose value:   " val
  for i in "${var[@]}";do
    [ "$i" = "$val" ] && exit 0;
  done
done

echo SUCCESS

With that the script will exit, but I want the script to continue and print SUCCESS.
I tried the break instruction but the while loop just continues and does not break.
Comment: Replace `exit 0` by `break 2` (that is, break two loop levels). Note that, if your bash supports it, an associative array (where the keys are the values of your indexed array) would simplify a bit and require only one loop level: `[[ -v var["$val"] ]] && break`.
Comment: I was typing in my answer while this comment happened. No problem, sorry for the confusion.
Answer: Avoiding the nested loops, requires an associative array approach from @Renaud Pacalet, an alternative is to format the array and use the [[...]]  instead of [...], something like:

With an extglob feature:

#!/usr/bin/env bash

var=( one two three )
pattern=$(IFS='|'; printf '@(%s)' "${var[*]}")

while read -rp "Choose value:  " val; do
  [[ "$val" = $pattern ]] && {
    printf "SUCCESS\n" && break
  }
done

From bashv 4.1 the extglob feature/support from [[ ... ]] is on by default, any lower version requires shopt -s extglob to enable it.

With a regex using the =~ operator:

#!/usr/bin/env bash

var=( one two three )
pattern=$(IFS='|'; printf '%s' "${var[*]}")

while read -rp "Choose value:   " val; do
  [[ "$val" =~ $pattern ]] && {
    printf "SUCCESS\n" && break
  }
done

The right hand side of the test does not need to be quoted, otherwise it will be treated as a literal and not a glob or regex.
Answer: Use a level with your break statement like so:
var=( one two three )
while true; do
  read -p "Choose value:   " val
  for i in "${var[@]}";do
    [ "$i" = "$val" ] && break 2;
  done
done
echo SUCCESS

It will break the outer loop (while at level 2).
Answer: You should replace exit 0 by break 2 (that is, break two loop levels). Another option is to print your success message and exit:
var=( one two three )
while true; do
  read -p "Choose value:   " val
  for i in "${var[@]}";do
    [ "$i" = "$val" ] && echo "SUCCESS" && exit 0;
  done
done

Finally, if your bash supports it, an associative array with your values as keys would simplify a bit and require only one loop level:
declare -A var=( ["one"]= ["two"]= ["three"]= )
while true; do
  read -p "Choose value:   " val
  [[ -v var["$val"] ]] && break
done

echo "SUCCESS"


Why I'm getting '000606 (57P03): No active warehouse selected in the current session. Select an active warehouse with the 'use warehouse' command.'

Question: I'm getting the following error when doing a 'dbt run'
000606 (57P03): No active warehouse selected in the current session.  Select an active warehouse with the 'use warehouse' command.
My profile has the following entry:
role: transform_role
schema: dbt
threads: 1
type: snowflake
user: transform_user
warehouse: transform_wh
I have also run the following in snowflake to set the user's default warehouse to transform_wh:
alter user transform_user set DEFAULT_WAREHOUSE = 'TRANSFORM_WH';
But I'm still getting the following error when doing 'dbt run':
05:24:41  Database Error in model my_first_dbt_model (models\example\my_first_dbt_model.sql)
05:24:41    000606 (57P03): No active warehouse selected in the current session.  Select an active warehouse with the 'use warehouse' command.
05:24:41
05:24:41    compiled SQL at target\run\learn_dbt\models\example\my_first_dbt_model.sql
05:24:41
I have seen similar questions but they don't seem to resolve my issues. I would appreciate any insight and/or help. Thanks.
Comment: And the warehouse is set to auto resume?
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: It's hard to know without more information, but the most likely cause is that your user's role doesn't have permissions to use the warehouse.
Comment: I finally figured out how to assign permission on a warehouse to a role. All things are resolved now. Thanks.
Answer: Try to mitigate the error, you need to create a virtual warehouse using the below command:
<code>CREATE [ OR REPLACE ] WAREHOUSE [ IF NOT EXISTS ] <name>
   [ [ WITH ] objectProperties ]
   [ [ WITH ] TAG ( <tag_name> = '<tag_value>' [ , <tag_name> = '<tag_value>' , ... ] ) ]
   [ objectParams ]
</code>
Reference: https://docs.snowflake.com/en/sql-reference/sql/create-warehouse


Show that $M$ is not maximal in $\mathbb Q$

Question: $\mathbb Q$ is a $\mathbb Z$ module. Let $M$ be a proper submodule of $\mathbb Q$.

Show that there is some $0 \neq b \in \mathbb Z$, such that $1/b \notin M$

If for all $b \in \mathbb Z$, $1/b \in M$, then $\mathbb Q = M$. contradiction. this is easy.

Show that $M \cap \mathbb Z \neq 0$. This is also easy.

Show that $M$ is not maximal in $\mathbb Q$. I can't figure this out.

i said that since $1/b \notin M$, we have $\mathbb Q = M + (1/b) \mathbb Z$.
i'm trying to find a contradiction from here. any help?
i also thought that if $M$ is maximal then $\mathbb Q/M$ is simple, then it is also cyclic. but this doesn't look useful.  thanks for help.
Comment: If $1/b\notin M$, can it be the case that $1/b^2 \in M + (1/b)\mathbb Z$?
Comment: @MarcPaul doesn't seem problematic to me
Comment: @madmatician If you _begin_ by saying "$M$ contains a non-zero integer, hence wlog $1\in M$" _then_ it's problematic...
Comment: @MarcPaul having said that i can't see the contradiction, i would appreciate it if you can tell why it can't be the case.
Answer: $\;\Bbb Q\;$ is a divisible abelian group (=divisible $\;\Bbb Z-$module), and this means that for any $\;n\in\Bbb N,\,\,q\in\Bbb Q\;$ there exists $\;p\in\Bbb Q\;$ s.t. $\;np=q\;$ .
Observe that any homomorphic image of a divisible group is also divisible, but no finite abelian group (in fact, no abelian group with finite exponent) can be divisible, so if $\;M\le\Bbb Q\;$ is maximal then $\;\Bbb Q/M\;$ is simple and thus finite (and of prime order, but we don't care about this), and thus it can't be divisible, contradiction.
Comment: "If $M \le Q$ is maximal, then $Q/M$ is simple and thus finite". Can you please explain what happened here?
Comment: $\;\Bbb Q/M\;$ simple $\;\iff\;$ it has no non-trivial normal subgroups. But this is an abelian group so *any* subgroup is normal, so it is simple iff it has no non-trivial subgroups at all $\;\iff\;$ it is of order a prime (and finite, among other things). Remember: the only abelian simple groups are those which are cyclic of primer order. I think you may have rushed a little to downvote: my answer is correct as far as I can see, though it may be out of your current knowledge. I can't know that.
Answer: A hugely elementary proof, since I don't know any algebra:
First, wlog $M\ne0$. Hence $M$ contains a non-zero integer.
Lemma Wlog $1\in M$.
Proof: Say $n\in M\cap\Bbb Z$, $n\ne 0$. Let $M'=\frac1n M$. Then
$M$ is maximal if and only if $M'$ is maximal. QED.
Lemma If $a,b\in\Bbb Z$, $a/b\in M$, $(a,b)=1$, then $1/b\in M$.
Proof: There exist $n,m\in\Bbb Z$ with $na+mb=1$. Hence $1/b=na/b+m\in M$, since $1\in M$. QED$
So $M\ne\Bbb Q$ implies that there exist $p$ and $n$ such that $1/p^n\in M$ but $1/p^{n+1}\notin M$ (otherwise the previous lemma shows that the reciprocal of any product of powers of primes is in $M$, so $M=\Bbb Q)$).
So $M$ is a proper submodule of $\frac1p M\ne\Bbb Q$.
Comment: Why is it the case that $M$ is maximal iff $M'$ is maximal?
Comment: @madmatician Because $\phi(t)=t/n$ defines an automorphism of $\Bbb Q$. (This is also why $\frac1p M\ne\Bbb Q$ at the end...)


About Regulated Functions

Question: Definition. Let $X$ be a Banach space. A mapping $f:[a,b]\to X$ is called regulated if it has one sided limits.
In the setting of a Hausdorff topological vector space $X$, can we still define regulated functions?
Answer: As in a Hausdorff topological vector space the one sided limit of a function is a defined object, you surely can do this, exactly as in the case of Banach spaces. (You even do not need the Hausdorff condition or vector space structure, as "having a limit" does not need this).

About Regulated Functions


What Windows user does an anonymous asp.net website run as in IIS 6?

Question: I have 2 web servers load-balanced, trying to access images from a 3rd server using pass-through authentication.
The servers are in a workgroup as my host does not support domains.
No matter what file/IIS permissions I set, the web servers can't get access to the images.
Just what user does an anonymous asp.net website run as in IIS 6?
Answer: The user IUSR_computername, which is a member of the Guest group. (more here)
If you create a new user with the same username and password on all three systems, and set that as the identity for your app, you should be able to access the files on the backend server without issue.
Answer: By default, most ASP.NET functions run under the app pool identity, which, by default, is NETWORK SERVICE.  This means that the computername$ account is seen across the network.
Some things run as the website's anonymous user account, which is IUSR_computername, and if you set impersonation="true" then most things will run as the IUSR_computername.
If you can place your site in a dedicated app pool, my recommendation is to create a custom user for your app pool, using passthrough auth as you suggested, with the same user/password.  The user must be added to the IIS_WPG group on each server.  Then make sure that impersonation is set to false, or isn't set (false by default).  Then that user will be used for network access.
It's possible that you will still get Code Access Security (CAS) errors.  If so, you'll need to grant the UNC path access using the caspool tool.


How to change values in realtime with jQuery or JavaScript?

Question: Here is my code: http://jsfiddle.net/tqjuco4x/1/
Here is my last question : Get colorpicker values in html?
I dont want to update it in my last question as its new problem and new thing I want to add in my code so that's why I ask in new question, hope editors not mind it.
How I can get live value without click on Change Color button. I mean in my code I have to pick color and then click on Change Color button so  is their any way to do it live, I mean I want to remove that button and when user pick color its update live ?
<button id="triggerImg">Change Color</button>

Is that possible in my code. hope you got my point.
Sorry for poor English.
Thanks
Comment: Please post your code in the question itself.
Comment: you can use onkeyup event on textbox using javascript
Comment: @AndrewL sure , i will do this
Comment: @MandarDhadve can you explain im new to these things , anyways thanks for help
Answer: It's simple. Use the .change event.
$("#clr1").on("change", function(){
    console.log("Change color to: " + this.val());
});

Edit: You're actually using JSColor library for your colour picker. I recommend you clean it up a bit if you're not using the other one.
What you should do is the following:
Create a function to listen to font edit:
function updateFont(color, jso){
    var hexStr = jso.toHEXString();
    console.log(hexStr);
}

And Create a function for your background change if needed.
Then change the input elements from:
<input class="jscolor" name="color" id="clr1" value="ab2567">
To:
<input class="jscolor" id="clr1" onchange="updateFont(this.jscolor)" name="color" value="ab2567">
Here's a modified fiddle for you.
Comment: Hi, thanks for help please if you dont mind can you explain i mean make a live example on jsfiddle, im new thats why i need some help to understand the working of codes
Comment: Hi , i dont know what happen but  code is not working .. look here http://jsfiddle.net/egq3udsb/ please see whats going wrong ..
Comment: @deccc Put the scripts at the top of the `head` tag and make sure jQuery is loaded.
Comment: Yes i do all things but i dont know why java code not replace new image when color pick ?
Comment: You're not. I just modified your code to do those things and it worked. If you're having further issues I recommend asking another question as comments are not for extended discussion.
Comment: sorry for that, i tried fresh code on my site and on jsbin , https://www.w3schools.com/html/tryit.asp, even again on jsfiddle , if i ask new question editors ask me to update my previous question and vote negative. sorry again , thanks a lot for your time .im unable to figure it out thats why i ask , anyways thanks again .. it matter for me your provide your knowledge to newbie .. thanks
Answer: You can use change on the text field. You can find the Docs jQuery docs here. And then change the CSS inside the callback function of change using jQuery css Read the docs for css here.
$( ".your-input-text" ).change(function() {
     //Change the CSS here.
     $( this ).css([
           color: $(this).val(), "background": "#fff"
     ]);
});

Answer: So i edited your jsfiddle
See jsfiddle
$(document).ready(function(){
$('#colorpicker').farbtastic('#color');

$('#clr1').change(function(){
let src = 'https:/test.com/IMGService.ashx?imagetype=typeit&postid=7406&width=100%&height=142&RenderText=[field title]&TextSize=96&TextColor=%23ff0000&BgColor=%23' + $('#clr1').val().replace('#','');
$('#testImg').attr('src', src);
});

$('#clr2').change(function(){
let src = 'https:/test.com/IMGService.ashx?imagetype=typeit&postid=7406&width=100%&height=142&RenderText=[field title]&TextSize=96&TextColor=%23ff0000&BgColor=%23' + $('#clr2').val().replace('#','');
$('#testImg').attr('src', src);
});
});

Comment: Thanks, but its not update the values , please look again , thanks for time and help
Comment: Hi, @jaapaap can you look it , as its not update values from javascript into html .. please look again in your code .. thanks again for your time and help
Answer: Probably what you want to do is -
<input id="txt_Search" type="text" onchange="Call()" />

Or, using simple jQuery
$("#txt_Search").keyup( function() {
    var searchQuery = $("#txt_Search").val();
    //your code
});

Comment: can you please explain it , i mean live example  on jsfiddle , thanks for help and time.


Slugify a thread link and create it on the home.html

Question: I am trying to slugify my hyperlinks. I created a Django board (home.html):
Currently I have:
http://127.0.0.1:8000/request/2/
But I want: http://127.0.0.1:8000/request/hallo-das-ist-ein-test-9/

  {% for topic in topics %}

      {{ topic.slug }}
       {{ topic.subject }}
      {{ topic.starter.username }}
      0
      0
      {{ topic.last_updated }}

  {% endfor %}

and
class Topic(models.Model):
    subject = models.CharField(max_length=255)
    category = models.CharField(max_length=255, null=True)
    last_updated = models.DateTimeField(auto_now_add=True)
    starter = models.ForeignKey(User, on_delete=models.CASCADE,
related_name='topics')
    slug = models.SlugField(unique=True)

def save(self, *args, **kwargs):
    self.slug = slugify(self.subject)
    super(Topic, self).save(*args, **kwargs)

You can see, the slugs were created. (First column = {{ topic.slug }})
How can I create a slugified link and link them to my thread hyperlinks? (e. g. "hallo das ist ein test :9")
My current code in views.py:
def home(request):
    topics = Topic.objects.all()
    return render(request, 'home.html', {'topics': topics})

def topic_posts(request, topic_pk):
    topic = get_object_or_404(Topic, pk=topic_pk)
    return render(request, 'topic_posts.html', {'topic': topic})

My current url.py:
urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^admin/', admin.site.urls),
    url(r'^new/$', views.new_topic, name='new_topic'),
    url(r'^request/(?P<topic_pk>\d+)/$', views.topic_posts,
name='topic_posts'),
    url(r'^request/(?P<topic_pk>\d+)/reply/$', views.reply_topic,
name='reply_topic'),

]
I already tried different approaches like:
def home(request):
    topics = Topic.objects.all()
    slug = Topic.slug
    return render(request, 'home.html', {'topics': topics, 'slug': slug})

def topic_posts(request, slug):
    slug = get_object_or_404(Topic, pk=slug)
    return render(request, 'topic_posts.html', {'slug': slug})

home.html:
{{ topic.subject }}

url.py:
urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^admin/', admin.site.urls),
    url(r'^new/$', views.new_topic, name='new_topic'),
    url(r'^request/(?P<slug>[-\w\d]+)/$', views.topic_posts,
 name='topic_posts'),
    url(r'^request/(?P<topic_pk>\d+)/reply/$', views.reply_topic,
 name='reply_topic'),
]

What I am doing wrong here...?
Comment: What do you mean by creating a slugified link and linking it to thread? Isn't this line of your code doing exactly that: `{{ topic.subject }}`?
Comment: Hi Olzhas, this piece of code results in: http://127.0.0.1:8000/request/2/ - I want: http://127.0.0.1:8000/request/hallo-das-ist-ein-test-9/. (Should be: {{ topic.subject }}) but this code is not working
Comment: That's really strange. It should be working based on the code you provided. Are you sure you have `{{ topic.subject }}` inside your  tag and not `{{ topic.pk }}`?
Answer: There are several changes needed for your expected behaviour.
In Table change:

to

In views, update the code like this:
def topic_posts(request, slug):
    topic = get_object_or_404(Topic, slug=slug)
    ...


Compositional techniques in top-line melody writing

Question: I want to start this post off by mentioning that I have seen the 1/16/2017 post on a similar topic;  That post related more to the lyrical/prosodic elements of the melody, and I am more interested in the composing of melodies.
I typically approach my songs (think pop music) with the vocal line interacting in some way with the other instruments.  For that reason, certain factors, such as chord voicing or contrapuntal motion can heavily influence the outline of a melody.
This time around, however, it just so happens that the instrumentals are completed, and I am ambivalent about the melodies that are basically just filler at this point.  So, I am looking to revise the melodies, leaving the completed tracks as they are--this is sort of the notion of top-lining, which is apparently a huge part of modern-day songwriting in pop music.
from Berklee.edu:

Toplining is an idiosyncratic process, at times requiring a
methodical, compositional approach and at others an experimental,
improvisational one. When working on a track, top-line songwriters
frequently start by coming up with several core vocal
melodies—"hooks"—and words or phrases that seem to match the tone of
the track (or the producer's requested topic). Over time and through
much trial and error, these ideas are refined into developed sections
like verse and chorus.

I am most curious about the compositional approach (as opposed to the experimental/trial and error/improvisational approach) regarding this concept.  What factors play a role in this process?  What do you suspect are the melody-writers main reference points when sitting down with a completed instrumental?  Perhaps one would consider the location of the bass?  Or the ensuring the complete chord is well balanced? Using tendency tones when appropriate (accented vs. unaccented passing tones)? etc . . .
I have never considered myself simply a melody writer because of my harmony/chord-based/holistic approach to songwriting, but I am trying to put myself in the shoes of someone who successfully writes unforgettable melodies and JUST THAT.  Where to begin??
Comment: @pro please suggest a book so that I can read it
Comment: In what way are chord sequences explained? More like, described. Do the explanations or descriptions enable you to create different but equally catchy chord sequences? What do the explanations allow you to do? And aren't melodies "explained" all the time in the same way? Chord-tone, non-chord-tone, leading tone, tension, resolution, weak beat, strong beat, long, short, ascending, descending, repeating, non-repeating, expected, surprising. Or ... what if success doesn't come from the properties of the actual melodies, but who you know and work with, and what and how many projects you get into?
Comment: Functional harmony gives us a roadmap for moving to and from the tonic, no?  It explains why the IV goes to the V and then to the I or vi.  The rules of melody tell us how to resolve tendency tones, how to use leaps and rhythm to create interest, and that repetition is an important aspect of a melody.  But I don't see a parallel concept in melody as, say, the circle of fifths, which is essentially a breeding ground for strong chord progressions
Comment: Lesson one: [Paul McCartney - Silly Love Songs](https://www.youtube.com/watch?v=ap87QgZKTNw). One simple chord structure [plus a bridge] 6 distinct melodies, most of which other composers would have been happy to run with. Song ends on the first line of the bridge. Genius.
Comment: Maybe you should try to find interviews of succesful topliners, perhaps they reveal something about their thought process?
Comment: Books have been written on this topic.  Could you narrow the question down a bit?
Comment: @piiperiReinstateMonica does a Rolling Stone interview with Sia count?  It didn't help
Comment: I guess you already know all the pieces in the puzzle. Basslines, rhythms, backing chord harmony and its notes. You can distinguish between chord tones and passing tones, expected vs unexpected, ascending and descending lines, tension and resolution... how to use all those musical elements and be _successful_ in pop music ... ???? There are many people working on those songs, and only some of them learn to do the toplining successfully. Their colleagues are musicians too, they work together and they watch how the topliners work but they still don't learn it!
Comment: @piiperiReinstateMonica you're suggesting, then, that it is a highly individualistic process--one that can't be easily explained by rules or theory?  Chord sequences/harmony tricks can be explained by theory and are used in pop music all the time . . . why not melodies?
Comment: @286642 Tunesmith by Jimmy Webb
Comment: If you were writing a melody for a song that would have lyrics and be sung, you would want to narrow your possible melody notes to fall within the vocal range of a singer.
Comment: @RockinCowboy that is certainly a factor.   Thanks.
Answer:
What factors play a role in this process?

An infinite number of factors play a role in this process if we are simply talking about combinations of notes to dictate melody, harmony and rhythm - even with finite structures like diatonic and chromatic scales.
But, there are certain guidelines to follow in order to help one compose "catchy" melodies. A look at how classical musicians compose melodies is a good place to begin when answering this question - even (or especially) as applied to pop music.
1.) Start with a melody
This is a debated topic, to be sure. But, it is also a time tested approach, going back through the centuries, for creating melodic ear-worms. I also understand that you it is somewhat of a contrary point to your initial question... But, even the snippet that you reference from the Berklee site seems to agree:

top-line songwriters frequently start by coming up with several core
vocal melodies

That said, it is difficult for any composer to write only unforgettable melodies and just that, as you put it. It will likely be especially difficult to do so with little or no wiggle room within the chord structures that you have already created.
So, the first piece of advice here would be to try and revamp your melodies into something more catchy or at least something going beyond "just filler" that you yourself are proud of and like to listen to. Then, allow yourself to potentially revamp parts of your rhythm and harmony to fit your new catchier melody (yes, that can be difficult sometimes - "Don't you touch my babies!" haha)
2.) Keep it simple
Some of the most memorable melodies are also some of the simplest. I will refer to Beethoven's 5th Symphony (I know, but it is really a great example for this topic.)
There is nothing more to say regarding the simplicity of the first melodic phrase - a triplet and a half note covering two tones. And, it is instantly recognizable ("Dun, dun, dun, Daaaaaah!")
3.) The 1, 2, 3 approach
1 - introduce a melody. 2 - repeat the first phrase. 3 - introduce variation to the melodic phrase.
This is used all over in classical music of course but, it is also used to this day in modern pop. Beethoven's 5th is also a good example for this and for the other guidelines, as well...
4.) Peaks & Valleys
This concept applies to so many aspects of music - the notes written on the staff, build up and release of tension, when the sounds are heard and the silence in between.
Some people seem to be born with the finesse to apply this concept in their music naturally and intelligently, some people spend their whole lives hoping to do so and are never effectively able to.
5.) Writing for the specific instrument
This is not generally due to issues of range as much as it is due to issues of ability and timbre. One can fairly easily transpose a melody to accommodate a specific range... but if a piece for piano contains a melody where consecutive notes jump two octaves, it would be impossible for a singer to perform without transcription.
Finally, piano and vocals obviously sound way different - so the age-old question applies, "what are you wanting to do?" What sort of mood are you hoping to achieve, etc...
This step is also not as immensely important to a catchy melody as the others - it is simply a good practice. This is because most, if not all, of the most catchy and unforgettable melodies can usually be fairly easily transcribed for other instruments (again, "keep it simple.")
In Pop
There are many and great examples of these principal's being applied in pop music. When talking about Nirvana's Nevermind in an interview on VH1 Classic Albums, Dave Grohl said, "We wanted them to be almost like children's songs; we would tell people they were intended to be as simple as possible."
If you listen to some of the songs from that album, such as In Bloom, you can see how simply the vocal melodies are composed and (almost) follow the '1, 2, 3 approach' in both verse and chorus.
There are many many other good examples out there - this is the first one that came to mind, thinking on the quote from Grohl.