Como selecionar um radio através de outro?

Question: Digamos que eu tenho 3 inputs do tipo 'radio' (A,B,C) e eu tenho outros dois 'radio'(X,Z) Logo de inicio os radios X,Z estarão desabilitados e só poderão ser auto-selecionados se o radio B ou C forem clicados, e se eu clicar no radio A, os radios(X,Z) devem voltar e ficar desabilitadas novamente.
Segue o código como exemplo, to querendo colocar tudo isso em JavaScrip (não sei se tem outra forma, mas o meu interesse seria JS):
<FORM>
   <fieldset><legend> CAIXA 1 </legend>
      <input type="radio" id ="rada" name="planoSaud" />A
      <input type="radio" id="radb" name="planoSaud" />B
      <input type="radio" id="radc" name="planoSaud" />C
   </fieldset>
</FORM>
<FORM>
   <fieldset><legend> CAIXA 2 </legend>
      <input type="radio" id ="radx" name="planoSaud" />X
      <input type="radio" id="radz" name="planoSaud" />Z
   </fieldset>
</FORM>

Valeu!
Answer: Você pode adicionar um eventListener aos radios A, B e C. Adicione também disabled="disabled" aos radios X e Y para eles carregarem desabilitados:

var els = document.querySelectorAll("#rada, #radb, #radc");
for(x=0;x<els.length; x++){
   els[x].addEventListener("change", function() {

   if(this.id == 'rada'){
   }

   document.querySelector('#radx').disabled = document.querySelector('#radz').disabled = this.id == 'rada' ?
   true : false;

   if(this.id == 'rada'){
      document.querySelector('#radx').checked = document.querySelector('#radz').checked = false;
   }

  });
}
<FORM>
   <fieldset><legend> CAIXA 1 </legend>
      <input type="radio" id ="rada" name="planoSaud" />A
      <input type="radio" id="radb" name="planoSaud" />B
      <input type="radio" id="radc" name="planoSaud" />C
   </fieldset>
</FORM>
<FORM>
   <fieldset><legend> CAIXA 2 </legend>
      <input disabled="disabled" type="radio" id ="radx" name="planoSaud" />X
      <input disabled="disabled" type="radio" id="radz" name="planoSaud" />Z
   </fieldset>
</FORM>
Comment: Ali no caso quando eu clicar no Rad'B' e depois clicar no Rad'Z' por exemplo, e sem seguida eu clicar no Rad'A' o Rad'Z' é apenas desabilitado, teria como eu limpar ele, pois ele ainda fica como se estivesse selecionado.
Comment: @Ricksoz97 Resposta atualizada.
Comment: Teria algum outro método que poderia ser utilizando sem usar `querySelector`? devido a eu estar iniciando ainda a utilizar lógica de programação (tanto pra page web quanto pra software). Ai no caso eu estava utilizando em alguns exercícios o `document.getElementById('teste').disabled= false` e com o `querySelector`eu não estou conseguindo rodar ele direito no JS.
Comment: @Ricksoz97 Tem sim... peraí que vou fazer aqui e te mando
Comment: @Ricksoz97 Aí seria necessário criar um array com os ids dos radios A, B e C. Veja neste JSFiddle: https://jsfiddle.net/62s22u65/


Laravel - View [.site.Home.index] not found

Question: Fui abrir meu localhost hoje para continuar dando inicio ao meu projeto e me deparei com esse erro em todas as páginas que tento acessar, ontem antes de fechar as páginas estava funcionando.
Erro:
View [.site.Home.index] not found.

web.php
Route::get('/', 'SiteController@index');
Route::get('Contato', 'SiteController@Contato');
Route::get('Dicas', 'SiteController@Dicas');

sitecontroller:
public function Dicas(){

        session_start();
        return view('/site.Dicas.index') ;
    }
    public function Regulamento(){
        session_start();
        return view('/site.Regulamento.index') ;
    }
    public function Termos(){
        session_start();
        return view('site.Termos.index') ;
    }
    public function Tutorial(){
        session_start();
        return view('/site.Tutorial.index') ;
    }

Comment: Experimente usar o comando `Ctrl+Shift+F` e pesquisar por `site.Home.index`. Talvez você usava o arquivo e acabou deletando acidentalmente
Comment: sou novo no laravel aonde colocaria esse comando? @MatheusReis
Comment: Esqueci de citar que era pra fazer isso no `VSCode`. Ele tem a opção de pesquisar em todos os arquivos dentro de um `workspace`
Comment: @MatheusReis o site.Home.index existe e qual era o comando q era para executar? acho q vc editou
Comment: `Ctrl+Shift+F`, ele localiza o texto, dentro de todos os seus arquivos
Comment: Não tem barra e mostre aonde está a view
Comment: Pra que chamar a Sessions assim tá errado
Comment: @MatheusReis coloquei e ele achou o ` site.Home.index` na minha pagina SiteController pois la que dou o `return view`
Comment: @VirgilioNovic ja tirei a barra e mesmo assim da o mesmo erro, e onte estava funcionando com a / normalmente, como se chama a session de maneira correta?
Comment: Tem bastante coisa fora do lugar a Sessions vai depender se precisa aí não tô vendo necessidade é preciso ver as pastas
Answer: Estava com o mesmo erro uma vez em um projeto o motivo era que sem querer tinha movido minha pasta resources para outro lugar verifique se sua Pasta resources esta na raiz da pasta do seu projeto
Comment: Obrigado, sem querer pelo visualcode Tinha trocado a pasta de lugar


Does the word 'root' in the context of 'function roots' and 'nth roots' have any relation?

Question: This has been something that in all of my years of mathematics, I haven't ever questioned. Is there any connection to the word 'root' in the context of function roots (e.g. polynomial roots) and nth roots?
In the context of taking the nth root of a number, it's essentially asking 'what number can be raised by n to equal x?'. Thus the 2 root of 32 is asking, 'x^2 = 32: solve for x'
Now in the context of function roots, it's asking 'for what value of the independent variable does the function equal zero?'.
So my question: What's the significance of the word 'root'? What's the history of this word? Why's it being applied to two seemingly different things?
Thanks,
Comment: $f(x) = x^k - a = 0$?
Comment: @user251257 For some reason I find this really interesting. Is this really the connection? The 'nth root' problem is a just a typical function root problem but with constraints?
Comment: what constraints?
Comment: @Teague yes.  The n'th root is a simplification of the general finding a polynomial root.
Comment: The constraint that f(x) = x^k - a
Comment: @QthePlatypus My mind is blown.
Comment: For the history, see *[Earliest Known Uses of Some of the Words of Mathematics](http://jeff560.tripod.com/mathword.html)* under *[R](http://jeff560.tripod.com/r.html)* for "RADIX, ROOT, UNKNOWN, SQUARE ROOT". Note that *radix* is Latin for *root*.
Comment: Another possibly useful link: http://mathforum.org/library/drmath/view/52673.html
Answer: Any formula that asks you to find the n'th root of a number such as $ \sqrt[k]{a} $ can be transformed into an equivalent polynomial root problem $ f(x) = x^k - a = 0$. So finding the n'th root is a special case of the general polynomial root.
Comment: All these years... Thanks for the insight.


How to check ssh availability if check ssh OK then connect to server 1 and if ssh NOT OK then connect to server 2?

Question: I have 2 servers.
The first server is always active and the second server is always in the stanby state.
I'm trying to write a bash script to check the status of these two servers before doing the task.
If the first host dies (or the connect SSH to server 1 not OK) then it will connect SSH to the second host for execution to task.
Any idea on how to do it?
Comment: Check here: https://stackoverflow.com/questions/4936807/how-to-do-ssh-with-a-timeout-in-a-script you should be able to detect a timeout/failure
Comment: `if ssh server1 true ; then ssh server1 ; else ; ssh server2 ; fi`?
Comment: @FreudianSlip: Because, the connection between 2 server is VPN tunnel so able timeout/failure unable use my case.
Comment: @Biffen: Can you more explain for me?
Comment: @donald.sys Explain what?
Comment: @donald.sys Whether you're going over a vpn or not, the ssh timeout or the timeout command will still work.  Ssh wont care if its a vpn or not.
Answer: EDIT2: since OP mentioned that there is a file named IP.list from which server names should be read then following may help you here.
while read server
do
  if [[ -n $(ssh user_name@"$server" "ls -ld /tmp") ]]
  then
      echo "$server is up."
      echo "Exiting from script now.."
      exit;
  else
      echo "$server is NOT up, look for another server."
  fi
done < "IP.txt"

EDIT: Since OP is saying ping is not an option to check server's availability then using ssh only for servers. Considering that your source server(from where you are running the script) and target server(whose status you are checking are having passwordless connection between them so that you will NOT be prompted for any password)
if [[ -n $(ssh user_name@server_name "ls -ld /tmp") ]]
then
    echo "Server 1 is up."
else
    echo "Server is NOT up, look for another server."
fi

You could simple do ping to SERVER1 and see if that is happening successfully in case it not it means server is not up and you could move your things to another stand up server.
if [[ $(ping -c5 SERVER1 | grep -q "5 packets transmitted, 5 received") -eq 0 ]]
then
    echo "Server1 is up."
else
    echo "Server is NOT up, look for another server."
fi

Comment: Because security system, all my servers are deny ping. Do you have a ideas diffirent?
Comment: @donald.sys, please check my edit now and let me know then?
Comment: `[[ $(ssh user_name@server1 exit 10) -eq 10 ]]` is unlikely to ever be true. You're comparing the *output* of `ssh`, not its exit code.
Comment: @Biffen, cool, changed it now and tested too, in case of errors it shows errors.
Comment: @RavinderSingh13:
Yes. But it was not what I expected.
I have a IP.txt file with the contents is 192.168.56.101 and 192.168.56.102. I want to check ssh the connect to two hosts and execution with cases:
**+ If connect SSH to 192.168.56.101 is success then it's will execution run script.sh file.**
**+ If connect SSH to 192.168.56.101 is fail, then it's execution the connect SSH to  192.168.56.102 to run script.sh.**
Comment: @RavinderSingh13 That'll work, but it's unnecessarily complex (and who wants to see the contents (OK, not *contents*) of `/tmp` each time?). Why not just replace the whole `[[ … ]]` with `ssh user_name@server_name true`?
Comment: @Biffen, when I tested it it is not showing me the content of `/tmp`(since I am using `ls -ld`) + when I tried simply doing ssh then it never came back out of that server's session so only I thought to execute a command for ssh and see its status then.


Basic Pygame Graphics

Question: I am just starting to learn pygame graphics. I drew a circle in pygame and was wondering how I program it to change colors.
For example: it changes colors from blue to red.
I need it to keep changing colors until I close pygame and it would be nice if the colors gradually changed from one to another instead of an instant change? Any ideas how I could do this?
import pygame
pygame.init()

RED =   (255,  0,  0)
BLUE =  (  0,  0,255)
BLACK = (  0,  0,  0)
SIZE = (1000,1000)
screen = pygame.display.set_mode(SIZE)

pygame.draw.circle(screen,RED,(500,500),200)

pygame.display.flip()
pygame.time.wait(3000)
pygame.quit()

Answer: I shall progress from simple to harder, and more complex..
Simplest: A for loop that changes the color 3 times, simplest:
import pygame
pygame.init()

RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
SIZE = (1000,1000)
screen = pygame.display.set_mode(SIZE)
colors = (RED, BLACK, BLUE) # tho allow you to iterate over the colors

for c in colors:
    pygame.draw.circle(screen,c,(500,500),200)
    pygame.display.flip()
    pygame.time.wait(1000)
pygame.quit()

Medium: Now an infinite loop, that ends when you close the window..
import pygame, itertools

RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)

colors = (RED, BLACK, BLUE) # to allow you to iterate over the colors

SIZE = (1000,1000)
screen = pygame.display.set_mode(SIZE)

# to cycle through the colors
cycle = itertools.cycle(colors) # create an infinite series..

clock = pygame.time.Clock() # regulate fps

while True:
    # handling events
    for event in pygame.event.get():
        if event.type == pygame.QUIT: # close window event
            pygame.quit()

    c = cycle.next()
    pygame.draw.circle(screen,c,(500,500),200)
    pygame.display.flip()

    clock.tick(6) # run at maximum 6 frames per second

Hardest and most complex: This is the final one, the colors fade into the next one..
import pygame, itertools

def fade_into(c1, c2, n):
    """ Give the next color to draw \n"""
    "Args: c1,c2 => colors, n => int"
    dif = [(c1[i]-c2[i])/float(n) for i in range(3)] # calculate the per-frame difference
    return [c1[i]-dif[i] for i in range(3)] # subtract that difference

RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)

FADE_SPEED = 80 # no of frames for shifting

colors = (RED, BLACK, BLUE) # to allow you to iterate over the colors

SIZE = (1000,1000)
screen = pygame.display.set_mode(SIZE)

# to cycle through the colors
cycle = itertools.cycle(colors)

## needed for fading
c_color = cycle.next() # RED    current_color
n_color = cycle.next() # BLACK  next_color
frames = FADE_SPEED
## --------------

clock = pygame.time.Clock() # regulate fps

while True:
    # handling events
    for event in pygame.event.get():
        if event.type == pygame.QUIT: # close window event
            pygame.quit()

    c_color = fade_into(c_color, n_color, frames) # get next color

    pygame.draw.circle(screen,map(int,c_color),(500,500),200)
    pygame.display.flip()

    frames -= 1
    if frames == 0: # translation complete
        frames = FADE_SPEED
        n_color = cycle.next() # get next color

    clock.tick(40) # run at maximum of 40 frames per second

If you have any doubts, please comment below..
Comment: You, good sir, deserve a medal. That is the most helpful and thoughtful answer given to any question that I have ever seen on StackOverflow. If only all people who answered put the same kind of thought into replies as you do - +1, and I wish I could give more.
Answer: Pygame does not have scene graph, so you need to redraw your shape in a loop and call display.flip() to update.

Basic Pygame Graphics


Proving uniform convergence

Question:
Prove uniform convergence of function series: $$ \sum_{n=0}^\infty \frac{1}{n^2  + x} \sin \frac{1}{n^2  + x}$$ on $ \Bbb R $

I'm stuck with a problem, because I've proven that is uniformly convergent(proof below), while a friend of mine, gave a counterexample to this problem, $$ x = \frac{1 - \frac{\pi n^2}{2}}{\pi/2} $$ and then it is only $$\sum_{n=0}^\infty \frac{\pi}{2}\sin \frac{\pi}{2} =  \sum_{n=0}^\infty \frac{\pi}{2} $$ , so it not uniformly convergent.
Here is my proof of uniform convergence:
$$ \frac{1}{n^2  + x} \sin \frac{1}{n^2  + x} <  \frac{1}{n^2  + x}    $$ , since $$ \sin {x} < 1 $$
and
$$ \frac{1}{n^2  + x}  < \frac{1}{n^2} $$ , which is convergent.
Hence, I claim that by Weierstrass M-Test : $$ \sum_{n=0}^\infty \frac{1}{n^2  + x} \sin \frac{1}{n^2  + x} $$ is uniformly convergent on $$ \Bbb R $$ .
So, where is the mistake? I'd appreciate any help.
P.S Sorry, for any mistakes in latex.
EDIT: I'm awfully sorry it should be : $$ \sum_{n=0}^\infty \frac{1}{n^2  + x} \sin \frac{1}{n^2  + x}$$
Comment: The $n$-th term has a singularity in $-n^2$. You have uniform convergence on $(0,\infty)$, but not on all of $\mathbb{R}$.
Comment: It looks as if you are assuming that $x\ge0$ in your argument. If that is the case, your argument is fine. If not, then you need to assume that $x$ is bounded below before you can make similar estimates. I show how this can be done in my answer.
Answer: As $x$ approaches $-n^2$, $\frac1{n^2+x}\sin\left(\frac1{n^2+x}\right)$ oscillates wildly between very large numbers. Since uniform convergence only worries about the tail, we can fix this by assuming that $x$ is not the negative of a perfect square and that $x\gt-m^2$.
Let $M,N\gt2m$, then
$$
\begin{align}
\sum_{n=M}^N\frac1{n^2+x}
&\le\sum_{n=M}^N\frac1{n^2-m^2}\\
&\le\sum_{n=M}^N\frac1{n^2-(n/2)^2}\\
&\le\frac43\sum_{n=M}^N\frac1{n^2}\\
&\le\frac43\sum_{n=M}^N\frac1{n(n-1)}\\
&=\frac43\left(\frac1{M-1}-\frac1N\right)
\end{align}
$$
This is independent of $x$ as long as $x\gt-m^2$.

Proving uniform convergence


posiçao de vetor em C nao recebe novo valor na atribuição

Question: O valor de um índice de um vetor não recebe atribuição;

Ler 10 valores reais e armazenar em um vetor. Modifique o vetor de modo que os valores ímpares sejam aumentados em 5%, e os valores pares sejam
aumentados em 2%. Imprima o vetor resultante.

<code>#include <stdio.h>

int main()
{
    int n[11]={0};

    for(int i=0;i<10;i++)
    {
        printf("digite o %d numero: \n", i+1);
        scanf("%d", &n[i]);
    }

    for(int i=0;i<10;i++)
    {
       if(n[i]%2==0)
       {
           n[i] = n[i]*0.02;
       }
       else
       {
            n[i] = n[i]*0.05;
       }
    }

    for(int i=0;i<10;i++)
    {
        printf("[%d] = %d\n", i+1, n[i]);
    }
    return 0;
}
</code>
Answer: Cara tem um problema, somente números inteiros são pares ou impar e você disse numero real, editei seu codigo aí, no caso eu converto de float para real uma variavel auxiliar e verifico, e para aumentar vc multiplica por 1.05 ou 1.02 no caso, multiplicando por 0.05 vc ta diminuido vc ta pegando 5% do valor, agora por 1.05, você aumenta para 105% do valor, da uma olhada no código e tenta entender, e sempre use uma constante, ou uma varaivel para definir tamanho, que facilita a manipulação do array

<code>#include <stdio.h>

int main()
{
    const int tam=10;
    float n[tam];

    for(int i=0;i<tam;i++)
    {
        printf("digite o %d numero: \n", i+1);
        scanf("%f", &n[i]);
    }

    for(int i=0;i<tam;i++)
    {
       int a = n[i];
       if(a%2==0)
       {
           n[i] = n[i]*1.02;
       }
       else
       {
            n[i] = n[i]*1.05;
       }
    }

    for(int i=0;i<tam;i++)
    {
        printf("n[%d] = %.2f\n", i+1, n[i]);
    }
    return 0;
}</code>


When are things not executed on the main thread in an iOS app?

Question: I know to make UI updates you need to execute the updates on the main thread. I do that using
<code>[[NSOperationQueue mainQueue] addOperationWithBlock:]
</code>
But at the moment I just simply add it when a UI update doesn't work, without understanding why.
How do you actually know which things are executed on the main thread and which things aren't? Are generally all callbacks and delegate functions on a side thread? What about functions that are executed when certain events are triggered, like button presses?
I would like to know a general rule when something isn't on the main thread, so that I don't have to wait for something to break first.
Comment: This question is way too general. Delegation and callbacks are implementation details and architecture patterns. You cannot make a blanket statement like All delegates are called on main thread. UITableViewDataSource is an example that calls its delegate on the main thread whereas NSURLSessionTaskDelegate is always called asynchronously. It depends where you are. All UI events will and should be main thread.
Comment: So how do you know which delegate is main thread and which is asynchronous? Can you look it up somewhere for each delegate?
Comment: all you can always go if([[NSThread currentThread] isEqual:[NSThread mainThread]) but again it depends. You need to provide examples rather than a generalized question, where exactly are you struggling?
Comment: I'm not struggling anywhere in particular. I develop Apps and sometimes the UI doesn't change the way it should. Every time I realize it's because a specific callback updates the UI of which I didn't know it runs on a side thread. Now I wonder how I can know when using a new callback, delegate, etc. if it's running on a side thread or the main thread. Surely this must be documented somewhere? It can't be that everyone just waits for their code to break to realize it's on the wrong queue.
Comment: Like I said it depends what framework, but almost all UIKit frameworks will callback to the main thread. Networking and core data might not. Depends on the framework sometimes its documented sometimes its not but there is no website that will list all the frameworks and which ones call back to main thread etc.
Comment: Ok thanks, sounds like trial and error will be the quickest way then.
Answer: You can always check if you are running on main thread with +isMainThread method:
<code>-(void)uiUpdateMethod
{
    if([NSThread isMainThread])
    {
        //main just exec code
    }
    else
    {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            //exec code
        }];
    }
}
</code>
However as I understand you want to know exactly what methods are performing on background thread. So unfortunately this is quite complicated question and answer is framework documentation.


Can I ask a question about dual citizenship?

Question: I have a question about a specific situation concerning the possibility of acquiring dual citizenship between Canada and Norway. I've considered Law SE, but I'm unsure whether such a question would constitute legal advice. I also feel that such a question would be better asked here. My question would be along the lines of whether acquiring a second citizenship would require me to renounce my original citizenship, haven been given certain circumstances for possible exemptions to renouncing the original citizenship.
Can I ask such a question here?
Answer: Sounds like a perfect fit to me.
Answer: It's not just a perfect fit, we already have a few questions similar to yours, for example:

Will I forfeit my French citizenship when taking on US citizenship?
What happens when Chinese acquire foreign citizenship?
Renunciation of original nationality in the process of becoming a Dutch citizen

There is also a tag called dual-citizenship


How to set Media Styles in Media 7.1.2 / Media 7.2.X?

Question: Where is the latest form of the component in the Media project family that allows styles to be defined for Media files?
I see a lot of references to the idea that the Media module contains, once contained, or can be compatible with, a UI component that is similar to the Drupal 7 core Image Styles system that allows formats to be defined. Apparently, once upon a time this lived at /admin/config/media-image-styles
There's a module, Styles, by Aaron of Media fame, that has a sub-module called File Styles. On the Styles project decription, it suggests that the Media module implements the API this provides in its bundled sub-module Media Styles. But the latest 7.2.x dev (and also, the latest stable version of the 7.1 branch) of Media that I have downloaded contains no such module, the URL path given for it above goes nowhere, and I can't find any such module as a seperately distributed module. Styles contains a UI module, but this seems to be unrelated to Media, and Styles hasn't been updated since 2011, whereas Media has been in near-constant development since then (with latest Media 7.2.x dev enabled, for me the Styles UI url crashes out with a fatal error Call to a member function getExternalUrl() on a non-object in... ). Also, Styles isn't even mentioned on the current Media project page.
From the way people talked about this media styles UI, it sounds like it was once a very important part of the Media project. I understand the Media project has been in a state of flux for years and documentation has lagged behind the current state of the project.
Where is the latest form of that component that allows styles to be defined for Media files?
Here's some (seemingly now all out of date) related reading:

A documentation page which mentions the path, and has some workarounds dated early 2011
An issue which led to the creation of that documentation page
Aaron's original media styles road map, explaining the rationale behind the Styles module before it was released, written in Jan 2011
Just saw this confirmation that Styles module is definitely deprecated and on its way out of the media family

Edit: Found a clue, buried at the bottom of a "Configuration" documentation page:

The Media module used to rely heavily on the Styles module before
  Media was converted to prefer the file entity and file fields...
  defining new 'display' or view modes... can be implemented using
  http://drupal.org/project/entity_view_mode

But I can't see anything in that linked module that seems to support the kind of functionality I've seen discussed. There's a limited tutorial for the 7.2 branch which involves using Entity View Mode, but it uses it to define image styles for images, using the regular image style interface. Doesn't look to be anything for file styles for non-image files such as videos, or anything that could do anything more advanced, like have one style that shows a video's thumbnail image and another style that shows a video player. The search is still on...
Comment: Related question: http://drupal.stackexchange.com/questions/11182/show-media-preview-image-on-views But the url in the accepted answer (also present in docs linked to above) goes nowhere in the latest versions of Media
Answer: A lot has changed since the madness that was http://drupal.org/node/1092444. Thankfully, theming and setting display formatters for file entities is now much easier and more straightforward.
The following documentation is for Media 2.x and File Entity, although much of it works with Media 1.x with slight alterations (e.g., in Media 1.x, the link to the "File Types" page is in Configuration instead of Structure).
Displaying Media
The File Entity and Media modules work together to provide a unified method for storing, managing, and displaying Media in Drupal. They allow a user to create file fields that can be configured to store and display many different types of media, including images, video, and audio. among others. In order to display these different types of media, file fields need formatters, often provided by the module that provides the Media type, and a little extra configuration.
Definitions
I'll explain a couple of the moving parts first, and then get into customizing the display of files on a site.
File types
Files are grouped into File Types. Each file type is defined by a list of mime types, a universal way of specifying file formats on the internet. The default file types are Application, Audio, Image, Text, Video, and Other. There is currently no way to define new file types in the UI.
View Modes
View Modes are used to tell Drupal 7 (and soon 8) that a piece of content is in a certain context. The content can then be altered or displayed in a way that best suits that context. Two view modes that most people are probably familiar with are the default teaser and full modes. Custom view modes can be defined with modules like Entity View Mode, Display Suite, or in a custom module with hook_entity_info_alter().
The Good Stuff, or: Managing the display of your File Field
A file field's display is managed per file type. Navigate to Structure -> File Types. You will see a list of available file types with links to "Manage fields", "Manage display", and "Manage file display" for each.
Manage Fields
The File Entity module makes all files full fieldable entities, the same as nodes and taxonomy terms. Just like in the "Content types" section, you can add custom fields to each file type.
Manage Display
Again, like in "Content types", you can manage the display of custom fields on each file type. This section does not control the formatting of the files themselves, only the display of fields attached to the file entity.
In this section you will also see a toggle for "Custom Display Settings". When expanded you can enable and disable view modes available for this entity. A view mode must be checked here in order for it to be available in "Manage File Display". At this time it's recommended to use only custom view modes defined by the user and the following default view modes; the rest are left over from Styles module integration and will eventually be removed:

"Teaser" (Currently not included by default. You can add it with the patch in the issue above or define it as a custom view mode)
"Full"
"Preview" (Used in admin contexts, e.g., for placeholders in WYSIWYG fields, in the Media browser, and in the Media field widget)

Manage File Display
In "Manage File Display" you can configure formatters for your file types (yes!). Many Media provider modules add their own formatters here; for example, Media: Youtube and Media: Vimeo both provide a "Preview Image" and "Video" formatter.
Formatters can be enabled and configured for each view mode enabled in their file type's "Manage Display" section. For example, a user may want to display a Media: Vimeo preview image when a node is viewed as a teaser, the Vimeo video when the full node is viewed, and a video with different width and height formatter settings when the node is viewed with a custom view mode called "video gallery". Many formatters (notably "Image") allow the user to select the image styles they have defined in Configuration -> Image Styles.
Because multiple media providers can use the same field, formatters are arranged in a top-to-bottom cascade. Drupal will use the first formatter that can be applied to the output of a field. If a video field enables the "Media: Youtube Video", "Media: Vimeo Video", and "Large filetype icon" formatters for the "Full" view mode, Drupal will use the Youtube formatter if the file's mime type is video/youtube, the Vimeo formatter if the mime type is video/vimeo, and fall back to the large filetype icon if the mime type is video/{anything else}.
Configuring the File Field to display using "Manage File Display" settings
In order for the file field to display using the formatters defined in "Manage File Display", it must be set to display the "rendered file". Navigate to the "Manage Display" page for the content type that contains your file field. Choose "Rendered file" as the file field's format for all view modes in which you would like to use the formatters defined in "Manage File Display".
Further Theming
You can create custom theme functions and template files for even more control with theme hook overrides. The theme suggestions provided by the File Entity module are:
file__{file type}
file__{file type}__{view mode}
file__{mime type}
file__{mime type}__{view mode}
file__{file id}
file__{file id}__{view mode}

Replace all '/' and '__' in mime types with '_' for theme functions and '-' for template files.
Some Media provider modules replace these with their own templates and theme hook suggestions. You can view all available theme hook suggestions with the Devel Theme Developer module, Mothership's Poor Themer's Helper, or hopefully consult the provider's docs for more info.
Outro
Hope this helps. I plan on adding this to the Media documentation, so if I missed something, misspoke somewhere, or a section needs clarification please let me know.
And some short answers to the OP's specific questions:

Media 1.x vs 2.x: even though 2.x is unstable, it's as reliable as many stable version modules on Drupal.org. I think it's worth using for the vastly improved features, but because there's so much work going on support in the issue queue is slow, and as with any dev branch new updates may break your implementation. Still, I use it on production.
Media is in development. Some things don't work as you would hope yet (e.g., non-image WYSIWYG integration). But it still works better at what it does than the combination of modules you have to install to do what it does without it. And it's getting better.
Comment: I've suggested an edit to clarify the section about teaser, full and preview view modes. Can't remember if you can see it straight away or if it needs to be checked by a moderator first - but if you either confirm that it's accurate or edit it so it is, I'll accept this as covering everything I asked for - an excellent piece of documentation (thanks again!)
Comment: Great answer! So the way to control thumbnails and videos seperately is have specific view modes set to use video, and specific view modes set to use images. Makes sense now. Quick question - is the 'teaser' view mode called 'preview' in Media 1.X? The view modes I see in 1.X are Full, Link, Preview, Small, Large, Original, Tokens (no Teaser) - I'd like to be certain about which are the deprecated Styles ones.
Comment: The teaser view mode isn't included in either current version. If I remember correctly, preview is used for WYSIWYG integration, since most WYSIWYGs crash if you try to insert an iframe. You can make a teaser view mode yourself, or just apply the patch in the issue mentioned above. Reading through that issue will explain everything you need to know about Media, Styles, and the weird view modes being used right now.
Comment: Okay, so while that issue is still in development and uncomitted it's very much part of the official plan. So have I understood this correctly: Preview is also non-deprecated, alongside Full and Teaser (it appears so from that issue), but is intended specifically for admin contexts such as displaying placeholder elements within a WYSIWYG editor? Is Preview also the view mode used by the Media content form widget to display uploaded and saved media on node edit forms?
Comment: It may be, and possibly in the Media browser too -- I don't remember off the top of my head. An easy way to check would be to switch it's formatter to URL to file, and see what breaks.
Comment: Yes, on 1.X Preview controls what appears in the media widget. I might give Media 2.X another try since some of the biggest problems I had with it were seemingly strange default display choices which it's now clear how to control. Thanks!
Comment: The tutorial at http://drupal.org/node/1699054 is basically a walkthrough of the system I've described here. I recommend it.
Comment: Yes, it's also the last of the links in my question. It was useful for seeing roughly how some parts of the picture fit together, this answer filled in the gaps and answered the remaining things I was unsure about.
Comment: Insightful answer. To not create a view mode for every image style, see ticket https://www.drupal.org/node/1244476


How to access private fields/methods/properties using f# interactive

Question: F# interactive is a powerful development tool as it allows to run either WinForm or Wpf window and invoke arbitrary code in there.
This gives a way for a 'try-before-you code' approach.
Very often I wish to 'break the boundaries' explicitly and

invoke private/protected methods
access/change private fields and properties

Is there a workaround to achieve this?
Answer: FSI doesn't provide any particular support for this, but you can use Reflection to do the things you want.
open System.Reflection
let field = typeof<MyType>.GetField("fieldName", BindingFlags.NonPublic ||| BindingFlags.Instance)
field.SetValue(myInstance, newVal)

You can go further and define methods or operators to make this even easier.  For instance you can set up F#'s dynamic assignment operator to assign to private fields:
let (?<-) o s v =
  let field = (o.GetType()).GetField(s, BindingFlags.NonPublic ||| BindingFlags.Instance)
  field.SetValue(o,v)

myInstance?fieldName <- newVal (* Note: no quotes around fieldName here *)

Here's some crude code to resolve public or private fields, properties, or methods.  Note that there are plenty of ways in which this will fail (in particular, trying to use it on overloaded methods will not work).
open System
open System.Reflection
open Microsoft.FSharp.Reflection

type DynamicHelper =
  static member MkMethod<'t,'u> (mi:MethodInfo) o : 't -> 'u=
    let typ = typeof<'t>
    fun t ->
      let args =
        if (typ = typeof<unit>) then [||]
        else
          if not (FSharpType.IsTuple typ) then [| box t |]
          else
            FSharpValue.GetTupleFields t
      mi.Invoke(o, args) :?> 'u

let (?) (o:'a) s : 'b =
  let ty = o.GetType()
  let field = ty.GetField(s, BindingFlags.Instance ||| BindingFlags.Public ||| BindingFlags.NonPublic)
  if field <> null then field.GetValue(o) :?> 'b
  else
    let prop = ty.GetProperty(s, BindingFlags.Instance ||| BindingFlags.Public ||| BindingFlags.NonPublic)
    if prop <> null then prop.GetValue(o, null) :?> 'b
    else
      let meth = ty.GetMethod(s, BindingFlags.Instance ||| BindingFlags.Public ||| BindingFlags.NonPublic)
      let d,r = FSharpType.GetFunctionElements(typeof<'b>)
      typeof<DynamicHelper>.GetMethod("MkMethod").MakeGenericMethod([|d;r|]).Invoke(null, [| box meth; box o |]) :?> 'b

With this you can dynamically invoke methods and properties as such:
let (t:System.Type) = "test"?GetType()?BaseType


Why doesn't log transformation change position of maximum

Question: I'm not looking for rationale why log transformation doesn't change position of maximum. I came across this when reading about maximum likelihood and don't really get it about this log transformation. Until now I was taking it as given, but when I wanted to articulate it I couldn't. I was drawing few log graphs and thinking about it, but came to no conclusion.
So, in my case I'm looking for parameters in maximum likelihood method:
$$\theta^* = arg max_{\theta} \prod_{n=1}^{m} p_{data}(x; \theta)= arg max_{\theta} log(\prod_{n=1}^{m} p_{data}(x; \theta)) = arg max_{\theta}\sum_{n=1}^{m} log(p_{data}(x; \theta))$$
$p_{data}(x; \theta)$ is meant as probability distribution parametrized by parameters $\theta$ and we have m training points(or size of sample is m).
I understand log increases anywhere, but how does this prove this application of transformation?(This is rationale given in my book)
Comment: A maximizer of the product is a maximizer of the log of that product and vice versa because log is strictly increasing. That's it.
Answer: Suppose you have $x,y > 0$. Then $x > y \Leftrightarrow \log x > \log y$. Thus if we have a function $f: \mathbb R _{> 0} \to \mathbb R$, then $x > 0 $ is a maximizer of $f$ iff $f(x) > f(y)$ for all $y >0$ iff $\log f(x) > \log f(y)$ for all $y >0$ iff $x$ is a maximizer of $\log f$.


Quero converter uma lista para uma lista de tipo generico?

Question: Quero que uma lista de determinado tipo se torne uma lista de um unico tipo :
exemplos
List<usuarios> se transformar em uma List<T>

obs : não sei se isso é possivel
Ou uma Lista de maça vire uma Lista<T>
o motivo disso é que tenho um metodo que só aceita listas<T> eu queria que ele aceitasse qualquer coisa...
Comment: Teria como [edit] e postar um exemplo de um trecho de código que tenha tentado aplicar essa idéia? (essa parte do método que comentou, e o código que deve chamar esse método). Seria bom que explicasse o que queria que acontecesse, e o que aconteceu de fato. Idealmente, um [mcve].
Comment: Gabriel, seja bem vindo ao StackOverflow. Recomendo a leitura no [tour](https://pt.stackoverflow.com/tour) para entender um pouco mais como funciona as coisas por aqui.
Answer: O proprio List<T> já é um generic, basta você passar o Tipo como List<string> por exemplo e terá uma lista genérica. Caso precise de uma lista que aceite qualquer tipo pode usar o ArrayList ou o proprio List passando Object no tipo (List<Object>).
Comment: Olá, Stan; Seria legal se você pudesse editar sua reposta acrescentando um exemplo de código para ilustrar melhor. (Demonstrando que o  de fato é qualquer tipo, facilitaria para o autor visualizar)
Comment: Vlw Bacco pela dica


Three inequalities with sums of fractions over two positive integers

Question: In a proof, I arrive at three inequalities for all $p,q \geqslant 0$:
\begin{align}
\frac{p+1}{q+1} + \frac{q+1}{p+1} &\geqslant 1 +
      \frac{p}{2q+1} + \frac{q}{2p+1} + \frac{1}{p+q+1};\cr
\frac{2q+3}{p+1} + \frac{p+2}{q+2} &\geqslant 2 +
      \frac{2q+1}{2p+1} + \frac{2}{p+q+2};\cr
\frac{q+1}{p+1} + \frac{q+2}{p+2} + \frac{p+2}{q+2} +
      \frac{p+1}{q+1} &\geqslant 2 + \frac{2p+1}{2q+2} +
      \frac{2q+1}{2p+2} + \frac{2}{p+q+2}.
\end{align}
Any idea on how to attack these?
EDIT: Following the pieces of advice in comments, I expanded everything to get rid of the fractions and form bivariate polynomials which must be positive. In the first case, there is an obvious factor $pq$. Since the polynomial is zero if $p=q$ (the inequality is tight), this means that $p-q$ is another factor, yielding $pq(p-q)^2(2p+2q+3) \geqslant 0$. In the case of the second polynomial, there is a trivial factor $q$, and, again $p-q$. I didn't know how to guess the two last factors, but Wolfram|Alpha helped: $q(p-q)(p-q-1)(2p+2q+5)
    \geqslant 0$.
The last one is fearsome, although the polynomial must have a factor $p-q$.
Comment: Just a hint. Multiply both sides of the first by $$(p + 1) (q + 1) (2 q + 1) (2 p + 1) (p + q + 1)$$ to eliminate all fractions. Then factor to get $$p (p - q)^2 q (3 + 2 p + 2 q)>=0$$
Comment: In general, you can reach the simplest form by adding and multiplying everything together using brute force. It may look hard, but really, it just takes some time.
Comment: Thanks, Ivan and Karolis. It took me almost an hour to get the first one right by hand, but nothing really hard.
Answer: For the last one, multiply through by $2(p+1)(q+1)(p+2)(q+2)(p+q+2)$ to get rid of the fractions; then Wolfram|Alpha factors the difference between the left-hand side and the right-hand side as
$$
(p-q)^2\left(2p^2(q+1)+p(2q^2+9q+8)+2(q+2)^2\right)\;,
$$
which is $\ge0$ for $p,q\ge0$.
Comment: Thank you, joriki. I have a theorem now!
Answer: The first one can also be slightly generalized. If $c>=0$ then:
$$
\frac{p+c}{q+c} + \frac{q+c}{p+c} \ge 1 + \frac{p}{2q+c} + \frac{q}{2p+c} + \frac{c}{p+q+c}
$$
The proof is the same as suggested in my comment above.


Profiling C++ Destructor Calls

Question: I am profiling a C++ application compiled on optimization level -O3 with the intel c++ compiler from intel composer xe 2013. The profiler (Instruments on OS X) states that a very large portion of time is being spent calling the destructor for a particular type of object. However, it will not provide me with information regarding what function allocated the object in the first place. Is there any tool that can provide the information on what functions allocate the largest quantity of a certain type of object?
Edit: I have also tried the -profile-functions flag for the intel c++ compiler with no success.
Comment: Are you looking for a tool that will work in OS X?
Comment: The strict requirement is that it must work with C++
Comment: If you are using `g++/gcc`, `gprof` will be adequate for your needs, I think. Check out this [tutorial on gprof](http://www.thegeekstuff.com/2012/08/gprof-tutorial/).
Comment: Do you control the source code for the object in question?
Comment: Is the constructor defined in a header file or in a separate c++ implementation file (separate compilation unit)?
Comment: It is defined in the header file on account of being a template. Just the constructor is a template, not the object.
Answer: You could add two more parameters to the constructor, the file and the line number.  Save that information in the object, and print it when the destructor is called.  Optionally you could hide some of the ugliness in a macro for the constructor.
<code>#include <iostream>
#include <string>
using std::string;

class Object
{
    string _file;
    int _line;
  public:
    Object( const char * file, int line ) : _file(file), _line(line) {}
   ~Object() { std::cerr << "dtor for object created in file: " << _file << " line: " << _line << std::endl; }
};

int main( int argc, char * argv[] )
{
    Object obj( __FILE__, __LINE__ );
    return 0;
}
</code>
This is how it runs
<code>$ g++ main.cpp -o main && ./main
dtor for object created in file: main.cpp line: 16
$
</code>

Profiling C++ Destructor Calls


At what tempo would J.S.Bach play his fughettas?

Question: As the title says, I'd like to know at what tempo should J.S.Bach's fughettas be played. I specifically speak about BWV 704 Fughetta: Lob sei dem allmächtigen Gott, but I believe it's applicable in general. For this one I have seen two printed versions and none of them mentions any tempo. And for instance here it's played at c. 1/2 = 80, but my intuition would be to play it quite more slowly:

Is there any consensus on the proper tempo or proper tempo feeling of such a piece?
Answer: Tempo assignments and the tempi of performances by others are not normative.
If you consider a slower or faster tempo as more reasonable or more adequate you can always choose another tempo. Mind there will always be people who find it should have been different.
Comment: This.
Plenty of my favorite pieces come in a variety of tempi. They're usually not crazily different, but definitely distinct. I pick the one I prefer. New pieces without a tempo guideline (Italian or otherwise) I treat the same: I take it as a guideline. Some I play slower, some I play faster. I consider them ballpark indications. If there are no guidelines whatsoever, I figure out my own tempo. More often than not, it's in the ballpark when I find a recording or other version. Might be me, but a piece of music seems to carry its speed limits with it.
Answer: I cannot find online manuscripts of Bach's fughettas, but manuscripts are available for the Well Tempered Clavier and the 15 Two Part Inventions. Manuscripts are the actual scores written out by Bach himself.
Those two manuscript sources do not have tempo indications. Certainly no metronome markings but also not even expression markings like "allegro."
At that time musicians had a general understanding about how something should be performed based on meter and the rhythmic value of notes, and also basic genres. As an example, a sarabande in 3/2 meter with lots of half notes was understood to played properly at a slow tempo. But a courante in the same 3/2 meter with lots of quarter notes and shorter values would be played at a brisk tempo. A lot of that was just understanding the conventions of those dance genres, but I think the performance of those dances probably informed the performance of other musical genres with similar meters and rhythm values.
This doesn't mean their were absolutely no tempo/expression markings. Plenty of baroque music would indicate 'vivace', 'gave', etc between musical sections or movements. But it's important to understand many pieces have no indication and there are assumed performance conventions.
I have an Alfred edition of Bach's Inventions which includes an index of metronome markings from about a dozen different previous editions. Some of those tempos differ by double!
I think it's perfectly acceptable for you to try a wide range of slow tempos. Given the title you want gravitas not sprightly (IMO.)
Answer: The tempo choice is often up to the performer. It's not clear what tempi are meant even if an indication is used. This article has some discussion: http://www.pianosociety.com/pages/bachsnotationoftempo/
Tempo may have to be varied depending on venue acoustics. A place with a long reverb time sometimes requires a slower tempo than does a place with short times.  One has to experiment (if there's time) and rely on your own musical taste.
I did read (somewhere) that composers often start using the usual Italian phrases (allegro, adagio, etc.) then try metronome markings, then return to Italian phrases. It's not an exact science (but teaching a judgement to a computer is even harder that teaching it to incoming freshmen).


Show that the set of points $\left\{x\in\mathbb{R}^2 \mid \frac{(x-p)\cdot(q-p)}{|q-p|}\ < \frac{1}{2}|q-p|\right\}$ is the half plane.

Question: Let $H(p,q)$ be a half plane in $\mathbb{R}^2$ such that $H(p,q) = \{x\in\mathbb{R}^2 \mid |x - p| < |x-q|\}$.
Show that
$$H(p,q) = \left\{x\in\mathbb{R}^2 \mid \frac{(x-p)\cdot(q-p)}{|q-p|}\ < \frac{1}{2}|q-p|\right\}$$
My attempt so far
$$|x-p| < |x-q|$$
$$\sqrt{|x|^2+|p|^2-2x\cdot p} < \sqrt{|x|^2+|q|^2-2x\cdot q}$$
$$|x|^2+|p|^2-2x\cdot p < |x|^2+|q|^2-2x\cdot q$$
$$-2x\cdot p+2x\cdot q < |q|^2-|p|^2$$
$$-2x\cdot p+2x\cdot q < q\cdot q-p\cdot p$$
$$-2x\cdot(q-p) <(q+p)\cdot(q-p)$$
But i feel like I've reached a dead end. Probably because I took the wrong direction/approach. Any tips to solving the stated problem?
Answer: Pick up at this line: $$|x|^2+|p|^2-2x\cdot p < |x|^2+|q|^2-2x\cdot q$$
$$2x \cdot q - 2x \cdot p + |p|^2 < |q|^2$$
$$2x \cdot q - 2x \cdot p - 2p \cdot q + 2|p|^2 < |q|^2 - 2 p \cdot q + |p|^2$$
$$2(x - p) \cdot (q-p) < (q-p) \cdot (q-p)$$
I think it is easy enough to finish from here.
Answer: $$\begin{align*}&|x-p|^2<|x-q|^2\iff (x-p)\cdot (x-p)<(x-q)\cdot(x-q)\iff\\{}\\
&|x|^2-2x\cdot p+|p|^2<|x|^2-2x\cdot q+|q|^2\iff|p|^2+2x\cdot(q-p)<|q|^2\iff\\{}\\
&|p|^2+2(x-p)\cdot(q-p)<|q|^2-2p\cdot(q-p)<0\iff\\{}\\
&2(x-p)\cdot(q-p)<|q|^2-2p\cdot q+|p|^2=|q-p|^2\end{align*}$$


Is this correct way to implement GMail widget in Lift?

Question: I'm trying to implement a GMail widget similar to those on iGoogle or Netvibse to practise how to use Comet in Lift web framework.
Currently what I have is the following code, its short and works amazingly.
But I'm not sure about is this best way to implement it. Because retrieve mails from GMail is a time-consuming job, and the following code only has one GMailListener, which will blocks when get mails from GMail.
I guess that means if there are two users on my website, for example UserA and UserB.
Although the following code is thread safe, but if they both on the page that using this Comet, UserB still have to wait until mail of UserA is processed to get his own result, right?
What is the best way to avoid the blocking?
import net.liftweb.actor.LiftActor
import net.liftweb.util.Schedule
import net.liftweb.util.Helpers._
import net.liftweb.http.CometActor
import net.liftweb.http.js.JsCmds.SetHtml
import net.liftweb.http.js.jquery.JqJsCmds._

case class FetchGMail(userID: Int, sender: CometActor)
case class NewStuffs(mails: List[Stuff])

object GMailListener extends LiftActor
{
    def getMails(userID: Int) = {
        // Get Mails from GMail
    }

    def messageHandler = {
        case FetchGMail(userID, sender) =>
            println("Get FetchMail request")
            sender ! NewStuffs(getMails(userID))
            Schedule.schedule(this, FetchGMail(userID, sender), 5 minutes)
    }
}

class Inbox extends CometActor with JSImplicit
{
    def render =
Empty Inbox

    GMailListener ! FetchGMail(1, this)

    override def lowPriority = {
        case NewStuffs(mails) =>
            println("get new mails")
            partialUpdate(AppendHtml("mails",
{mails}
))
    }
}

Answer: Just keep in mind that an actor can only process one message at a time and will only consume resources when it is processing messages.  Your GmailListener is a singleton, so it could be a bottleneck right now, but there is no reason you can't create an instance of GmailListener for each user.  Each instance will only wake up and utilize a thread to do Gmail lookups when your schedule call dictates.  Just make sure that you shut the corresponding GmailListener down when the Inbox shuts down.  Take a look at net.liftweb.http.CometListener which I think should help with that.


RedisToGo - remote Redis server. When to use one?

Question: I like the concept of relying on third-party service hosting my data but what's the point of using super-fast NoSQL storage via remote hosting?
It maybe in different datacenter or even country! And network calls always cost a lot in comparison with local storage.
Or should I use a service like this just in case when I don't query it very often?
Answer:
what's the point of using super-fast
  NoSQL storage via remote hosting?

Because your web/application server is presumably at the remote site as well, thereby enabling it to query the NoSQL database at LAN speeds and then deliver the resulting webpage to your users.
Answer: Hosted Redis is a double edged sword. While you don't have to install and maintain the server, your app's performance will be variable. You should pick hosted redis only when the ping times are very low. If you are not sure, ask for their IP and do a ping/tracert from your server (not from your laptop).
Answer: Also presumably both your site and remote redis server are located in datacenters, so connection is fast.
Someone did the test and reported something like 8 000 - 10 000 ops per second if use machine in different data center. This is still huge performance.


Kafka 0.8 producer, use of "request.required.acks" property

Question: From 0.8 Documentation under  producer config
the property request.required.acks

value controls when the producer receives an acknowledgement from the broker.
Typical values are
(1) 0, which means that the producer never waits for an acknowledgement from the broker
(2) 1, which means that the producer gets an acknowledgement after the leader replica has received the data
(3) -1, which means that the producer gets an acknowledgement after all in-sync replicas have received the data

How do I receive this acknowledgement in producer when the request.required.acks value is 1. The producer.send(MessageKey) being a void I couldn't find any options to retrieve it.
Comment: Just guessing, but maybe an exception is thrown if sending didn't receive an acknowledgement?
Answer: The API for the producer send leaves much to be desired, particularly in the async mode. Those acks are hidden from the user of the producer object. If they fail, you will eventually see an exception.
The problem in the async case is that you will not know were the batch that failed began, so some guessing will be involved if you want to retry the sends later.
It seems that there are plans to improve this in future releases (> 0.8.0).


D3.js: Text is not showing inside a circle(They are on the same level of an element-group). How do I bring the text to the front?

Question: The title says it all, this is the codepen.  The text is not showing within the circles. How do I do to put the text on the front?. This is the code:
var dataset = [ 5, 10, 15, 20, 25, 40 ];

    var w=600,h=600;

    var svg=d3.select("body").append("svg")
                                      .attr("width",w)
                                      .attr("height",h);
    //1st level:All circles group
    var circlesGroup = svg.append("g").classed("general-group",true);
    //2nd level: Group of circle and text
    var elementGroup= circlesGroup
      .selectAll('circle')
      .data(dataset)
      .enter()
      .append("g").classed("element-group",true);

    var circle=elementGroup.append('circle');

    var circleAttributes= circle
      .attr("cx", function(d,i){return i*80+40;})
      .attr("cy", h/2)
      .attr("r", 20)
      .attr("stroke","black")
      .attr("fill", "white")
      .classed("circle",true);

    //text to show
      elementGroup.append("text")
       .attr("text-anchor", "middle")
       .text(function(d) {
         return parseInt(d);
       }).classed('tweet-number', true);

      circle.on('click', function(d,i){

        svg.selectAll('circle').transition().duration(500).attr("r", 20);

      if(d3.select(this).attr("r")==20){
          d3.select(this).transition().duration(500).attr("r", 36);
        }else{
          d3.select(this).transition().duration(500).attr("r", 20);
        }

      });

    //adding background image
    var circlesSelection=svg.selectAll('circle');

This is the generated html which seems to be fine since the circle is at the same level of the text in the element group as it should be:
<svg width="600" height="600">
    <g class="general-group">
        <g class="element-group">
            <circle cx="40" cy="300" r="20" stroke="black" fill="white" class="circle"/>
            <text text-anchor="middle" class="tweet-number">5</text>
        </g>
        <g class="element-group">
            <circle cx="120" cy="300" r="36" stroke="black" fill="white" class="circle"/>
            <text text-anchor="middle" class="tweet-number">10</text>
        </g>
        <g class="element-group">
            <circle cx="200" cy="300" r="20" stroke="black" fill="white" class="circle"/>
            <text text-anchor="middle" class="tweet-number">15</text>
        </g>
        <g class="element-group">
            <circle cx="280" cy="300" r="20" stroke="black" fill="white" class="circle"/>
            <text text-anchor="middle" class="tweet-number">20</text>
        </g>
        <g class="element-group">
            <circle cx="360" cy="300" r="20" stroke="black" fill="white" class="circle"/>
            <text text-anchor="middle" class="tweet-number">25</text>
        </g>
        <g class="element-group">
            <circle cx="440" cy="300" r="20" stroke="black" fill="white" class="circle"/>
            <text text-anchor="middle" class="tweet-number">40</text>
        </g>
    </g>
</svg>

Thank you very much!
Answer: You forgot to set the x and y positions of the text elements:
//text to show
elementGroup.append("text")
    .attr("text-anchor", "middle")
    .attr("x", function(d,i){return i*80+40;}
    .attr("y", h/2)
    .text(function(d) {
        return parseInt(d);
     })
    .classed('tweet-number', true);

Here is your CodePen: http://codepen.io/anon/pen/mOyrMM
The <g> element wrap its content and autosize according to the contents, but it doesn't position the contents.
That being said, an alternative is using translate to the groups, and not setting any position for the texts or the circles:
elementGroup.attr("transform", function(d,i){
    return "translate(" + (i*80+40) + "," + h/2 + ")";
});

The result is the same, check the CodePen: http://codepen.io/anon/pen/yVyVYy
Comment: great answer, I will try the 2nd approach as well just to learn, is there any way with d3 of positioning both vertically and horizontally without using css? and on the codepen you did the onclick for resizing the circle is not working anymore if I press on the number. The number is not expanding if the circle expands as well, should I use a transform over the element group?...what is the common approach in this case? I want to press anywhere on the circle and make it expand......
Comment: First: your code doesn't tell the text to expand. And for avoiding the number getting in the way of the click event, set "pointer-events" to "none" for the texts.


Python: Filtering lists with lambda

Question: Write a Python lambda function which takes a list called my_list and returns a list which includes only even numbers in the same order.
My solution:
f = list(filter(lambda x: (x % 2 == 0), my_list))
print(f)

I'm having issues because I'm doing a homework problem online and it runs various test cases on it and it says my_list isn't defined. Which I understand why that is, because it isn't... but it seems like the question is looking for a broad function which I don't know how to do in this case.
2 questions:

Does my solution look correct?
If so, how do I tailor this so that the homework will accept various inputs?
Comment: From the first line of your post, maybe you are looking for something like this?
`f = lambda lst: [x for x in lst if x % 2 == 0]` You can call it on any list of integers.
Comment: You can just assign to `my_list` a list of arbitrary integers as test data, e.g. `my_list = [3, 7, 4, 1, 2]`
Answer: It does not look correct since f is not a lambda function but a list.
OK, it uses lambda but it is not lambda.
You would probably need to write something like:
f = lambda my_list: list(filter(lambda x: (x % 2 == 0), my_list))

or similar.
For example:
f = lambda my_list: [x for x in my_list if x % 2 == 0]

should also satisfy the requirement.

Of course now print(f) will "print the function".
Answer:
I'm doing a homework problem online and it runs various test cases

Your function is actually correct. But, well, online coding assessment usually use a stdin as input. Python use input() method to retrieve string from stdin. So if you want your submission accept various input, you probably need to add this.
my_list = list(map(int, input().split(' ')))

That will split string input by space character ' ' to be a list. Then, all content in list converted to integer by map function. Since the return value of map function is not a list, you need list method to convert map result into list. The new list will be saved to my_list variable.
But, again, it depends on your input specification. If your input specification are eg: "1, 2, 4, 5". use ', ' as split parameter.

Python: Filtering lists with lambda


How to enable TernJS in sublime text with ES6 modules (Import Statements) on macOS

Question: It is really unclear how to setup tern to work with Sublime Text and ES6 Modules.
What steps should I need to take to enable it?
Answer:
Install tern_for_sublime using Sublime's Package Control
Also, install Fix Mac Path using Sublime's Package Control (why?)
Create a file named .tern-config in you Home directory (not your project):
/Users/<your-username>/.tern-config
{
  "plugins": {
    "node": {},
    "es_modules": {}
  },
  "libs": [
    "ecma5",
    "ecma6"
  ],
  "ecmaVersion": 6
}

To automatically show completions after "." is typed, open your sublime preferences (found in Sublime Text > Preferences > Settings - User) and add this line:
"auto_complete_triggers": [{ "characters": ".", "selector": "source.js"}]

Optionally, you can override settings per project by creating a .tern-project file in the root of your project.

Enjoy.
Comment: Great! By the way, I want to know what your font face, it's beautiful!
Comment: Thank @YangMingYuan! (: I use Hack
https://github.com/chrissimpkins/Hack


How to skip some changes before release branch

Question: I had git history like this
<code>  o  [release]
 /
----o0---o1---o2---o3---o4 [develop]
</code>
and then,I want release new version now, but I want skip o1 and o2 commits... because they are unfinished features, so, how to?
Comment: If they are unfinished features, why are they merged into the develop branch?
Comment: There are many reasons, maybe replan the release schedule, maybe developer mistake, anyways, just have some can't  to release futures..
Comment: In which case, I think cherry picking the commits that you did want onto the release branch would be the only course of action.  See here for more information: http://think-like-a-git.net/sections/rebase-from-the-ground-up/cherry-picking-explained.html
Answer: Based on your graph the release branch does not have any of the commits o0-o4. They are all on the develop branch.
If you want to start a release branch without o1 and o2 here is a solution
<code>git rebase <sha of o0> -i
</code>
Now you can move the commits around
Your log would look something like this
<code>----o0---o3---o4---o1---o2 [develop]
</code>
If the moving worked you can start a release from o4


What is going on with this Taylor Series?

Question: I created a program to find high degree Taylor series approximations for any function, but I notice an interesting behavior as higher order polynomials are included. My understanding is that a function such as f(x) = sin(x) is entire, and can be represented infinitely, since it is continuous and differentiable at any point. However, after my Taylor series powers go beyond ~50, the graph becomes hypersensitive and "noisy".
I am posting this to ask if there are flaws in my understanding of these types of power series, or if there is a good explanation of this behavior. I also wonder whether it is preventable in order to obtain a very high order representation of an oscillating function.
I have attached some photos of the described behavior.
Image 1
Image 2
Image 3
Comment: Presumably, your Taylor Series is a Mclaurin Series (i.e. a Taylor Series expanded about x=0) and so the more periods out you graph the function the more numerical errors (i.e. computer precision rounding limitations) can/will compound.
Comment: Could you send Desmos link?
Comment: the errors in 50th term will be negated by next terms, Maybe 100 terms will negate the error in 50th term, But then , the erros in 100th terms will be negated by next 50 terms and so and so, Even if you reach a very large number of terms, At very large "x", You will still have some noise
Comment: @JoanS.GuillametF. https://www.desmos.com/calculator/xxhtsgysln
Answer: The Taylor series for $\sin(x)$ does converge to $\sin(x)$ for every $x$, but that doesn't mean it is very good in practice for approximating $\sin(x)$.  Consider a particular Taylor polynomial $$S_N(x) = \sum_{n=0}^N \frac{f^{(n)}(0)}{n!} x^n$$
where $f^{(n)}(0) = 1$ for $n = 1, 5, 9, \ldots$, $-1$ for $3, 7, 11, \ldots$, $0$ otherwise. If $N$ is large that is an extremely good approximation to $f(x)$ when $x$ is very close to $0$.  But it is a polynomial of degree $N$ (if $N$ is odd), and so it grows rapidly for large $|x|$, while $f(x) = \sin(x)$ is bounded on the real line.  So if you compare the graphs of $f$ and $S_N$, you should see $S_N$ following $f$ very closely on some interval around $0$ and then shooting off to $+\infty$ or $-\infty$ rapidly.  The larger $N$ is, the larger the interval where it is a good approximation.
But that's assuming exact arithmetic.  The terms that made $S_{50}(x)$ large are still present in $S_{100}(x)$, they are just cancelled by other terms.  When you do the calculations numerically, the inevitable rounding errors mean that the cancellation is not exact.  A sum of large numbers of different signs that should almost cancel is a recipe for disaster in numberical work.  That is what produces the
"noisy" result.
EDIT: Here are $\sin(x)$ (blue) with $S_{99}(x)$ (red) and $S_{199}(x)$ (green) as plotted in Maple using Digits = 100 (i.e. $100$ decimal digit arithmetic).  This seems to be enough for the interval in the plot.

And here is the same with the default setting (which used hardware floating-point, roughly equivalent to $16$ digits).  Note that $S_{99}$ seems to still be OK, but $S_{199}$ gives "chaotic" results for $x > 35$ or so.
Comment: Excellent answer, thank you! I wonder though: is there a way to graph such a high degree polynomial sum (w/ a term such as x^400) without encountering computer rounding errors? I am thinking of a system where a less speedy computation would be performed that results in a cleaner and more exact conclusion. It definitely makes sense that an application like Desmos would struggle with a string (1/200! * (x)^200 + 1/201! * (x)^201 + 1/202! * (x)^202...). Is there any point in this, though? Maybe it would be better to add together split taylor series, each centered around a different X coordinate.
Comment: You can use high-precision arithmetic in a CAS such as Maple. I'll put an example in my answer.
Comment: @Colter Why go with a polynomial approximation at all? Trig functions like Sin and Cos are well implemented in most math/eng software.  Far easier to just take x modulo the period length and plug that into the trig function.
Comment: @AmateurDotCounter Just for the fun of it, and for a programming task. Definitely not practical in any sense, but I found it cool nonetheless.


Python como repetir meu codigo

Question: gostaria de repetir esse codigo pra nao iterar ele 300 vezes , é um robo pra clicar na tela,queria que ele se repetisse , o codigo é esse ,sou novo aqui e na programação nao se se coloquei certo o formato da pergunta aqui e nao foi como o codigo no vscode mas é basicamente isso hehe
import pyautogui

import time

pyautogui.moveTo(28,295,duration=0.5)

pyautogui.click(30,295,duration=0.5)

pyautogui.moveTo(650,220,duration=1)

pyautogui.click(650,220,duration=1)

pyautogui.moveTo(650,670,duration=0.3)

pyautogui.click(650,670,duration=1)

Comment: Seja bem vindo Lutgens10,  veja se esta pergunta ( e os links que estão nela) te ajuda: [Como fazer este programa se repetir?](https://pt.stackoverflow.com/questions/401392/como-fazer-este-programa-se-repetir)

Aconselho você a fazer o nosso [Tour](https://pt.stackoverflow.com/tour)
Answer: Para isso você pode usar o while loop ou o for loop:
import pyautogui
import time

i = 0

while i < 300:

    pyautogui.moveTo(28,295,duration=0.5)
    pyautogui.click(30,295,duration=0.5)

    pyautogui.moveTo(650,220,duration=1)
    pyautogui.click(650,220,duration=1)

    pyautogui.moveTo(650,670,duration=0.3)
    pyautogui.click(650,670,duration=1)

    i += 1

import pyautogui
import time

for _ in range(300):

    pyautogui.moveTo(28,295,duration=0.5)
    pyautogui.click(30,295,duration=0.5)

    pyautogui.moveTo(650,220,duration=1)
    pyautogui.click(650,220,duration=1)

    pyautogui.moveTo(650,670,duration=0.3)
    pyautogui.click(650,670,duration=1)

Comment: obrigado cara muito obrigado
Comment: cara ta dando um erro no console   invalid syntax (,line8) pylint(syntax-error)  [8,10]
Comment: a sintaxe da resposta está correta. Sugiro que você compare como você digitou o código aí, com o que está aqui.

Lembrando que vocẽ tem que configurar a ferramenta que está usand para editar código para usar "espaços" e nao "tabs" (ou 'tabuladores' ,   vai saber como está a tradução)
Comment: estou usando o vscode , ele nao deixa fazer o while que merda , nao sei mudar pra espaços hahahah vou pesquisar aqui valeu
Answer: import pyautogui
import time

i = 0

while i < 300:

    pyautogui.moveTo(28,295,duration=0.5)
    pyautogui.click(30,295,duration=0.5)

    pyautogui.moveTo(650,220,duration=1)
    pyautogui.click(650,220,duration=1)

    pyautogui.moveTo(650,670,duration=0.3)
    pyautogui.click(650,670,duration=1)

    i += 1

Comment: Além do código não possuir qualquer explicação o que essa resposta tem de diferente da resposta já aceita?

Python como repetir meu codigo


C# write image to TCP socket

Question: I have the following code that saves an image from a camera to disk:
public static Image getAndSaveImage(int imageCount)
{
    var image = _camera.GetImage() as ThermalImage;
    image.Palette = PaletteManager.Iron;
    _camera.GetImage().EnterLock();
    Image camImage = _camera.GetImage().Image;
    _camera.GetImage().ExitLock();
    camImage.Save("./images/picture" + Convert.ToString(imageCount) + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
    return camImage;
}

As you see, I am saving the image to a file. Currently, this method is called within a loop. I want to replace the saving to disk with a websocket, so clients can connect to this socket and receive bitmap images from the underlying stream. Since a bitmap is an array, this should work, shouldn't it?
I read at some documentations that I can use the TcpListener class.
So I would do the following:
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);

server.Start();
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();

How can I write my bitmap image into this stream so a python client on the other
side
 can fetch the images? Do I need to handle the TCP handshakes on my own?
Thanks a lot
Answer: Edit: originally, the question asked about WebSocket specifically; everything below is predicated on that - now removed - position.
WebSocket, RFC6455, is not a naked socket - it is a non-trivial frame-based protocol that starts off similarly to HTTP 1.1 before transitioning to a different protocol. So; if you want to use WebSocket, you would probably want to use a web-socket server implementation - doing it by hand is not fun (trust me, I know).
If you want simple, ASP.NET (including ASP.NET Core and Kestrel) has an inbuilt WebSocket API, trivially googlable.
However! Because it is a frame-based protocol, you won't be using a regular Stream. WebSocket has 2 main data frame types: text and binary (if we ignore the early prototypes of WebSocket that only had text, and was fundamentally a different protocol that shaded a name)  - in your case you'll want binary, obviously, and your best bet is probably to change your existing code to save to a MemoryStream, then get the buffer from the MemoryStream to pass to the WebSocket API. The simplest approach there is ToArray() on the MemoryStream, but the more efficient approach is to use GetBuffer() or TryGetBuffer(), and use an API that accepts an oversized buffer with offset (usually 0) and length (which will be (int)memoryStream.Length).
If you don't actually mean WebSocket, but you just mean "a TCP socket, accessed over the internet", then ignore everything I've said; TcpListener should be fine.
Comment: @ItFreak k; as a side note, though; IIRC many image encoders need to "seek" the stream, which `NetworkStream` *does not allow*; in that case, you might again want to use `MemoryStream` as the original storage to call `.Save(...)` with, then just rewind your stream (`memoryStream.Position = 0;`) and copy the contents from the `MemoryStream` to the `NetworkStream` - `memoryStream.CopyTo(networkStream)`
Comment: Thanks for the hint. I am actually a Java developer and need to use C# for this specifc camera. the goal is to provide the images over a stream o a python client can fetch the images. But yout answer was very useful for clarification:)
Comment: @ItFreak btw, a few years ago I wrote a custom web-socket client/server implementation for Stack Overflow, which we called NetGain - it is [available here](https://github.com/StackExchange/NetGain) - however, in the last few months, we have switched over to a Kestrel/libuv based web-socket server in .NET Core
Comment: @ItFreak there's a huge difference between "a stream" and "WebSocket"; if you don't actually need WebSocket, I would say: don't - just use TCP. Usually, when we're talking WebSocket, we're talking about browser clients.
Comment: Thanks a lot! I will just use TCP now

C# write image to TCP socket


Linear Algebra Find Matrix that satisfies the proposition

Question: Let (V, K) be a finite-dimensional vector space and φ ∈ L(V, V ). Find φ
such that if A is its matrix representation with respect to some basis of V ,
then $A^2(I − A) = 0$ but φ is not a projection. This problem shows you that
if a map φ satisfies the relation $φ^3 = φ^2$
, this does not necessarily imply that
φ is idempotent and hence a projection!
Hint: do not attempt to find the most general φ. It is sufficient to provide
an example for such a linear transformation in the case $(V, K) = (R^
2
, R)$.
I've tried to do this by chance and didn't get what satisfies this
Is there a proper way to solve this other than by luck
Answer: You want to find some kind of linear map $\varphi$ such that $\varphi^2 \neq \varphi$ but does not change, when you apply it to itself again. Do you know a map $\alpha$ such that for all maps $\beta$ we always have $\alpha \circ \beta = \alpha$? If you have found one, can you find an $\varphi\neq \alpha$ such that $\varphi^2 = \alpha$?
Comment: I couldnt find , Could you help me finding one and what approach should I use
Comment: one approach that I took was to consider A=[2 1 ,-4 -2 ] so that A^2 = 0
Comment: Finding a $A$ such that $A^2=0$ is a good way. So we have $A^2\neq A$, so $A$ is no projection. And $A^3 = A^2 \circ A = 0 \circ A = 0 = A^2$. So you have found what you wanted. This property of $A$ is called nilpotency (or $A$ is nilpotent). The example $[0 1, 0 0]$ is a bit easier but your $A$ works as well.


$x^n-a$ is irreducible in $\mathbb{Z}[x]$ if $a$ is not a $p$th power for $p\vert n$.

Question: One can easily show that if $n$ is $2$ or $3$, and $a\in\mathbb{Z}$ such that $a$ is not an $n$th power, then $x^n-a$ is irreducible over $\mathbb{Z}$ since it has no roots. However, I believe more generally that:

If $n$ is any positive integer and $a\in\mathbb{Z}$ such that $a$ is not a $p$th power for any prime factor $p$ of $n$, then $x^n-a$ is irreducible over $\mathbb{Z}$.

However, it does not suffice to just check that $x^n-a$ has no roots when $n\geq 3$. So how can one prove this? Is it even true? What if we replace $\mathbb{Z}$ with an arbitrary UFD?
Edit: As per Thomas Andrews's example, assume $\pm a$ is not a $p$th power, not just $a$. In the UFD case, assume no associate of $a$ is a $p$th power.
Comment: Use that $x^n-a$ is irreducible over integers iff it's irreducible over rationals (Gauss' lemma) and look at [When is $X^n-a$ is irreducible over F?](https://math.stackexchange.com/questions/133581/when-is-xn-a-is-irreducible-over-f)
Comment: $x^4+4$ is reducible. You need to exclude $\pm a$ being a $p$th power, at least.
Answer: Let $p(x)\in\mathbb Z[x]$ be an irreducible polynomial which divides $x^n-a.$ By necessity, $p(x)$ is a monic polynomial.
Now, let $d=\deg p(x),$ and assume $d<n.$
Let $\alpha$ be a root of $p(x).$
Show that then $$p(x)=\prod_{\zeta\in J}(x-\zeta\alpha)$$ where $J$ is some subset of the group $G$ of $n$th roots of $1.$
We can show that $J$ is actually the subgroup of size $d,$ and then that we get all the roots by multiplying:
$$x^n-a=\prod_{i=1}^{n/d}\zeta^{-i}p(\zeta^i x)=\zeta^{K}\prod_{i}p(\zeta x)$$
where $\zeta$ is a primitive $n$th root of $1,$ and $K$ is some integer.
But then, substituting $x=0,$ $$-a=\zeta^Kp(0)^{n/d}.$$
That means $\zeta^K$ must be real, hence $\pm1,$ and $\pm a$ is a perfect $n/d$th power.
In particular, if $p\mid n/d,$ then $\pm a=$ is a perfect $p$th power.
Comment: Can you explain why $J$ must be a subgroup of $G$?
Comment: If $\zeta^n=1$ is a primitive root, and $a\in J,$ then the map $\zeta\mapsto \zeta, \alpha\mapsto a\alpha$ is an automorphism of $\mathbb Q[\alpha,\zeta].$ But if $b\in J,$ then $b\alpha$ is a root of $p(x),$ then the image of $b\alpha$ in the automorphism is also a root of $p(x),$ and the image of $b\alpha$ is $ab\alpha.$ So $ab\in J.$ Since $G$ is finite, that is all we need to prove $J$ is a subgroup. @Anon
Comment: This assumes $\alpha$ is not rational, but if $\alpha$ is rational, then it is an integer, and $a=\alpha^n$ gives us a solution.
Comment: Thanks! That makes sense then.


Work around to getting Backup and Migrate to work with Acquia Dev Cloud?

Question: Currently, when you host a site onto Acquia Dev Cloud, they disable the ability to install backup and migrate module due to it affecting their "server" setup. This proves to be a big nuisance when trying to create a quick backup of a site and to even make scheduled hourly backups. The suggest us to use the Acquia platform to do backups, but it's totally inefficient since it cannot schedule your own backup times. And doing this via drush is troublesome if you just want to do a quick backup because you wanted to make a change on a site just in case it breaks it.
How would one go around this problem of backing up a site with Acquia dev cloud?
Comment: How did you try to install backup and migrate there (I haven't faced the issue at doing it from command line) ? And who replied to you ? Non technical are sometimes in first line of support and may give non sense replies.
Answer: The best is enable your access to the command line to their server.
For this you need to store your public ssh_key in your profile on their platform.
Then to find the exact server and username to connect do :

Sign in to the Acquia Cloud interface.
Select your application and
environment.
In the menu to the left, click Users and Keys, to see your exact command :

What follows is using drush ... but wait ... you can automate the use of drush : I explain.
Once logged, you can use drush from the command line, like this :
cd dev/livedev/docroot
drush ard
Since you have access to the command line, you can also use scp to transfer your backup.
By the way you won't have the possibility to access crontab -e there, however, you can write a script and execute from your computer to connect via ssh, do the backup, and get it using scp.
Once this script is written, you can use the cron from your computer to execute it every hour if you want.
That script would look like :
cd ~/dev/livedev/docroot
drush ard
cd drush-backups/archive-dump/
cd `ls -Art | tail -n 1`
mv `ls -Art | tail -n 1` ~/last_backup.tgz
You can store it remotely as ~/backup.sh locally in your cron you put
ssh -t -t yourlogin@youraddress '~/backup.sh && exit' && scp yourlogin@youraddress:~/last_backup.tgz /home/yourself
For an explanation of the -t -t, see https://serverfault.com/questions/224307/ssh-fails-to-execute-remote-command-when-run-from-cron-bash-script-works-from
If any other issue, with ssh from cron, please watch also : https://serverfault.com/questions/186448/crontab-to-run-bash-script-ssh-command-in-it-not-working
Another solution is to use the scheduled job from their interface, as explained there : https://docs.acquia.com/acquia-cloud/manage/cron
If any other problem please comment.
Comment: Myself I never use Backup and Migrate ... using that, makes sense only when you don't have ssh and drush access. I tell you here how all the professionals are working : They go on drush ard + scp  or similar stuff ... and eventually automate that.
Comment: This was not the question to be covered here but, same fashion to act is ok, because drush provides the way to restore backups.

Be aware that Acquia platform is not built, in my opinion, for people like wordpress developers, who know just a bit of css, html and are scared of the command line.

That's why my first answer what about automating drush with cron, and then verifying if you really couldn't not install backup and migrate ... indeed you can.
Comment: paying 20k for acquia on an Enterprise account is really stupid that i can't even use back up migrate.
Comment: what if you wanted to revert to a previous change an hour ago? you'd have to make sure your custom script does that. also ssh is not friendly for non users of the terminal if you want to revert.
Answer: Correction : The install of Backup And Migrate works.
Follow the procedure explained before to enable ssh access.
Once logged in, do
cd ~/dev/livedev/docroot
Then
drush -y en backup_migrate
That's all. I tried. It just works. Here is screenshot :
Comment: i ssh into the acquia dev server and tried to enable it via drush, but it does not work. see: http://prntscr.com/fjc695 it throws errors. "exception 'DatabaseSchemaObjectExistsException' with message 'Table backup_migrate_profiles already exists.' "
Comment: run :
drush -y pmu backup_migrate && drush -y en backup_migrate

That will clean up the db first.
Comment: nope. still throws the error.


Multiple 's in a row using Markdown Syntax?

Question: I'm trying to include multiple blockquotes using markdown, but I'm stuck on the syntax for closing out the initial blockquote and starting a new one instead of continuing in the current blockquote and adding additional paragraphs...
=== Current syntax ===
>   Review1
>   -- Person1

>   Review2
>   -- Person2

=== Current result ===

Review1
    -- Person1

Review2
    -- Person2

=== Wanted result ===

Review1
    -- Person1

Review2
    -- Person2

Comment: duplicate of http://stackoverflow.com/questions/12979577/how-can-i-write-two-separate-blockquotes-in-sequence-using-markdown
Comment: Does this answer your question? [How can I write two separate blockquotes in sequence using markdown?](https://stackoverflow.com/questions/12979577/how-can-i-write-two-separate-blockquotes-in-sequence-using-markdown)
Answer: Put in a comment
>   Review1
>   -- Person1

<!>

>   Review2
>   -- Person2

or a manual line break
>   Review1
>   -- Person1

>   Review2
>   -- Person2

Result

Review1
    -- Person1

Review2
    -- Person2
Comment:  didn't work for me I had to use . The triple dash works with pandoc, but it's not necessary for normal parsing. See [here](http://stackoverflow.com/questions/4823468/store-comments-in-markdown-syntax)
Comment: Using JSDoc here. The comment method worked for me (with a full HTML comment), but the line break did not.
Comment: This unfortunately doesn't work for Markdown settings that disallow HTML input.


Allow a row child to expand if necessary, but otherwise occupy minimum size

Question: I wrote a Flutter package that provides sign in buttons for social platforms. Here's an example of what one looks like:

I'm struggling to get this button to look nice when a parent makes it stretch. For example, placing this button in a column with CrossAxisAlignment.stretch. I would like the icon and text to remain as they are, and the spare space 'added' to the blue on the right hand side.
As you can see from the code, this is a RaisedButton with an Icon and Text, plus some padding (as defined by Google's standards). It uses a Row with MainAxisSize.min:
    // Code omitted for clarity (see link above for full version)
    ButtonTheme(
      child: RaisedButton(
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(1.0),
              child: Container(
                height: 38.0,
                width: 38.0,
                child: Center(
                  child: Image(...),
                    height: 18.0,
                    width: 18.0,
                  ),
                ),
              ),
            ),

            SizedBox(width: 14.0),
            Padding(
              padding: const EdgeInsets.fromLTRB(0.0, 8.0, 8.0, 8.0),
              child: Text("Sign in with Google"),
            ),
          ],
        ),
      ),
    );

I tried adding a Spacer to the row as the final widget, but that causes the row to always expand to fill its parent. Instead, I want it to only fill the parent when the parent forces it to.
Any suggestions for how to tackle this?
Answer: You can use the Align widget as a parent of your RaisedButton , something like this :
         child: Align(
                alignment: Alignment.centerLeft,
                child: RaisedButton(
                  onPressed: onPressed,
                  color: darkMode ? Color(0xFF4285F4) : Colors.white,
                  child: Row(
                    mainAxisSize: MainAxisSize.min,

Using this , your Row won't expand :)
OR
Use LayoutBuilder if you want to expand the button according the parent widget :
         @override
          Widget build(BuildContext context) {
            return LayoutBuilder(
              builder: (context, constraints) {
                return ButtonTheme(
                  height: 40.0,
                  padding: const EdgeInsets.all(0.0),
                  shape: RoundedRectangleBorder(
                    // Google doesn't specify a border radius, but this looks about right.
                    borderRadius: BorderRadius.circular(3.0),
                  ),
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: RaisedButton(
                      onPressed: onPressed,
                      color: darkMode ? Color(0xFF4285F4) : Colors.white,
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: <Widget>[
                          // The Google design guidelines aren't consistent. The dark mode
                          // seems to have a perfect square of white around the logo, with a
                          // thin 1dp (ish) border. However, since the height of the button
                          // is 40dp and the logo is 18dp, it suggests the bottom and top
                          // padding is (40 - 18) * 0.5 = 11. That's 10dp once we account for
                          // the thin border.
                          //
                          // The design guidelines suggest 8dp padding to the left of the
                          // logo, which doesn't allow us to center the image (given the 10dp
                          // above). Something needs to give - either the 8dp is wrong or the
                          // 40dp should be 36dp. I've opted to increase left padding to 10dp.
                          Padding(
                            padding: const EdgeInsets.all(1.0),
                            child: Container(
                              height: 38.0, // 40dp - 2*1dp border
                              width: 38.0, // matches above
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(3.0),
                              ),
                              child: Center(
                                child: Image(
                                  image: AssetImage(
                                    "graphics/google-logo.png",
                                    package: "flutter_auth_buttons",
                                  ),
                                  height: 18.0,
                                  width: 18.0,
                                ),
                              ),
                            ),
                          ),

                          SizedBox(width: 14.0 /* 24.0 - 10dp padding */),
                          Padding(
                            padding: const EdgeInsets.fromLTRB(0.0, 8.0, 8.0, 8.0),
                            child: Text(
                              text,
                              style: TextStyle(
                                fontSize: 18.0,
                                fontFamily: "Roboto",
                                fontWeight: FontWeight.w500,
                                color: darkMode
                                    ? Colors.white
                                    : Colors.black.withOpacity(0.54),
                              ),
                            ),
                          ),
                          constraints.minWidth == 0 ? SizedBox.shrink() : Spacer(),
                        ],
                      ),
                    ),
                  ),
                );
              },
            );
          }

Comment: Your first answer didn't work for me. But the second did :-)


Travel listings module for Drupal

Question: I'm using Drupal 7 and can't find a suitable module to add travel listings content type. It would be great if that module would just work by having specific fields, like location and address, as well as enable the possibility to have a main index page that lists all the listings in a category.
I found Listings module, but that's only for Drupal 6.
Thank you!
Comment: No, views is basically a gui that you can use to query for nodes in drupal. It's a module that you can add to your drupal site (https://www.drupal.org/project/views).
Comment: You should be able to do this by just adding your own content type of "Travel", then managing the fields on that content type and adding the fields that you need. A main index page that lists all the listings of a given category would simply just be a view.
Comment: @Jance thank you, is the "View" also a content type?
Answer: Since we have the flexibility of the content type and field creation systems you don't really need someone else to post a module creating the exact content type you need (it is unlikely your requirements are exactly the same as the author of such a module).
So instead you can yourself:

Create your own custom content type
Add the fields you require to the content type
Create a listing of your content using the views module - If you install the advanced help module you will get lots of help documentation on creating views by clicking the little question mark links scattered around the views user interface.
Comment: Fully agree ... Though I'd also add the [Rules](https://www.drupal.org/project/rules) module and the [Flag](https://www.drupal.org/project/flag) module
Comment: @Pierre.Vriens: would you add those in relation to one of the requirements in the question or just as useful add-ons?
Comment: I'd add them to your answer, as add-ons ...

Travel listings module for Drupal


Help with this recurrence

Question: $$
T(n) = \begin{cases}
6, & n=0 \\
9T(n-2)+n, & n>0
\end{cases}
$$
I don't know how to resolve this.....Can you tell me how can I solve it?
Comment: There is a missing initial condition - what is $T(1)$? Without this information, we cannot for example compute $T(3)$.
Comment: I can't read the question.  There seems to be something missing.  Please clarify
Comment: Have you tried the methods explained in Wilf's "generatingfunctionology", my favourite reference for this topic ?
Answer: Simple way is to follow it a couple of terms and see the pattern. So assuming $n = 2m$ is even,
$$
\begin{split}
T(n)
&= 9T(n-2)+n \\
&= 9 (9T(n-4) + (n-2)) + n\\
&= 9^2T(n-4) + 9(n-2) + n \\
&= 9^3 T(n-6) + 9^2 (n-4) + 9(n-2) + n \\
&\ldots \\
&= 9^m T(0) + \sum_{k=0}^{m-1} 9^k (n-2k)
\end{split}
$$
Can you finish it? (Note: if $n = 2m+1$ is odd, you will end up with $9^mT(1)$ in the last term and some other related changes will be needed.)
A different way is to propose a solution of the form $T(n) = a^n$ for some $a \in \mathbb{R}$, plug it in and see what values of $a$ will fit...
Comment: If $n$ is odd, then it will be $T(1)$ in the last step of the calculation.
Comment: @Kumar made the changes

Help with this recurrence


Bolzano--Weierstrass Theorem implies Nested Interval Property

Question: This question is from abbott's Understanding Analysis:

Start with the Bolzano--Weierstrass Theorem and use it to
  construct a proof of the Nested Interval Property.

My try: Let $I_n=[a_n,b_n]$ be closed intervals such that $I_1 \supseteq I_2 \supseteq \dots$. So here $a_n$ is a (nondecreasing) bounded sequence, so it contains a convergent subsequence by hypothesis, so does $b_n$.
But here I am stuck. I have temptation to use Monotone Convergence Theorem, but that would imply that I am assuming Axiom of Completeness, or worse, Nested Interval Property itself!
Comment: The Axiom of spremum must be taken as a starting point.
Comment: The Bolzano-Weierstrass recursion build the intervals that you want. Construct with every choice of the Bolzano-Weierstrass the intervals.
Answer: As you noted, there is a subsequence $n_k$  such that $a_{n_k}\to a$.  As $I_n$ is closed and contains almost all $a_{n_k}$, we have $a\in I_n$. As this holds for all $n$, $a\in\bigcap I_n$


What is the adherent value of $(\frac1n,1)$ in this topology?

Question: The question is to find the adherent value of $(\frac1n,1)$ in the toplogy $\{\mathbb{R}^2,\emptyset, (B_r)_{r>0}\}$
where $B_r=\{(x,y)\in\mathbb{R}^2, (x-3)^2+y^2<r^2\}$
That is
for any $r>0$ we have $$card\{n\in\mathbb{N}, (\frac1n,1)\in B_r\}=+\infty$$
$(\frac1n,1)\in B_r\Rightarrow (3-\frac1n)^2<r^2-1$ for $r>1$ we have $|3-\frac1n|<\sqrt{r^2-1}$
how to continue please
Comment: This is the same questioned you asked before but with a different center for $B_r.$
Answer: [Update] OP wanted the set of $\omega$-accumulation points, neither accumulation points nor adherent points.

An $\omega$-accumulation point of a set $A$ in a topological space $X$ is a point $x$ that every open set containing x contains infinitely many points of $A$. [Wikipedia: Limit point]

Let $A=\{(\frac{1}{n},1)\mid n\in\mathbb{N}\}\subset\mathbb{R}^2$. Then the set of $\omega$-accumulation points of $A$ is
$$
\mathbb{R}^2\setminus B_\sqrt{10}
$$

Let $d_n=\sqrt{(3-\tfrac{1}{n})^2+1}$ be a sequence of real numbers. Then $d_n$ converges to $\sqrt{10}$.
For any $x\in B_\sqrt{10}$, we have $d_x=\|(3,0)-x\|<\sqrt{10}$. Since $d_n$ converges to $\sqrt{10}$, there exists a natural number $N$ such that $d_x<d_n<\sqrt{10}$ for all $n\geq N$. Consider the open set $B_{d_N}$. Since $d_x<d_N$, we have $x\in B_{d_N}$, but $A\cap B_{d_N}$ is finite. Thus $x$ is not an $\omega$-accumulation point of $A$.
However, for $x\notin B_\sqrt{10}$ we have $d_x=\|(3,0)-x\|\geq\sqrt{10}$ so that if any open ball $B_r$ contains $x$ then $r$ should be greater than $\sqrt{10}$. When $r>\sqrt{10}$, note that $B_r$ contains all points of $A$. Therefore $x$ is an $\omega$-accumulation point of $A$.

A limit point (or accumulation point) of a set $A$ in a topological space $X$ is a point $x$ that every neighbourhood of $x$ with respect to the topology on $X$ also contains a point of $A$ other than $x$ itself. [Wikipedia: Limit point]

Let $A=\{(\frac{1}{n},1)\mid n\in\mathbb{N}\}\subset\mathbb{R}^2$. Then the set of limit (or accumulation) points of $A$ is
$$
\mathbb{R}^2\setminus \bigl( B_\sqrt{5} \cup \{(1,1)\} \bigr)
$$

The closest point in $A$ from the center $(3,0)$ of $B_r$ is $(1,1)$ and the distance between the two points is $\sqrt{5}$. Thus $A\cap B_\sqrt{5}=\varnothing$.
For any $x\in B_\sqrt{5}$, we have an open set $B_\sqrt{5}$ containing $x$ but $A\cap B_\sqrt{5}=\varnothing$. Thus there is no limit (or accumulation) point of $A$ in $B_\sqrt{5}$.
Note that $A\cap B_\sqrt{6}=\{(1,1)\}$ since $\|(3,0)-(\tfrac{1}{n},1)\|=\sqrt{(3-\tfrac{1}{n})^2+1}>\sqrt{6}$ for all $n\geq2$. Thus $(1,1)$ is not a limit (or accumulation) point of $A$.
If $x\notin B_\sqrt{5}$ and $x\neq(1,1)$, then the distance between $x$ and the center $(3,0)$ of $B_r$ is greater than or equal to $\sqrt{5}$. What is an open set $B_r$ containing $x$? That is, $B_r$ for $r>\sqrt{5}$, and moreover, $(1,1)\in A\cap B_r$. Therefore, $x$ is a limit (or accumulation) point of $A$.

An adherent point of a subset $A$ of a topological space $X$, is a point $x$ in $X$ such that every open set containing $x$ contains at least one point of $A$. [Wikipedia: Adherent point]

Let $A=\{(\frac{1}{n},1)\mid n\in\mathbb{N}\}\subset\mathbb{R}^2$. Then the set of adherent points of $A$ is
$$
\mathbb{R}^2\setminus B_\sqrt{5}
$$

For any $x\in B_\sqrt{5}$, we have an open set $B_\sqrt{5}$ containing $x$ but $A\cap B_\sqrt{5}=\varnothing$. Thus there is no adherent point of $A$ in $B_\sqrt{5}$.
If $x\notin B_\sqrt{5}$, the distance between $x$ and the center $(3,0)$ of $B_r$ is greater than or equal to $\sqrt{5}$. What is an open set $B_r$ containing $x$? That is, $B_r$ for $r>5$, and moreover, $(1,1)\in A\cap B_r$. Therefore, $x$ is an adherent point of $A$.
Comment: why it is not for $\sqrt{10}$
Comment: It is not the definition we use of adherent point
Comment: @Vrouvrou you want infinitely many points of the set in each neighbourhood? That's called an accumulation point (or $\omega$-acculation point if you always want at least countably many, or total accumulation point if we want as many points as the set has).
Comment: so accumulation points
Comment: @HennoBrandsma in the sours i have, $x$ is an adherent point iiff $\forall V\in\mathcal{V}_x, \rm card\{n\in\mathbb{N}, u_n\in V\}$ so i want to see where i have infinitly many points of the sequence
Comment: $\forall V\in\mathcal{V}_x, \rm card\{n\in\mathbb{N}, u_n\in V\}=+\infty$
Comment: you say for example that $(\frac12,1)$ is an accumulation point but it is false his neighborhooh contains only 2 point of the sequence (1 and $\frac12$) not an infinity !!
Comment: @ ChoF, nice answer. +1.