remote log in to Windows

Question: From a remote machine, is there an easy way to log into windows?  Maybe using psexec.exe or mstsc.exe?  This would be lauched by a script.
I know the username and password.  I only need this to work on Windows 7 and on 2008 R2.
Comment: What's the objective?
Comment: To expand on Chris_K's comment, the phrase "log into" is ambiguous in this context.  You need to explain what you want to happen.
Comment: I want the same thing that would happen if I connected to the machine, pressed Ctrl-Alt-Del and entered my username and password to log into windows as that user.
Comment: Given that you already name mstsc.exe - what the heck do you want to know? How to START mstsc? How to log into the other machine without it having remote desktop enabled? I dont see anything left after starting mstsc.exe that you already know.
Comment: You can save Remote Desktop settings into an .rdp file and then open it from the command line.  Type mstsc -? for the command-line syntax.
Comment: I think you should discuss this with your system administrator.
Answer: Take a look at Remote Desktop Protocol (RDP). Microsoft currently refers to their official RDP server software as Remote Desktop Services, formerly "Terminal Services". Their official client software is currently referred to as Remote Desktop Connection, formerly "Terminal Services Client".
You will need to enable the service on the target, but after that, you should be good to go.
Answer: If you want "the same thing" as an interactive logon, you would need to do an interactive logon. mstsc would require you to enter the username and password, but you could simply save the credentials for the given context of your script.

remote log in to Windows


Set a condition for one field to be unique in all the content types.

Question: I am working with Drupal 8, and have a custom post type called: chapter. This content type is connected with a taxonomy term called: Book.
Now, I have a field called: number, for specifying the chapter one, two or three. this field should be unique. For example, if I say chapter 1 I can not repeat it ever again in the same book, but I can upload the chapter 1 for another book. I also can upload all the chapters for the same book in a different order.
So the rule is: Just add a unique chapter number per book.
The final goal is to create a view and be able to order my chapters by the number.
Do I have to use the rules module for that? Or maybe, there is a better approach?.
Answer: You can implement a custom validation constraint and a hook_entity_bundle_field_info_alter to set the new constraint to your field.
Check: https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-custom-validation-constraint


how do i give a the first letter of an array called word a value?

Question: I need to give a the first letter of a word a value.  How do i do this in arrays?  Its at the line
firstLetter=word.charAt(len);

    public class FirstNLast{

        private String word[];
        private String sentence = "";
        private String newWord;
        private StringBuilder strBuff;
        private int len;
        private char firstLetter;
        private char lastLetter;

    public FirstNLast(){

        word = sentence.split(" ");
        newWord = "";
        strBuff = new StringBuilder();
        len = 0;
        firstLetter = ' ';
        lastLetter = ' ';
         }

    public void setWord(String[] word){

        this.word = word;
         }

    public void compute(){

        len = word.length;
        firstLetter=word.charAt(len);
        lastLetter=word.charAt(len-1);
   }
}

Comment: `word.charAt(len)` how is it working? Since `word` is an array.
Answer: Arrays don't have a first letter; they have a first element. In this case, that element is a String, and it has a first letter. So, you want the first letter of the first element:
firstLetter=word[0].charAt(0);


c# - Como fechar uma instancia específica do internet explorer?

Question: Consigo com este código.
    foreach (Process p in Process.GetProcessesByName("explorer")) {p.Kill();}

Porém preciso fechar apenas uma instancia pegando talvez pelo titulo da janela.
Esta é a janela que precisa ser fechada. Obs: não tenho o handle dela e sim, é uma janela e não um alert javascript ou algo assim.

EDIT:
com a sugestão do @Bruno Warmling

RESULTADO VARIAVEL P:

RESULTADO windowtextlist
Answer: Adicione a referencia para Microsoft Internet Controls na aba COM.
Adicione nos usings a referencia para a biblioteca importada anteriormente.
using SHDocVw

Depois faça da seguinte forma:
const string janelaParaFechar = "Google";
foreach (InternetExplorer ie in new ShellWindows())
{
    if (Path.GetFileNameWithoutExtension(ie.FullName).Equals("iexplore", StringComparison.OrdinalIgnoreCase) && ie.Document.nameProp == janelaParaFechar)
    {
        ie.Quit();
    }
}

Se essa não funcionar, há outro jeito..
Inclua as funções abaixo:
[DllImport("user32", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]

private extern static bool EnumThreadWindows(int threadId, EnumWindowsProc callback, IntPtr lParam);
[DllImport("user32", SetLastError = true, CharSet = CharSet.Auto)]

private extern static int GetWindowText(IntPtr hWnd, StringBuilder text, int maxCount);

private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

public static IList<string> GetWindowText(Process p)
{
    List<string> titles = new List<string>();
    foreach (ProcessThread t in p.Threads)
    {
        EnumThreadWindows(t.Id, (hWnd, lParam) =>
        {
            StringBuilder text = new StringBuilder(200);
            GetWindowText(hWnd, text, 200);
            titles.Add(text.ToString());
            return true;
        }, IntPtr.Zero);
    }
    return titles;
}

Depois utilize da seguinte forma:
string janelaParaFechar = "Google - Internet Explorer";
foreach (Process process in Process.GetProcessesByName("iexplore"))
{
    var windowTextList = GetWindowText(process);
    if (windowTextList?.Count > 0 && windowTextList.Contains(janelaParaFechar))
    {
        process.Kill();
    }
}

Comment: Mas então você deve informar o nome do processo host dessa janela... e **não** o `explorer`.
Comment: Mas então você está usando Edge e não o internet explorer?
Comment: uso o webbrowser do c# e ele usa IE
Comment: Incluí mais uma forma de fazer
Comment: windowTextList vem com 73 itens mas nenhum é a aba que tem que ser fechada
Comment: e só retorna um processo pra você?
Comment: sim só há essa janela do IE aberta, o processo está retornando certo
Comment: vou editar a pergunta e colocar os resultados que vieram
Comment: @MiltonMachadoPereira mas pq você esta tentando fazer isso matando o processo, se você tem um `WebBrowser`? Essa aplicação com o `WebBrowser` é sua? você tem controle sobre a programação dela??
Comment: pq essa janela de erro é aberta em uma nova janela, então eu perco o controle sobre ela, só daria certo de outro jeito se eu conseguisse abrir a janela de erro num novo webbrowser.
Comment: editei a questao
Comment: Cara, o processo tem que ser `iexplore` e não `explorer`. Explorer é o gerenciador de janelas do Windows e não o Windows Explorer. Tenta mudar lá
Comment: dai nao vem nenhum processo
Comment: pior que eu acho que essa janela nao tem processo ou é um processo filho, que nao aparece no gerenciador de tarefas
Comment: consegui com o findWindowByCaption do windows... pegando pelo texto "Ocorreu o seguinte erro: -- Caixa de diálogo Página da Web" que fica no title da janela


where syntax error goes in my javascript code?

Question: If I run this code in Firebug everything goes fine and works:
var ingarray =$(".ingsparts");

$.each(ingarray ,function(n){
var ing = ingarray[n];
console.log($(ing).find('.name').val());
console.log($(ing).find('.value').val())

});

but if I run this, it doesn't work:
var ingarray =$(".ingsparts");

$.each(ingarray ,function(n){
var ing = ingarray[n];
var in = $(ing).find('.name').val();
var ms = $(ing).find('.value').val();

});

Comment: What about providing the actual error message? ;-)
Comment: Why do you think it doesn't work
Comment: thanks all. i forget that In is reserved
Answer: It seems that in is a reserved word; use another variable name.
Comment: Yes indeed, `in` is an operator. For a full list of reserved words, see Section 7.6.1 of [the specification](http://www.ecma-international.org/publications/standards/Ecma-262.htm).
Answer: in is a reserved word in Javascript (see here for more info), you will have to rename this variable.
Answer: Yeah, dont use in as variable name, but also, your each can be done more simply:
var ingarray = $(".ingsparts");

ingarray.each(function(){
  var name = $(this).find('.name').val();
  var value = $(this).find('.value').val();
  ...
});

Answer: The second example defines the in and ms variables inside the function. This means that they get function scope and are not usable outside of the function. So the variables are set, but never used and not accessed.


PHP is not being executed by proxy_fcgi and php_fpm on Zabbix frontend

Question: I have installed php7.0-fpm and enabled proxy_fcgi mod for Zabbix frontend.
However when I try to get access from any page I get PHP source code of that page instead of normal page.
My configs are the next:
/etc/php/7.0/fpm/pool.d/www.conf
[www]
user= www-data
group = www-data
listen = /run/php/php7.0-fpm.sock
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
pm = dynamic
pm.max_children=10
pm.start_servers =5
pm.min_spare_servers = 2
pm.max_spare_servers = 7
chdir = /usr/share/zabbix/

/etc/apache2/sites-enabled/zabbix.conf
<VirtualHost *:80>
    Include conf-available/zabbix.conf
    <FilesMatch \.php$>
    SetHandler "proxy:unix:/run/php/php7.0-fpm.sock|fcgi://localhost/usr/share/zabbix/"
    </FilesMatch>
</VirtualHost>

Loaded Modules:
 core_module (static)
 so_module (static)
 watchdog_module (static)
 http_module (static)
 log_config_module (static)
 logio_module (static)
 version_module (static)
 unixd_module (static)
 access_compat_module (shared)
 actions_module (shared)
 alias_module (shared)
 auth_basic_module (shared)
 authn_core_module (shared)
 authn_file_module (shared)
 authz_core_module (shared)
 authz_host_module (shared)
 authz_user_module (shared)
 autoindex_module (shared)
 deflate_module (shared)
 dir_module (shared)
 env_module (shared)
 filter_module (shared)
 mime_module (shared)
 mpm_worker_module (shared)
 negotiation_module (shared)
 proxy_module (shared)
 proxy_fcgi_module (shared)
 setenvif_module (shared)
 status_module (shared)

I get only php source code during any page access:
<?php
/*
** Zabbix
** Copyright (C) 2001-2017 Zabbix SIA
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/

require_once dirname(__FILE__).'/include/config.inc.php';

In logs everything is clear, no errors at all.
Could you please help?
Answer: Changed. Looks like there is error in your configuration file just put SetHandler "proxy:unix:/run/php/php7.0-fpm.sock|fcgi://localhost" instead of SetHandler "proxy:unix:/run/php/php7.0-fpm.sock|fcgi://localhost/usr/share/zabbix/".
I check it on my VM and everything is working like it should.
Comment: Please have a look more attentively to the list:  proxy_module (shared)
 proxy_fcgi_module (shared)
Comment: @user54 my fail.
Comment: @user54 i changed answer. It configuration issue.
Comment: I tried, didn't change situation at all.
Comment: One way or another I was needed that it be resolved ASAP so among alternative options I decided to use mod_fastcgi. With it everything works perfectly. Moving through Google I found that no only me have such issue with proxy mod.
Comment: @user54 yesterday I deployed your setup from scratch and everything in work after my fix. May be need to look deeper.
Comment: As I mentioned before I tried different options with proxy_mod_fcgi, but the situation didn't change at all. With fastcgi_usage it works fine without issues.  One way or another thanks for help.


Postfix a lot of relay acces denied errors in maillog

Question: I'm on Centos 6.5 with Postfix/Dovecot and some virtual domains.
Postfix works fine, but I've got a lot of messages like this "NOQUEUE: reject: RCPT from 1-160-127-12.dynamic.hinet.net[126.96.36.199]: 454 4.7.1 : Relay access denied; from= to= proto=SMTP" in my maillog.
I've tried to close port 25 with iptables, when I do so - I got no such messages, but my mail system starts work incorrectly and can't receive mail from other hosts.
Please help!
My postconf -n:
<code>    alias_database = $alias_maps
    alias_maps = hash:/etc/postfix/aliases
    broken_sasl_auth_clients = yes
    command_directory = /usr/sbin
    config_directory = /etc/postfix
    daemon_directory = /usr/libexec/postfix
    data_directory = /var/lib/postfix
    debug_peer_level = 2
    html_directory = no
    inet_interfaces = all
    inet_protocols = ipv4
    mail_owner = postfix
    mailq_path = /usr/bin/mailq.postfix
    manpage_directory = /usr/share/man
    message_size_limit = 20971520
    mydestination = localhost.$mydomain, localhost
    newaliases_path = /usr/bin/newaliases.postfix
    queue_directory = /var/spool/postfix
    readme_directory = /usr/share/doc/postfix-2.6.6/README_FILES
    relay_domains = *
    sample_directory = /usr/share/doc/postfix-2.6.6/samples
    sendmail_path = /usr/sbin/sendmail.postfix
    setgid_group = postdrop
    smtp_tls_cert_file = /etc/pki/tls/certs/example.com.crt
    smtp_tls_key_file = /etc/pki/tls/private/example.com.key
    smtp_tls_loglevel = 1
    smtp_tls_session_cache_database = btree:/etc/postfix/smtp_tls_session_cache
    smtp_tls_session_cache_timeout = 3600s
    smtp_use_tls = yes
    smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination
    smtpd_sasl_auth_enable = yes
    smtpd_sasl_local_domain = example.com
    smtpd_sasl_path = /var/run/dovecot/auth-client
    smtpd_sasl_security_options = noanonymous
    smtpd_sasl_tls_security_options = $smtpd_sasl_security_options
    smtpd_sasl_type = dovecot
    smtpd_tls_cert_file = /etc/pki/tls/certs/example.com.crt
    smtpd_tls_key_file = /etc/pki/tls/private/example.com.key
    smtpd_tls_loglevel = 1
    smtpd_tls_received_header = yes
    smtpd_tls_session_cache_database = btree:/etc/postfix/smtpd_tls_session_cache
    smtpd_tls_session_cache_timeout = 3600s
    smtpd_use_tls = yes
    soft_bounce = yes
    tls_random_source = dev:/dev/urandom
    unknown_local_recipient_reject_code = 550
    virtual_alias_maps = hash:/etc/postfix/vmail_aliases
    virtual_gid_maps = static:2222
    virtual_mailbox_base = /var/vmail
    virtual_mailbox_domains = hash:/etc/postfix/vmail_domains
    virtual_mailbox_maps = hash:/etc/postfix/vmail_mailbox
    virtual_minimum_uid = 2222
    virtual_transport = virtual
    virtual_uid_maps = static:2222
</code>
Please help! Will attach master.cf or anything other if needed.
Comment: What is the purpose of this SMTP server. Receiving mail for your domain?  sending mail outbound to other domains for clients in your network?
Comment: In general: there are some websites on this server. Each has own virtual mailboxes.  So the mission is to receive mail for all mailboxes on all domains of this server and to send emails from registered virtual mailboxes.
Answer: relay_domains should be the names you receive mail for.  The "outside world" will connect to your server (according to DNS MX records) and send mail for those domains.  Bad people will try to connect the same way, but try to send email to random other domains, they will be rejected and you will see the log message you see above.  It's perfectly normal.
However, I don't like that your relay_domains is set to '*'.  This is bad, put it back to the default (or comment it out) which is $mydestination, and make sure "mydestination" is set properly.
To allow "your" clients to connect (to send outgoing mail to other people's domains), check the smtpd_recipient_restrictions (which looks ok above), which basically says, people on "your" network, or clients that have authenticated can send to any outside domain.
But I don't see "mynetworks" is set up at all, so unless your outgoing mail clients are authenticated they won't be able to send.  You probably want to set up "mynetworks".
Comment: I understand about bad people, and I also see that my config blocks their tries. But I've got huge logs because of them. Can I disable logging of this situation?


Como faço pra exibir variaveis numa página django?

Question: Eu sou novo no django e estou tirar algumas informações de uma página web usando lxml. Gostaria de saber como faço pra exibir os valores na minha página web.
import requests
from lxml import html
from django.shortcuts import render

def list_data(request):
    return render(request, 'data.html', {})

def get_idhm(url):
    page = requests.get(url)
    tree = html.fromstring(page.content)
    idhm = tree.xpath('//*[@id="responseMunicipios"]/ul/li[6]/div/p[2]/text()')
    return idhm[0]

def get_population(url):
    page = requests.get(url)
    tree = html.fromstring(page.content)
    values = tree.xpath('//*[@id="responseMunicipios"]/ul/li[3]/div/p[2]/text()')
    return values[0]

essa é a view.
Answer: Como você pode ver no exemplo que mostrou, tem um metodo chamado list_data. Nele você renderiza data.html e um dicionario vazio. Nesse dicionário você pode colocar os valores que serão exibidos no HTML. Segue exemplo:
views.py
def list_data(request):
    return render(request, 'data.html', {"message": "Hello World"})

data.html

{{message}}


Docker not updating changes in directory

Question: I am new in docker and i am trying to test a node server
Dockerfile
FROM node:8

WORKDIR /home/test-ci-node
COPY . .
EXPOSE 8080
CMD [ "node", "server.js" ]

server.js
var http = require('http');

//create a server object:
http.createServer(function (req, res) {
    console.log("got req");
    res.write('Hello World'); //write a response to the client
    res.end(); //end the response
}).listen(8080); //the server object listens on port 8080

console.log("listining at 8080");

and i started my docker image with command

docker run -p 8080:8080 -d docker_img

now in server.js i changed the response to

res.write('Hello World changed!');

and then i tried to restart container but changes were not reflected,
i tried few google methods but results were same.
for changes to reflect i had to rebuild the image.
so is there a right way to reflect changes without rebuilding the image.
Comment: Well, your code only copies on build. So if you want to change your server.js externally, you need to use shared volume like -v /var/www/docker:/home/test-ci-node
Comment: I saw you are a new contributor. Don't forget to read the [Code of Conduct](https://stackoverflow.com/conduct), and please remember to validate the answer that solved your problem so that it doesn't appear in unsolved problems :)
Answer: In your docker file, you are using
COPY . .

This mean that, when you build your docker, you copy your current folder to the default folder of your container. Probably /root
But this copy isn't executed every time you RUN the container or START it, it's only when you BUILD.
To be able to see every change you make in real time without re BUILD, you need to create a volume, wich will be a link between your host and your container. Every content changing on the host or the container will be shared to the other.
Note that in your dockerfile, declaring a VOLUME won't actually change anything, it's just an information. To actually make a volume you need to add -v /host/path:/container/path in your docker run command line.
Answer: Remove copy statement and past below with your own path, ADD also supports global variables
ADD /host/path /container/path


What is it called when the tritone is added to a minor scale?

Question: While improvising today, I discovered that you can create some quite cool, melancholic sounds by adding the tritone to a harmonic minor scale. For A minor, the resulting scale would be

A B C D D# E F G# A

I guess, I'm not the first one to discover this, which got me wondering, whether there was some kind of a name for it.
The two uses that I found were to either play around the fifth (like E F E D# E), or to use it in conjunction with the raised seventh of the harmonic scale.
Analyzing the scale, it occurred to me that the D# is actually the major seventh of the dominant chord, which makes the second use quite logical (major third and major seventh of the dominant chord).
Are there any better insights into the use of the tritone with a minor scale? And is there a name for it?
Comment: You've just discovered the ["blue note"](https://en.wikipedia.org/wiki/Blues_scale#Hexatonic). It's basically a combination of harmonic minor and blues hexatonic minor.
Comment: @piiperi That's exactly why I asked: I felt like I've stumbled across the tip of an iceberg, and I felt curious, how other, more musical people than me, have named that iceberg, and what other aspects they have discovered about it. I didn't want to narrow the scope of the question to the specific spike of ice that I saw sticking out of the water. And, no, I didn't record anything. I just stashed the general idea away in my brain, in the hope of being able to find other good uses and variations of it in the near future.
Comment: Well said, a tip of an iceberg! :) I suspect that you probably lack the necessary tools to see what the iceberg consists of - a huge variety of different harmonic turns that can be done with a set of notes as wide as what you listed. And the thing is - if you use the notes to play melodic lines, your imagination may accompany it with harmonic turns that use even notes outside the set of notes you listed. :) Even with the C major scale, depending on how you play it, your mind may imagine e.g. a D major chord, B major chord, E major or A major chord somewhere, even though they contain sharps.
Comment: It is impossible to guess or reverse-engineer what you have played, through exchange of textual messages. Can you upload a recording somewhere? A whole world of different harmonic changes and songs can be done with the notes of the C major scale: C D E F G A B. Or the A minor harmonic scale A B C D E F G#. _Adding_ a note or two does not make the world of possible musical things any smaller, it makes it even larger. :)
Comment: I'll make an answer with an example of what I mean.
Answer:
...A B C D D# E F G# A

Just the list of tones isn't enough to describe in a meaningful way what is happening. It could have various musical meanings.

D# could be a chromatic passing or neighbor tone.
D# could be the temporary leading tone of E, harmonically V/v

A lot depends on the harmonic context. Even if you have playing only a single melodic line there is usually an implied harmonic context. The harmonic context will really be the thing that informs us about what it could be called.
Even this... E F E D# E ...isn't really enough to say.
D# looks like a chromatic neighbor tone, but whatever you played before it could imply something else.

...use of the tritone with a minor scale

That wording sort of implies a harmonic tritone. If you aren't playing A and D# simultaneously or outlining A to D# in some way, that wording might be a bit misleading. At least for me I would be expecting to hear the discordant sound of a tritone. Just E F E D# E alone won't necessarily produce that tritone sound.

EDIT
An additional point occurred to me that I think is worth mentioning. Whether this tone is a raised ^4 or lowered ^5 scale degree it is an alteration of a tonal degree. (The tonal degrees are tonic ^1, subdominant ^4, and dominant ^5.) Glossing over some details, tonal music basically does not alter those degree, or those alterations signal a shift in tonal center. That can be contrasted with alterations to modal degrees like the submediant where such alterations don't change the tonal center but change the mode. For example, in minor a raised submediant gives the modal flavor of the Dorian mode.
In terms of what to call this particular tone we can first ask if a tonal shift if occurring. If not, then some sort of unessential, embellishment is the likely best description. I don't think that changes anything about my answer above, but it might help to point out the tonal degree alteration aspect.
There is one other possibility. This may be stretch, but given that the OP mentioned in comments...

The harmonic context was basically a constant alternation between the tonic minor (Am) and the dominant major (E). Just a simple improvisation

...an additional thing should be pointed out.
Let's take the list of tones and permute them to start on E:

[E F G# A] [B C (D)   E]
                    ^
                    D#

the square brackets denote tetrachords
the parenthesis on D natural mean either omit or treat an unessential
the arrow shows the addition of D# to the scale

If we treat the scale this way, we get two harmonic tetrachords and the scale becomes E double harmonic. If you play this scale on A, you would call it the fourth mode of the double harmonic scale. According to Wikipedia the fourth mode is the most common mode of the scale.
Strictly speaking the D natural should be skipped in order to really define the double harmonic. In which case we are dealing with an altered tonal degree.
Comment: The harmonic context was basically a constant alternation between the tonic minor (Am) and the dominant major (E). Just a *simple* improvisation :-)
Comment: What would be a better term for the added note if I'm not using it as a harmonic tritone (i.e. not sounding together with A, but rather like an addition to the scale, using it next to either D, E, or G#)?
Comment: What style is this: rock, classical, blues? `G#` and `D#`, like `G# B D#` or `G# E D# E` or something else?
Comment: +1 for tha last sentence alone - in A minor , D# isn't a tritone. And with D and E either side, it won't be. Maybe put an A in..?
Comment: @cmaster, I added some detail about alteration of `D` versus just simply adding `D#`
Answer: Adding the D♯/E♭ into your playing isn't much to do with the harmonic (or any other) minor.
It's a flat 5 in blues, or a sharp 4 in jazz. Take your pick - especially if you're a guitarist..!
It's a note that's been used and used since the early 1900s, as so out of tune it sounds really good.Works just as well in major keys too.Since it's between the sub-dominant and the dominant notes in a diatonic situation, it doesn't really fall into either camp. Did the player mean to play a semitone higher, or a semitone lower? What the heck, it's sweet and sour!
Answer: You may have been doing many different things with the notes, depending on how you emphasized the notes in relation to a beat you heard in your mind. Maybe you just flirted with the blue note - maybe you played something "modal" ... but perhaps you were outlining chord changes with the notes you played. Maybe your playing lead yourself to imagine chord changes you weren't even outlining! With the notes listed you could arpeggiate e.g. an Am, Dm, F, E7 chord. Or a Dm6. Or maybe you just played an A note and imagined something like a Dm? It depends on many things. Extra things that can be done by adding a D# note are e.g. B7, which would be a "secondary dominant" for Am. Or an F7 which could be seen just as a bluesy IV chord for C, but perhaps a bit like a tritone substitute for B7.
I really can only guess what really happened with your improvisation, but here's an example of something that could be done with the notes. First there's just an improvised solo guitar line, trying to outline a melancholic progression. Then there's the same solo, but with piano and bass accompaniment.

Many chords of the accompaniment use notes outside the set you listed. But when it comes to melodies, what you play is not all you hear! :)
Like you said in your comment, you may have just found the tip of an iceberg. To develop a sensitivity for harmonic changes, and an understanding of what it is that you're painting with your improvised solos, I recommend learning to accompany songs with chords by ear. I, IV, V, etc. C - F - G - C. Am - Dm - B7 - E7 - Am, etc. In my honest opinion, knowing harmony so that you can recognize and improvise chord changes, and how the melody notes interact with the changes, is a key to musical playing that's missing from some young players these days. They want to "play scales" or modes, but don't have a hands-on understanding for functional harmony. New pop songs seem to use just pentatonic scales, which are ambivalent about harmonic turns. A pentatonic scale can be played almost anywhere without knowing what's happening with the chords, and on the other hand, a pentatonic melody can be quite freely accompanied with chords. But when you play these notes that you have in your set - B, F, D#, G# - not so! That's heavy stuff, it says something about possible harmonic changes. :)
Comment: Thanks a lot, that gives me some stuff to think about :-)
Comment: @cmaster The solo was meant to exaggerate the harmony aspect, and the accompaniment was some sort of a realization of the harmony I was thinking about when playing the solo. Other people will get different ideas. But the point is, when you play the important notes like D# strongly on a strong beat, it can alter the harmonic feeling almost like if you had played a whole chord. Practice it: record your solo, listen to it and try to find suitable accompaniment chords that highlight the nature of the solo.
Comment: @piiperi - wouldn't the chords come first in that sort of situation. If I noodle without them, they're always going through my mind - otherwise I don't know where I am, and it's aimless.
Comment: @Tim that's exactly the question I was trying to bring up - the improviser should have some sort of a structural blueprint of what's happening, and the OP seemed to lack the harmonic aspect of it. He seemed to be trying to make sense of individual notes without considering what kinds of harmonic structures might be built from them. At least for me it works both ways - whatever I hear brings suitable chords and possible changes to my mind as it's happening, and I usually try to beef up the changes or redirect it somewhere. When I make mistakes, they feed the action-reaction loop just the same.
Comment: In this case I started with an idea of something like Московские окна by Tikhon Khrennikov, because the E-D#-E thing reminded me of how it starts, and because things like that allows doing B7-E7-Am movements as well as Am - E/G# - Am7/G - Am6/F# and Gm6/E - A7 - Dm, which I thought were examples of strong movements that could be - if not _outlined_ - at least brought to mind with the given set of notes.
Comment: @piiperi - absolutely. A good improviser can show the chord structure without using any chords, just by the notes he plays. And of course a chord structure begs certain notes *to* be played.


Prove that $\frac{3a^3+7b^3}{2a+3b}+\frac{3b^3+7c^3}{2b+3c}+\frac{3c^3+7a^3}{2c+3a}\ge 3\left(a^2+b^2+c^2\right)-\left(ab+bc+ca\right)$

Question: Let $a;b;c>0$. Prove that $$\frac{3a^3+7b^3}{2a+3b}+\frac{3b^3+7c^3}{2b+3c}+\frac{3c^3+7a^3}{2c+3a}\ge 3\left(a^2+b^2+c^2\right)-\left(ab+bc+ca\right)$$

My proof:
That inequality is equivalent
$2a^4b+2b^4c+2c^4a+3ab^4+3bc^4+3ca^4\ge 5a^2b^2c+5a^2bc^2+5ab^2c^2$
It is easy to prove $ab^4+bc^4+ca^4\ge a^2b^2c+a^2bc^2+ab^2c^2$ ( divide both sides by $abc$ and use Cauchy-Schwarz's inequality)
So we need to prove $2a^4b+2b^4c+2c^4a+2ab^4+2bc^4+2ca^4\ge 4a^2b^2c+4a^2bc^2+4ab^2c^2$
$\Leftrightarrow \sum_{cyc} (a-b)^2(2c^3+bc^2-b^2c+ac^2-a^2c+3ab^2+3a^2b)\ge 0$ .Done
This is my proof but I spend a lot of time getting the last inequality. I need another solution use SOS which is easier than mine.
Comment: Why not Muirhead? $(4,1,0)\succ (2,2,1)$. AM-GM is easy too... as $(4,1,0)+(0,1,4)=2*(2,1,2)$.
Comment: Yea, i know. We have so many solution for this problem but i am researching only about S.O.S.
Answer: Yes, SOS helps.
Indeed,
$$\sum_{cyc}\frac{3a^3+7b^3}{2a+3b}-\sum_{cyc}(3a^2-ab)=\sum_{cyc}\left(\frac{3a^3+7b^3}{2a+3b}-3b^2+ab\right)=$$
$$=\sum_{cyc}\frac{(a^2-b^2)(3a+2b)}{2a+3b}=\sum_{cyc}\left(\frac{(a^2-b^2)(3a+2b)}{2a+3b}-(a^2-b^2)\right)=$$
$$=\sum_{cyc}\frac{(a-b)^2(a+b)}{2a+3b}\geq0.$$


Custom InkCanvas (MSDN Code Sample not working properly)

Question: I want to use custom brushes with the InkCanvas.
Their is a code snippet from MSDN. (http://msdn.microsoft.com/en-us/library/ms747347.aspx)
If i use that code and move my mouse VERY fast i get space between the brushes(ellipses):

And my question is of course how to fix this but I'm also curious why this is happening (I want to learn from it) I thought maybe i did something wrong but even if i cut/paste the example it's happening.
One little thing i noticed when reading the code was this comment in the CustomStroke class
<code>// Draw linear gradient ellipses between
// all the StylusPoints in the Stroke
</code>
Seems to me like it should draw ellipses between the points not only at the points.
I'm using C#.NET.
Again in short:

Why is this happening
Help me fix it :)
Answer: Why this is happening
The custom InkCanvas in the example draws an ellipse at every collected StrokePoint but makes no attempt to draw lines between them.  The standard InkCanvas control is implemented by drawing lines between the points it is given.  This is why the custom InkCanvas implementation from the example leaves gaps and the built-in one doesn't.
How to "fix" it
The custom code could easily be extended to not leave gaps:  In addition to drawing ellipses at each point, it could draw lines between each pair of points.
Code to draw connecting lines might be added before the code to draw the ellipses, like this:
<code>// Draw connecting lines
var geo = new StreamGeometry();
using(geoContext = geo.Open())
{
  geoContext.StartFigure(stylusPoints[0], false, false);
  geoContext.PolyLineTo(stylusPoints.Skip(1).Cast<Point>(), true, false);
}
drawingContext.DrawGeometry(null, connectingLinePen, geo);

// Draw ellipses
for(int i = 1; i < stylusPoints.Count; i++)
{
  ... etc ...
</code>
This code works by constructing a polyline StreamGeometry and then drawing it to the context.  Using a StreamGeometry in this context is generally more efficient than creating a PathGeometry with a Polyline or doing a bunch of DrawLine calls directly on the drawingCanvas.
Note:  Using a better digitizer won't solve the underlying problem, which is that the custom InkCanvas is actually designed to only show data at the sampled points and not in between.
Comment: Thank you, it's working now. I just needed to add a line to connect the dots together.
Answer: ReDAeR
Look this
http://msdn.microsoft.com/en-us/library/bb531278.aspx
Answer: Why this is happening:  The WPF InkCanvas control has a limited number of inputs per second when using a mouse; meaning that your stylus inputs will have greater and greater distances between them as you move the mouse faster and faster.  The sample itself appears to draw elipses at every stylus input point, not in-between the points.
How to solve this:  use a Tablet PC - a digitizer such as on a Tablet PC  has a much higher number of inputs per second so it is more difficult to encounter, or fill in the blanks - essentially estimate based on previous points, perhaps a bezier curve.
Comment: Ok but why is it only happening when I'm using a Custom InkCanvas? The regular InkCanvas works as expected


Unfirom convergence of sequence of functions

Question: Let $\{f_n(x)\}$ be sequence of functions defined on a set $E$. Let for any $n$ we have $|f_n(x)|\leqslant c_n$ and $c_n\to 0$ as $n\to \infty$. Does it follow that $f_n$ converges uniformly on $E$?
I can't prove it rigorously.
Comment: What is $x$?  Is $x$ fixed before choosing $n$?
If you have $||f_n(x)||_E \le c_n$, then the answer is yes.
Comment: @GNUSupporter, It means that you fix $n$ and for any $x\in E$ we have $|f_n(x)|\le c_n$. Can you show the proof please?
Comment: This standard result is from the definition of sup-norm.
Comment: Maybe it's standard but I can't prove it. I would be very grateful to you for your help!
Answer: Yes,
By the given hypothesis if $f(x)=\lim_{n\to \infty} f_n(x)$ then $f(x)=0$.
So $M_n=\sup_{x\in E} |f_n(x)-f(x)|=\sup_{x\in E} |f_n(x)|\leq c_n\to 0$ for $n\to \infty $
Thus $f_n$ converges uniformly to $f$
Comment: Very nice result! What about if $c_n\to L$ as $n\to \infty$ and $L\neq 0$?
Comment: then the answer is no
Comment: Can you show a countereexample?
Comment: Well you can consider $f_n(x)=x^n;x\in[0,1] $ Here $c_n=1$ .$f_n$ does not converge uniformly
Answer: Counterexample is the following:
Let $f_n(x)=x^n$ on $E=[0,1)$. For any fixed $n$ we see that $|f_n(x)|=x^n<1=c_n$ and $c_n\to 1\neq 0$ but $\{f_n(x)\}$ does not coverges uniformly on $E$.
Comment: the OP has asked for a proof ;not counter example


Interpolation of missing values using results produced by arima

Question: I would like to know if anyone knows how to apply the arima results to calculate missing values in the observation period.  I am looking for something similar to forecast.arima(), that forecasts values based on arima results.
Does anyone has experiences in using data from other sources that are complete but with less accuracy, to replace the missing values? Is it feasible to decompose both datasets using stl and recalculate the new values using the observation data?
I am using daily climatic observations for a large number of years, although some of the missing data is between observations, I have also large periods of time without any observations.
Answer: Box and Jenkins all the way back in the first edition of their book (1970) proposed backcasting as a way to "fill in" missing values in the middle of a time series.  The link I gave is for the most recent 2008 edition.


The expectation including an indicator function

Question: I stumbled upon this homework question and I simply cannot wrap my head around it:

As far as I understood it, I would start off with the following:

But I get completely stuck from here on out. Perhaps my first move is already wrong. Could anyone please help?
Thank you very much in advance!
Comment: You have one too many integral signs.  There should be one per $d$.  The rest is calculus.
Comment: Thank you very much!
Answer: You should begin with
$\int\limits_{-\infty}^\infty e^{mx} I_{X \leq d} f(x) dx$
where $I$ is the indicator, $f$ is the density function. This then becomes
$\int\limits_{-\infty}^d e^{mx} \frac{1}{\sqrt{2 \pi}} e^{-x^2/2} dx$
The main trick you'll want to use is $e^{mx} e^{-x^2 / 2} = e^{-x^2/2 + mx}$. Then, you'll want to complete the square.
Comment: Thank you very much! I got the correct answer! I greatly appreciate the effort!
Comment: @MathNoob123 You're welcome! I'm glad I could help.


Drupal 7 view's operator "Is one of"

Question: In Drupal 5 there was a possibility to filter our content type's NIDs using "is one of" operator. So I have a view where I only used one filter like
<code>Node: Node ID -> Is One Of -> <?php return callback_function() ?>
</code>
This callback_function() returns an array of NIDs and my view works just perfect. While moving project to Drupal 7 I discovered that there is no more such operator. Does anybody knows any possibility to use this good old "Is One Of" operator? Thank you!
Comment: I just found that there was a *Views PHP Filter* module that allows to use PHP in filters, but it only exist for D5 and D6.
Answer: Solution was to use View PHP module and Global: PHP field in filters.

Drupal 7 view's operator "Is one of"


the KeyError: 1 problem , whats the problem?

Question: in this code :
j=1
for item in orderOFsssReserve:
  fforderOFsssReservefff=[]
  for item0 in orderDoubles1:
    if(item.studentidof== item0.userid):
      orders_student[j].setdefault(j, []).append(item0)
      break

in this line of code  :
      orders_student[j].setdefault(j, []).append(item0)

I have this error :
KeyError: 1

help me please
Comment: You're using the variable `j` in your code, where did you define that? The error signals that you are trying to retrieve an element from a dictionary using the key '1', which is not available in your dictionary. I suspect that is caused by you using the `j` variable in your code.
Comment: Obviously, there is no key `1` in `orders_student`. Post your input values.
Comment: i defined the `j =1` variable befor this code .
Answer: my problem was:

orders_student[j].setdefault(j, []).append(item0)

and i try this :

orders_student.setdefault(j, []).append(item0)

it works !


Erro: non-static method getAtivo() cannot be referenced from a static context no java

Question: Eu estou tentando acessar o  método da classe Projeto getAtivo pela classe Curso no método getNumeroProjetosAtivos, mas quando tento acessar aparece o erro:

Non-static method getAtivo() cannot be referenced from a static
context.

Aqui a classe Curso
package ProvaLogica;

import java.util.List;
import java.util.ArrayList;

public class Curso {
    private String nome;
    private String sigla;
    private List<Projeto> projetos;

    public Curso(String nome, String sigla ) {
        this.nome = nome;
        this.sigla = sigla;
        this.projetos = new ArrayList<>();
    }

    public void adicionarProjeto(Projeto projeto) {
        this.projetos.add(projeto);
    }

    public int getNumeroProjetos() {
        int soma = 0;
        for (int i = 0; i < projetos.size(); i++) {
            soma = i + soma;
        }
        return soma;
    }

    public List<Projeto> getProjetosAtivos() {
        return this.projetos;

    }

    public  int getNumeroProjetosAtivos() {

        int soma = 0;
        for (int i = 0; i <= projetos.size(); i++) {
            if (Projeto.getAtivo () ) {
                soma++;
            }
        }
        return soma;
    }

    public String getNome() {
        return nome;
    }

    public String getSigla() {
        return sigla;
    }
}

E aqui a classe Projeto
package ProvaLogica;

import java.util.List; import java.util.ArrayList;

public class Projeto {
    private String titulo;
    private boolean ativo;
    private Curso curso;
    private List<Pessoa> participantes;

    public Projeto (String titulo, boolean ativo, Curso curso ){
        this.titulo = titulo;
        this.ativo = ativo;
        this.curso = curso;
        this.participantes = new ArrayList<>();

    }

    public String getTitulo(){
        return this.titulo;
    }

    public  boolean getAtivo(){
        return this.ativo;
    }
    public void adicionarParticipante(Pessoa pessoa){
        try{
            if (this.ativo == true)
                this.participantes.add(pessoa);
        }catch(RuntimeException erro1){
                System.out.println("Não é possível adicionar participante em um projeto não ativo");
            }

    }

    public int getNumeroParticipantes(){
        int soma= 0;
        for (int i=0 ; i<participantes.size(); i++){
            soma = i+soma;
        }
        return soma;
    }

}

Comment: https://pt.stackoverflow.com/search?q=cannot+be+referenced+from+a+static
Comment: Isto responde à sua pergunta? [Referência estática dando erro ao acessar](https://pt.stackoverflow.com/questions/365986/refer%c3%aancia-est%c3%a1tica-dando-erro-ao-acessar)
Answer: Há um erro de lógica em sua implementação.
Estou supondo que o problema está na implementação do método getNumeroProjetosAtivos:
Veja que está tentando acessar um método de classe, porém deveria usar um método de instância de uma classe para acessar o método getAtivo(). Por isto o compilador está dando um erro de que o método getAtivo() não é estático, porque na verdade você tentou acessar aquele método diretamente através da implementação da classe Projeto.
Para saber a causa raiz do erro é necessário entender o que é um método estático, métodos estáticos pertencem a uma classe e são acessados diretamente sem a necessidade da instância de uma classe. Eu posso utilizá-lo diretamente fazendo uma chamada através da classe (que é o que tentou fazer).
Os métodos estáticos são frequentemente métodos utilitários encontrados nas classes System, Wrapper e Collections. Os métodos estáticos são criados quando o estado do objeto não tem efeito em seu comportamento porque dependem apenas de seus parâmetros de entrada.
Você pode saber mais sobre métodos estáticos acessando a documentação.
Desta forma, uma maneira de corrigir o problema seria acessando o método getAtivo() de uma instância da classe Produto.
Outro erro está na maneira que está iterando sobre os elementos desta coleção. Neste trecho:
for (int i = 0; i <= projetos.size(); i++) {

Da maneira que declarou as variáveis ocorrerá um erro java.lang.IndexOutOfBoundsException, então será necessário corrigir a maneira que itera sobre a coleção. Para isso basta remover o '='.
O código final ficará desta forma:
public  int getNumeroProjetosAtivos() {
int soma = 0;
for (int i = 0; i < projetos.size(); i++) {
    if (projetos.get(i).getAtivo () ) {
       soma++;
    }
}
return soma;

Aprenda mais sobre o método get do tipo List.


Example from MSDN does not work - try/finally

Question: I have been reading about try/finally on MSDN and found out following code. They say it WILL run the Finally clause but when I run it, it just does not continue and does not run it. What is the problem?
 public class TestTryFinally
    {
        public static void Main()
        {
            int i = 123;
            string s = "Some string";
            object o = s;

            try
            {
                // Invalid conversion; o contains a string not an int
                i = (int)o;
            }

            finally
            {
                Console.Write("i = {0}", i);
            }
        }
    }

Answer: Looks fine to me. It will indeed run the finally block. My guess is that the debugger is popping up a dialog box for you, and you're not managing to force execution to continue.
Run it not under the debugger - that will avoid the debugger getting in the way as it tries to "help" you.
Comment: Can you explain what "popping up" is, please?
Comment: @Simon: He means the exception popup.
Answer: Are you sure that the window is not closing so fast that you do not notice?
Put in a readline to make it wait:
public class TestTryFinally
    {
        public static void Main()
        {
            int i = 123;
            string s = "Some string";
            object o = s;

            try
            {
                // Invalid conversion; o contains a string not an int
                i = (int)o;
            }

            finally
            {
                Console.Write("i = {0}", i);
                Console.Write("Press Enter to continue.");
                Console.ReadLine();
            }
        }
    }

Answer: Just to expand on Jon Skeet's answer, the debugger will not pop up if you catch the exception.
try {
    i = (int)o;
}
catch(InvalidCastException e) {}
finally {
    Console.Write("i = {o}",i);
}


Google App Script Function: Return Drive Filename from File URL

Question: I've searched extensively for an answer to this, but have not had much luck. I think it should be a fairly simple answer. Here's what I'm trying to do:

I have a list of (other) Google Sheets document URLs in a Google Sheet.
I'd like to have a simple function that loads the URL in each line and returns the file name.
To illustrate, if the URLs are in A2:A10, a user could input a custom function like =GetFileName(A2) and it would return the file name corresponding to the Google Sheet URL that is in A2.

Here's the code that I have thus far, but it's returning an error, " TypeError: SpreadsheetApp.openByURL is not a function (line 3)."
function getFileName(fileURL) {

  var GetFile = SpreadsheetApp.openByURL(fileURL);
  var GetName = GetFile.getName();
  return GetName;

}

UPDATE *************
Here's the code that worked for me. Basically, it loops through the sheet with IDs to pull file names. Not the most efficient, but works for relatively short lists just fine.
function getFileName() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  // DocumentIDs are listed in the 'tool' sheet
  var targetSheet = ss.getSheetByName("tool");
  // Find the last row
  var LastRow = targetSheet.getLastRow();

  //Loop Begins
  //Initializing variable assumes that the first valid Drive ID is in the 3rd row.
  for(var i = 3; i < LastRow; i++) {

    // Get the Document ID. This gets the Document ID
    var LookupID = targetSheet.getRange(i,1).getValue();

    // Get the Filename
    var FileOpen = SpreadsheetApp.open(DriveApp.getFileById(LookupID));
    var FileName = FileOpen.getName();

    // Write the FileName in the second column
    targetSheet.getRange(i,2).setValue(FileName);

    Logger.log(i);
    Logger.log(LookupID);
    Logger.log(FileName);

  }

}

Answer: Suggestion:
You can try this script together with using clickable image to act as a button for the function to run the script below:
function convertURLtoSheetName() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var cell = ss.getActiveCell().getValue();
  var getSheetName = SpreadsheetApp.openByUrl(cell).getName();
  var seturl = SpreadsheetApp.newRichTextValue().setText(getSheetName).setLinkUrl(cell).build();
  ss.getActiveCell().setRichTextValue(seturl);

}

Here is how you assign a script function to an image:
Answer: Custom Functions Cannot open other spreadsheets (SpreadsheetApp.openById() or SpreadsheetApp.openByUrl()).
reference
Comment: Thanks! I didn't realize that. In that case, I guess the best approach would be to just create an array with all the URLs and get the file names in a loop. That make sense?


Using Central Limit Theorem to determine number of simulations required

Question: I am trying to determine how many simulations are adequate to estimate number of claims in the next twelve months using a homogenous poisson process.
What I did is simulate 1000 times, find the mean and standard deviation of those simulations, and used CLT to find N (5% confidence interval), what I found is a really small number (<1), this can't be possible. How come CLT doesn't work in this case? is it because 1000 is too small?
I simulated 1000 times and I have a vector with 1000 elements. I calculated the average of these elements and the standard deviation, and I used the formula:
(0.05*Average)/(standard deviation/sqrt(n))=1.96 for a 5% CI with 95% probability.
edit: I followed the formula in the photo, when I calculated the standard deviation, it is very large (around 80).
Comment: Your last formula doesn't make sense to me. If you put sample std. dev for the std.dev in the formula, it's wrong, since you normally divide the deviation of a $X$ by $\sqrt{N}$ to get the normalizing constant in this case. Btw, where did you get your formula?
Comment: I tried to follow the follow in the image, didn't really work for me
Comment: Where did you get this formula from? Do you have any references? It seems it plugs in $\alpha$ inside the probability, and $1-\alpha$ outside on the LHS, which doesn't make sense when $\alpha=0$
Comment: this is from my lecture in uni :) when I use the sample deviation, I get a really small number using that formula, I also tried using your formula down below, and I get 4000k which is very large?
Comment: What did you put for $w$ in that formula? There is no large or small, it depends on your $w$ :). What is your sample mean and sample std. deviation?
Comment: my sample mean is 6365 and deviation is 83, I used 0.05 for w to have a 95% CI, and I got 4m as my N
Comment: Well, if you input 0.05 for $w$, it means you want to be 95 % sure that your mean resides in $6365\pm 0.05$, which can be large of course, since your standard deviation is around $80$. don't use $w$ as a probability. Use it for constraining your range, i.e. $[\mu \pm w]$
Comment: Correcting here also: $[\mu \pm w/2]$
Answer: Let's say you've made several experiments and got your means as $X_1,X_2,...X_N$. The essence of CLT is approximating sample mean as normal, i.e. $\bar{X}=\frac{1}{N}\sum_{i=1}^N{X_i}$ is assumed to be normal. And, rest assured that $1000$ is not a small number in this case. So, your estimated sample mean is approximately normally distributed.
If you want to have a $95 \%$ CI for your estimate, you can just add and subtract $2\sigma_{\bar{X}}$ to your observed mean. Here, if you don't know the true deviation of $X_i$ (if you know it,  $\sigma_{\bar{X}}=\frac{\sigma_{X_i}}{\sqrt{N}}$, you can also estimate it using your sample set.
Your question, "what should $N$ be for 95% CI?", is not complete. For every $N$, you can have a 95 % CI. Of course, for small $N$, it'll be large since you're more uncertain and vice versa. Here, you can adjust $N$ to limit the width of your CI, i.e. what should N be such that my CI has width = $w$? For this, we first calculate the width (for 95 % CI), and that is $4\sigma_{\bar{X}}=4\frac{\sigma}{\sqrt{N}}$, and you'll have $N\approx \left(\frac{4\sigma}{w}\right)^2$
Comment: is the sigma in (4σ/w)^2 the sample standard deviation from my 1000 simulations?
Comment: Sorry for misunderstanding in my first comment, you can plug in the sample standard deviation for $\sigma$, yes. Normally, $\sigma$ is true dev, where $S$ is denoted for sample dev.
Comment: Hi! so I want to compute N so that my range is constrained as 6365±5, i used your formula and got 4200, which seems reasonable. However, i was just wondering, how come in your formula, there's no sample mean and 1.96? i.e. the critical value for 95% probability?
Comment: Btw, my mistake: $\mu \pm w/2$, so N is nearly 1K. Since you have a normal distribution, and know the sample deviation, the width doesn't depend on $\mu$. Please check the link in my answer. And, that $1.96$ is actually embedded in $2\sigma$ in my formula. The number $1.96$ is for std. normal, which has $\sigma=1$, and $2\sigma \approx 1.96$.
Comment: But my sigma is 80 and no where close to 1, does that mean its not normally distributed?
Comment: You're confusing std. normal dist. vs normal dist. $\bar{X}$ is normal while $\frac{\bar{X}-\mu}{\sigma}$ is std. normal.
Comment: so the correct formula is (4*std)/(w/2) all squared?
Comment: No, the formula is true,  but $w$ is the complete width, i.e $10 \pm 2$ has $w=4$.
Comment: @gunes, excuse my dimness. Is $2\sigma_{\bar X}$ to approximate $\Phi^{-1}(.975) \sigma_{\bar X}$?
Comment: @Student yes. $\Phi(2)\approx 0.975$ (not perfectly equal), this is a common approximation.
Comment: @gunes thank you for confirming. That is interesting because I'd always seen it written to two decimal places. Perhaps a difference of disciplines?
Comment: Most z tables use 4 decimal places. But, it's because $\pm 2\sigma$ corresponds to 95 % CI for normal data. The right and left ends of it each has 2.5 % of the data, which makes the CDF value at 2 0.975


How to get body outside of request.post() in node.js?

Question: I am getting response from request.post but I want the body to send outside of request.post(), how do I do that?
request.post(options, (err, resp, body) => {
      if (err) {
          return console.log(err);
      }
      console.log(JSON.parse(body));
  });

Comment: Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call)
Answer: This seems like you're looking for a controller-service structure, where the controller lists the endpoints and calls the service functions.
This is a very much simplified version, but you could do something like this:
let serviceFunction = (err, resp, body) => {
    if (err) {
          return console.log(err);
    }
    console.log(JSON.parse(body));
}

request.post(options, serviceFunction);

This way you separate the endpoint definition and the handling of the request.


Can someone explain why there is a lack of symmetry in accessing methods from smypy

Question: I know quite a bit about core python, but the class part is somewhat of a mystery to me.
For example I'm having difficulty understanding
sympy.ntheory.primetest
The documentation for sympy includes a primality test  assessable as
   sympy.ntheory.primetest.isprime(n)

https://docs.sympy.org/latest/modules/ntheory.html#sympy.ntheory.primetest.isprime
So if I want to reference isprime without all the preceding stuff, I can do
(1)  from sympy.ntheory.primetest import isprime
and then  isprime(31) for example,  will return True.
However I can also do
(2) from sympy.ntheory import isprime
and then isprime(31) will also work. So the primetest part is redundant.
So the question is why do both (1) and (2) work?
I would have thought just (1) would work.
To add further confusion, consider  is_square
Here we have, according to the documentation,
sympy.ntheory.primetest.is_square
but in order to use is_square by itself I must do
from sympy.ntheory.primetest import is_square
whereas if I do
 from sympy.ntheory import is_square

I get an error
ImportError: cannot import name 'is_square' from 'sympy.ntheory'
So there seems to be a lack of symmetry with  some of these methods.
In the is_square case I needed to include primetest in the import statement in order to avoid getting an error, whereas for isprime it made no difference if I included primetest or omitted it. Why is there a difference?
Comment: Strictly speaking these are functions, not methods.  They aren't bound to a class or instance of a class. So import can be more flexible.
Answer: This is often refereed to as "re-exporting" names. Essentially, the authors of sympy chose to strip away a level of module-namespacing to make importing commonly used functions more convenient.
sympy.ntheory's __init__.py includes the import
from .primetest import isprime, is_gaussian_prime

as well as the __all__ export
__all__ = [
    # ...
    'isprime', 'is_gaussian_prime',
    # ...
]

This exposes the function isprime from sympy.ntheory.primetest as an member of sympy.ntheory, and allows isprime to be glob imported with from sympy.ntheory import *. As you noted, not all names in the ntheory submodules are re-exported in this way. Names that are not re-exported (like is_square) must be accessed through their defining submodule.
Comment: Also, sympy's `__init__.py` does the same thing, so you could even write `from sympy import isprime`.


Há como acrescentar figuras sobre um plot no R

Question: Gero está figura:

ao usar esse código:
library(tidyverse)
library(plotly)

 tres <- readRDS(
url("https://rawcdn.githack.com/fsbmat/StackOverflow/b4fbf2fe0a59555a2cf77776ab9454a4fb06ba83/tres.rds"))

plot <- tres %>% ggplot(aes(Time, Pontos,
                            fill=Time,
                            text=paste("Time:", Time, "
",
                                       "Pontuação: ", Pontos)))+
  geom_col(show.legend = FALSE)+
  theme_bw()+
  geom_text(aes(label=Pontos),nudge_y = 2)
ggplotly(plot, tooltip = "text", width = 600, height = 600)%>%
layout(showlegend = FALSE,
title = list(
text = paste0('Os três primeiros colocados', '
', '', 'Campeonato Brasileiro de 2019', '')),
margin=0) %>% style(textposition = "top")

Gostaria de saber se há como adicionar estas figuras usando códigos no R:

Para gerar a figura abaixo no próprio R usando a função ggplotly:

Consegui fazer a figura no ggplot, com o código:
library(png)
ouro <- readPNG('~/Caminho da Figura/Ouro.png')
prata <- readPNG('~/Caminho da Figura/Prata.png')
bronze <- readPNG('~/Caminho da Figura/Bronze.png')

tres %>% ggplot(aes(Time, Pontos,
                            fill=Time,
                            text=paste("Time:", Time, "
",
                                       "Pontuação: ", Pontos)))+
  geom_col(show.legend = FALSE)+
  theme_bw()+
  geom_text(aes(label=Pontos),nudge_y = 2)+
  annotation_raster(ouro, ymin = 75,ymax= 90.1,xmin = 0.75,xmax = 1.25)+
  annotation_raster(prata, ymin = 59,ymax= 74.1,xmin = 1.75,xmax = 2.25)+
  annotation_raster(bronze, ymin = 59,ymax= 74.1,xmin = 2.75,xmax = 3.25)

Link para as figuras: Clique aqui!
Comment: Caro Guilherme, me desculpe a ignorância em não observar a obviedade da tag. Mas acho sua solução ótima, parabéns pela iniciativa e obrigado por ajudar a melhorar o stackoverflow em português!
Comment: Olá fsbmat, uma duvida, qual a relação do plotfy com a pergunta? Plotfy é uma lib JS, tem algo especifico ou correlacionado?
Comment: Oi Guilherme, vc leu errado, o nome correto da função é plotly!
Comment: Não fsbmat, eu não li errado, é a tag que você adicionou [tag:plotly], essa tag é sobre uma LIB javascript
Comment: Vc escreveu Plotfy na sua primeira pergunta, eu escrevi plotly. Essa última tag é referente a um pacote do software R que possui esse nome!
Comment: Caro fsbmat, isso é claramente um erro de digitação comum quando se digita rápido, é bem óbvio.... o que importa é a descrição da tag (print: https://i.stack.imgur.com/V9Kuu.png), se ler ela se refere a lib JS do Plotly e não a de Python e a de R, mas ao menos essa confusão por parte dos usuários de JS, Python e R que usam essa tag me fez tomar uma decisão, vou separar em 3 tags diferentes para evitar problemas nas organizações das perguntas para ajudar futuros visitantes a pesquisarem. Até breve.
Answer: Consegui fazer a figura também no ggplotly, usando o código abaixo:
plot <- tres %>% ggplot(aes(Time, Pontos,
                            fill=Time,
                            text=paste("Time:", Time, "
",
                                       "Pontuação: ", Pontos)))+
geom_col(show.legend = FALSE)+
theme_bw()+
geom_text(aes(label=Pontos),nudge_y = 2)

ggplotly(plot, tooltip = "text", width = 600, height = 600)%>%
  layout(images = list(list(
    source = raster2uri(as.raster(ouro)),
    x = 0.75, y = 75,
    sizex = 0.5, sizey = 15.1,
    xref = "x", yref = "y",
    xanchor = "left", yanchor = "bottom",
    sizing = "stretch"
  ), list(
    source = raster2uri(as.raster(prata)),
    x = 1.75, y = 59,
    sizex = 0.5, sizey = 15.1,
    xref = "x", yref = "y",
    xanchor = "left", yanchor = "bottom",
    sizing = "stretch"
  ), list(
    source = raster2uri(as.raster(bronze)),
    x = 2.75, y = 59,
    sizex = 0.5, sizey = 15.1,
    xref = "x", yref = "y",
    xanchor = "left", yanchor = "bottom",
    sizing = "stretch"
  )),
  showlegend = FALSE,
  title = list(text = paste0('Os três primeiros colocados',
                             '
',
                             '',
                             'Campeonato Brasileiro de 2019',
                             '')),
  margin=0) %>%
  style(textposition = "top")


What is the best way to put comments section to user profile

Question: I need add ability to add comment for user profile. What i am thinking is, create a content type with empty body and leave just comments, and afterwards insert that node to user_profile.
But i don't know how to append comments to user profile tpl file. How to do this, or maybe other suggestions?

After some research i decided to make my own module to add comments on
  user profile, i will make a block and insert this block to only user
  page user/*, and will track user id to show proper comments.
Comment: Do you use profile2 module ? what is your drupal version?
Comment: yes i have profile2 module, drupal version 7
Answer: If you use Profile2, this creates profiles as node type entities so you can turn comments on as each profile will have settings similar to that when you create content types.
Comment: there is not setting for add comment ,`admin/structure/profiles/add` or in `admin/structure/profiles/manage/test` . profile  not support commenting by default
Comment: My bad, just tried and you are correct there is no option. My answer is how it used to work for Drupal 6
Comment: any other suggestions?
Comment: You could look at http://drupal.org/project/reply but this is in dev
Answer: If you want add comment to profile  in template files, do you  think how you want realate those with eachothers?
I suggest you using modules like commentfield . install and add a comment field in your profile type.
Your right,  please look at this issue and this
Comment: in this module you cannot add comments on a view page
Comment: I said some module like it ,as example [reply](http://drupal.org/project/reply)


Apresentar DIV sobre outra DIV

Question: Estou usando uma DIV com a mensagem "processando" e fundo opaco, todas as vezes que ocorre uma requisição (iteração do usuário ao clicar em um botão).
Porém, esta tela também é apresentada quando estou com uma tela modal aberta, e acaba acontecendo que a tela de processamento não fica sobreposta sobre a tela modal.
Todo o meu layout foi desenvolvido com Bootstrap 3.
Como faço para sobrepor a div de processamento sobre a modal?
Comment: Você quer que fique exatamente como na imagem? Já tentou alterar o Z-index dessa Div de processamento para que o Z-index seja maior que o da Modal?
Comment: O problema é que o z-index que o bootstrap usa é 1050. É padrão para toda Modal
Answer: CSS oferece a possibilidade de se trabalhar em camadas nas suas páginas, assim você pode sobrepor elementos uns sobre os outros usando a propriedade z-index...
Como você disse que o bootstrap usa um valor z-index de 1050 você pode alterar isso sobrescrevendo a regra css para o z-index do modal, para fazer isso sua folha de estilo precisa estar abaixo da folha da folha do Bootstrap no seu documento HTML ou então as únicas regras que vão ser sobrescritas são as suas.
Para obter mais informações sobre o uso da propriedade Clique Aqui
Answer: A solução é você renderizar o HTML do modal de processamento após o modal de cadastro. Para organizar tudo, segue exemplo:

Quando chamar o modal de processamento, irá sobrepor o outro modal.
Comment: na verdade @Matheus isso já está acontecendo. É o botão confirmar da tela de cadastro que requisita a renderização da tela de processamento.

Apresentar DIV sobre outra DIV


How to get text of an object of type View

Question: Agnostically, we are recognizing the currently showing layout without knowing its name, then we are traversing through all the views in the layout to get their ids using
id = container.getChildAt(i).getId()

then converting the obtaind id to a View using
view = findViewById(id)

then we are trying to get the text assigned to that view using
view.getText()

but '.getText' method is not defined on objects of type View
please let mek know to get the text assigned to an object of type View.
Comment: what do you mean under the name if a layout or the View? If you mean `R.id.some_name` - it is not a name existing in runtime - it is `static int` Java identifier, existing only int source code.
`getText()` - is getter for property of instances of certain class that have this property. Layout doesn't have such
Answer: You can check the type of View using instanceof and cast to TextView and get value.
Example:
    if (view instanceof Textview)
    {
      ((TextView)view).getText();
    } else if (view instanceof EditText)
   {
     ((EditText)view).getText();
   }

Instead of getting ids and finding views using findViewById(id) you can use the child from container.
i.e. you can do like this
if (container.getChildAt(i) instanceof TextView)
{
....
}

Comment: ok..but i am not sure if the view i am getting is a TextView or Edittext or exactly what?
Comment: Eg. instanceof EditText


What is an Affine Transformation?

Question: What is an affine transformation? Which families of distribution are closed under affine transformation?
Comment: Could you please be more specific in what context you need to know that, whether this is a homework question and what is wrong with http://en.wikipedia.org/wiki/Affine_transformation ?
Comment: All location-scale families are, by definition, closed under affine transformations, because in one dimension an affine transformation is just a shift in location together with a rescaling. Any family that is not already a location-scale family can be made into one by including all such transformations of its members.
Comment: I was asked in an interview.... the question was "give an example of statistical distribution, other than normal distribution, which is closed under affine transformation".
Comment: To add to @whuber's excellent comment that shows that the answer to the interview questions was "any": one can make any univariate distribution into a location-scale family by replacing the density $f(x)$ with $f^*(x)=\frac{f(\frac{x-mean}{sd})}{sd}$.
Comment: https://en.wikipedia.org/wiki/Affine_transformation
Answer: An affine transformation has the form $f(x) = Ax + b$ where $A$ is a matrix and $b$ is a vector (of proper dimensions, obviously).
Answer: Affine transformation(left multiply a matrix), also called linear transformation(for more intuition please refer to this blog: A Geometrical Understanding of Matrices), is parallel preserving, and it only stretches, reflects, rotates(for example diagonal matrix or orthogonal matrix) or shears(matrix with off-diagonal elements) a vector(the same applies to many vectors/a matrix), and the "non-affine"(also a type of projective transformation as explained in the comment by @whuber) transformation may be like the first example in the following diagram:

More generally speaking affine transformation has the following three properties:

straight lines preserved
  parallel lines preserved
  ratios of lengths along lines preserved (midpoints preserved)
Comment: It is difficult to see in what sense a projective transformation is any kind of "opposite" to an affine transformation.  Indeed, affine transformations are special kinds of projective transformations.
Comment: The projective transformations are the rational functions of order 1.  On the line, for instance, they are given by four numbers $a,b,c,d$ as $$x\to \frac{ax+b}{cx+d}.$$ Usually they are limited to numbers where $ad-bc\ne 0$ for which the transformation is invertible. The transformations associated with $(a,b,c,d)$ and $(a\lambda,b\lambda,c\lambda,d\lambda)$ are the same when $\lambda\ne 0,$ making this a three-dimensional family of transformations.  The affine transformations are those for which $c=0$ and $d\ne 0.$
Comment: @whuber Glad to know that, then I wonder what the other projective transformations are except affine transformation? I mean the formal name of the "non-affine" transformation? Thanks for helping me figure out the "bug".
Comment: FWIW, what makes a transformation "affine" instead of just "linear" is that *in addition* to multiplication by a (noninvertible) matrix, one is allowed to add a constant vector to the result, thereby shifting it away from the origin.  You give only the definition of "linear transformation" here.
Answer: In your comment the interview question you were asked was  "give an example of statistical distribution, other than normal distribution, which is closed under affine transformation".
The example to which the question refers is the fact that if you have a normally distributed random variable $X$, say $X\sim \text{N}(\mu,\sigma^2)$, then an affine transformation is also normally distributed $aX+b \sim \text{N}(a\mu+b,a^2\sigma^2)$.
The terminology in Statistics for distributions which are 'closed under affine transformation' is $\textbf{location-scale family}$.
One example which would answer the question is the continuous uniform distribution. If $X\sim U[\alpha,\beta]$, and $Y= aX+b$ then
$$Y\sim U[a\alpha+b, a\beta+b].$$
Comment: +1.  Some care is needed with the notation when $a\lt 0,$ though.
Answer: So I look here:  http://mathworld.wolfram.com/AffineTransformation.html
It is a rotation.  All points on a line, stay on the same line.
Per @Luca:
It can have scaling, shear, translation as well.  No bending.  Straight lines are always straight.
Comment: Affine is not just a rotation. It could be translation, shearing, scaling, rotation (and others) or any combinations of it AFAIK. I know normal distribution is closed under Affine transformations and it may be the case for the whole exponential family, but I am not sure about that.
Comment: @Luca *All* affine transformations of $\mathbb{R}^n$ can be derived from the linear transformations of $\mathbb{R}^{n+1}=\{x_1,x_2,\ldots,x_{n+1}\}$ that preserve the hyperplane $x_{n+1}=1$. Few of those linear transformations will be "rotations," though: by definition, the matrix of a rotation is orthogonal.
Comment: It would have to be some extraordinarily flexible "augmentation."  After all, suppose a transformation increases the length (Euclidean norm) of a vector: there does not appear to be any meaningful way to make that transformation somehow a component of an orthogonal transformation, which preserves all lengths.  Part of the issue might be that transformations which preserve lines, as you say in your second sentence, are *projective* transformations, which includes much more than rotations; yet not all projective transformations are affine.
Comment: @Luca, I was thinking rotation in the homogenous sense, where a translation was a rotation through another dimension.  Thank you for the clarification.  The center of the rotation is in $\mathbb{R}^n$ then projected back to the original dimensionality of $\mathbb{R}^{m \leqslant n}$
Comment: a common type of affine transformation is $\frac{aX-b}{c}$ btw
Comment: @EngrStudent: Yeah, with homogeneous coordinates to make it a linear operation, it makes sense. But it still does not cover the full range of affine transformations, I think.
Comment: I just thought of it in terms of physics.  I wonder if there is an augmentation that could make it literally a rotation - meeting the orthogonality criterion.

What is an Affine Transformation?


Como adicionar delay para Display:block

Question: Eu estou criando um site, e eu gostaria que nele houvesse um "botão" com o ícone do Whatsapp, e ao passar o mouse por cima desse botão, ele se expandisse e mostrasse o número que eu pus lá. Atualmente o código está assim:
HTML:

(99)99999-9999

CSS:
#whatsapp{
position:fixed;
width:40px;
height:40px;
margin-top:calc(50vh - 55px);
background:url(img/whatsapp.png);
background-color: #25D366;
background-position: center center;
background-size: cover;

}
#whatsapp:hover{
width:50px;
transition-duration: 0.2s;
}

#whatsnumber{
display:none;
font-size:2rem;
position: fixed;
margin-top:calc(50vh - 55px);
margin-left: 40px;
width:max-width;
height:40px;
background: #25D366;
line-height: 40px;
border-right: 10px solid #25D366;
color: white;
}

#whatsapp:hover ~ #whatsnumber{
display: block;
}

#whatsnumber:hover{
display: block;
}

#whatsapp:not(hover){
width:40px;
transition-duration: 0.2s;
}

A ideia é que tem duas DIVs, uma (#whatsapp) que ao passar o mouse por cima vai se expandir, e outra (#whatsnumber) que ao passar o mouse por cima deveria esperar um segundo e então aparecer.
Eu tentei usar o transition-delay para fazer o "display:block" ter efeito após um segundo, mas não está funcionando.
Como resolver?
Comment: Você gostaria de uma forma de aumentar a sua div ao passar por cima da mesma?
Answer: Segue uma alternativa.

div {
  clear: both;
}

.icon {
  position: absolute;
  top: 0px;
  left: 0px;
  height: 32px;
  width: 32px;
  background-repeat: no-repeat;
  background-size: calc(100% - 4px);
  background-position: center;
}

.social {
  position: relative;
  float: left;
  width: 32px;
  padding-left: 32px;
  box-sizing: border-box;
  overflow: hidden;
  line-height: 32px;
  border-radius: 5px;
  box-shadow: 0px 0px 5px black;
  white-space: nowrap;
  transition: width 0.5s linear;
  margin: 3px 0px;
}

.social:hover {
  width: 150px;
}

.icon-whatsapp {
  background-image: url('https://image.flaticon.com/icons/svg/220/220236.svg');
}

.icon-skype {
  background-image: url('https://image.flaticon.com/icons/svg/220/220235.svg');
}

.icon-tweet {
  background-image: url('https://image.flaticon.com/icons/svg/220/220233.svg');
}

.icon-facebook {
  background-image: url('https://image.flaticon.com/icons/svg/220/220200.svg');
}

  (99)99999-9999

  (99)99999-9999

  (99)99999-9999

  (99)99999-9999

Answer: Não é possível adicionar transição nos eventos: display e visibility.
A explicação é:

Ambos o visibility: hidden; e o display: none; não respondem a event
  handlers, enquanto que o opacity permite event handlers de serem
  chamados.

Então pode chegar ao resultado esperado utilizando opacity e a transição (transition) com 1 segundo:

#whatsapp{
position:fixed;
width:40px;
height:40px;
margin-top:calc(50vh - 55px);
background:url(img/whatsapp.png);
background-color: #25D366;
background-position: center center;
background-size: cover;
transition: all 1s;
}
#whatsapp:hover{
width:50px;
}

#whatsnumber{
opacity:0;
font-size:2rem;
position: fixed;
margin-top:calc(50vh - 55px);
margin-left: 40px;
width:max-width;
height:40px;
background: #25D366;
line-height: 40px;
border-right: 10px solid #25D366;
color: white;
transition: all 1s;
}

#whatsapp:hover ~ #whatsnumber{
opacity: 1;
}

#whatsnumber:hover{
opacity: 1;
}

#whatsapp:not(hover){
width:40px;
}

(99)99999-9999

Mais informações nessa pergunta: transition não funciona no Javascript

Como adicionar delay para Display:block


JAGS: posterior predictive distribution

Question: I am fitting a simple linear regression model with R & JAGS:
model {
    for (i in 1:length(ri)){
        ri[i] ~ dnorm(mu[i],tau)
        mu[i] <- alpha + b.vr*vr[i] + b.ir*ir[i]
    }

    #posterior predictive distribution
    for (j in 1:length(pvr)){
        pmu[j] <- alpha + b.vr*pvr[j] + b.ir*pir[j]
        pri[j] ~ dnorm(pmu[j],tau)
     }

    #priors for regression
    alpha ~ dnorm(0,0.01)
    b.vr ~ dunif(-10,0)
    b.ir ~ dunif(0,10)

    #prior for precision
    tau ~ dgamma(0.001,0.001)
    sigma <- 1/sqrt(tau)
}

I am trying to calculate the posterior predictive distribution with new data (pvr and pir in the model). But somehow the reported results (pri) do not make sense (the means of pri are smaller than expected).
Could someone explain me, is something wrong with the model specification?
Comment: could you at a minimum provide the input data that you are using?
Answer: disclaimer I still don't fully understand your model; but without at least a reproducible example, this is the best I can offer. It is not clear exactly what you are doing here. For example, how are pvr and pir calculated? Would it make sense to calculate them inside the same model?
Answer
I am assuming that your data includes observations for mu[] but not pmu[] and you want to estimate pmu[j] given j values of pvr and pir.
Append the pir and pvr to the ir and vr columns, get rid of the second for loop, and then consider the values of mu[] estimated using pir and pvr to be the posterior predictive estimates of mu. Then replace the two for loops with this:
for (i in 1:length(ri)+length(pri)){
    ri[i] ~ dnorm(mu[i],tau)
    mu[i] <- alpha + b.vr*vr[i] + b.ir*ir[i]
}

I have done something similar, but without predicted regressors, similar to the example given by Gelman et al in 'Bayesian Data Analysis' (pp 598-599 starting under posterior predictive simulations).
Comment: @David pvr and pri are user supplied data: they are the predicted regressors...
Comment: @teucer are they predicted from user-supplied values of `ir` and `vr`? if so, how? and if so, why not calculate `pri` and `pvr` yourself inside the JAGS model?
Comment: @teucer, this is a shot in the dark since I still don't understand your model, and this might be the same as what you already have, but would it make sense to append the `pir` and `pvr` to the `ir` and `vr` columns, get rid of the second `for` loop, and then consider the values of `mu[]` estimated using `pir` and `pvr` to be the posterior predictive estimates of mu?
Comment: @David I want to have some credible interval for the predictions (`pri`), this is why having `mu` is not enough. If I append `pvr` and `pir` I would get `alpha`, `b.vr` and `b.ir` for the whole `ri`, right? Or can I have `ri` with missing values e.g. (1,2,3,NA,NA) and append the regressors?
Comment: @teucer yes, you can have ri with missing values; this is a neat feature of bugs that simplifies calculation of a predictive interval.
Comment: @David could please edit your answer accordingly so that I can accept?As I said earlier having only the mean is not enough for my purposes, I would like to have the other statistics...
Comment: @teucer I have updated my answer, I will be interested to know if it works.
Comment: @David Thx! Actually the both approaches work as outlined in [link](http://www.stanford.edu/group/mapss/colloquium/papers/hierarchicalJackman.pdf) (page 39, second paragraph). Your solution is obviously more eficient...

JAGS: posterior predictive distribution


How to create a windows service in XP

Question: How can I turn a given normal application into a Windows service under Windows XP?
EDIT: This is a server application, so it has no GUI and does not require any input or output.
Comment: You should take this question to StackOverflow since it deals with development.
Comment: Not really. Running programs as a system service is fairly sysadmin-y, and as the answers below show, don't involve what we'd call programming or development.
Comment: You can't turn any application into a Windows Service.  It has to implement specific routines so SC knows how to communicate with it.  Sure you can create the service given the instructions below but that does NOT mean it will run.

ex.  do this on Windows XP  sc.exe create "Foo Service" binPath= "%SystemRoot%\system32\notepad.exe"

this creates fine

but then try to run it

SC Start "Foo Service"

[SC] StartService FAILED 1053:

The service did not respond to the start or control request in a timely fashion.
Comment: Definitely seems like a serverfault question to me.
Comment: @JD (first comment) - Which is something I could not possibly have known beforehand. It doesn't -seem- like a StackOverflow question to me, and it probably won't to other people either. (second comment) - Why not post that comment as an answer? It definitely contains useful information.
Answer: You can use SC to create user defined services. This command will create a service:
sc.exe create "Service Name" binPath= "C:\Your Program.exe"

Note there must be a space between binpath= and the program location.
To Delete the service use:
sc.exe delete "Service Name"

Comment: Putting a normal program into use as a service like this is asking for trouble.  If it is a gui program, forget it.  You'll never see the screen.  If it's a console program it cannot rely on the user to enter anything and no output sent to the screen will be seen.

As JD suggested, asking on StackOverflow may yield better long term results.
Comment: Use this answer in conjunction with Oleksandr's SRVANY.EXE answer below.  This will allow you to start/stop the application like a service from the Windows services manager.
Answer: Use SRVANY.EXE from Windows * Resource Kit
For Cygwin applications Use cygrunsrv (NT/W2K service initiator)
Answer: Also, once you successfully started your normal application as a service, I would suggest to test how the application behaves when you log off.
Some applications (old ones?) don't like receiving the message that is sent when logging of or shutting down the computer.
Answer: FireDaemon is another option for doing this.

How to create a windows service in XP


Run ignored test in Resharper 2016.1 in VS2015

Question: Upgraded Resharper to 2016.1 and I'm not able to run NUnit tests marked with the Ignore attribute. This was possible before by right clicking the test and run. Is this a change or am I missing something?
It is very frustrating, I have many tests which I ignore on the build machine which I would like to run locally.
Answer: Resharper has been using NUnit itself to run it's tests for a long time, so it seems you must have done a really big upgrade, from an early version of Resharper that executed the test methods itself. NUnit simply will not run an ignored test, even if you programmatically tell it to do so. Or, to put it differently, NUnit "runs" ignored tests by reporting that they are ignored.
This is actually the definition of "Ignored" in NUnit. It was designed a long time ago to deal with tests that should not be run, generally for a very short period, while the developer is doing other work. It shows up as a warning in any test runs because, in the ideal world, Ignored tests should not make it into your CI runs. It may be the wrong attribute for you to use for your purposes, especially if you want to be able to run it some of the time. If you want a test that is only run when expressly selected, we have the "Explicit" attribute instead. Other behavior is possible, but it would take a feature request.


java.lang.NoSuchFieldError: DESCR

Question: When I try the
http://www.softwarepassion.com/getting-started-with-drools-flow/ tutorial
I get this exception:
<code>Exception in thread "main" java.lang.NoSuchFieldError: DESCR
       at
org.drools.compiler.PackageBuilder.addKnowledgeResource(PackageBuilder.java:539)
       at
org.drools.builder.impl.KnowledgeBuilderImpl.add(KnowledgeBuilderImpl.java:28)
       at
com.softwarepassion.droolsflow.SPDroolsFlowExample.readKnowledgeBase(SPDroolsFlowExample.java:30)
       at
com.softwarepassion.droolsflow.SPDroolsFlowExample.main(SPDroolsFlowExample.java:20)
</code>
How can I resolve this?
Answer: This usually indicates incompatible versions of two libraries. Get the most up-to-date jars of drools and try again. Also make sure you don't have multiple versions on the classpath.
Comment: thanks bhozho my problem was i have used multiple versions of same jar on the class path that was the problem
Comment: You saved my coffee break ;)

java.lang.NoSuchFieldError: DESCR


In Swift 3.1, UnsafeMutablePointer.initialize(from:) is deprecated

Question: In Swift 3.1, UnsafeMutablePointer.initialize(from:) is deprecated. Xcode suggests I use UnsafeMutableBufferPointer.initialize(from:) instead. I have a code block that looks like this:
let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 64)
pointer.initialize(from: repeatElement(0, count: 64))

The code gives me a compile time warning because of the deprecation. So I'm going to change that to:
let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 64)
let buffer = UnsafeMutableBufferPointer(start: pointer, count: 64)
_ = buffer.initialize(from: repeatElement(0, count: 64))

Is this the right way to do this? I just wanted to make sure that I'm doing it correctly.
Answer: It is correct, but you can allocate and initialize memory slightly simpler with
let pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: 64)
pointer.initialize(to: 0, count: 64)

Creating a buffer pointer view can still be useful because that
is a collection, has a count property and can be enumerated:
let buffer = UnsafeMutableBufferPointer(start: pointer, count: 64)

for byte in buffer {
    // ...
}

but that is independent of how the memory is initialized.
Comment: Did not answer the question…
Comment: @StackUnderflow: The question was *"Is this the right way to do this"* which I answered with *"It is correct"* – followed by a simpler solution. Please let me know what you find unclear about this.
Comment: Compile time warning still exists.
Comment: @StackUnderflow: That is strange. I just double-checked with both Xcode 9.2 (Swift 4) and Xcode 9.3 beta 3 (Swift 4.1) that the above code compiles without warnings. – What exact warning do you get at which line?


Como detectar se o navegador aceita eventos xmlhttprequest?

Question: É o seguinte, gurizada, para deixar meu objeto compatível com navegadores antigos (senão me xingam) eu criei um novo problema. É difícil desviar o caminho de acordo com a versão do navegador porque não era tão padronizado, os navegadores aceitavam um recurso e outro não, então fiz o seguinte:
var reqEngatilhar = function(){
    este.concluido = false;
    timeoutId = setTimeout(reqTimeout, este.timeout);
    if(este.Request.hasOwnProperty("onload")){
        este.Request.addEventListener("error", reqErro, true);
        este.Request.addEventListener("progress", reqMon, false);
        este.Request.addEventListener("abort", reqAbort, false);
        este.Request.addEventListener("load", reqFim, false);
        console.log("$Http reqEngatilhar usando eventos...");
    } else {
        este.Request.onreadystatechange = function (e) { reqSwitch(e); };
        console.log("$Http reqEngatilhar usando onreadystatechange...");
    }
}

Esta funçãozinha define os eventos dentro do meu objeto quando muda o estado da requisição xmlhttprequest (onde este=this fora da função). Mas alguns navegadores não aceitam os eventos via addEventListener, então ele define onreadystatechange que fará a "distribuição" chamando a função certa.
O problema é o teste este.Request.hasOwnProperty("onload") que está funcionando apenas para o Safari (meu site só abre no Safari kkkkk).
Então eu pergunto: qual a forma correta (ou melhor possível) de detectar se o navegador aceita os eventos xmlhttprequest via addEventListener?
Comment: Porque não usas `on...` para todos? qual são os browsers que queres suportar? IE7?
Comment: Eu tenho usado o MDN como referência, e ao que parece usar addEventListener é a tendência. IE7 não me interessa, mas mesmo o IE9 dá uns problemas. Eu fiz essa função porque deu problema onde não deveria, mas não anotei o navegador/versão - falha minha.
Answer: Faça assim:
if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    try {
        req = new XMLHttpRequest();
    } catch(e) {
        req = false;
    }
} else if(window.ActiveXObject) { // Se for IE usa o control ActiveX
    try {
        req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
        try {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e) {
            req = false;
        }
    }
}
return req;

Referência completa: https://github.com/pmcfernandes/r/blob/master/Linq.js
Comment: Essa resposta não tem a ver com a pergunta.
Comment: Estou a exemplificar como ficar o código funcionar para todos os browsers. Penso que se a pessoa for no mínimo inteligente vai tirar partido disso. O stack não é um site de fixes mas de ajuda para corrigir e escrever código existem outros sites como o freelancer


Independent joint conditional probability

Question: I am new to conditional probability. I would like to do some inference. If we know p(z|x) and p(z|y), can we infer p(z|x,y)? What can we deduce if x and y are independent? Thank you very much.
Comment: Although I cannot trace the questions and answers, I am sure this question has been asked on CV in the past. In any case, there is no answer to this question with this insufficient amount of information.
Comment: Thanks Xi'an. I have tried the following: p(z|x, y) = p(z,x|y)p(y)/p(x,y). Assume that x and y are independent, the RHS becomes: p(z,x|y)p(y)/p(x,y) = p(z,x|y)/p(x). I don't know how to proceed then. Alternatively,  p(z|x, y) = p(x,y|z)p(z)/p(x,y). If x, y are independent, can we write p(x,y|z) = p(x|z)p(y|z)?
Answer: There is not enough information in $p(z|x)$ and $p(z|x)$ to determine $p(z|x,y)$. In particular, when $X$ and $Y$ are independent, they may become dependent conditional on $Z$: take for instance the exponential variates $X$, $Y$, and $Z$, related by
$$X\sim\mathcal{E}(1)\qquad Y\sim\mathcal{E}(1)\qquad Z|X,Y\sim\mathcal{E}(XY)$$
In this case,
$$Y|X,Z\sim f(y|x,z)\propto xy\exp\{-y-xyz\}$$
is a Gamma$(2,1+xz)$ that depends on $x$.
Comment: Could you briefly explain what your notation "$\mathcal E$" means?


Find the number of polynomial zeros of $z^4-7z^3-2z^2+z-3=0$.

Question:
Find the number of solutions of $$z^4-7z^3-2z^2+z-3=0$$ inside the unit disc.

The Rouche theorem fails obviously. Is there any other method that can help?
I have known the answer by Matlab, but I have to prove it by complex analysis.
Thanks!
Comment: [This](http://math.stackexchange.com/questions/375254/finding-the-number-of-zeros-of-a-function-in-a-given-annulus) might be of help
Comment: It should be $-2z^2$?
Comment: Couldn't this be solved by algebra?
Comment: Sorry, I'm preparing for a complex analysis exam.
Answer: Let $f(z)=z^4-7z^3-2z^2+z-3$ and $g(z)=-7z^3$. Then, for $\lvert z\rvert=1$,
$$
\lvert\, f(z)-g(z)\rvert=\lvert z^4-2z^2+z-3\rvert
<7=\lvert -7z^3\rvert=\lvert g(z)\rvert.
$$
Rouche Theorem provides that $f$ possesses exactly 3 roots inside the unit disc.
The only part to check is that $\lvert z^4-2z^2+z-3\rvert
<7,$ which holds since we have the "$\le$" part, and the only way to have "$=$" is if every term in $z^4-2z^2+z-3$ is negative, which is impossible.
Answer: Note that $|z^4-2z^2+z-3|<7$ if $|z|=1$. The triangle inequality only says "$\leq$" but equality can only occur if $z^4$, $-2z^2$, $z$ and $-3$ all have the same argument. So it suffices to check $z=-1$.


Como requisitar dados do dia no SQL com Unix Time Stamp (PHP)

Question: Ola estou com um com uma duvida aqui, estou criando um código para obter quantos usuários logaram no meu site hoje, porem eu salvo a ultima data que ele logou com Unix Time Stamp.
Eu só estou conseguindo obter o usuários que logaram nas ultimas 24 horas, porem, oque eu quero, é obter os usuário que logaram no dia.
Segue meu código:
$time_24h = time()-86400;

$users_today = $sql->query("SELECT * FROM {$table_prefix}_Users WHERE last_used > {$time_24h}")->rowCount();

Estou usando a conexão PDO.
quem puder me ajudar, ficaria muito grato, obrigado pela atenção :)
Comment: Depende da base de dados. Se puder postar qual é na pergunta, melhor, pois isto é algo para ser resolvido do lado do SQL e não do PHP. Trazer os dados para filtrar localmente gera tráfego e processamento desnecessário. A maior parte dos engines de DB permitem você fazer as conversões localmente, assim como obter o dia corrente de uma data para comparar com o de hoje
Comment: ola @Bacco, estou usando MySql.
Comment: Dei uma complementada com algumas considerações importantes. Qualquer dúvida avise.
Answer: O ideal seria resolver na camada SQL, que depende do engine usado.
Para MySQL
Basta fazer direto no select:
                       .--- converte de Unix para Timestamp, compativel com MySQL
                       |
SELECT ... WHERE DATE(FROM_UNIXTIME(last_used)) = CURRENT_DATE;
                  |                                |
                  '--- extrai a data, sem horas    '--- compara com data de hoje

Resolvendo com PHP
Uma maneira de fazer com PHP é simplesmente determinar quando começa o dia em Unix Timestamp, e adicionar 86399 segundos, e localizar valores nesta faixa, ficando assim:
$hoje = time();                            // Pega o timestamp do servidor já em segundos
$iniciododia = ( $hoje % 86400 ) * 86400;  // "arredonda" para 0h00 do dia
$fimdodia = $iniciododia + 86399;           // e obtem o 23h59m59 do dia

Aplicando à sua query:
"SELECT * FROM {$table_prefix}_Users WHERE last_used BETWEEN $iniciododia AND $fimdodia"
                                                     |
           retorna dados entre 0h00m00 e 23h59m59 ---'

A solução dada serve para outros dias, trocando o time() pelo dia desejado, mas se quer somente os do dia atual, pode simplificar mais ainda:
$hoje = time();                            // Pega o timestamp do servidor já em segundos
$iniciododia = ( $hoje % 86400 ) * 86400;  // "arredonda" para 0h00 do dia
// ... desnecessário calcular o fim do dia para data atual ...
"SELECT * FROM {$table_prefix}_Users WHERE last_used >= $iniciododia"

Se for só a contagem
Lembre-se que é desnecessário trazer todos os dados se quiser saber apenas a contagem. Da forma como está sua query original, você está trazendo todos os dados do DB para a data desejada desnecessáriamente. Considere fazer isto:
"SELECT COUNT(*) FROM {$table_prefix}_Users WHERE last_used >= $iniciododia"

aí basta pegar o único valor retornado em vez do rowCount().
Answer: Você pode obter os usuarios logados no dia (no formato YYYY-mm-dd) usando a classe DateTime do php e a função DATE_FORMAT do MYSQL. Você poderia fazer assim:
//dataAtual  terá o formato YYYY-mm-dd, ou 0000-00-00, ano com quatro
//digitos, mes e dia com dois
$dataAtual = (new DateTime())->format('Y-m-d');

//aqui você formata last_used no formato YYYY-mm-dd
$users_today = $sql->query("SELECT * FROM {$table_prefix}_Users WHERE
DATE_FORMAT(FROM_UNIXTIME(last_used), '%Y-%m-%d') = {$dataAtual}")->rowCount();

A função FROM_UNIXTIME converte do formato Unix timestamp para o formato Datetime, que por sua vez é formatado apenas para Date.
Comment: ola, eu estou usando o código que você esta sugerindo, porem o sql não esta achando nada, eu acho que o last_used, no código que você me mostrou, depois de uma pesquisada, teria que ser Y-m-d só que eu estou guardando as datas em Unix Time Stamp, se eu estiver errado, por favor me corriga. Obrigado por responder a minha pergunta :D
Comment: @Dante ola, realmente me confundi, achei que sua data estava no formato datetime. Já corrigi a resposta para se adaptar à sua situação. Basicamente converti de unix time stamp para datetime.
Comment: bom, tentei o novo código que você escreveu, mas não funcionou =/. A resposta do @Bacco era o que eu precisava, mas mesmo assim, obrigado pela ajuda